コード例 #1
0
        public void Render(Camera camera, params Mesh[] meshes)
        {
            var viewMatrix       = Matrix.LookAtLH(camera.Position, camera.Target, camera.Up);
            var projectionMatrix = Matrix.PerspectiveFovLH(0.78f, (float)width / height, 0.01f, 1.0f);

            foreach (var mesh in meshes)
            {
                var worldMatrix = Matrix.RotationYawPitchRoll(mesh.Rotation.Y, mesh.Rotation.X, mesh.Rotation.Z) *
                                  Matrix.Translation(mesh.Position);

                var worldView       = worldMatrix * viewMatrix;
                var transformMatrix = worldView * projectionMatrix;

                Parallel.For(0, mesh.Faces.Length, faceIndex =>
                {
                    var face = mesh.Faces[faceIndex];

                    // Face-back culling
                    //var transformedNormal = Vector3.TransformNormal(face.Normal, worldView);

                    //if (transformedNormal.Z >= 0)
                    //{
                    //    return;
                    //}

                    // Render this face
                    var vertexA = mesh.Vertices[face.A];
                    var vertexB = mesh.Vertices[face.B];
                    var vertexC = mesh.Vertices[face.C];

                    var pixelA = Project(vertexA, transformMatrix, worldMatrix);
                    var pixelB = Project(vertexB, transformMatrix, worldMatrix);
                    var pixelC = Project(vertexC, transformMatrix, worldMatrix);

                    //var color = 0.25f + (faceIndex % mesh.Faces.Length) * 0.75f / mesh.Faces.Length;
                    var color = 1.0f;


                    if (Wireframe)
                    {
                        Algorithm.Line(pixelA.Coordinates.X, pixelA.Coordinates.Y, pixelB.Coordinates.X,
                                       pixelB.Coordinates.Y, Color.White, DrawPoint);
                        Algorithm.Line(pixelB.Coordinates.X, pixelB.Coordinates.Y, pixelC.Coordinates.X,
                                       pixelC.Coordinates.Y, Color.White, DrawPoint);
                        Algorithm.Line(pixelC.Coordinates.X, pixelC.Coordinates.Y, pixelA.Coordinates.X,
                                       pixelA.Coordinates.Y, Color.White, DrawPoint);
                    }
                    else
                    {
                        DrawTriangle(pixelA, pixelB, pixelC, new Color4(color, color, color, 1), mesh.Texture);
                    }
                });
            }
        }
コード例 #2
0
        void SetSceneConstants()
        {
            FreeLook freelook    = Demo.FreeLook;
            Vector3  up          = MathHelper.Convert(freelook.Up);
            Vector3  eye         = MathHelper.Convert(freelook.Eye);
            Vector4  eyePosition = new Vector4(eye, 1);

            sceneConstants.View = Matrix.LookAtLH(eye, MathHelper.Convert(freelook.Target), up);
            Matrix.PerspectiveFovLH(FieldOfView, AspectRatio, _nearPlane, FarPlane, out sceneConstants.Projection);
            Matrix.Invert(ref sceneConstants.View, out sceneConstants.ViewInverse);

            Texture2DDescription depthBuffer = lightDepthTexture.Description;
            Vector3 lightPosition            = sunLightDirection * -60;
            Matrix  lightView = Matrix.LookAtLH(lightPosition, Vector3.Zero, up);
            //Matrix lightProjection = Matrix.OrthoLH(depthBuffer.Width / 8.0f, depthBuffer.Height / 8.0f, _nearPlane, FarPlane);
            Matrix lightProjection = Matrix.PerspectiveFovLH(FieldOfView, (float)depthBuffer.Width / (float)depthBuffer.Height, _nearPlane, FarPlane);

            sceneConstants.LightViewProjection = lightView * lightProjection;

            DataStream data;

            _immediateContext.MapSubresource(sceneConstantsBuffer, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out data);
            Marshal.StructureToPtr(sceneConstants, data.DataPointer, false);
            _immediateContext.UnmapSubresource(sceneConstantsBuffer, 0);
            data.Dispose();

            sunLightDirectionVar.Set(new Vector4(sunLightDirection, 1));

            Matrix overlayMatrix = Matrix.Scaling(info.Width / _width, info.Height / _height, 1.0f);

            overlayMatrix *= Matrix.Translation(-(_width - info.Width) / _width, (_height - info.Height) / _height, 0.0f);
            overlayViewProjectionVar.SetMatrix(overlayMatrix);


            lightProjectionVar.SetMatrixTranspose(ref sceneConstants.Projection);
            lightViewVar.SetMatrixTranspose(ref sceneConstants.View);
            lightViewInverseVar.SetMatrix(ref sceneConstants.ViewInverse);
            lightViewportWidthVar.Set(_width);
            lightViewportHeightVar.Set(_height);
            lightEyePositionVar.Set(ref eyePosition);

            float   tanHalfFovY    = (float)Math.Tan(FieldOfView * 0.5f);
            float   tanHalfFovX    = tanHalfFovY * AspectRatio;
            float   projectionA    = FarPlane / (FarPlane - _nearPlane);
            float   projectionB    = -projectionA * _nearPlane;
            Vector4 viewParameters = new Vector4(tanHalfFovX, tanHalfFovY, projectionA, projectionB);

            lightViewParametersVar.Set(ref viewParameters);


            viewportWidthVar.Set(_width);
            viewportHeightVar.Set(_height);
            viewParametersVar.Set(ref viewParameters);
        }
