Exemplo n.º 1
0
        public void MultiplyOperation_Test()
        {
            MultiplyOperation op = new MultiplyOperation(new Integer(2), new Integer(4));

            Assert.AreEqual(8, op.Value);
            Assert.AreEqual("2 x 4", op.ToString());
        }
Exemplo n.º 2
0
        public void Solutions_DivideOperator_Test()
        {
            //Try to represent the equation ((5+1) x 3) - 4
            IEquation node1     = new AddOperation(new Integer(5), new Integer(1));
            IEquation node2     = new MultiplyOperation(node1, new Integer(3));
            IEquation equation1 = new MinusOperation(node2, new Integer(4));

            //Try to represent the equation 1 + 2  +3
            IEquation node3     = new AddOperation(new Integer(1), new Integer(2));
            IEquation equation2 = new AddOperation(node3, new Integer(3));

            Solutions solutions = new Solutions();

            solutions.Add(equation1);
            solutions.Add(equation2);

            IEquation equation3 = new Integer(14);

            Solutions new_solutions = solutions / equation3;

            Assert.AreEqual(2, new_solutions.Count);
            Assert.AreEqual(1, new_solutions[0].Value);
            Assert.AreEqual((decimal)6 / (decimal)14, new_solutions[1].Value);

            new_solutions = solutions / new Integer(3);
            Assert.AreEqual(2, new_solutions.Count);
            Assert.AreEqual((decimal)14 / (decimal)3, new_solutions[0].Value);
            Assert.AreEqual(2, new_solutions[1].Value);
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            var input = Console.ReadLine();

            while (input != "exit")
            {
                var     op5 = new PowerOperation();
                var     op4 = new DivideOperation(op5);
                var     op3 = new MultiplyOperation(op4);
                var     op2 = new SubstractOperation(op3);
                var     op1 = new AddOperation(op2);
                Command command;
                try
                {
                    command = new Command(input);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    throw;
                }

                var result = op1.Calculate(command);
                Console.Write(result == null
                    ? $"Operation {command.Operation} is not supported"
                    : $"{command} = {result} \n");

                input = Console.ReadLine();
            }
        }
Exemplo n.º 4
0
 public override IBuildIntention <IMultiplyOperation> GetBuildIntention(IConversionContext context)
 {
     var(toBuild, maker) = MultiplyOperation.Create();
     return(new BuildIntention <IMultiplyOperation>(toBuild, () =>
     {
         maker.Build(Left.GetOrThrow().ConvertElementOrThrow(context), Right.GetOrThrow().ConvertElementOrThrow(context));
     }));
 }
Exemplo n.º 5
0
        public void MultiplyNumbers()
        {
            MultiplyOperation op = MultiplyOperation.Instance;

            Assert.AreEqual(3 * 2, op.Apply(3, 2));
            Assert.AreEqual(1.2 * 3.4, op.Apply(1.2, 3.4));
            Assert.AreEqual(4 * 2.3, op.Apply(4, 2.3));
            Assert.AreEqual(1.2 * 3, op.Apply(1.2, 3));
        }
Exemplo n.º 6
0
        public void DAGUsageCases2()
        {
            // We first initialize our shader.
            ShaderCode code = new ShaderCode(BindingStage.VertexShader);
            {
                // We write a simple Tranform code:
                code.InputOperation.AddInput(PinComponent.Position, PinFormat.Floatx3);
                Pin positon = code.InputOperation.PinAsOutput(PinComponent.Position);

                // We first need to expand our position to float4 (adding 1 at the end).
                ExpandOperation expand = new ExpandOperation(PinFormat.Floatx4, ExpandType.AddOnesAtW);
                expand.BindInputs(positon);
                Pin expPosition = expand.Outputs[0];

                // We now create constant transform matrix.
                ConstantOperation mvpConstant = code.CreateConstant("MVP", PinFormat.Float4x4);
                Pin MVP = mvpConstant.Outputs[0];

                // We multiply matrix and pin.
                MultiplyOperation mul = new MultiplyOperation();
                mul.BindInputs(MVP, expPosition);
                Pin transPosition = mul.Outputs[0];

                // We just bind transformed position to output.
                code.OutputOperation.AddComponentAndLink(PinComponent.Position, transPosition);
            }

            // We create constant buffer manually.
            ConstantBufferLayoutBuilder builder = new ConstantBufferLayoutBuilder();

            builder.AppendElement("MVP", PinFormat.Float4x4, Pin.NotArray);
            ConstantBufferLayout layout = builder.CreateLayout();

            // We now fill the data.
            FixedShaderParameters parameters = code.FixedParameters;

            parameters.AppendLayout(layout);
            if (!parameters.IsDefined)
            {
                throw new Exception();
            }

            GraphicsDevice device = InitializeDevice();

            // We have all parameters defined, compile the shader.
            VShader shader = code.Compile(device, parameters) as VShader;

            // Shader expects data in constant buffers.
            TypelessBuffer     buffer         = new TypelessBuffer(Usage.Default, BufferUsage.ConstantBuffer, CPUAccess.Write, GraphicsLocality.DeviceOrSystemMemory, 4 * 4 * 4);
            ConstantBufferView constantBuffer = buffer.CreateConstantBuffer(layout);

            // We fill the buffer.
            constantBuffer.Map(MapOptions.Write);
            constantBuffer.SetConstant("MVP", Math.Matrix.Matrix4x4f.Identity);
            constantBuffer.UnMap();
        }
