CreateTranslation() public static method

public static CreateTranslation ( Vector3 position ) : Matrix
position Vector3
return Matrix
        private void Transform(AstroObject astroObject, Matrix3D baseTransformation, FrameworkElement txt)
        {
            // Transform Model
            if (astroObject == null)
            {
                return;
            }
            var m = Matrix.Identity;

            m *= Matrix.CreateTranslation(0, 60, 0);
            m *= Matrix.CreateRotationX(Microsoft.Xna.Framework.MathHelper.ToRadians(90));
            m *= baseTransformation.ToXnaMatrix();
            astroObject.Transform = m;
            astroObject.IsVisible = true;

            // Transform FrameworkElement
            // Center at origin of the TextBlock
            var centerAtOrigin = Matrix3DFactory.CreateTranslation(-txt.ActualWidth * 0.5, -txt.ActualHeight * 0.5, 0);
            // Swap the y-axis
            var scale = Matrix3DFactory.CreateScale(1, -1, 1);
            // Move a bit away from the center
            var translation = Matrix3DFactory.CreateTranslation(0, 50, 0);
            // Calculate the complete transformation matrix based on the first detection result
            var world = centerAtOrigin * translation * scale * baseTransformation;

            // Calculate the final transformation matrix by using the camera projection matrix
            var vp = Matrix3DFactory.CreateViewportTransformation(Viewport.ActualWidth, Viewport.ActualHeight);
            var mp = Matrix3DFactory.CreateViewportProjection(world, Matrix3D.Identity, arDetector.Projection, vp);

            // Apply the final transformation matrix to the TextBox
            txt.Projection = new Matrix3DProjection {
                ProjectionMatrix = mp
            };
            txt.Visibility = Visibility.Visible;
        }
Beispiel #2
0
        public void Update(GameTime gameTime)
        {
            var direction = XVector3.Transform(XVector3.UnitZ,
                                               Matrix.CreateRotationX(MathHelper.ToRadians(Game.Client.Pitch)) *
                                               Matrix.CreateRotationY(MathHelper.ToRadians(-(Game.Client.Yaw - 180) + 180)));

            var cast = VoxelCast.Cast(Game.Client.World,
                                      new TRay(Game.Camera.Position, new TVector3(direction.X, direction.Y, direction.Z)),
                                      Game.BlockRepository, TrueCraftGame.Reach, TrueCraftGame.Reach + 2);

            if (cast == null)
            {
                Game.HighlightedBlock = -Coordinates3D.One;
            }
            else
            {
                var provider = Game.BlockRepository.GetBlockProvider(Game.Client.World.GetBlockID(cast.Item1));
                if (provider.InteractiveBoundingBox != null)
                {
                    var box = provider.InteractiveBoundingBox.Value;

                    Game.HighlightedBlock     = cast.Item1;
                    Game.HighlightedBlockFace = cast.Item2;

                    DestructionEffect.World = HighlightEffect.World = Matrix.Identity
                                                                      * Matrix.CreateScale(new XVector3((float)box.Width, (float)box.Height, (float)box.Depth))
                                                                      * Matrix.CreateTranslation(new XVector3((float)box.Min.X, (float)box.Min.Y, (float)box.Min.Z))
                                                                      * Matrix.CreateTranslation(new XVector3(cast.Item1.X, cast.Item1.Y, cast.Item1.Z));
                }
            }
        }
Beispiel #3
0
        public Matrix GetScaleMatrix()
        {
            if (scaleMatrix.HasValue == false)
            {
                var screenSize = Client.ScreenManager.CurrentScreen.GetLayoutSize();

                var gameWorldSize = new Vector2(screenSize.Width, screenSize.Height);
                var vp            = graphicsDevice.Viewport;

                var scaleX = vp.Width / gameWorldSize.X;
                var scaleY = vp.Height / gameWorldSize.Y;
                scaleY = scaleX;

                var translateX = (vp.Width - (gameWorldSize.X * scaleX)) / 2f;
                var translateY = (vp.Height - (gameWorldSize.Y * scaleY)) / 2f;


                var camera = Matrix.CreateScale(scaleX, scaleY, 1)
                             * Matrix.CreateTranslation(translateX, translateY, 0);

                scaleMatrix = camera;
            }

            return(scaleMatrix.Value);
        }