コード例 #3
0
ファイル: Mesh.cs プロジェクト: 07101994/aiv-fast2d
        // here we update translations, scaling and rotations
        protected virtual void ApplyMatrix()
        {
            if (this.noMatrix)
            {
                return;
            }
#if __SHARPDX__
            Matrix4 m = Matrix4.Translation(-this.pivot.X, -this.pivot.Y, 0) *
                        Matrix4.Scaling(this.scale.X, this.scale.Y, 1) *
                        Matrix4.RotationZ(this.rotation) *
                        Matrix4.Translation(this.position.X, this.position.Y, 0);
#else
            // WARNING !!! OpenTK uses row-major while OpenGL uses column-major
            Matrix4 m =
                Matrix4.CreateTranslation(-this.pivot.X, -this.pivot.Y, 0) *
#if !__MOBILE__
                Matrix4.CreateScale(this.scale.X, this.scale.Y, 1) *
#else
                Matrix4.Scale(this.scale.X, this.scale.Y, 1) *
#endif
                Matrix4.CreateRotationZ(this.rotation) *
                // here we do not re-add the pivot, so translation is pivot based too
                Matrix4.CreateTranslation(this.position.X, this.position.Y, 0);
#endif

            Matrix4 projectionMatrix = Window.Current.ProjectionMatrix;

            if (this.Camera != null)
            {
                m *= this.Camera.Matrix();
                if (this.Camera.HasProjection)
                {
                    projectionMatrix = this.Camera.ProjectionMatrix();
                }
            }
            else if (Window.Current.CurrentCamera != null)
            {
                m *= Window.Current.CurrentCamera.Matrix();
                if (Window.Current.CurrentCamera.HasProjection)
                {
                    projectionMatrix = Window.Current.CurrentCamera.ProjectionMatrix();
                }
            }

            Matrix4 mvp = m * projectionMatrix;
#if __SHARPDX__
            // transpose the matrix for DirectX
            mvp.Transpose();
#endif

            // pass the matrix to the shader
            this.shader.SetUniform("mvp", mvp);
        }