Exemplo n.º 7
0
        public override HlslTreeNode Reduce()
        {
            Factor1.Outputs.Remove(this);
            Factor2.Outputs.Remove(this);
            var multiplication = new MultiplyOperation(Factor1, Factor2);

            var addition = new AddOperation(multiplication, Addend);

            Replace(addition);

            return(addition.Reduce());
        }
Exemplo n.º 8
0
        public void MultiplyOperation_Calculate_Success()
        {
            var operation = new MultiplyOperation();
            var input     = new OperationInput <int>()
            {
                Num1 = 3, Num2 = 5
            };
            var output = operation.Do(input);

            Assert.IsNotNull(output);
            Assert.IsInstanceOfType(output, typeof(OperationOutput <int>));
            Assert.AreEqual(((OperationOutput <int>)output).Result, 15);
        }
Exemplo n.º 9
0
        private HlslTreeNode CreateDotProductNode(Instruction instruction)
        {
            var addends       = new List <HlslTreeNode>();
            int numComponents = instruction.Opcode == Opcode.Dp3 ? 3 : 4;

            for (int component = 0; component < numComponents; component++)
            {
                IList <HlslTreeNode> componentInput = GetInputs(instruction, component);
                var multiply = new MultiplyOperation(componentInput[0], componentInput[1]);
                addends.Add(multiply);
            }

            return(addends.Aggregate((addition, addend) => new AddOperation(addition, addend)));
        }
Exemplo n.º 10
0
        public void Equation_Test1()
        {
            //Try to represent the equation ((5+1) x 3) - 4
            IEquation node1 = new AddOperation(new Integer(5), new Integer(1));

            Assert.AreEqual(6, node1.Value);

            MultiplyOperation node2 = new MultiplyOperation(node1, new Integer(3));

            Assert.AreEqual(18, node2.Value);

            MinusOperation equation = new MinusOperation(node2, new Integer(4));

            Assert.AreEqual(14, equation.Value);
            Assert.AreEqual("((5 + 1) x 3) - 4", equation.ToString());
        }
Exemplo n.º 11
0
        public void Equation_Test3()
        {
            //Try to represent the equation ((6 / 3) + 2) x 5
            IEquation node1 = new DivideOperation(new Integer(6), new Integer(3));

            Assert.AreEqual(2, node1.Value);

            IEquation node2 = new AddOperation(node1, new Integer(2));

            Assert.AreEqual(4, node2.Value);

            IEquation equation = new MultiplyOperation(node2, new Integer(5));

            Assert.AreEqual(20, equation.Value);
            Assert.AreEqual("((6 / 3) + 2) x 5", equation.ToString());
        }
Exemplo n.º 12
0
        public void MultiplyOperation_TwoMatrices_OneMatrix()
        {
            var input1 = new Matrix(new int[1, 1] {
                { 1 }
            });
            var input2 = new Matrix(new int[1, 1] {
                { 1 }
            });

            var inputArray = new Matrix[] { input1, input2 };

            var operation = new MultiplyOperation();
            var output    = operation.Apply(inputArray);

            Assert.Single(output);
        }