Beispiel #4
0
        public BasicEntity(ModelDefinition modelbb, MaterialEffect material, Vector3 position, double angleZ, double angleX, double angleY, Vector3 scale, MeshMaterialLibrary library = null, Entity physicsObject = null)
        {
            Id                  = IdGenerator.GetNewId();
            Name                = GetType().Name + " " + Id;
            WorldTransform      = new TransformMatrix(Matrix.Identity, Id);
            ModelDefinition     = modelbb;
            Model               = modelbb.Model;
            BoundingBox         = modelbb.BoundingBox;
            BoundingBoxOffset   = modelbb.BoundingBoxOffset;
            SignedDistanceField = modelbb.SDF;

            Material = material;
            Position = position;
            Scale    = scale;

            RotationMatrix = Matrix.CreateRotationX((float)angleX) * Matrix.CreateRotationY((float)angleY) *
                             Matrix.CreateRotationZ((float)angleZ);

            if (library != null)
            {
                RegisterInLibrary(library);
            }

            if (physicsObject != null)
            {
                RegisterPhysics(physicsObject);
            }

            WorldTransform.World        = Matrix.CreateScale(Scale) * RotationMatrix * Matrix.CreateTranslation(Position);
            WorldTransform.Scale        = Scale;
            WorldTransform.InverseWorld = Matrix.Invert(Matrix.CreateTranslation(BoundingBoxOffset * Scale) * RotationMatrix * Matrix.CreateTranslation(Position));
        }
Beispiel #5
0
            /// <summary>
            /// Initializes World matrix of this location on the 3d world
            /// </summary>
            private void InitializeWorldMatrix()
            {
                if (VectorPoint.Z > 0)
                {
                    WorldMatrix = Matrix.CreateRotationY((float)Math.Atan(VectorPoint.X / VectorPoint.Z));
                }
                else
                {
                    WorldMatrix = Matrix.CreateRotationY(-MathHelper.Pi + (float)Math.Atan(VectorPoint.X / VectorPoint.Z));
                }

                WorldMatrix = WorldMatrix * Matrix.CreateTranslation(VectorPoint);
            }
        public void TestMeshRendererRenderCity()
        {
            var c = new OBJToRAMMeshConverter(new RAMTextureFactory());


            var importer = new ObjImporter();

            importer.AddMaterialFileStream("Town001.mtl", new FileStream("../../bin/GameData/Core/Town/OBJ03/Town001.mtl", FileMode.Open));
            importer.ImportObjFile("../../bin/GameData/Core/Town/OBJ03/Town001.obj");

            var mesh = c.CreateMesh(importer);

            var texturePool           = new TexturePool();
            var meshpartPool          = new MeshPartPool();
            var vertexDeclarationPool = new VertexDeclarationPool();

            var renderer = new SimpleMeshRenderer(texturePool, meshpartPool, vertexDeclarationPool);

            vertexDeclarationPool.SetVertexElements <TangentVertex>(TangentVertex.VertexElements);


            var el = renderer.AddMesh(mesh);

            el.WorldMatrix = Matrix.CreateTranslation(Vector3.Right * 0 * 2 + Vector3.UnitZ * 0 * 2);


            var game = new XNAGame();

            game.IsFixedTimeStep = false;
            game.DrawFps         = true;
            game.Graphics1.PreparingDeviceSettings += delegate(object sender, PreparingDeviceSettingsEventArgs e)
            {
                DisplayMode displayMode = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode;
                e.GraphicsDeviceInformation.PresentationParameters.BackBufferFormat = displayMode.Format;
                e.GraphicsDeviceInformation.PresentationParameters.BackBufferWidth  = displayMode.Width;
                e.GraphicsDeviceInformation.PresentationParameters.BackBufferHeight = displayMode.Height;
                game.SpectaterCamera.AspectRatio = displayMode.Width / (float)displayMode.Height;
            };
            game.Graphics1.ToggleFullScreen();



            game.AddXNAObject(texturePool);
            game.AddXNAObject(meshpartPool);
            game.AddXNAObject(vertexDeclarationPool);
            game.AddXNAObject(renderer);

            game.Run();
        }
        public MainPage()
        {
            InitializeComponent();

            totalElapsedTime = TimeSpan.FromSeconds(0.0);
            rotationSpeed    = 2.0;

            // Create camera and models
            camera = new Camera((float)ds.Width / (float)ds.Height);
            Earth  = new Earth();
            Sun    = new Sun {
                IsVisible = false, Transform = Matrix.CreateTranslation(-4, 0, 0)
            };

            DataContext = this;
        }