コード例 #4
0
        void SetSceneConstants()
        {
            FreeLook freelook = Demo.Freelook;
            Vector3  up       = MathHelper.Convert(freelook.Up);

            sceneConstants.View        = Matrix.LookAtLH(MathHelper.Convert(freelook.Eye), MathHelper.Convert(freelook.Target), up);
            sceneConstants.Projection  = Matrix.PerspectiveFovLH(FieldOfView, AspectRatio, _nearPlane, FarPlane);
            sceneConstants.ViewInverse = Matrix.Invert(sceneConstants.View);

            Vector3 light = new Vector3(20, 30, 10);
            Texture2DDescription depthBuffer = lightDepthTexture.Description;
            Matrix lightView       = Matrix.LookAtLH(light, Vector3.Zero, up);
            Matrix lightProjection = Matrix.OrthoLH(depthBuffer.Width / 8.0f, depthBuffer.Height / 8.0f, _nearPlane, FarPlane);

            sceneConstants.LightViewProjection = lightView * lightProjection;

            DataStream data;

            _immediateContext.MapSubresource(sceneConstantsBuffer, MapMode.WriteDiscard, SharpDX.Direct3D11.MapFlags.None, out data);
            Marshal.StructureToPtr(sceneConstants, data.DataPointer, false);
            _immediateContext.UnmapSubresource(sceneConstantsBuffer, 0);
            data.Dispose();

            inverseProjectionVar.SetMatrix(Matrix.Invert(sceneConstants.Projection));
            inverseViewVar.SetMatrix(sceneConstants.ViewInverse);
            lightInverseViewProjectionVar.SetMatrix(Matrix.Invert(sceneConstants.LightViewProjection));
            lightPositionVar.Set(new Vector4(light, 1));
            eyePositionVar.Set(new Vector4(MathHelper.Convert(freelook.Eye), 1));
            eyeZAxisVar.Set(new Vector4(Vector3.Normalize(MathHelper.Convert(freelook.Target - freelook.Eye)), 1));

            float tanHalfFOVY = (float)Math.Tan(FieldOfView * 0.5f);

            tanHalfFOVXVar.Set(tanHalfFOVY * AspectRatio);
            tanHalfFOVYVar.Set(tanHalfFOVY);
            float projectionA = FarPlane / (FarPlane - _nearPlane);
            float projectionB = -projectionA * _nearPlane;

            projectionAVar.Set(projectionA);
            projectionBVar.Set(projectionB);

            Matrix overlayMatrix = Matrix.Scaling(info.Width / _width, info.Height / _height, 1.0f);

            overlayMatrix *= Matrix.Translation(-(_width - info.Width) / _width, (_height - info.Height) / _height, 0.0f);
            overlayViewProjectionVar.SetMatrix(overlayMatrix);
        }
コード例 #5
0
ファイル: SharpDXGraphics.cs プロジェクト: raiker/BulletSharp
        void SetSceneConstants()
        {
            FreeLook freelook = Demo.Freelook;
            Vector3  up       = MathHelper.Convert(freelook.Up);

            sceneConstants.View        = Matrix.LookAtLH(MathHelper.Convert(freelook.Eye), MathHelper.Convert(freelook.Target), up);
            sceneConstants.Projection  = Matrix.PerspectiveFovLH(FieldOfView, AspectRatio, _nearPlane, FarPlane);
            sceneConstants.ViewInverse = Matrix.Invert(sceneConstants.View);

            Vector3 light = new Vector3(20, 30, 10);
            Texture2DDescription depthBuffer = lightDepthTexture.Description;
            Matrix lightView       = Matrix.LookAtLH(light, Vector3.Zero, up);
            Matrix lightProjection = Matrix.OrthoLH(depthBuffer.Width / 8.0f, depthBuffer.Height / 8.0f, _nearPlane, FarPlane);

            sceneConstants.LightViewProjection = lightView * lightProjection;

            using (var data = sceneConstantsBuffer.Map(MapMode.WriteDiscard))
            {
                Marshal.StructureToPtr(sceneConstants, data.DataPointer, false);
                sceneConstantsBuffer.Unmap();
            }

            effect2.GetVariableByName("InverseProjection").AsMatrix().SetMatrix(Matrix.Invert(sceneConstants.Projection));
            effect2.GetVariableByName("InverseView").AsMatrix().SetMatrix(sceneConstants.ViewInverse);
            effect2.GetVariableByName("LightInverseViewProjection").AsMatrix().SetMatrix(Matrix.Invert(sceneConstants.LightViewProjection));
            effect2.GetVariableByName("LightPosition").AsVector().Set(new Vector4(light, 1));
            effect2.GetVariableByName("EyePosition").AsVector().Set(new Vector4(MathHelper.Convert(freelook.Eye), 1));
            effect2.GetVariableByName("EyeZAxis").AsVector().Set(new Vector4(Vector3.Normalize(MathHelper.Convert(freelook.Target - freelook.Eye)), 1));

            float tanHalfFOVY = (float)Math.Tan(FieldOfView * 0.5f);

            effect2.GetVariableByName("TanHalfFOVX").AsScalar().Set(tanHalfFOVY * AspectRatio);
            effect2.GetVariableByName("TanHalfFOVY").AsScalar().Set(tanHalfFOVY);
            float projectionA = FarPlane / (FarPlane - _nearPlane);
            float projectionB = -projectionA * _nearPlane;

            effect2.GetVariableByName("ProjectionA").AsScalar().Set(projectionA);
            effect2.GetVariableByName("ProjectionB").AsScalar().Set(projectionB);

            Matrix overlayMatrix = Matrix.Scaling(2 * info.Width / _width, 2 * info.Height / _height, 1.0f);

            overlayMatrix *= Matrix.Translation(-(_width - info.Width) / _width, (_height - info.Height) / _height, 0.0f);
            effect2.GetVariableByName("OverlayViewProjection").AsMatrix().SetMatrix(overlayMatrix);
        }