Exemplo n.º 13
0
        public void MultiplyOperation_2x1by1x2_2x2Matrix()
        {
            var input1 = new Matrix(new int[2, 1] {
                { 1 }, { 2 }
            });
            var input2 = new Matrix(new int[1, 2] {
                { 1, 2 }
            });

            var inputArray = new Matrix[] { input1, input2 };

            var operation = new MultiplyOperation();
            var output    = operation.Apply(inputArray).Single();

            Assert.Equal(2, output.RowCount);
            Assert.Equal(2, output.ColumnCount);
        }
Exemplo n.º 14
0
        public void MultiplyVectorToInteger()
        {
            MultiplyOperation op = MultiplyOperation.Instance;
            Vector            v  = new Vector(new object[] { 1, 2, 3 });

            var result = op.Apply(v, 2);

            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(Vector));

            var vector = (Vector)result;

            Assert.AreEqual(3, vector.Length);
            Assert.AreEqual(2, vector[0]);
            Assert.AreEqual(4, vector[1]);
            Assert.AreEqual(6, vector[2]);
        }
Exemplo n.º 15
0
        public void MultiplyRealByVector()
        {
            MultiplyOperation op = MultiplyOperation.Instance;
            Vector            v  = new Vector(new object[] { 1, 2, 3 });

            var result = op.Apply(1.5, v);

            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(Vector));

            var vector = (Vector)result;

            Assert.AreEqual(3, vector.Length);
            Assert.AreEqual(1 * 1.5, vector[0]);
            Assert.AreEqual(2 * 1.5, vector[1]);
            Assert.AreEqual(3 * 1.5, vector[2]);
        }
Exemplo n.º 16
0
        private void startTheQuiz()
        {
            // Create object to corresponding operation
            sumOperation      = new SumOperation(50, 50, sum);
            minusOperation    = new MinusOperation(50, 50, subtraction);
            divideOperation   = new DivideOperation(50, 50, division);
            multiplyOperation = new MultiplyOperation(50, 50, multiplication);

            // Change labels with question mark to value
            setLabels(plusLeftLabel, plusRightLabel, sumOperation);
            setLabels(minusLeftLabel, minusRightLabel, minusOperation);
            setLabels(divideLeftLabel, divieRightLabel, divideOperation);
            setLabels(timesLeftLabel, timesRightLabel, multiplyOperation);

            // Start the timer
            timeLeft       = 30;
            timeLabel.Text = "30 seconds";
            timer.Start();
        }
Exemplo n.º 17
0
        public void MultiplyOperation_TwoMatricesWithOneValue_MatricesMultiplied()
        {
            var input1 = new Matrix(new int[2, 2] {
                { 1, 1 }, { 1, 1 }
            });
            var input2 = new Matrix(new int[2, 2] {
                { 2, 2 }, { 2, 2 }
            });
            var expectedMatrix = new Matrix(new int[2, 2] {
                { 4, 4 }, { 4, 4 }
            });

            var inputArray    = new Matrix[] { input1, input2 };
            var expectedArray = new Matrix[] { expectedMatrix };

            var operation = new MultiplyOperation();
            var output    = operation.Apply(inputArray);

            Assert.Equal(expectedArray, output, new MatrixComparer());
        }
Exemplo n.º 18
0
        public void MultiplyOperation_TwoMatrices_MatricesMultiplied()
        {
            var input1 = new Matrix(new int[2, 2] {
                { 1, 2 }, { 3, 4 }
            });
            var input2 = new Matrix(new int[2, 2] {
                { 5, 6 }, { 7, 8 }
            });
            var expectedMatrix = new Matrix(new int[2, 2] {
                { 19, 22 }, { 43, 50 }
            });

            var inputArray    = new Matrix[] { input1, input2 };
            var expectedArray = new Matrix[] { expectedMatrix };

            var operation = new MultiplyOperation();
            var output    = operation.Apply(inputArray);

            Assert.Equal(expectedArray, output, new MatrixComparer());
        }
Exemplo n.º 19
0
        public static Operation CreateOperation(string operate)
        {
            Operation operation = null;

            switch (operate)
            {
            case "+":
                operation = new AddOperation();
                break;

            case "-":
                operation = new MinusOperation();
                break;;

            case "*":
                operation = new MultiplyOperation();
                break;

            case "/":
                operation = new DivideOperation();
                break;
            }
            return(operation);
        }