Beispiel #8
0
        public void ApplyTransformation()
        {
            if (_dynamicPhysicsObject == null)
            {
                //RotationMatrix = Matrix.CreateRotationX((float) AngleX)*Matrix.CreateRotationY((float) AngleY)*
                //                  Matrix.CreateRotationZ((float) AngleZ);
                Matrix scaleMatrix = Matrix.CreateScale(Scale);
                _worldOldMatrix = scaleMatrix * RotationMatrix * Matrix.CreateTranslation(Position);

                WorldTransform.Scale = Scale;
                WorldTransform.World = _worldOldMatrix;

                WorldTransform.InverseWorld = Matrix.Invert(Matrix.CreateTranslation(BoundingBoxOffset * Scale) * RotationMatrix * Matrix.CreateTranslation(Position));

                if (StaticPhysicsObject != null && !GameSettings.e_enableeditor)
                {
                    AffineTransform change = new AffineTransform(
                        new BEPUutilities.Vector3(Scale.X, Scale.Y, Scale.Z),
                        Quaternion.CreateFromRotationMatrix(MathConverter.Convert(RotationMatrix)),
                        MathConverter.Convert(Position));

                    if (!MathConverter.Equals(change.Matrix, StaticPhysicsObject.WorldTransform.Matrix))
                    {
                        //StaticPhysicsMatrix = MathConverter.Copy(Change.Matrix);

                        StaticPhysicsObject.WorldTransform = change;
                    }
                }
            }
            else
            {
                //Has something changed?
                WorldTransform.Scale = Scale;
                _worldOldMatrix      = Extensions.CopyFromBepuMatrix(_worldOldMatrix, _dynamicPhysicsObject.WorldTransform);
                Matrix scaleMatrix = Matrix.CreateScale(Scale);
                //WorldOldMatrix = Matrix.CreateScale(Scale)*WorldOldMatrix;
                WorldTransform.World = scaleMatrix * _worldOldMatrix;

                WorldTransform.InverseWorld = Matrix.Invert(Matrix.CreateTranslation(BoundingBoxOffset * Scale) * RotationMatrix * Matrix.CreateTranslation(Position));
            }
        }
Beispiel #9
0
        protected override void WhenUpdatedByUi()
        {
            _transform =
                Matrix.CreateTranslation(new Vector3(-_properties.Origin.X, -_properties.Origin.Y, 0.0f)) *
                Matrix.CreateScale(Scale.X, Scale.Y, 1) *
                Matrix.CreateRotationZ(Rotation) *
                Matrix.CreateTranslation(new Vector3(_properties.Position, 0.0f));

            Vector2 leftTop = Vector2.Zero;

            var leftBottom  = new Vector2(0, _texture.Height);
            var rightTop    = new Vector2(_texture.Width, 0);
            var rightBottom = new Vector2(_texture.Width, _texture.Height);

            // Transform all four corners into work space
            Vector2.Transform(ref leftTop, ref _transform, out leftTop);
            Vector2.Transform(ref rightTop, ref _transform, out rightTop);
            Vector2.Transform(ref leftBottom, ref _transform, out leftBottom);
            Vector2.Transform(ref rightBottom, ref _transform, out rightBottom);

            _polygon[0] = leftTop;
            _polygon[1] = rightTop;
            _polygon[3] = leftBottom;
            _polygon[2] = rightBottom;

            // Find the minimum and maximum extents of the rectangle in world space
            Vector2 min = Vector2.Min(
                Vector2.Min(leftTop, rightTop),
                Vector2.Min(leftBottom, rightBottom));

            Vector2 max = Vector2.Max(
                Vector2.Max(leftTop, rightTop),
                Vector2.Max(leftBottom, rightBottom));

            // Return as a rectangle
            _boundingRectangle = new Rectangle(
                (int)min.X,
                (int)min.Y,
                (int)(max.X - min.X),
                (int)(max.Y - min.Y));
        }
Beispiel #10
0
        public BasicEntity(ModelDefinition modelbb, MaterialEffect material, Vector3 position, Matrix rotationMatrix, Vector3 scale)
        {
            Id                  = IdGenerator.GetNewId();
            Name                = GetType().Name + " " + Id;
            WorldTransform      = new TransformMatrix(Matrix.Identity, Id);
            Model               = modelbb.Model;
            ModelDefinition     = modelbb;
            BoundingBox         = modelbb.BoundingBox;
            BoundingBoxOffset   = modelbb.BoundingBoxOffset;
            SignedDistanceField = modelbb.SDF;

            Material       = material;
            Position       = position;
            RotationMatrix = rotationMatrix;
            Scale          = scale;
            RotationMatrix = rotationMatrix;

            WorldTransform.World        = Matrix.CreateScale(Scale) * RotationMatrix * Matrix.CreateTranslation(Position);
            WorldTransform.Scale        = Scale;
            WorldTransform.InverseWorld = Matrix.Invert(Matrix.CreateTranslation(BoundingBoxOffset * Scale) * RotationMatrix * Matrix.CreateTranslation(Position));
        }