コード例 #6
0
ファイル: MainWindow.xaml.cs プロジェクト: mkmkmk/OnePlanet
        private void Draw()
        {
            _manager.Clear(Color.Black);

            var context = _manager.Device.ImmediateContext;

            var eyePosition = Vector3.Transform(new Vector3(0, (float)_distSum / 3f, 0), _viewRotation);

            _view = Matrix.LookAtRH(eyePosition, new Vector3(0, 0, 0), Vector3.UnitZ);

            var time = (float)_clock.Elapsed.TotalSeconds;

            float dt        = _timeDelta;
            int   stepsTodo = (int)Math.Floor((time - _prevGameSec) / dt);

            while (stepsTodo-- > 0)
            {
                float   r   = Math.Max(0.05f, _position.Length());
                Vector3 acc = _position * (-1f / r / r / r);
                _velocity = _velocity + acc * dt;
                _position = _position + _velocity * dt;
            }

            SetWorld(context, Matrix.Translation(_position * _scale) * Matrix.Translation(0, 0, 3));
            _sphere.Draw();

            SetWorld(context, Matrix.Translation(0f, 0f, -4f));
            _plane.Draw();

            SetWorld(context, Matrix.Translation(0, 0, 3));
            _sun.Draw();

            _manager.Present();

            _prevGameSec = time;
        }
コード例 #7
0
        /// <summary>
        ///
        /// </summary>
        public InteractionHandle3D()
        {
            this.Material = PhongMaterials.Orange;
            //selectionColor.EmissiveColor = Color.Blue;
            //selectionColor.SpecularColor = Color.Black;
            //selectionColor.ReflectiveColor = Color.Black;

            for (int i = 0; i < 4; i++)
            {
                var translate = Matrix3DExtensions.Translate3D(positions[i].ToVector3D());
                this.cornerHandles[i] = new DraggableGeometryModel3D()
                {
                    DragZ      = false,
                    Visibility = Visibility.Visible,
                    Material   = this.Material,
                    Geometry   = NodeGeometry,
                    Transform  = new MatrixTransform3D(translate),
                };
                this.cornerHandles[i].MouseMove3D += OnNodeMouse3DMove;
                this.cornerHandles[i].MouseUp3D   += OnNodeMouse3DUp;
                this.cornerHandles[i].MouseDown3D += OnNodeMouse3DDown;

                this.edgeHandles[i] = new MeshGeometryModel3D()
                {
                    Geometry   = (i % 2 == 0) ? EdgeHGeometry : EdgeVGeometry,
                    Material   = this.Material,
                    Visibility = Visibility.Visible,
                    Transform  = new MatrixTransform3D(translate),
                };
                this.edgeHandles[i].MouseMove3D += OnEdgeMouse3DMove;
                this.edgeHandles[i].MouseUp3D   += OnEdgeMouse3DUp;
                this.edgeHandles[i].MouseDown3D += OnEdgeMouse3DDown;


                translate = Matrix3DExtensions.Translate3D(0.5 * (positions[i] + positions[(i + 1) % 4]).ToVector3D());
                this.midpointHandles[i] = new DraggableGeometryModel3D()
                {
                    DragZ     = false,
                    DragX     = (i % 2 == 1),
                    DragY     = (i % 2 == 0),
                    Material  = this.Material,
                    Geometry  = BoxGeometry,
                    Transform = new MatrixTransform3D(translate),
                };
                this.midpointHandles[i].MouseMove3D += OnNodeMouse3DMove;
                this.midpointHandles[i].MouseUp3D   += OnNodeMouse3DUp;
                this.midpointHandles[i].MouseDown3D += OnNodeMouse3DDown;

                this.Children.Add(cornerHandles[i]);
                this.Children.Add(edgeHandles[i]);
                this.Children.Add(midpointHandles[i]);
            }

            // 3 --- 2
            // |     |
            // 0 --- 1
            var m0 = Matrix.Scaling(+2, 1, 1) * Matrix.Translation(positions[0]);

            this.edgeHandles[0].Transform = new MatrixTransform3D(m0.ToMatrix3D());
            var m2 = Matrix.Scaling(+2, 1, 1) * Matrix.Translation(positions[3]);

            this.edgeHandles[2].Transform = new MatrixTransform3D(m2.ToMatrix3D());

            var m1 = Matrix.Scaling(1, +2, 1) * Matrix.Translation(positions[1]);

            this.edgeHandles[1].Transform = new MatrixTransform3D(m1.ToMatrix3D());
            var m3 = Matrix.Scaling(1, +2, 1) * Matrix.Translation(positions[0]);

            this.edgeHandles[3].Transform = new MatrixTransform3D(m3.ToMatrix3D());

            this.dragTransform = new MatrixTransform3D(this.Transform.Value);
        }