Exemplo n.º 20
0
        public Factorial()
        {
            var ifBlockScope = Scope.CreateAndBuild(new List <Scope.IsStatic> {
            });
            var elseBlock    = Scope.CreateAndBuild(new List <Scope.IsStatic> {
            });

            var inputKey = new NameKey("input");
            var input    = MemberDefinition.CreateAndBuild(inputKey, new NumberType(), false);

            var facKey = new NameKey("fac");
            var fac    = MemberDefinition.CreateAndBuild(facKey, MethodType.CreateAndBuild(new NumberType(), new NumberType()), false);


            var methodScope = Scope.CreateAndBuild(new List <Scope.IsStatic> {
                new Scope.IsStatic(input, false)
            });


            Module =
                ModuleDefinition.CreateAndBuild(
                    Scope.CreateAndBuild(
                        new List <Scope.IsStatic> {
                new Scope.IsStatic(MemberDefinition.CreateAndBuild(facKey, MethodType.CreateAndBuild(new NumberType(), new NumberType()), false), false)
            }),
                    new ICodeElement[] {
                AssignOperation.CreateAndBuild(
                    MethodDefinition.CreateAndBuild(
                        new NumberType(),
                        new NumberType(),
                        input,
                        methodScope,
                        new ICodeElement[] {
                    ElseOperation.CreateAndBuild(
                        IfOperation.CreateAndBuild(
                            LessThanOperation.CreateAndBuild(
                                MemberReference.CreateAndBuild(input),
                                ConstantNumber.CreateAndBuild(2)),
                            BlockDefinition.CreateAndBuild(
                                ifBlockScope,
                                new ICodeElement[] {
                        ReturnOperation.CreateAndBuild(
                            ConstantNumber.CreateAndBuild(1))
                    },
                                new ICodeElement[0])),
                        BlockDefinition.CreateAndBuild(
                            elseBlock,
                            new ICodeElement[] {
                        ReturnOperation.CreateAndBuild(
                            MultiplyOperation.CreateAndBuild(
                                NextCallOperation.CreateAndBuild(
                                    SubtractOperation.CreateAndBuild(
                                        MemberReference.CreateAndBuild(input),
                                        ConstantNumber.CreateAndBuild(1)),
                                    MemberReference.CreateAndBuild(fac)),
                                MemberReference.CreateAndBuild(input)))
                    },
                            new ICodeElement[0]))
                },
                        new ICodeElement[0],
                        false),
                    MemberReference.CreateAndBuild(fac)
                    )
            },
                    new NameKey("factorial")
                    );
        }
Exemplo n.º 21
0
        /// <summary>
        /// Calls the IOperation that corresponds to the input OperationType
        /// </summary>
        /// <param name="operationType">The operation to perform.</param>
        public void PerformOperation(OperationType operationType)
        {
            IOperation operation = null;

            switch (operationType)
            {
            case OperationType.Add:
                operation = new AddOperation();
                break;

            case OperationType.Minus:
                operation = new MinusOperation();
                break;

            case OperationType.Multiply:
                operation = new MultiplyOperation();
                break;

            case OperationType.Divide:
                operation = new DivideOperation();
                break;

            case OperationType.Negate:
                operation = new NegateOperation();
                break;

            case OperationType.SquareRoot:
                operation = new SquareRootOperation();
                break;

            case OperationType.Exponential:
                operation = new ExponentialOperation();
                break;

            case OperationType.Power:
                operation = new PowerOperation();
                break;

            case OperationType.Reciprocal:
                operation = new ReciprocalOperation();
                break;

            case OperationType.Sine:
                operation = new SineOperation();
                break;

            case OperationType.Cosine:
                operation = new CosineOperation();
                break;

            case OperationType.Clear:
                operation = new ClearOperation();
                break;

            case OperationType.Swap:
                operation = new SwapOperation();
                break;

            case OperationType.Rotate:
                operation = new RotateOperation();
                break;
            }
            if (operation != null)
            {
                /*
                 * Exception handling is done within each class that implements IOperation.
                 * Refactoring to multiple operation types (e.g. BinaryOperation,
                 * UnaryOperation, and StackOperation) can make the code DRYer as each type
                 * can use similar exception handling.
                 */
                operation.Perform(stack);
            }
        }
Exemplo n.º 22
0
        public override HlslTreeNode Reduce(MultiplyAddOperation node)
        {
            var multiplication = new MultiplyOperation(node.Factor1, node.Factor2);

            return(new AddOperation(multiplication, node.Addend));
        }