Beispiel #11
0
        /// <summary>
        /// Animates Selected Location Center and zoom in camera
        /// </summary>
        /// <param name="l">Location will be animated</param>
        private void AnimateLocationSelection(LocationsVM.Location l)
        {
            float   zoomFactor = 0.20f;
            Vector3 v          = new Vector3(l.VectorPoint.X, 0, l.VectorPoint.Z);

            Matrix cam = Matrix.CreateLookAt(new Vector3(0, 0, 0), v, Vector3.Up);

            l.IsAnimatingView = true;
            XNAMatrixAnimation animCam = new XNAMatrixAnimation(l.Object3dEffect.View, cam, TimeSpan.FromSeconds(0.3), 30);

            animCam.OnAnimating += (XNAMatrixAnimation sender, XNAMatrixAnimationEventArgs e) =>
            {
                l.Object3dEffect.View = e.Value;
            };
            animCam.OnCompleted += (XNAMatrixAnimation sender, XNAMatrixAnimationEventArgs e) =>
            {
                l.Object3dEffect.View = e.Value;
                l.IsAnimatingView     = false;
            };
            animCam.Start();

            Matrix world = l.WorldMatrix * Matrix.CreateTranslation(new Vector3(-l.VectorPoint.X * zoomFactor, -l.VectorPoint.Y, -l.VectorPoint.Z * zoomFactor));

            l.IsAnimatingWorld = true;
            XNAMatrixAnimation animWorld = new XNAMatrixAnimation(l.Object3dEffect.World, world, TimeSpan.FromSeconds(0.3), 30);

            animWorld.OnAnimating += (XNAMatrixAnimation sender, XNAMatrixAnimationEventArgs e) =>
            {
                l.Object3dEffect.World = e.Value;
            };
            animWorld.OnCompleted += (XNAMatrixAnimation sender, XNAMatrixAnimationEventArgs e) =>
            {
                l.Object3dEffect.World = e.Value;
                l.IsAnimatingWorld     = false;
            };
            animWorld.Start();
        }
Beispiel #12
0
        private void HandleGesture()
        {
            while (TouchPanel.IsGestureAvailable)
            {
                GestureSample gestureSample = TouchPanel.ReadGesture();
                switch (gestureSample.GestureType)
                {
                case GestureType.FreeDrag:
                    _gestureTimer.Stop();
                    _gestureState = GestureStateEnum.OnFreeDrag;

                    float rotateRate    = 0.01f;
                    float translateRate = 0.1f;
                    _cameraMatrix = _cameraMatrix * Matrix.CreateRotationY(-gestureSample.Delta.X * rotateRate);
                    _cameraMatrix = _cameraMatrix * Matrix.CreateTranslation(0f, -gestureSample.Delta.Y * translateRate, 0f);

                    //rotate radar
                    Dispatcher.BeginInvoke(delegate()
                    {
                        (radarCanvas.RenderTransform as System.Windows.Media.RotateTransform).Angle += MathHelper.ToDegrees((gestureSample.Delta.X * rotateRate));
                    });

                    break;

                case GestureType.DragComplete:
                    _gestureTime = 0;
                    _gestureTimer.Start();

                    break;

                case GestureType.Tap:
                    _gestureState = GestureStateEnum.OnMotion;

                    if (myVM.ClickedNearbyLocation != null)
                    {
                        AnimateLocationDeselection(myVM.ClickedNearbyLocation);
                        myVM.ClickedNearbyLocation.IsClickedOnView = false;
                        if (OnLocationReleased != null)
                        {
                            OnLocationReleased(this, myVM.ClickedNearbyLocation);
                        }
                    }

                    if (_gestureState != GestureStateEnum.OnPressHold)
                    {
                        _gestureState = GestureStateEnum.OnPressHold;

                        float   mouseX     = gestureSample.Position.X;
                        float   mouseY     = gestureSample.Position.Y;
                        Vector3 nearsource = new Vector3((float)mouseX, (float)mouseY, 0f);
                        Vector3 farsource  = new Vector3((float)mouseX, (float)mouseY, -1f);

                        Vector3 nearPoint = _device.Viewport.Unproject(nearsource, _projectionMatrix, _cameraMatrix, _phoneWorld);
                        Vector3 farPoint  = _device.Viewport.Unproject(farsource, _projectionMatrix, _cameraMatrix, _phoneWorld);

                        Vector3 direction = -farPoint + nearPoint;
                        direction.Normalize();
                        Ray pickRay = new Ray(nearPoint, direction);

                        if (myVM.ClickedNearbyLocation != null)
                        {
                            AnimateLocationDeselection(myVM.ClickedNearbyLocation);
                            myVM.ClickedNearbyLocation.IsClickedOnView = false;
                            if (OnLocationReleased != null)
                            {
                                OnLocationReleased(this, myVM.ClickedNearbyLocation);
                            }
                        }

                        foreach (LocationsVM.Location l in myVM.SelectedNearbyLocations)
                        {
                            float?result = pickRay.Intersects(l.PlacemarkBoundingSphere);
                            if (result.HasValue)
                            {
                                AnimateLocationSelection(l);
                                l.IsClickedOnView = true;
                                if (OnLocationSelected != null)
                                {
                                    OnLocationSelected(this, l);
                                }

                                break;
                            }
                        }
                    }

                    break;
                }
            }
        }