コード例 #8
0
        private void UpdateTransforms(object sender)
        {
            var cornerTrafos = this.cornerHandles.Select(x => (x.Transform as MatrixTransform3D)).ToArray();
            var cornerMatrix = cornerTrafos.Select(x => (x).Value).ToArray();

            this.positions = cornerMatrix.Select(x => x.ToMatrix().TranslationVector).ToArray();

            BoundingBox bb;

            if (sender == cornerHandles[0] || sender == cornerHandles[2])
            {
                Application.Current.MainWindow.Cursor = Cursors.SizeNESW;
                bb = BoundingBox.FromPoints(new[] { positions[0], positions[2] });
            }
            else if (sender == cornerHandles[1] || sender == cornerHandles[3])
            {
                Application.Current.MainWindow.Cursor = Cursors.SizeNWSE;
                bb = BoundingBox.FromPoints(new[] { positions[1], positions[3] });
            }
            else
            {
                if (sender == midpointHandles[0] || sender == midpointHandles[2])
                {
                    Application.Current.MainWindow.Cursor = Cursors.SizeNS;
                }
                else
                {
                    Application.Current.MainWindow.Cursor = Cursors.SizeWE;
                }
                positions = this.midpointHandles.Select(x => x.Transform.Value.ToMatrix().TranslationVector).ToArray();
                bb        = BoundingBox.FromPoints(positions);
            }

            // 3 --- 2
            // |     |
            // 0 --- 1
            positions[0].X = bb.Minimum.X;
            positions[1].X = bb.Maximum.X;
            positions[2].X = bb.Maximum.X;
            positions[3].X = bb.Minimum.X;

            positions[0].Y = bb.Minimum.Y;
            positions[1].Y = bb.Minimum.Y;
            positions[2].Y = bb.Maximum.Y;
            positions[3].Y = bb.Maximum.Y;

            for (int i = 0; i < 4; i++)
            {
                if (sender != cornerHandles[i])
                {
                    cornerTrafos[i].Matrix = Matrix3DExtensions.Translate3D(positions[i].ToVector3D());
                }

                var m = Matrix3DExtensions.Translate3D(0.5 * (positions[i] + positions[(i + 1) % 4]).ToVector3D());
                ((MatrixTransform3D)this.midpointHandles[i].Transform).Matrix = m;
            }

            // 3 --- 2
            // |     |
            // 0 --- 1
            var m0 = Matrix.Scaling(positions[1].X - positions[0].X, 1, 1) * Matrix.Translation(positions[0]);

            ((MatrixTransform3D)this.edgeHandles[0].Transform).Matrix = (m0.ToMatrix3D());
            var m2 = Matrix.Scaling(positions[1].X - positions[0].X, 1, 1) * Matrix.Translation(positions[3]);

            ((MatrixTransform3D)this.edgeHandles[2].Transform).Matrix = (m2.ToMatrix3D());

            var m1 = Matrix.Scaling(1, positions[2].Y - positions[1].Y, 1) * Matrix.Translation(positions[1]);

            ((MatrixTransform3D)this.edgeHandles[1].Transform).Matrix = (m1.ToMatrix3D());
            var m3 = Matrix.Scaling(1, positions[2].Y - positions[1].Y, 1) * Matrix.Translation(positions[0]);

            ((MatrixTransform3D)this.edgeHandles[3].Transform).Matrix = (m3.ToMatrix3D());
        }