Exemplo n.º 23
0
        void Initialize()
        {
            // Initialize shader code.
            vertexShaderCode = new ShaderCode(BindingStage.VertexShader);

            {
                // We register inputs.
                vertexShaderCode.InputOperation.AddInput(PinComponent.Position, PinFormat.Floatx2);  //< Position.
                vertexShaderCode.InputOperation.AddInput(PinComponent.TexCoord0, PinFormat.Floatx2); //< Texture coordinate.
                vertexShaderCode.InputOperation.AddInput(PinComponent.User0, PinFormat.Floatx4);     //< Custom attribute 0.
                vertexShaderCode.InputOperation.AddInput(PinComponent.User1, PinFormat.UInteger);    //< Fill ID.


                // Position transform array (dynamically sized).
                ConstantOperation positionTransformOp = vertexShaderCode.CreateConstant("PositionTransform",
                                                                                        PinFormat.Float4x4, Pin.NotArray, null);

                // Texture transform array (dynamically sized).
                ConstantOperation textureTransformOp = vertexShaderCode.CreateConstant("TextureTransform",
                                                                                       PinFormat.Float4x4, Pin.NotArray, null);

                // We expand the position.
                ExpandOperation expandPos = new ExpandOperation(PinFormat.Floatx4, ExpandType.AddOnesAtW);
                expandPos.BindInputs(vertexShaderCode.InputOperation.PinAsOutput(PinComponent.Position));

                // We transform position by matrix.
                MultiplyOperation multiply = new MultiplyOperation();
                multiply.BindInputs(positionTransformOp.Outputs[0], expandPos.Outputs[0]);
                Pin position = multiply.Outputs[0];

                // We expand texture coordinate.
                ExpandOperation expandTex = new ExpandOperation(PinFormat.Floatx4, ExpandType.AddOnesAtW);
                expandTex.BindInputs(vertexShaderCode.InputOperation.PinAsOutput(PinComponent.TexCoord0));

                // We transform by matrix.
                MultiplyOperation multiply2 = new MultiplyOperation();
                multiply2.BindInputs(textureTransformOp.Outputs[0], expandTex.Outputs[0]);
                Pin texcoord = multiply2.Outputs[0];


                // We register outputs.
                vertexShaderCode.OutputOperation.AddComponentAndLink(PinComponent.Position, position);
                vertexShaderCode.OutputOperation.AddComponentAndLink(PinComponent.TexCoord0, texcoord);
                vertexShaderCode.OutputOperation.AddComponentAndLink(PinComponent.User0,
                                                                     vertexShaderCode.InputOperation.PinAsOutput(PinComponent.User0));
                vertexShaderCode.OutputOperation.AddComponentAndLink(PinComponent.User1,
                                                                     vertexShaderCode.InputOperation.PinAsOutput(PinComponent.User1));
            }
            vertexShaderCode.Immutable = true;

            pixelShaderCode = new ShaderCode(BindingStage.PixelShader);

            {
                // We register inputs.
                pixelShaderCode.InputOperation.AddInput(PinComponent.Position, PinFormat.Floatx4);  //< Position.
                pixelShaderCode.InputOperation.AddInput(PinComponent.TexCoord0, PinFormat.Floatx4); //< Texture coordinate.
                pixelShaderCode.InputOperation.AddInput(PinComponent.User0, PinFormat.Floatx4);     //< Custom attribute 0.
                pixelShaderCode.InputOperation.AddInput(PinComponent.User1, PinFormat.UInteger);    //< Fill ID.

                // We resgister interface constants.
                ConstantOperation interfaceConstant = pixelShaderCode.CreateConstant("Fills", PinFormat.Interface,
                                                                                     Pin.DynamicArray, null);

                // TODO: distance from border must be "evaluated".

                // We  convert position/tex coordinate.
                SwizzleOperation swizzlePos = new SwizzleOperation(SwizzleMask.XY);
                swizzlePos.BindInputs(pixelShaderCode.InputOperation.PinAsOutput(PinComponent.Position));
                Pin position = swizzlePos.Outputs[0];

                SwizzleOperation swizzleTex = new SwizzleOperation(SwizzleMask.XY);
                swizzleTex.BindInputs(pixelShaderCode.InputOperation.PinAsOutput(PinComponent.TexCoord0));
                Pin texcoord = swizzleTex.Outputs[0];

                // We now add the fill operation.
                FillElementOperation fillOperation = new FillElementOperation();
                fillOperation.BindInputs(position, texcoord, pixelShaderCode.InputOperation.PinAsOutput(PinComponent.User0),
                                         pixelShaderCode.InputOperation.PinAsOutput(PinComponent.User1), interfaceConstant.Outputs[0]);

                // The output is colour.
                pixelShaderCode.OutputOperation.AddComponentAndLink(PinComponent.RenderTarget0, fillOperation.Outputs[0]);
            }
            pixelShaderCode.Immutable = true;

            // Depth-stencil state.
            depthStencilState = new DepthStencilState();
            depthStencilState.DepthTestEnabled  = false;
            depthStencilState.DepthWriteEnabled = false;

            // Blend state
            blendState = new BlendState();
            blendState.AlphaBlendDestination = BlendOperand.One;
            blendState.AlphaBlendSource      = BlendOperand.Zero;
            blendState.AlphaBlendOperation   = BlendOperation.Add;

            blendState.BlendDestination = BlendOperand.SrcAlphaInverse;
            blendState.BlendSource      = BlendOperand.SrcAlpha;
            blendState.BlendOperation   = BlendOperation.Add;

            // We enable blending.
            blendState[0] = true;

            // Rasterization state.
            rasterizationState                      = new RasterizationState();
            rasterizationState.FrontFacing          = Facing.CCW;
            rasterizationState.CullMode             = CullMode.None;
            rasterizationState.FillMode             = FillMode.Solid;
            rasterizationState.MultiSamplingEnabled = true; //< May change that in future.


            // We intern all states.
            depthStencilState  = StateManager.Intern(depthStencilState);
            blendState         = StateManager.Intern(blendState);
            rasterizationState = StateManager.Intern(rasterizationState);
        }