Beispiel #13
0
 void updateview()
 {
     mat = MX.CreateTranslation(-pos.X, -pos.Y, 0) * MX.CreateScale(G.zoom) * MX.CreateTranslation(G.w / 2, G.h / 2, 0);
 }
Beispiel #14
0
        public override void Update(GameTime gameTime)
        {
            if (!Game.IsActive)
            {
                return;
            }

            var mouse    = Mouse.GetState();
            var keyboard = Keyboard.GetState(playerIndex);
            var gamepad  = GamePad.GetState(playerIndex);

            if (MouseEnabled)
            {
                Point mouseDelta = mouseMoveComponent.MouseDelta;
                Yaw   += Angle.Degrees(mouseDelta.X);
                Pitch += Angle.Degrees(mouseDelta.Y);
            }

            /*if(LastMousePosition != null) {
             *  Vector2l last = LastMousePosition.Value, delta = new Vector2l(mousePosition.X - last.X, mousePosition.Y - last.Y);
             *  Yaw += Angle.Degrees(delta.X);
             *  Pitch += Angle.Degrees(delta.Y);
             * }
             *
             * mouse.Position = new Vector2l(Game.Context.Viewport.Width / 2, Game.Context.Viewport.Height / 2);
             * LastMousePosition = new Vector2l(Game.Context.Viewport.Width / 2, Game.Context.Viewport.Height / 2);*/

            bool    run          = keyboard.IsKeyDown(KeyRun);
            float   walkSpeed    = run ? RunSpeed : WalkSpeed;
            Vector3 flyDirection = run ? FlyUpDirection * RunMultiplier : FlyUpDirection;

            if (keyboard.IsKeyDown(KeyFlyUp))
            {
                Position += flyDirection;
            }
            if (keyboard.IsKeyDown(KeyFlyDown))
            {
                Position -= flyDirection;
            }

            Vector2 facing   = new Vector2(0, -1).Rotate(Yaw); // Positive is forward, negative is backwards.
            Vector2 strafing = new Vector2(1, 0).Rotate(Yaw);  // Positive is right, negative is left.
            Vector2 movement = Vector2.Zero;

            if (keyboard.IsKeyDown(KeyForward))
            {
                movement += facing;
            }
            if (keyboard.IsKeyDown(KeyBackward))
            {
                movement -= facing;
            }
            if (keyboard.IsKeyDown(KeyStrafeRight))
            {
                movement += strafing;
            }
            if (keyboard.IsKeyDown(KeyStrafeLeft))
            {
                movement -= strafing;
            }

            if (movement != Vector2.Zero)
            {
                Position += new Vector3(movement.X, 0, movement.Y).Normalized() * walkSpeed;
            }

            Pitch = Pitch.MaxDegrees(-90);
            Pitch = Pitch.MinDegrees(90);

            View = Matrix.CreateTranslation(-Position) *
                   Matrix.CreateFromYawPitchRoll(Yaw.InRadians, 0, 0) *
                   Matrix.CreateFromYawPitchRoll(0, Pitch.InRadians, 0) *
                   Matrix.CreateFromYawPitchRoll(0, 0, Roll.InRadians);

            base.Update(gameTime);
        }
        public void TestThrowBarrels()
        {
            var texFactory = new RAMTextureFactory();
            var c          = new OBJToRAMMeshConverter(texFactory);


            RAMMesh mesh = OBJParserTest.GetBarrelMesh(c);

            var texturePool           = new TexturePool();
            var meshpartPool          = new MeshPartPool();
            var vertexDeclarationPool = new VertexDeclarationPool();

            var renderer = new SimpleMeshRenderer(texturePool, meshpartPool, vertexDeclarationPool);

            vertexDeclarationPool.SetVertexElements <TangentVertex>(TangentVertex.VertexElements);



            var gameMeshes = new List <OBJParserTest.TestGameMesh>();
            var engine     = new PhysicsEngine();
            PhysicsDebugRendererXNA debugRenderer = null;

            var root = CreatePhysicsQuadtree(16, 4);

            var physicsElementFactoryXNA = new MeshPhysicsFactoryXNA(engine, root);
            var physicsElementFactory    = physicsElementFactoryXNA.Factory;

            var game = new XNAGame();

            game.IsFixedTimeStep = false;
            game.DrawFps         = true;

            var visualizer = new QuadTreeVisualizerXNA();

            game.AddXNAObject(physicsElementFactoryXNA);

            game.AddXNAObject(texturePool);
            game.AddXNAObject(meshpartPool);
            game.AddXNAObject(vertexDeclarationPool);
            game.AddXNAObject(renderer);


            game.InitializeEvent += delegate
            {
                engine.Initialize();
                debugRenderer = new PhysicsDebugRendererXNA(game, engine.Scene);
                debugRenderer.Initialize(game);
            };

            bool showPhysics = true;

            game.DrawEvent += delegate
            {
                if (game.Keyboard.IsKeyPressed(Keys.P))
                {
                    showPhysics = !showPhysics;
                }
                if (showPhysics)
                {
                    debugRenderer.Render(game);
                }
                visualizer.RenderNodeGroundBoundig(game, root,
                                                   delegate(ClientPhysicsQuadTreeNode node, out Color col)
                {
                    col = Color.Green;

                    return(node.PhysicsObjects.Count == 0);
                });

                visualizer.RenderNodeGroundBoundig(game, root,
                                                   delegate(ClientPhysicsQuadTreeNode node, out Color col)
                {
                    col = Color.Orange;

                    return(node.PhysicsObjects.Count > 0);
                });
            };
            game.UpdateEvent += delegate
            {
                engine.Update(game.Elapsed);
                if (game.Keyboard.IsKeyPressed(Microsoft.Xna.Framework.Input.Keys.F))
                {
                    var pEl = physicsElementFactory.CreateDynamicElement(mesh,
                                                                         Matrix.CreateTranslation(
                                                                             game.SpectaterCamera.CameraPosition +
                                                                             game.SpectaterCamera.CameraDirection));
                    pEl.Actor.LinearVelocity = game.SpectaterCamera.CameraDirection * 30;

                    var rEl = renderer.AddMesh(mesh);


                    gameMeshes.Add(new OBJParserTest.TestGameMesh(rEl, pEl));
                }

                for (int i = 0; i < gameMeshes.Count; i++)
                {
                    var m = gameMeshes[i];
                    m.RenderElement.WorldMatrix = m.PhysicsElement.World;
                }
            };

            game.Run();
        }
        public void TestOBJToRAMMeshConverterPerObjectVisualCool()
        {
            var textureFactory = new RAMTextureFactory();
            var c = new OBJToRAMMeshConverter(textureFactory);


            var importer = new ObjImporter();

            importer.AddMaterialFileStream("Town001.mtl", new FileStream("../GameData/Town/OBJ03/Town001.mtl", FileMode.Open));
            importer.ImportObjFile("../GameData/Town/OBJ03/Town001.obj");

            var meshes = c.CreateMeshesFromObjects(importer);

            var texturePool           = new TexturePool();
            var meshpartPool          = new MeshPartPool();
            var vertexDeclarationPool = new VertexDeclarationPool();

            var renderer = new SimpleMeshRenderer(texturePool, meshpartPool, vertexDeclarationPool);

            vertexDeclarationPool.SetVertexElements <TangentVertex>(TangentVertex.VertexElements);



            var spheres = new List <ClientPhysicsTestSphere>();
            var engine  = new PhysicsEngine();
            PhysicsDebugRendererXNA debugRenderer = null;

            var root = CreatePhysicsQuadtree(20, 5);

            var physicsElementFactoryXNA = new MeshPhysicsFactoryXNA(engine, root);
            var physicsElementFactory    = physicsElementFactoryXNA.Factory;

            var physicsElements = new List <MeshStaticPhysicsElement>();

            for (int i = 0; i < 0 * 100 + 1 * meshes.Count; i++)
            {
                var mesh = meshes[i];
                var el   = renderer.AddMesh(mesh);
                el.WorldMatrix = Matrix.CreateTranslation(Vector3.Right * 0 * 2 + Vector3.UnitZ * 0 * 2);

                var pEl = physicsElementFactory.CreateStaticElement(mesh, Matrix.Identity);
                physicsElements.Add(pEl);
            }
            var gameMeshes = new List <OBJParserTest.TestGameMesh>();

            var game = new XNAGame();

            game.IsFixedTimeStep                    = false;
            game.DrawFps                            = true;
            game.SpectaterCamera.FarClip            = 5000;
            game.Graphics1.PreparingDeviceSettings += delegate(object sender, PreparingDeviceSettingsEventArgs e)
            {
                DisplayMode displayMode = GraphicsAdapter.DefaultAdapter.CurrentDisplayMode;
                e.GraphicsDeviceInformation.PresentationParameters.BackBufferFormat = displayMode.Format;
                e.GraphicsDeviceInformation.PresentationParameters.BackBufferWidth  = displayMode.Width;
                e.GraphicsDeviceInformation.PresentationParameters.BackBufferHeight = displayMode.Height;
                game.SpectaterCamera.AspectRatio = displayMode.Width / (float)displayMode.Height;
            };
            game.Graphics1.ToggleFullScreen();

            var barrelMesh = OBJParserTest.GetBarrelMesh(c);
            var crateMesh  = OBJParserTest.GetCrateMesh(c);

            var sphereMesh = new SphereMesh(0.3f, 20, Color.Green);
            var visualizer = new QuadTreeVisualizerXNA();

            game.AddXNAObject(physicsElementFactoryXNA);

            game.AddXNAObject(texturePool);
            game.AddXNAObject(meshpartPool);
            game.AddXNAObject(vertexDeclarationPool);
            game.AddXNAObject(renderer);


            game.InitializeEvent += delegate
            {
                engine.Initialize();
                debugRenderer = new PhysicsDebugRendererXNA(game, engine.Scene);
                debugRenderer.Initialize(game);
                sphereMesh.Initialize(game);

                for (int i = 0; i < meshes.Count; i++)
                {
                    var mesh = meshes[i];
                    var data = mesh.GetCollisionData();

                    /*if (data.TriangleMesh != null)
                     *  physicsElementFactory.MeshPhysicsPool.PreloadTriangleMesh(engine.Scene, data.TriangleMesh);*/
                }
            };

            bool showPhysics = true;

            game.DrawEvent += delegate
            {
                if (game.Keyboard.IsKeyPressed(Keys.P))
                {
                    showPhysics = !showPhysics;
                }
                if (showPhysics)
                {
                    debugRenderer.Render(game);
                }

                /*visualizer.RenderNodeGroundBoundig(game, root,
                 *  delegate(ClientPhysicsQuadTreeNode node, out Color col)
                 *  {
                 *      col = Color.Green;
                 *
                 *      return node.PhysicsObjects.Count == 0;
                 *  });
                 *
                 * visualizer.RenderNodeGroundBoundig(game, root,
                 * delegate(ClientPhysicsQuadTreeNode node, out Color col)
                 * {
                 *     col = Color.Orange;
                 *
                 *     return node.PhysicsObjects.Count > 0;
                 * });*/

                for (int i = 0; i < physicsElements.Count; i++)
                {
                    var el = physicsElements[i];
                    //game.LineManager3D.AddBox(BoundingBox.CreateFromSphere( el.BoundingSphere), Color.Orange);
                }
                for (int i = 0; i < spheres.Count; i++)
                {
                    sphereMesh.WorldMatrix = Matrix.CreateTranslation(spheres[i].Center);
                    sphereMesh.Render(game);
                }
            };
            game.UpdateEvent += delegate
            {
                engine.Update(game.Elapsed);
                sphereMesh.Update(game);
                if (game.Keyboard.IsKeyPressed(Microsoft.Xna.Framework.Input.Keys.F))
                {
                    var pEl = physicsElementFactory.CreateDynamicElement(crateMesh,
                                                                         Matrix.CreateTranslation(
                                                                             game.SpectaterCamera.CameraPosition +
                                                                             game.SpectaterCamera.CameraDirection));
                    pEl.Actor.LinearVelocity = game.SpectaterCamera.CameraDirection * 30;

                    var rEl = renderer.AddMesh(crateMesh);


                    gameMeshes.Add(new OBJParserTest.TestGameMesh(rEl, pEl));
                }
                if (game.Keyboard.IsKeyPressed(Microsoft.Xna.Framework.Input.Keys.E))
                {
                    var pEl = physicsElementFactory.CreateDynamicElement(barrelMesh,
                                                                         Matrix.CreateTranslation(
                                                                             game.SpectaterCamera.CameraPosition +
                                                                             game.SpectaterCamera.CameraDirection));
                    pEl.Actor.LinearVelocity = game.SpectaterCamera.CameraDirection * 30;

                    var rEl = renderer.AddMesh(barrelMesh);


                    gameMeshes.Add(new OBJParserTest.TestGameMesh(rEl, pEl));
                }


                for (int i = 0; i < gameMeshes.Count; i++)
                {
                    var m = gameMeshes[i];
                    m.RenderElement.WorldMatrix = m.PhysicsElement.World;
                }
            };

            game.Run();
        }
        MathboxRenderer(Machine machine, ScreenManager screenManager)
        {
            Machine       = machine;
            Memory        = Machine.Mathbox.Memory16;
            ScreenManager = screenManager;

            if (!(screenManager.Game is I_Robot.Game game))
            {
                throw new Exception("VideoInterpreter can only be used with I_Robot.Game");
            }
            Game = game;

            DisplayListManager = new DisplayList.Manager(this);
            Object             = new ObjectRenderer(this);
            Terrain            = new TerrainRenderer(this);

            // create our scene buffer
            // this buffer has a z-buffer
            SceneBuffer = new RenderTarget2D(
                Game.GraphicsDevice,
                Game.GraphicsDevice.Viewport.Width,
                Game.GraphicsDevice.Viewport.Height,
                false,
                Game.GraphicsDevice.PresentationParameters.BackBufferFormat,
                DepthFormat.None,
                8,
                RenderTargetUsage.DiscardContents);

            // create our two screen buffers
            // these buffers do not require depth sorting, they are simply raw bitmaps
            // however the contents need to be preserved when rendering context is reset
            for (int n = 0; n < ScreenBuffers.Length; n++)
            {
                ScreenBuffers[n] = new RenderTarget2D(
                    Game.GraphicsDevice,
                    Game.GraphicsDevice.Viewport.Width,
                    Game.GraphicsDevice.Viewport.Height,
                    false,
                    Game.GraphicsDevice.PresentationParameters.BackBufferFormat,
                    DepthFormat.None,
                    0,
                    RenderTargetUsage.PreserveContents);
            }

            camTarget   = new Vector3(0f, 0f, 0f);
            camPosition = new Vector3(0f, 0f, -1f);

            double scaleToMonitor = Emulation.Machine.MonitorAspectRatio / Emulation.Machine.NativeAspectRatio;

            projectionMatrix = Matrix.CreatePerspectiveFieldOfView(
                MathHelper.ToRadians(45f),
                (float)(Game.GraphicsDevice.Viewport.AspectRatio / scaleToMonitor),
                0.1f,
                65536f);

            // it's important to move the projection matrix down a bit, this matches what I, Robot seems to do
            projectionMatrix = projectionMatrix * Matrix.CreateTranslation(new Vector3(0, -0.1f, 0));
            viewMatrix       = Matrix.CreateLookAt(camPosition, camTarget, Vector3.Up);
            worldMatrix      = Matrix.CreateWorld(Vector3.Zero, Vector3.Forward, Vector3.Down);

            basicEffect       = new BasicEffect(Game.GraphicsDevice);
            basicEffect.Alpha = 1f;
            basicEffect.VertexColorEnabled = true; // Want to see the colors of the vertices, this needs to be on
            // Lighting requires normal information which VertexPositionColor does not have
            // If you want to use lighting and VPC you need to create a custom def
            basicEffect.LightingEnabled = false;
        }
 void SetWorldMatrix(ref Vector3 position, ref Matrix rotation)
 {
     D3DTS_WORLD = rotation * Matrix.CreateTranslation(position);
 }