コード例 #9
0
        public void Update()
        {
            //Calculate deltaTime
            var passedTime = (float)(DateTime.Now - _prevFrameTime).Milliseconds / 1000;

            //Determine direction of travel
            var moveDirection = Vector2.Zero;

            moveDirection.X = Keyboard.IsKeyDown(Key.D) ? 1.0f : 0.0f;
            if (moveDirection.X.Equals(0.0f))
            {
                moveDirection.X = -(Keyboard.IsKeyDown(Key.A) ? 1.0f : 0.0f);
            }

            moveDirection.Y = Keyboard.IsKeyDown(Key.W) ? 1.0f : 0.0f;
            if (moveDirection.Y.Equals(0.0f))
            {
                moveDirection.Y = -(Keyboard.IsKeyDown(Key.S) ? 1.0f : 0.0f);
            }

            var currPos = Mouse.GetPosition(Application.Current.MainWindow);

            //Mouse Rotation
            var mouseLook = Vector2.Zero;

            if (Mouse.RightButton == MouseButtonState.Pressed)
            {
                var mouseMovement = currPos - _prevMousePos;

                //Debug.Log(LogLevel.Info,mouseMovement.ToString());
                //mouseLook.X = (float) (mouseMovement.X/Math.Abs(mouseMovement.X));
                //mouseLook.Y = (float)(mouseMovement.Y / Math.Abs(mouseMovement.Y));

                mouseLook.X = (float)(mouseMovement.X);
                mouseLook.Y = (float)(mouseMovement.Y);
            }

            //Calculate rotation
            _totalYaw   += mouseLook.X * ROTATION_SPEED * passedTime;
            _totalPitch += mouseLook.Y * ROTATION_SPEED * passedTime;
            Rotating     = Matrix.RotationYawPitchRoll(_totalYaw, _totalPitch, 0);

            Translation = Matrix.Translation(EyePosition);
            Scale       = Matrix.Scaling(1.0f);

            //Update Forward,Right and up based on the current rotation of the Camera
            Forward     = Vector3.TransformCoordinate(Vector3.ForwardLH, Rotating);
            Right       = Vector3.TransformCoordinate(Vector3.Right, Rotating);
            UpDirection = Vector3.Cross(Forward, Right);

            EyePosition += moveDirection.X * Right * MOVE_SPEED * passedTime;
            EyePosition += moveDirection.Y * Forward * MOVE_SPEED * passedTime;


            var viewDirection = (Vector3)Vector3.Transform(Vector3.ForwardLH, Rotating);

            viewDirection.Normalize();
            TargetPosition = EyePosition + viewDirection;

            _prevFrameTime = DateTime.Now;
            _prevMousePos  = currPos;

            //Debug.Log(LogLevel.Info,EyePosition.ToString());
        }
コード例 #10
0
        public virtual void Render(TargetBase target)
        {
            if (!Show)
            {
                return;
            }

            var context2D = target.DeviceManager.ContextDirect2D;

            context2D.BeginDraw();

            if (EnableClear)
            {
                context2D.Clear(Color.Black);
            }

            var sizeX         = (float)target.RenderTargetBounds.Width;
            var sizeY         = (float)target.RenderTargetBounds.Height;
            var globalScaling = Matrix.Scaling(Math.Min(sizeX, sizeY));

            var centerX = (float)(target.RenderTargetBounds.X + sizeX / 2.0f);
            var centerY = (float)(target.RenderTargetBounds.Y + sizeY / 2.0f);

            if (textFormat == null)
            {
                // Initialize a TextFormat
                textFormat = new TextFormat(target.DeviceManager.FactoryDirectWrite, "Calibri", 96 * sizeX / 1920)
                {
                    TextAlignment = TextAlignment.Center, ParagraphAlignment = ParagraphAlignment.Center
                };
            }

            if (pathGeometry1 == null)
            {
                var sizeShape = sizeX / 4.0f;

                // Creates a random geometry inside a circle
                pathGeometry1 = new PathGeometry1(target.DeviceManager.FactoryDirect2D);
                var pathSink      = pathGeometry1.Open();
                var startingPoint = new Vector2(sizeShape * 0.5f, 0.0f);
                pathSink.BeginFigure(startingPoint, FigureBegin.Hollow);
                for (int i = 0; i < 128; i++)
                {
                    float angle = (float)i / 128.0f * (float)Math.PI * 2.0f;
                    float R     = (float)(Math.Cos(angle) * 0.1f + 0.4f);
                    R *= sizeShape;
                    Vector2 point1 = new Vector2(R * (float)Math.Cos(angle), R * (float)Math.Sin(angle));

                    if ((i & 1) > 0)
                    {
                        R      = (float)(Math.Sin(angle * 6.0f) * 0.1f + 0.9f);
                        R     *= sizeShape;
                        point1 = new Vector2(R * (float)Math.Cos(angle + Math.PI / 12), R * (float)Math.Sin(angle + Math.PI / 12));
                    }
                    pathSink.AddLine(point1);
                }
                pathSink.EndFigure(FigureEnd.Open);
                pathSink.Close();
            }

            context2D.TextAntialiasMode = TextAntialiasMode.Grayscale;
            float t = clock.ElapsedMilliseconds / 1000.0f;

            context2D.Transform = Matrix.RotationZ((float)(Math.Cos(t * 2.0f * Math.PI * 0.5f))) * Matrix.Translation(centerX, centerY, 0);

            context2D.DrawText("SharpDX\nDirect2D1\nDirectWrite", textFormat, new RectangleF(-sizeX / 2.0f, -sizeY / 2.0f, +sizeX / 2.0f, sizeY / 2.0f), sceneColorBrush);

            float scaling = (float)(Math.Cos(t * 2.0 * Math.PI * 0.25) * 0.5f + 0.5f) * 0.5f + 0.5f;

            context2D.Transform = Matrix.Scaling(scaling) * Matrix.RotationZ(t * 1.5f) * Matrix.Translation(centerX, centerY, 0);

            context2D.DrawGeometry(pathGeometry1, sceneColorBrush, 2.0f);

            context2D.EndDraw();
        }