Exemplo n.º 24
0
        public unsafe void DAGUsageCases()
        {
            // We first initialize our shader.
            ShaderCode code = new ShaderCode(BindingStage.VertexShader);

            {
                // We write a simple Tranform code:
                code.InputOperation.AddInput(PinComponent.Position, PinFormat.Floatx3);
                Pin positon = code.InputOperation.PinAsOutput(PinComponent.Position);

                // We first need to expand our position to float4 (adding 1 at the end).
                ExpandOperation expand = new ExpandOperation(PinFormat.Floatx4, ExpandType.AddOnesAtW);
                expand.BindInputs(positon);
                Pin expPosition = expand.Outputs[0];

                // We now create constant transform matrix.
                ConstantOperation mvpConstant = code.CreateConstant("MVP", PinFormat.Float4x4);
                Pin MVP = mvpConstant.Outputs[0];

                // We multiply matrix and pin.
                MultiplyOperation mul = new MultiplyOperation();
                mul.BindInputs(MVP, expPosition);
                Pin transPosition = mul.Outputs[0];

                // We just bind transformed position to output.
                code.OutputOperation.AddComponentAndLink(PinComponent.Position, transPosition);
            }

            // Immutate it.
            code.Immutable = true;


            // We create constant buffer manually.
            ConstantBufferLayoutBuilder builder = new ConstantBufferLayoutBuilder();

            builder.AppendElement("MVP", PinFormat.Float4x4, Pin.NotArray);
            ConstantBufferLayout layout = builder.CreateLayout();

            // We now fill the data.
            FixedShaderParameters parameters = code.FixedParameters;

            parameters.AppendLayout(layout);
            if (!parameters.IsDefined)
            {
                throw new Exception();
            }



            using (GraphicsDevice device = InitializeDevice())
            {
                // We create shaders.

                // We have all parameters defined, compile the shader.
                VShader shader = code.Compile(device, parameters) as VShader;

                // Shader expects data in constant buffers.
                TypelessBuffer     tbuffer        = new TypelessBuffer(Usage.Dynamic, BufferUsage.ConstantBuffer, CPUAccess.Write, GraphicsLocality.DeviceOrSystemMemory, 4 * 4 * 4);
                ConstantBufferView constantBuffer = tbuffer.CreateConstantBuffer(layout);

                // We fill the buffer.
                constantBuffer.Map(MapOptions.Write);
                constantBuffer.SetConstant("MVP", new Math.Matrix.Matrix4x4f(1, 0, 0, 0,
                                                                             0, 1, 0, 0,
                                                                             0, 0, 1, 0,
                                                                             -0.5f, -0.5f, 0, 1));
                constantBuffer.UnMap();

                PShader pshader;
                VShader vshader = shader;
                using (ShaderCompiler compiler = device.CreateShaderCompiler())
                {
                    // And pixel shader.
                    compiler.Begin(BindingStage.PixelShader);
                    ShaderCompiler.Operand colour = compiler.CreateFixed(PinFormat.Floatx4, Pin.NotArray, new Vector4f(1, 0, 0, 1));
                    compiler.Output(colour, PinComponent.RenderTarget0);
                    pshader = compiler.End(null) as PShader;
                }

                // We create triangles.
                Geometry       geometry = new Geometry();
                TypelessBuffer buffer   = new TypelessBuffer(Usage.Static,
                                                             BufferUsage.VertexBuffer, CPUAccess.None, GraphicsLocality.DeviceOrSystemMemory, 4 * 4 * 3);

                byte[] d = buffer.Map(MapOptions.Read);
                fixed(byte *p = d)
                {
                    float *data = (float *)p;

                    // Vertex 0:
                    data[0] = -0.5f; data[1] = -0.5f; data[2] = 0.0f; data[3] = 1.0f;

                    // Vertex 1:
                    data[4] = 0.5f; data[5] = -0.5f; data[6] = 0.0f; data[7] = 1.0f;

                    // Vertex 2:
                    data[8] = 0.0f; data[9] = 0.5f; data[10] = 0.0f; data[11] = 1.0f;
                }

                buffer.UnMap();


                // Create vertex buffer and view.
                VertexBufferView vbuffer = buffer.CreateVertexBuffer(VertexFormat.Parse("P.Fx4"));

                // We construct geometry.
                geometry[0]       = vbuffer;
                geometry.Topology = Topology.Triangle;

                // Blend state.
                BlendState blendState = new BlendState();
                blendState[0] = false;

                blendState = StateManager.Intern(blendState);

                RasterizationState rastState = new RasterizationState();
                rastState.CullMode = CullMode.None;
                rastState.FillMode = FillMode.Solid;

                rastState = StateManager.Intern(rastState);

                DepthStencilState depthState = new DepthStencilState();
                depthState.DepthTestEnabled  = false;
                depthState.DepthWriteEnabled = false;

                depthState = StateManager.Intern(depthState);

                // Enter rendering loop.
                bool isClosed = false;
                window.Closed += delegate(Window w)
                {
                    isClosed = true;
                };

                for (uint i = 0; i < 1000; i++)
                {
                    window.DoEvents();

                    if (!isClosed)
                    {
                        SwapChain chain = device.SwapChain;

                        device.Enter();
                        try
                        {
                            // We just clear.
                            device.Clear(chain, Colour.Black);

                            // Set blend/rast.
                            device.SetBlendState(blendState, Colour.White, 0xFFFFFFFF);
                            device.RasterizationState = rastState;
                            device.SetDepthStencilState(depthState, 0);

                            // Sets states.
                            device.SetVertexShader(vshader, geometry, null, null, new ConstantBufferView[] { constantBuffer });
                            device.SetPixelShader(pshader, null, null, null, new RenderTargetView[] { chain }, null);

                            device.Viewport = new Region2i(0, 0, (int)chain.Width, (int)chain.Height);

                            // Render.
                            device.Draw(0, 3);
                        }
                        finally
                        {
                            device.Exit();
                        }

                        chain.Present();
                        //Thread.Sleep(10);

                        Console.WriteLine(device.DevicePerformance.CurrentFPS);
                    }
                }


                // Dispose all.
                vshader.Dispose();
                pshader.Dispose();
                geometry.Dispose();
                vbuffer.Dispose();
                buffer.Dispose();
            }
        }
Exemplo n.º 25
0
        public override HlslTreeNode Reduce()
        {
            var addend1   = Addend1.Reduce();
            var addend2   = Addend2.Reduce();
            var constant1 = addend1 as ConstantNode;
            var constant2 = addend2 as ConstantNode;

            if (constant1 != null)
            {
                float value1 = constant1.Value;
                if (value1 == 0)
                {
                    Replace(addend2);
                    return(addend2);
                }
                if (constant2 != null)
                {
                    return(new ConstantNode(value1 + constant2.Value));
                }
            }

            if (constant2 != null)
            {
                float value2 = constant2.Value;
                if (value2 == 0)
                {
                    return(addend1);
                }
                if (value2 < 0)
                {
                    var sub = new SubtractOperation(addend1, new ConstantNode(-value2));
                    Replace(sub);
                    return(sub);
                }
            }

            if (addend1 == addend2)
            {
                var mul = new MultiplyOperation(new ConstantNode(2), addend1);
                Replace(mul);
                return(mul);
            }

            if (addend1 is NegateOperation negate1 && addend2 is NegateOperation == false)
            {
                var sub = new SubtractOperation(addend2, negate1.Value);
                Replace(sub);
                return(sub);
            }

            if (addend1 is NegateOperation == false && addend2 is NegateOperation negate2)
            {
                var sub = new SubtractOperation(addend1, negate2.Value);
                Replace(sub);
                return(sub);
            }

            Inputs[0] = addend1;
            Inputs[1] = addend2;
            return(this);
        }