コード例 #11
0
        //public Camera Camera2 { private set; get; }

        public MainViewModel()
        {
            EffectsManager = new DefaultEffectsManager();
            Title          = "Shadow Map Demo";
            SubTitle       = "WPF & SharpDX";

            // setup lighting
            this.AmbientLightColor     = new Color4(0.1f, 0.1f, 0.1f, 1.0f);
            this.DirectionalLightColor = Media.Colors.White;
            //this.DirectionalLightDirection = new Vector3(-1, -1, -1);
            // this.LightDirectionTransform = CreateAnimatedTransform(-DirectionalLightDirection.ToVector3D(), new Vector3D(0, 1, -1), 24);
            this.ShadowMapResolution = new Size(2048, 2048);

            // camera setup
            this.Camera = new PerspectiveCamera
            {
                Position      = new Point3D(0, 1, 1),
                LookDirection = new Vector3D(0, -1, -1),
                UpDirection   = new Vector3D(0, 1, 0)
            };

            Camera1 = new PerspectiveCamera
            {
                Position          = new Point3D(0, 5, 0),
                LookDirection     = new Vector3D(0, -1, 0),
                UpDirection       = new Vector3D(1, 0, 0),
                FarPlaneDistance  = 5000,
                NearPlaneDistance = 1,
                FieldOfView       = 45
            };

            // scene model3d
            var b1 = new MeshBuilder();

            b1.AddSphere(new Vector3(0, 0, 0), 0.5);
            b1.AddBox(new Vector3(0, 0, 0), 1, 0.25, 2, BoxFaces.All);
            Model     = b1.ToMeshGeometry3D();
            Instances = new[] { Matrix.Translation(0, 0, -1.5f), Matrix.Translation(0, 0, 1.5f) };

            var b2 = new MeshBuilder();

            b2.AddBox(new Vector3(0, 0, 0), 10, 0, 10, BoxFaces.PositiveY);
            Plane          = b2.ToMeshGeometry3D();
            PlaneTransform = new Media3D.TranslateTransform3D(-0, -2, -0);
            GrayMaterial   = PhongMaterials.Indigo;

            // lines model3d
            Lines = LineBuilder.GenerateBoundingBox(Model);
            //this.PropertyChanged += MainViewModel_PropertyChanged;
            // model trafos
            Model1Transform = new Media3D.TranslateTransform3D(0, 0, 0);
            Model2Transform = new Media3D.TranslateTransform3D(-2, 0, 0);
            Model3Transform = new Media3D.TranslateTransform3D(+2, 0, 0);

            // model materials
            RedMaterial   = PhongMaterials.Glass;
            GreenMaterial = PhongMaterials.Green;
            BlueMaterial  = PhongMaterials.Blue;
            GrayMaterial.RenderShadowMap = RedMaterial.RenderShadowMap = GreenMaterial.RenderShadowMap = BlueMaterial.RenderShadowMap = true;
            //var b3 = new MeshBuilder();
            //b3.AddBox(new Vector3(), 0.3f, 0.3f, 0.3f, BoxFaces.All);
            //b3.AddCone(new Vector3(0, 0.3f, 0), new Vector3(0, 0f, 0), 0.2f, true, 24);
            //LightCameraModel = b3.ToMesh();
            //LightCameraTransform.Children.Add(new Media3D.RotateTransform3D(new Media3D.AxisAngleRotation3D(new Vector3D(1, 0, 0), -135)));
            //LightCameraTransform.Children.Add(new Media3D.TranslateTransform3D(0, 3, 3));
            //UpdateCamera();
        }