Exemplo n.º 26
0
        public void Multiply()
        {
            var result = new MultiplyOperation().Perform(10, 5);

            Assert.AreEqual(50, result);
        }
Exemplo n.º 27
0
 protected VisitResult VisitMultiply(MultiplyOperation operation)
 {
     return(VisitBinary(Expression.Multiply, operation));
 }
Exemplo n.º 28
0
        public Factorial()
        {
            var ifBlockScope = Scope.CreateAndBuild(new List <IsStatic> {
            });
            var elseBlock    = Scope.CreateAndBuild(new List <IsStatic> {
            });

            var inputKey = new NameKey("input");
            var input    = MemberDefinition.CreateAndBuild(inputKey, new NumberType(), Access.ReadWrite);

            var facKey = new NameKey("fac");
            var fac    = MemberDefinition.CreateAndBuild(facKey, MethodType.CreateAndBuild(new NumberType(), new NumberType()), Access.ReadWrite);

            var methodScope = Scope.CreateAndBuild(new List <IsStatic> {
                new IsStatic(input, false)
            });

            RootScope =
                Model.Instantiated.RootScope.CreateAndBuild(
                    Scope.CreateAndBuild(
                        new List <IsStatic> {
                new IsStatic(MemberDefinition.CreateAndBuild(facKey, MethodType.CreateAndBuild(
                                                                 new NumberType(),
                                                                 new NumberType()), Access.ReadWrite), false)
            }),
                    new [] {
                AssignOperation.CreateAndBuild(
                    MethodDefinition.CreateAndBuild(
                        new NumberType(),
                        input,
                        methodScope,
                        new ICodeElement[] {
                    ElseOperation.CreateAndBuild(
                        IfOperation.CreateAndBuild(
                            LessThanOperation.CreateAndBuild(
                                MemberReference.CreateAndBuild(input),
                                ConstantNumber.CreateAndBuild(2)),
                            BlockDefinition.CreateAndBuild(
                                ifBlockScope,
                                new ICodeElement[] {
                        ReturnOperation.CreateAndBuild(
                            ConstantNumber.CreateAndBuild(1))
                    },
                                Array.Empty <ICodeElement>())),
                        BlockDefinition.CreateAndBuild(
                            elseBlock,
                            new ICodeElement[] {
                        ReturnOperation.CreateAndBuild(
                            MultiplyOperation.CreateAndBuild(
                                NextCallOperation.CreateAndBuild(
                                    SubtractOperation.CreateAndBuild(
                                        MemberReference.CreateAndBuild(input),
                                        ConstantNumber.CreateAndBuild(1)),
                                    MemberReference.CreateAndBuild(fac)),
                                MemberReference.CreateAndBuild(input)))
                    },
                            Array.Empty <ICodeElement>()))
                },
                        Array.Empty <ICodeElement>()),
                    MemberReference.CreateAndBuild(fac)
                    )
            },
                    EntryPointDefinition.CreateAndBuild(new EmptyType(), MemberDefinition.CreateAndBuild(new NameKey("input"), new NumberType(), Access.ReadWrite), Scope.CreateAndBuild(Array.Empty <IsStatic>()), Array.Empty <ICodeElement>(), Array.Empty <ICodeElement>())
                    );
        }