コード例 #12
0
        void IRenderer.Present(IVideoFrame src, rectangle dstrec, IntPtr window) // painting on block or rpreview-something with alpha=255
        {
            dstrec = new rectangle(point.Zero, this.viewsize);

            if (islost || device.TestCooperativeLevel() == ResultCode.DeviceLost /*||
                                                                                  * this.lastsize.Width != r.Width || this.lastsize.Height != r.Height*/)
            {
                Reset();
                //      this.lastsize = r.Size;

                islost = false;
            }
            if (src != null)
            {
                this.frame.Set(0, src.Width, src.Height, 0);

                var dr = (this.frame as IDirectXFrame).Textures[0].LockRectangle(0, LockFlags.Discard);

                Debug.Assert(this.frame.Width == src.Width);
                Debug.Assert(this.frame.Height == src.Height);


                using (var lck = this.opentk.GetDrawLock())
                {
                    src.CopyTo(dr.DataPointer, dr.Pitch);
                    //       Marshal.Copy(fill, 0, dr.DataPointer, dr.Pitch * src.Height);
                }
                (this.frame as IDirectXFrame).Textures[0].UnlockRectangle(0);
            }
            else
            {
                this.frame.Set(0, this.renderframe.Width, this.renderframe.Height, 0);

                var dr = (this.frame as IDirectXFrame).Textures[0].LockRectangle(0, LockFlags.Discard);

                Debug.Assert(this.frame.Width == this.renderframe.Width);
                Debug.Assert(this.frame.Height == this.renderframe.Height);

                using (var lck = this.opentk.GetDrawLock())
                {
                    this.renderframe.CopyTo(dr.DataPointer, dr.Pitch);
                    //       Marshal.Copy(fill, 0, dr.DataPointer, dr.Pitch * renderframe.Height);
                }
                (this.frame as IDirectXFrame).Textures[0].UnlockRectangle(0);
            }
            //    IDirectXFrame framesrc = (IDirectXFrame)src;

            /*   device.Viewport = new SharpDX.Mathematics.Interop.RawViewport()
             * {
             *     X = 0,
             *     Y = 0,
             *     Width = this.viewsize.width,
             *     Height = viewsize.height,
             *     MinDepth=0,
             *     MaxDepth=1
             * };*/

            device.Clear(ClearFlags.Target, new SharpDX.Mathematics.Interop.RawColorBGRA(0, 0, 255, 255), 1.0f, 0);

            device.BeginScene();

            device.SetStreamSource(0, vertices2, 0, Utilities.SizeOf <vertex>());
            device.VertexDeclaration = vertexDecl2;

            var m = Matrix.Scaling(dstrec.width, -dstrec.height, 1) * Matrix.Translation(dstrec.x, dstrec.height, 0);

            //   Matrix proj = Matrix.Scaling(1, -1, 1);
            //   m= Matrix.Multiply(m, proj);
            var worldViewProj = m * CreateViewMatrix(this.viewsize.width, this.viewsize.height);

            presenteffect.SetValue("worldViewProj", worldViewProj);
            presenteffect.SetValue("alpha", 1.0f);
            presenteffect.SetTexture("texture0", (this.frame as IDirectXFrame).Textures[0]);

            //       effect.Technique = technique;
            presenteffect.Begin();
            presenteffect.BeginPass(0);

            device.DrawPrimitives(PrimitiveType.TriangleList, 0, 2);

            presenteffect.EndPass();
            presenteffect.End();

            device.EndScene();

            presenteffect.SetTexture("texture0", null);
        }