Beispiel #1
0
        /// <summary>
        /// Calculate the center, scale and orientation of the gizmo.
        /// </summary>
        protected static void GizmoScaleCenterOrientation(GameObject3D selectedObject, GameObject3D gizmoCamera, out float scale, out Vector3 center, out Quaternion orientation)
        {
            center      = Vector3.Zero;
            orientation = new Quaternion();
            // Center
            center = selectedObject.Transform.Position;

            // Orientation
            if (Space == SpaceMode.Local)
            {
                orientation = selectedObject.Transform.Rotation;
            }
            else
            {
                orientation = new Quaternion();
            }

            // Calculate the distance from the object to camera position.
            if (gizmoCamera.Camera.OrthographicProjection)
            {
                scale = gizmoCamera.Camera.OrthographicVerticalSize / 5;
            }
            else
            {
                Vector3 cameraToCenter   = gizmoCamera.Camera.Position - center;
                float   distanceToCamera = cameraToCenter.Length();
                scale = (distanceToCamera / 16) / (gizmoCamera.Camera.RenderTargetSize.Width / 1400f); // Arbitrary number.
            }
        } // GizmoScaleCenterOrientation
        /// <summary>
        /// Load the resources.
        /// </summary>
        /// <remarks>Remember to call the base implementation of this method.</remarks>
        protected override void LoadContent()
        {
            // Hello World
            helloWorldText = new GameObject2D();
            helloWorldText.AddComponent <HudText>();
            helloWorldText.HudText.Text.Append("Hello World");
            helloWorldText.Transform.LocalPosition = new Vector3(10, 10, 0);
            // Creating a 3D World
            camera = new GameObject3D();
            camera.AddComponent <Camera>();

            /*body = new GameObject3D();
             * body.AddComponent<ModelFilter>();
             * body.ModelFilter.Model = new FileModel("LamborghiniMurcielago\\Murcielago-Body");
             * body.AddComponent<ModelRenderer>();
             * body.ModelRenderer.Material = new Constant();*/
            body = new GameObject3D(new FileModel("LamborghiniMurcielago\\Murcielago-Body"), new Constant());
            camera.Transform.LookAt(new Vector3(5, 0, 10), Vector3.Zero, Vector3.Up);

            body.ModelRenderer.Material = new BlinnPhong();
            ((BlinnPhong)body.ModelRenderer.Material).DiffuseColor = Color.Yellow;
            directionalLight = new GameObject3D();
            directionalLight.AddComponent <DirectionalLight>();
            directionalLight.DirectionalLight.Color     = new Color(250, 250, 140);
            directionalLight.DirectionalLight.Intensity = 1f;
            directionalLight.Transform.LookAt(new Vector3(0.5f, 0.65f, 1.3f), Vector3.Zero, Vector3.Forward);

            camera.Camera.PostProcess = new PostProcess();
            camera.Camera.PostProcess.ToneMapping.ToneMappingFunction = ToneMapping.ToneMappingFunctionEnumerate.FilmicALU;

            base.LoadContent();
        } // Load
        } // Update

        #endregion

        #region Render Gizmo For Picker

        /// <summary>
        /// Render the gizmo to the picker.
        /// </summary>
        private void RenderGizmoForPicker(GameObject3D gizmoCamera)
        {
            // Calculate the center, scale and orientation of the gizmo.
            Vector3    center;
            Quaternion orientation;
            float      scale;

            GizmoScaleCenterOrientation(selectedObject, gizmoCamera, out scale, out center, out orientation);

            // Calculate the gizmo matrix.
            Matrix transformationMatrix = Matrix.CreateScale(scale);

            transformationMatrix *= Matrix.CreateFromQuaternion(orientation);
            transformationMatrix *= Matrix.CreateTranslation(center);

            // Update Cones
            redLine.Transform.LocalMatrix = Matrix.Identity;
            redLine.Transform.Rotate(new Vector3(0, -90, 0));
            redLine.Transform.LocalMatrix = redLine.Transform.LocalMatrix * transformationMatrix;
            Picker.RenderObjectToPicker(redLine, Color.Red);

            greenLine.Transform.LocalMatrix = Matrix.Identity;
            greenLine.Transform.Rotate(new Vector3(90, 0, 0));
            greenLine.Transform.LocalMatrix = greenLine.Transform.LocalMatrix * transformationMatrix;
            Picker.RenderObjectToPicker(greenLine, new Color(0, 255, 0)); // Color.Green is not 0, 255, 0

            blueLine.Transform.LocalMatrix = Matrix.Identity;
            blueLine.Transform.LocalMatrix = blueLine.Transform.LocalMatrix * transformationMatrix;
            Picker.RenderObjectToPicker(blueLine, Color.Blue);
        } // RenderGizmoForPicker
 public override void OnCollisionStay(GameObject3D go, ContactCollection contacts)
 {
     DebugText.Text.ClearXbox();
     DebugText.Text.Append("White Box Info\n\n- Last event: Collision Stay");
     //var thisGo = (GameObject3D) Owner;
     //thisGo.RigidBody.Entity.ApplyImpulse(thisGo.Transform.Position, Vector3.Up * 0.5f);
 }
Beispiel #5
0
        public void AddObject(GameObject3D newObject)
        {
            if (Nodes.Count == 0)
            {
                bool maxObjectReached = Objects.Count > MaxNumberOfObjects;

                if (maxObjectReached)
                {
                    SubDivide();

                    foreach (var obj in Objects)
                    {
                        Distrubte(obj);
                    }

                    Objects.Clear();
                }
                else
                {
                    Objects.Add(newObject);
                }
            }
            else
            {
                Distrubte(newObject);
            }
        }
Beispiel #6
0
        } // RenderObjectsToPickerTexture

        #endregion

        #region Render Object To Picker

        /// <summary>
        /// Render Object To Picker.
        /// </summary>
        public void RenderObjectToPicker(GameObject gameObject)
        {
            if (gameObject is GameObject3D)
            {
                GameObject3D gameObject3D = (GameObject3D)gameObject;
                if (gameObject3D.LineRenderer != null)
                {
                    LineManager.Begin3D(gameObject3D.LineRenderer.PrimitiveType, viewMatrix, projectionMatrix);
                    for (int j = 0; j < gameObject3D.LineRenderer.Vertices.Length; j++)
                    {
                        LineManager.AddVertex(Vector3.Transform(gameObject3D.LineRenderer.Vertices[j].Position, gameObject3D.Transform.WorldMatrix), gameObject3D.LineRenderer.Vertices[j].Color);
                    }
                    LineManager.End();
                }
            }
            else if (gameObject is GameObject2D)
            {
                GameObject2D gameObject2D = (GameObject2D)gameObject;
                if (gameObject2D.LineRenderer != null)
                {
                    LineManager.Begin2D(gameObject2D.LineRenderer.PrimitiveType);
                    for (int j = 0; j < gameObject2D.LineRenderer.Vertices.Length; j++)
                    {
                        LineManager.AddVertex(gameObject2D.LineRenderer.Vertices[j].Position, gameObject2D.LineRenderer.Vertices[j].Color);
                    }
                    LineManager.End();
                }
            }
        } // RenderObjectToPicker
Beispiel #7
0
        } // GizmoScaleCenterOrientation

        #endregion

        #region Calculate 2D Mouse Direction

        /// <summary>
        /// Calculate how the mouse movement will affect the transformation amount.
        /// </summary>
        /// <param name="selectedObject">Selected object.</param>
        /// <param name="gizmoCamera">The camera.</param>
        /// <param name="direction">The direction indicates the axis.</param>
        /// <param name="transformationAmount">This value will be multiplied by the mouse position to calculate the transformation amount.</param>
        protected static void Calculate2DMouseDirection(GameObject3D selectedObject, GameObject3D gizmoCamera, Vector3 direction, out Vector2 transformationAmount)
        {
            // Calculate the center, scale and orientation of the gizmo.
            Vector3    center;
            Quaternion orientation;
            float      scale;

            GizmoScaleCenterOrientation(selectedObject, gizmoCamera, out scale, out center, out orientation);

            // Calculate the gizmo matrix.
            Matrix transformationMatrix = Matrix.CreateScale(scale);

            transformationMatrix *= Matrix.CreateFromQuaternion(orientation);
            transformationMatrix *= Matrix.CreateTranslation(center);

            // Calculate the direction of movement for every possible combination.
            vertices[0] = Vector3.Transform(new Vector3(0, 0, 0), transformationMatrix);
            vertices[1] = Vector3.Transform(direction, transformationMatrix);

            Vector3[] screenPositions = new Vector3[2];
            screenPositions[0] = EngineManager.Device.Viewport.Project(vertices[0], gizmoCamera.Camera.ProjectionMatrix, gizmoCamera.Camera.ViewMatrix, Matrix.Identity);
            screenPositions[1] = EngineManager.Device.Viewport.Project(vertices[1], gizmoCamera.Camera.ProjectionMatrix, gizmoCamera.Camera.ViewMatrix, Matrix.Identity);

            Vector3 aux = screenPositions[1] - screenPositions[0];

            transformationAmount = new Vector2
            {
                X = aux.X / aux.Length(),
                Y = aux.Y / aux.Length()
            };
        } // Calculate2DMouseDirection
        public void AddObject(GameObject3D newObject)
        {
            if (Nodes.Count == 0)
            {
                if (Objects.Count < MaxObjects)
                {
                    Objects.Add(newObject);
                }
                else
                {
                    Subdivide();

                    foreach (GameObject3D go in Objects)
                    {
                        Distribute(go);
                    }

                    Objects.Clear();
                }
            }
            else
            {
                Distribute(newObject);
            }
        }
        public override void OnCollisionExit(GameObject3D go, ContactCollection contacts)
        {
            DebugText.Text.ClearXbox();
            DebugText.Text.Append("White Box Info\n\n- Last event: Collision Exit");

            // Restore the last collided gameobject's original material
            go.ModelRenderer.Material = lastCollidedGOMaterial;
        }
 /// <summary>
 /// If you want to work with the XNA Final Engine Editor the main scene needs to inherit from this class.
 /// </summary>
 protected EditableScene()
 {
     // The engine is not initialized yet but it works.
     editorHiddenUpdateScript = new GameObject3D {
         Layer = Layer.GetLayerByNumber(31)
     };
     editorHiddenUpdateScript.AddComponent <HiddenEditorUpdateScript>();
 } // EditableScene
        } // UpdateTasks

        #endregion

        #region Helper Methods

        /// <summary>
        /// Makes a box that is affected by physics.
        /// </summary>
        private static GameObject3D MakeBox(Vector3 position, float width, float height, float depth, float mass, Material mat)
        {
            var cubeEntity = new Box(position, width, height, depth, mass);
            var gameObject = new GameObject3D(new XNAFinalEngine.Assets.Box(width, height, depth), mat);
            var rigidBody  = (RigidBody)gameObject.AddComponent <RigidBody>();

            rigidBody.Entity = cubeEntity;

            return(gameObject);
        } // MakeBox
        public override void OnCollisionEnter(GameObject3D go, ContactCollection contacts)
        {
            DebugText.Text.ClearXbox();
            DebugText.Text.Append("White Box Info\n\n- Last event: Collision Enter");

            // Save the last collided game object's material
            lastCollidedGOMaterial = go.ModelRenderer.Material;

            // Paint it green
            go.ModelRenderer.Material = greenMaterial;
        }
Beispiel #13
0
        private void Distrubte(GameObject3D newObject)
        {
            var location = newObject.World.Translation;

            foreach (var node in Nodes)
            {
                if (node.Bounds.Contains(location) != ContainmentType.Disjoint)
                {
                    node.AddObject(newObject);
                }
            }
        }
        public void Distribute(GameObject3D newObject)
        {
            Vector3 position = newObject.World.Translation;

            foreach (OctTree node in Nodes)
            {
                if (node.Bounds.Contains(position) != ContainmentType.Disjoint)
                {
                    node.AddObject(newObject);
                }
            }
        }
Beispiel #15
0
        } // Raycast

        /// <summary>
        /// Indicates if a ray intercepts a game object.
        /// </summary>
        public static GameObject3D Raycast(Ray ray, float distance, out RayCastResult result)
        {
            GameObject3D go = null;

            if (Scene.RayCast(ray, distance, out result))
            {
                var entityCollision = result.HitObject as EntityCollidable;
                if (entityCollision != null)
                {
                    go = (GameObject3D)entityCollision.Entity.Tag;
                }
            }
            return(go);
        } // Raycast
Beispiel #16
0
        } // Initialize

        #endregion

        #region Raycast

        /// <summary>
        /// Indicates if a ray intercepts a game object.
        /// </summary>
        public static GameObject3D Raycast(Vector3 origin, Vector3 direction, float distance, out RayCastResult result)
        {
            GameObject3D go  = null;
            var          ray = new Ray(origin, direction);

            if (Scene.RayCast(ray, distance, out result))
            {
                var entityCollision = result.HitObject as EntityCollidable;
                if (entityCollision != null)
                {
                    go = (GameObject3D)entityCollision.Entity.Tag;
                }
            }
            return(go);
        } // Raycast
Beispiel #17
0
        } // RenderObjectToPicker

        #endregion

        #region Render Icon To Picker

        /// <summary>
        /// Render Icon To Picker.
        /// </summary>
        public void RenderIconToPicker(GameObject gameObject, Color color)
        {
            if (gameObject is GameObject3D)
            {
                GameObject3D gameObject3D = (GameObject3D)gameObject;
                if (gameObject3D.Light != null || gameObject3D.Camera != null)
                {
                    // Component's screen position.
                    Vector3 screenPositions = EngineManager.Device.Viewport.Project(gameObject3D.Transform.Position, projectionMatrix, viewMatrix, Matrix.Identity);
                    // Center the icon.
                    screenPositions.X -= 16;
                    screenPositions.Y -= 16;
                    // Draw.
                    LineManager.DrawSolid2DPlane(new Rectangle((int)screenPositions.X, (int)screenPositions.Y, 32, 32), color);
                }
            }
        } // RenderIconToPicker
        /// <summary>
        /// Rotation gizmo based in Softimage XSI.
        /// </summary>
        internal RotationGizmo()
        {
            // Create the gizmo parts.
            redLine = new GameObject3D {
                Layer = Layer.GetLayerByNumber(31)
            };
            greenLine = new GameObject3D {
                Layer = Layer.GetLayerByNumber(31)
            };
            blueLine = new GameObject3D {
                Layer = Layer.GetLayerByNumber(31)
            };
            redLine.AddComponent <LineRenderer>();
            greenLine.AddComponent <LineRenderer>();
            blueLine.AddComponent <LineRenderer>();
            const int numberOfPoints = 50;
            const int radius         = 1;

            redLine.LineRenderer.Vertices      = new VertexPositionColor[numberOfPoints * 2];
            greenLine.LineRenderer.Vertices    = new VertexPositionColor[numberOfPoints * 2];
            blueLine.LineRenderer.Vertices     = new VertexPositionColor[numberOfPoints * 2];
            redLine.LineRenderer.Vertices[0]   = new VertexPositionColor(Vector3.Transform(new Vector3((float)Math.Sin(0), (float)Math.Cos(0), 0), Matrix.Identity), Color.Red);
            greenLine.LineRenderer.Vertices[0] = new VertexPositionColor(Vector3.Transform(new Vector3((float)Math.Sin(0), (float)Math.Cos(0), 0), Matrix.Identity), new Color(0, 1f, 0));
            blueLine.LineRenderer.Vertices[0]  = new VertexPositionColor(Vector3.Transform(new Vector3((float)Math.Sin(0), (float)Math.Cos(0), 0), Matrix.Identity), Color.Blue);
            for (int i = 1; i < numberOfPoints; i++)
            {
                float angle = i * (3.1416f * 2 / numberOfPoints);
                float x     = (float)Math.Sin(angle) * radius;
                float y     = (float)Math.Cos(angle) * radius;
                redLine.LineRenderer.Vertices[i * 2 - 1]   = new VertexPositionColor(Vector3.Transform(new Vector3(x, y, 0), Matrix.Identity), Color.Red);
                greenLine.LineRenderer.Vertices[i * 2 - 1] = new VertexPositionColor(Vector3.Transform(new Vector3(x, y, 0), Matrix.Identity), new Color(0, 1f, 0));
                blueLine.LineRenderer.Vertices[i * 2 - 1]  = new VertexPositionColor(Vector3.Transform(new Vector3(x, y, 0), Matrix.Identity), Color.Blue);
                redLine.LineRenderer.Vertices[i * 2]       = new VertexPositionColor(Vector3.Transform(new Vector3(x, y, 0), Matrix.Identity), Color.Red);
                greenLine.LineRenderer.Vertices[i * 2]     = new VertexPositionColor(Vector3.Transform(new Vector3(x, y, 0), Matrix.Identity), new Color(0, 1f, 0));
                blueLine.LineRenderer.Vertices[i * 2]      = new VertexPositionColor(Vector3.Transform(new Vector3(x, y, 0), Matrix.Identity), Color.Blue);
            }
            redLine.LineRenderer.Vertices[numberOfPoints * 2 - 1]   = new VertexPositionColor(Vector3.Transform(new Vector3((float)Math.Sin(0), (float)Math.Cos(0), 0), Matrix.Identity), Color.Red);
            greenLine.LineRenderer.Vertices[numberOfPoints * 2 - 1] = new VertexPositionColor(Vector3.Transform(new Vector3((float)Math.Sin(0), (float)Math.Cos(0), 0), Matrix.Identity), new Color(0, 1f, 0));
            blueLine.LineRenderer.Vertices[numberOfPoints * 2 - 1]  = new VertexPositionColor(Vector3.Transform(new Vector3((float)Math.Sin(0), (float)Math.Cos(0), 0), Matrix.Identity), Color.Blue);

            redLine.LineRenderer.Enabled   = false;
            greenLine.LineRenderer.Enabled = false;
            blueLine.LineRenderer.Enabled  = false;
        } // RotationGizmo
        } // Update

        #endregion

        #region Frame Objects

        /// <summary>
        /// Adjust the look at position and distance to frame the selected objects.
        /// The orientation is not afected.
        /// </summary>
        public void FrameObjects(List <GameObject> gameObjects)
        {
            BoundingSphere?frameBoundingSphere = null;  // Garbage is not an issue in the editor.

            foreach (var gameObject in gameObjects)
            {
                if (EditorManager.IsGameObjectVisible(gameObject) && gameObject is GameObject3D)
                {
                    GameObject3D gameObject3D = (GameObject3D)gameObject;
                    if (gameObject3D.ModelRenderer != null && gameObject3D.ModelRenderer.Enabled)
                    {
                        if (frameBoundingSphere == null)
                        {
                            frameBoundingSphere = gameObject3D.ModelRenderer.BoundingSphere;
                        }
                        else
                        {
                            frameBoundingSphere = BoundingSphere.CreateMerged(frameBoundingSphere.Value, gameObject3D.ModelRenderer.BoundingSphere);
                        }
                    }
                    // The rest of objects
                    else
                    {
                        if (frameBoundingSphere == null)
                        {
                            frameBoundingSphere = new BoundingSphere(gameObject3D.Transform.Position, 0);
                        }
                        else
                        {
                            frameBoundingSphere = BoundingSphere.CreateMerged(frameBoundingSphere.Value, new BoundingSphere(gameObject3D.Transform.Position, 0));
                        }
                    }
                }
            }
            // If at least one object is there...
            if (frameBoundingSphere != null)
            {
                editorCameraScript.LookAtPosition = frameBoundingSphere.Value.Center;
                editorCameraScript.Distance       = frameBoundingSphere.Value.Radius * 3 * Camera.AspectRatio + Camera.NearPlane + 0.1f;
            }
        } // FrameObjects
Beispiel #20
0
        } // RenderObjectToPicker

        /// <summary>
        /// Render Object To Picker.
        /// </summary>
        public void RenderObjectToPicker(GameObject gameObject, Color color)
        {
            if (gameObject is GameObject3D)
            {
                GameObject3D gameObject3D = (GameObject3D)gameObject;
                // Model Renderer)
                if (gameObject3D.ModelFilter != null && gameObject3D.ModelFilter.Model != null)
                {
                    constantShader.Resource.Parameters["diffuseColor"].SetValue(new Vector3(color.R / 255f, color.G / 255f, color.B / 255f));
                    constantShader.Resource.Parameters["worldViewProj"].SetValue(gameObject3D.Transform.WorldMatrix * viewMatrix * projectionMatrix);
                    constantShader.Resource.CurrentTechnique.Passes[0].Apply();
                    gameObject3D.ModelFilter.Model.Render();
                }
                // Lines
                else if (gameObject3D.LineRenderer != null)
                {
                    LineManager.Begin3D(gameObject3D.LineRenderer.PrimitiveType, viewMatrix, projectionMatrix);
                    for (int j = 0; j < gameObject3D.LineRenderer.Vertices.Length; j++)
                    {
                        LineManager.AddVertex(Vector3.Transform(gameObject3D.LineRenderer.Vertices[j].Position, gameObject3D.Transform.WorldMatrix), color);
                    }
                    LineManager.End();
                }
            }
            else
            {
                GameObject2D gameObject2D = (GameObject2D)gameObject;
                if (gameObject2D.LineRenderer != null)
                {
                    LineManager.Begin2D(gameObject2D.LineRenderer.PrimitiveType);
                    for (int j = 0; j < gameObject2D.LineRenderer.Vertices.Length; j++)
                    {
                        LineManager.AddVertex(Vector3.Transform(gameObject2D.LineRenderer.Vertices[j].Position, gameObject2D.Transform.WorldMatrix), color);
                    }
                    LineManager.End();
                }
            }
        } // RenderObjectToPicker
        } // NormalizedViewport

        #endregion

        #region Constructor

        /// <summary>
        /// Editor Viewport.
        /// </summary>
        public EditorViewport(RectangleF normalizedViewport, ViewportMode mode)
        {
            #region Controls

            viewportControl = new Container
            {
                Parent   = MainWindow.ViewportsSpace,
                Anchor   = Anchors.Left | Anchors.Top,
                CanFocus = false,
            };
            // Stores the normalized viewport to adapt to screen size changes.
            NormalizedViewport = normalizedViewport;

            ToolBarPanel topPanel = new ToolBarPanel {
                Width = viewportControl.Width
            };
            viewportControl.ToolBarPanel = topPanel;
            ToolBar toolBarTopPanel = new ToolBar
            {
                Parent  = topPanel,
                Movable = true,
                FullRow = true,
            };
            var modeComboBox = new ComboBox
            {
                Parent = topPanel,
                Width  = 200,
                Top    = 2,
            };
            modeComboBox.Items.AddRange(new [] { "Perspective", "Top", "Front", "Right", "Game" });
            modeComboBox.ItemIndex         = 0;
            modeComboBox.ItemIndexChanged += delegate
            {
                switch (modeComboBox.ItemIndex)
                {
                case 0: Mode = ViewportMode.Perspective; break;

                case 1: Mode = ViewportMode.Top; break;

                case 2: Mode = ViewportMode.Front; break;

                case 3: Mode = ViewportMode.Right; break;

                case 4: Mode = ViewportMode.Game; break;
                }
            };
            modeComboBox.Draw += delegate
            {
                if (modeComboBox.ListBoxVisible)
                {
                    return;
                }
                switch (Mode)
                {
                case ViewportMode.Perspective: modeComboBox.ItemIndex = 0; break;

                case ViewportMode.Top: modeComboBox.ItemIndex = 1; break;

                case ViewportMode.Front: modeComboBox.ItemIndex = 2; break;

                case ViewportMode.Right: modeComboBox.ItemIndex = 3; break;

                case ViewportMode.Game: modeComboBox.ItemIndex = 4; break;
                }
            };

            #endregion

            #region Cameras

            // Assets
            ambientLight = new AmbientLight {
                Name = "Editor Camara Ambient Light ", Color = Color.White, Intensity = 5f
            };
            postProcess = new PostProcess   {
                Name = "Editor Camera Post Process"
            };
            postProcess.ToneMapping.ToneMappingFunction = ToneMapping.ToneMappingFunctionEnumerate.FilmicALU;
            postProcess.Bloom.Enabled = false;

            // Editor Camera
            viewportCamera = new GameObject3D();
            viewportCamera.AddComponent <Camera>();
            viewportCamera.Camera.Enabled        = true;
            viewportCamera.Layer                 = Layer.GetLayerByNumber(31);
            viewportCamera.Camera.RenderingOrder = int.MinValue;
            editorCameraScript            = (ScriptEditorCamera)viewportCamera.AddComponent <ScriptEditorCamera>();
            editorCameraScript.Mode       = ScriptEditorCamera.ModeType.Maya;
            editorCameraScript.ClientArea = viewportControl.ClientArea;
            // Camera to render the gizmos and other editor elements.
            // This is done because the gizmos need to be in front of everything and I can't clear the ZBuffer wherever I want.
            helperCamera = new GameObject3D();
            helperCamera.AddComponent <Camera>();
            helperCamera.Camera.Enabled     = true;
            helperCamera.Camera.CullingMask = Layer.GetLayerByNumber(31).Mask; // The editor layer.
            helperCamera.Camera.ClearColor  = Color.Transparent;
            helperCamera.Layer = Layer.GetLayerByNumber(31);
            // Set the viewport camara as master of the gizmo camera.
            helperCamera.Camera.MasterCamera = viewportCamera.Camera;

            #endregion

            // Set default camera transformation in each mode.
            Mode = ViewportMode.Perspective;
            Reset();
            Mode = ViewportMode.Top;
            Reset();
            Mode = ViewportMode.Front;
            Reset();
            Mode = ViewportMode.Right;
            Reset();

            // Set current mode.
            Mode = mode;

            // Adjust viewport dimentions and render target size when the size changes.
            Screen.ScreenSizeChanged += OnScreenSizeChanged;
        } // EditorViewport
        /// <summary>
        /// Load the resources.
        /// </summary>
        /// <remarks>Remember to call the base implementation of this method.</remarks>
        protected override void LoadContent()
        {
            mainSceneExecuting = true;

            #region Setup Input Controls

            // Create the virtual buttons to control the scene selection.
            new Button
            {
                Name           = "Next Scene",
                ButtonBehavior = Button.ButtonBehaviors.DigitalInput,
                KeyButton      = new KeyButton(Keys.Right),
            };
            new Button
            {
                Name           = "Next Scene",
                ButtonBehavior = Button.ButtonBehaviors.DigitalInput,
                KeyButton      = new KeyButton(Buttons.DPadRight),
            };
            new Button
            {
                Name           = "Next Scene",
                ButtonBehavior = Button.ButtonBehaviors.AnalogInput,
                AnalogAxis     = AnalogAxes.LeftStickX,
            };
            new Button
            {
                Name           = "Previous Scene",
                ButtonBehavior = Button.ButtonBehaviors.DigitalInput,
                KeyButton      = new KeyButton(Keys.Left),
            };
            new Button
            {
                Name           = "Previous Scene",
                ButtonBehavior = Button.ButtonBehaviors.DigitalInput,
                KeyButton      = new KeyButton(Buttons.DPadLeft),
            };
            new Button
            {
                Name           = "Previous Scene",
                ButtonBehavior = Button.ButtonBehaviors.AnalogInput,
                AnalogAxis     = AnalogAxes.LeftStickX,
                Invert         = true,
            };
            new Button
            {
                Name           = "Load Scene",
                ButtonBehavior = Button.ButtonBehaviors.DigitalInput,
                KeyButton      = new KeyButton(Keys.Enter),
            };
            new Button
            {
                Name           = "Load Scene",
                ButtonBehavior = Button.ButtonBehaviors.DigitalInput,
                KeyButton      = new KeyButton(Buttons.A),
            };
            new Button
            {
                Name           = "Back To Menu",
                ButtonBehavior = Button.ButtonBehaviors.DigitalInput,
                KeyButton      = new KeyButton(Keys.Escape),
            };
            new Button
            {
                Name           = "Back To Menu",
                ButtonBehavior = Button.ButtonBehaviors.DigitalInput,
                KeyButton      = new KeyButton(Buttons.Back),
            };
            new Button
            {
                Name           = "Show Statistics",
                ButtonBehavior = Button.ButtonBehaviors.DigitalInput,
                KeyButton      = new KeyButton(Keys.F1),
            };
            new Button
            {
                Name           = "Show Statistics",
                ButtonBehavior = Button.ButtonBehaviors.DigitalInput,
                KeyButton      = new KeyButton(Buttons.Start),
            };

            #endregion

            #region Intro Video

            // Load and play the intro video...
            introVideo = new GameObject2D();
            introVideo.AddComponent <VideoRenderer>();
            introVideo.VideoRenderer.Video = new Video("LogosIntro");

            #endregion

            #region Statistics

            Layer.GetLayerByNumber(26).Name    = "Statistics Layer";
            Layer.CurrentCreationLayer         = Layer.GetLayerByNumber(26);
            Layer.GetLayerByNumber(26).Visible = false;
            statistics = new GameObject2D();
            statistics.AddComponent <ScriptStatisticsDrawer>();

            #endregion

            // This scene will be assigned to this layer.
            Layer.GetLayerByNumber(25).Name = "Examples Main Scene Layer";
            // But we hide it until the video is over.
            Layer.GetLayerByNumber(25).Visible = false;
            // Creates the scene objects in this layer;
            Layer.CurrentCreationLayer = Layer.GetLayerByNumber(25);

            #region 3D Camera

            // Camera
            examplesCamera = new GameObject3D();
            examplesCamera.AddComponent <Camera>();
            examplesCamera.AddComponent <SoundListener>();
            examplesCamera.Camera.RenderTargetSize = Size.FullScreen;
            examplesCamera.Camera.FarPlane         = 100;
            examplesCamera.Camera.NearPlane        = 1f; // Do not place a small value here, you can destroy performance, not just precision.
            examplesCamera.Transform.LookAt(new Vector3(0, 0, 25), Vector3.Zero, Vector3.Up);
            examplesCamera.Camera.ClearColor  = Color.Black;
            examplesCamera.Camera.FieldOfView = 180 / 6f;
            examplesCamera.Camera.PostProcess = new PostProcess();
            examplesCamera.Camera.PostProcess.ToneMapping.AutoExposureEnabled = false;
            examplesCamera.Camera.PostProcess.ToneMapping.LensExposure        = 0f;
            examplesCamera.Camera.PostProcess.ToneMapping.ToneMappingFunction = ToneMapping.ToneMappingFunctionEnumerate.FilmicALU;
            examplesCamera.Camera.PostProcess.MLAA.EdgeDetection = MLAA.EdgeDetectionType.Color;
            examplesCamera.Camera.PostProcess.MLAA.Enabled       = true;
            examplesCamera.Camera.AmbientLight = new AmbientLight
            {
                Color     = new Color(80, 75, 85),
                Intensity = 5f,
            };

            #endregion

            finalEngineLogo = new GameObject3D(new FileModel("XNAFinalEngine"), new BlinnPhong {
                DiffuseColor = new Color(250, 250, 250)
            });
            finalEngineLogo.Transform.Position   = new Vector3(-37, 6, 0);
            finalEngineLogo.Transform.LocalScale = new Vector3(1.3f, 1.3f, 1.3f);

            xnaLogo = new GameObject3D(new FileModel("XNA"), new BlinnPhong {
                DiffuseColor = new Color(250, 120, 0)
            });
            xnaLogo.Transform.Position   = new Vector3(-37, 6, 0);
            xnaLogo.Transform.LocalScale = new Vector3(1.3f, 1.3f, 1.3f);

            examplesLogo = new GameObject3D(new FileModel("Examples"), new BlinnPhong {
                DiffuseColor = new Color(150, 250, 0)
            });
            examplesLogo.Transform.Position   = new Vector3(40, 5.7f, 0);
            examplesLogo.Transform.LocalScale = new Vector3(1f, 1f, 1f);

            selectOneScene = new GameObject3D(new FileModel("SelectOneScene"), new BlinnPhong {
                DiffuseColor = new Color(150, 250, 0)
            });
            selectOneScene.Transform.Position = new Vector3(6, -55, 0);

            loading = new GameObject3D(new FileModel("Loading"), new BlinnPhong {
                DiffuseColor = new Color(150, 150, 150)
            });
            loading.Transform.Position    = new Vector3(-7, -5, 0);
            loading.ModelRenderer.Enabled = false;

            directionalLight = new GameObject3D();
            directionalLight.AddComponent <DirectionalLight>();
            directionalLight.DirectionalLight.Color     = new Color(190, 110, 150);
            directionalLight.DirectionalLight.Intensity = 1.2f;
            directionalLight.Transform.LookAt(new Vector3(0.6f, 0.05f, 0.6f), Vector3.Zero, Vector3.Forward);

            #region Scene Information

            exampleImage = new GameObject2D[4];
            exampleTitle = new GameObject2D[4];
            exampleText  = new GameObject2D[4];

            #region Warehouse Scene

            exampleImage[0] = new GameObject2D();
            exampleImage[0].AddComponent <HudTexture>();
            exampleImage[0].HudTexture.Texture = new Texture("ExamplesImages\\WarehouseScene");
            exampleImage[0].Transform.Position = new Vector3(75, 250, 0);
            exampleTitle[0] = new GameObject2D();
            exampleTitle[0].AddComponent <HudText>();
            exampleTitle[0].HudText.Text.Append("Warehouse");
            exampleTitle[0].HudText.Font       = new Font("BellGothicTitle");
            exampleTitle[0].Transform.Position = new Vector3(500, 200, 0);
            exampleText[0] = new GameObject2D();
            exampleText[0].AddComponent <HudText>();
            exampleText[0].HudText.Text.Append("This scene shows a Lamborghini Murcielago LP640 in a warehouse.\n\nThe car consists of 430.000 polygons. The scene includes an ambient light with spherical\nharmonic lighting and horizon based ambient occlusion (PC only), one directional light\nwith cascade shadows,two point lights and one spot light with a light mask. The post\nprocessing stage uses tone mapping, morphological antialiasing (MLAA), bloom and film\ngrain. Also a particles system that emits soft tiled particles was placed.\n\nAlmost all the car was modeled by me, with the exception of some interior elements, the\nengine and the rear lights because of my lack of texture experience and time.\n\nMehar Gill (Dog Fight Studios) provides me the warehouse model (originally created\nby igorlmax).\n\nThe reflections do not match the environment. I plan to address this soon.");
            exampleText[0].HudText.Font       = new Font("BellGothicText");
            exampleText[0].Transform.Position = new Vector3(500, 250, 0);

            #endregion

            #region Physics Scene

            exampleImage[1] = new GameObject2D();
            exampleImage[1].AddComponent <HudTexture>();
            exampleImage[1].HudTexture.Texture = new Texture("ExamplesImages\\PhysicsScene");
            exampleImage[1].Transform.Position = new Vector3(75, 250, 0);
            exampleTitle[1] = new GameObject2D();
            exampleTitle[1].AddComponent <HudText>();
            exampleTitle[1].HudText.Text.Append("Physics Demonstration");
            exampleTitle[1].HudText.Font       = new Font("BellGothicTitle");
            exampleTitle[1].Transform.Position = new Vector3(500, 200, 0);
            exampleText[1] = new GameObject2D();
            exampleText[1].AddComponent <HudText>();
            exampleText[1].HudText.Text.Append("Bepu physics library was integrated on the engine through a simple interface that hides the\ncommunication between the physic and graphic world.\n\nThis example shows the interaction between dynamic and kinematic rigid bodies and static\nmeshes. This example also loads a non-centered sphere, the interface implemented detects\nthe offset between the center of mass of the object and the model space center and match\nboth representations without user action.\n\nGarbage generation could be avoided if the initial pools are configured correctly and no other\nmemory allocation should occur. Bepu physics 1.2 has a bug in witch garbage is generated,\nto avoid this we use the developement version of Bepu that fix this bug.\n\n");
            exampleText[1].HudText.Font       = new Font("BellGothicText");
            exampleText[1].Transform.Position = new Vector3(500, 250, 0);

            #endregion

            #region Animation Scene

            exampleImage[2] = new GameObject2D();
            exampleImage[2].AddComponent <HudTexture>();
            exampleImage[2].HudTexture.Texture = new Texture("ExamplesImages\\AnimationScene");
            exampleImage[2].Transform.Position = new Vector3(75, 250, 0);
            exampleTitle[2] = new GameObject2D();
            exampleTitle[2].AddComponent <HudText>();
            exampleTitle[2].HudText.Text.Append("Animations");
            exampleTitle[2].HudText.Font       = new Font("BellGothicTitle");
            exampleTitle[2].Transform.Position = new Vector3(500, 200, 0);
            exampleText[2] = new GameObject2D();
            exampleText[2].AddComponent <HudText>();
            exampleText[2].HudText.Text.Append("This is the simple scene used to test the animation system. It includes three animations:\nwalk, run and shoot. Animation blending is performed in the transition between different\nactions.\n\nDog Fight Studios have shared with us three of their test animations resources. However\nthe animations should not be used in commercial projects.");
            exampleText[2].HudText.Font       = new Font("BellGothicText");
            exampleText[2].Transform.Position = new Vector3(500, 250, 0);

            #endregion

            #region Hellow World Scene

            exampleImage[3] = new GameObject2D();
            exampleImage[3].AddComponent <HudTexture>();
            exampleImage[3].HudTexture.Texture = new Texture("ExamplesImages\\HelloWorldScene");
            exampleImage[3].Transform.Position = new Vector3(75, 250, 0);
            exampleTitle[3] = new GameObject2D();
            exampleTitle[3].AddComponent <HudText>();
            exampleTitle[3].HudText.Text.Append("Hello World");
            exampleTitle[3].HudText.Font       = new Font("BellGothicTitle");
            exampleTitle[3].Transform.Position = new Vector3(500, 200, 0);
            exampleText[3] = new GameObject2D();
            exampleText[3].AddComponent <HudText>();
            exampleText[3].HudText.Text.Append("This is from the documentation's tutorial that shows you how to create a simple scene\nso that you can understand the basic mechanism involved in the creation of a game world.");
            exampleText[3].HudText.Font       = new Font("BellGothicText");
            exampleText[3].Transform.Position = new Vector3(500, 250, 0);

            #endregion

            #region Editor Scene

            /*#if !Xbox
             *  exampleImage[3] = new GameObject2D();
             *  exampleImage[3].AddComponent<HudTexture>();
             *  exampleImage[3].HudTexture.Texture = new Texture("ExamplesImages\\EditorScene");
             *  exampleImage[3].Transform.Position = new Vector3(75, 250, 0);
             *  exampleTitle[3] = new GameObject2D();
             *  exampleTitle[3].AddComponent<HudText>();
             *  exampleTitle[3].HudText.Text.Append("Editor");
             *  exampleTitle[3].HudText.Font = new Font("BellGothicTitle");
             *  exampleTitle[3].Transform.Position = new Vector3(500, 200, 0);
             *  exampleText[3] = new GameObject2D();
             *  exampleText[3].AddComponent<HudText>();
             *  exampleText[3].HudText.Text.Append("Unfortunately the editor is not finished, but most of the key elements are already done and it is\nvery easy to create new windows because everything is parameterized (thanks in part to .NET\nreflection) and its internal code is very clean.\n\nAt the moment it is possible to transform objects in global and local space, configure materials,\nlights, shadows, cameras and the post processing stage. You can also see the scene from\northographic views and perform undo and redo operations over almost all editor commands.\n\nIn the Editor Shortcuts section of the CodePlex documentation there is a list of all useful\nkeyboard shortcuts.");
             *  exampleText[3].HudText.Font = new Font("BellGothicText");
             *  exampleText[3].Transform.Position = new Vector3(500, 250, 0);
             #endif*/

            #endregion

            #endregion

            #region Legend

            demoLegend = new GameObject2D();
            var legend = (HudText)demoLegend.AddComponent <HudText>();
            legend.Color = new Color(0.5f, 0.5f, 0.5f, 1f);
            #if XBOX
            legend.Text.Append("Start to show the statistics\n");
            legend.Text.Append("Back to comeback to this menu");
            #else
            legend.Text.Append("Start or F1 to show the statistics\n");
            legend.Text.Append("Back or Escape to comeback to this menu");
            #endif

            #endregion

            // Set Default Layer.
            Layer.CurrentCreationLayer = Layer.GetLayerByNumber(0);

            MusicManager.LoadAllSong(true);
            MusicManager.Play(1, true);
        } // Load
Beispiel #23
0
        } // CreateSaveData

        #endregion

        #region Load Save Data

        /// <summary>
        /// Create the structure that will be serialized.
        /// It stores content managers, assets and game objects.
        /// </summary>
        private static void LoadSaveData(SceneData sceneData)
        {
            // Generate content managers data.
            foreach (var contentManagerData in sceneData.ContentManagersData)
            {
                // Create Content Manager
                AssetContentManager contentManager = new AssetContentManager { Name = contentManagerData.Name };
                foreach (var assetId in contentManagerData.AssetsId)
                {
                    // The not resourced assets are already created and can change the content manager without recreation.
                    foreach (var assetsWithoutResourceData in sceneData.AssetsWithoutResourceData)
                    {
                        if (assetId == assetsWithoutResourceData.Id)
                        {
                            assetsWithoutResourceData.Asset.ChangeContentManager(contentManager);
                            break;
                        }
                    }
                }
            }
            // Recreate game objects (and the transform component)
            foreach (var gameObjectData in sceneData.GameObjectData)
            {
                GameObject gameObject;
                if (gameObjectData.is3D)
                {
                    gameObject = new GameObject3D();
                    ((GameObject3D)gameObject).Transform.LocalMatrix = gameObjectData.LocalMatrix;
                }
                else
                {
                    gameObject = new GameObject2D();
                    ((GameObject2D)gameObject).Transform.LocalMatrix = gameObjectData.LocalMatrix;
                }
                gameObject.Name = gameObjectData.Name;
                gameObject.Layer = Layer.GetLayerByNumber(gameObjectData.LayerNumber);
                gameObject.Active = gameObjectData.Active;
                gameObjectData.NewGameObject = gameObject; // Use to recreate the hierarchy.
                foreach (var componentData in gameObjectData.ComponentData)
                {
                    // Create the component.
                    // Reflection is needed because we can't know the type in compiler time and I don't want to use an inflexible big switch sentence.
                    gameObject.GetType().GetMethod("AddComponent").MakeGenericMethod(componentData.Component.GetType()).Invoke(gameObject, null);
                    // Each serializable property will be copy to the new component.
                    PropertyInfo componentProperty = gameObject.GetType().GetProperty(componentData.Component.GetType().Name);
                    List<PropertyInfo> propertiesName = GetSerializableProperties(componentData.Component.GetType());
                    for (int i = 0; i < propertiesName.Count; i++)
                    {
                        var property = propertiesName[i];
                        Component component = (Component) componentProperty.GetValue(gameObject, null);
                        Object value = property.GetValue(componentData.Component, null);
                        property.SetValue(component, value, null);
                    }
                }
            }
            // Recreate hierarchy.
            foreach (var gameObjectData in sceneData.GameObjectData)
            {
                // If it is has a parent.
                if (gameObjectData.ParentId != long.MaxValue)
                {
                    // Search all loaded game objects
                    foreach (var searchedGameObjectData in sceneData.GameObjectData)
                    {
                        if (searchedGameObjectData.Id == gameObjectData.ParentId)
                        {
                            if (gameObjectData.is3D)
                                ((GameObject3D)gameObjectData.NewGameObject).Parent = (GameObject3D)searchedGameObjectData.NewGameObject;
                            else
                                ((GameObject2D)gameObjectData.NewGameObject).Parent = (GameObject2D)searchedGameObjectData.NewGameObject;
                            break;
                        }
                    }
                }
            }
        } // CreateSaveData
        /// <summary>
        /// Translation gizmo based in Softimage XSI.
        /// </summary>
        internal TranslationGizmo()
        {
            if (constantShader == null)
            {
                constantShader = new Shader("Materials\\PickerConstant");
            }
            // Create the gizmo parts.
            Cone cone = new Cone(0.1f, 0.2f, 10);

            redCone = new GameObject3D(cone, new Constant())
            {
                Layer = Layer.GetLayerByNumber(31)
            };
            greenCone = new GameObject3D(cone, new Constant())
            {
                Layer = Layer.GetLayerByNumber(31)
            };
            blueCone = new GameObject3D(cone, new Constant())
            {
                Layer = Layer.GetLayerByNumber(31)
            };
            lines = new GameObject3D {
                Layer = Layer.GetLayerByNumber(31),
            };
            lines.AddComponent <LineRenderer>();
            lines.LineRenderer.Vertices = new VertexPositionColor[6];
            vertices[0]   = new Vector3(0, 0, 0);
            vertices[1]   = new Vector3(1, 0, 0);
            vertices[2]   = new Vector3(0, 1, 0);
            vertices[3]   = new Vector3(0, 0, 1);
            vertices[4]   = new Vector3(1, 1, 0);
            vertices[5]   = new Vector3(0, 1, 1);
            vertices[6]   = new Vector3(1, 0, 1);
            planeRedGreen = new GameObject3D(new Plane(vertices[2], vertices[0], vertices[4], vertices[1]), new Constant {
                DiffuseColor = new Color(255, 255, 0)
            })
            {
                Layer = Layer.GetLayerByNumber(31),
            };
            planeGreenBlue = new GameObject3D(new Plane(vertices[5], vertices[3], vertices[2], vertices[0]), new Constant {
                DiffuseColor = new Color(0, 255, 255)
            })
            {
                Layer = Layer.GetLayerByNumber(31),
            };
            planeBlueRed = new GameObject3D(new Plane(vertices[0], vertices[3], vertices[1], vertices[6]), new Constant {
                DiffuseColor = new Color(255, 0, 255)
            })
            {
                Layer = Layer.GetLayerByNumber(31),
            };
            planeRedGreenInv = new GameObject3D(new Plane(vertices[4], vertices[1], vertices[2], vertices[0]), new Constant {
                DiffuseColor = new Color(255, 255, 0)
            })
            {
                Layer = Layer.GetLayerByNumber(31),
            };
            planeGreenBlueInv = new GameObject3D(new Plane(vertices[2], vertices[0], vertices[5], vertices[3]), new Constant {
                DiffuseColor = new Color(0, 255, 255)
            })
            {
                Layer = Layer.GetLayerByNumber(31),
            };
            planeBlueRedInv = new GameObject3D(new Plane(vertices[1], vertices[6], vertices[0], vertices[3]), new Constant {
                DiffuseColor = new Color(255, 0, 255)
            })
            {
                Layer = Layer.GetLayerByNumber(31),
            };
            planeAll = new GameObject2D {
                Layer = Layer.GetLayerByNumber(31),
            };
            planeAll.AddComponent <LineRenderer>();
            planeAll.LineRenderer.Vertices = new VertexPositionColor[8];

            redCone.ModelRenderer.Enabled           = false;
            greenCone.ModelRenderer.Enabled         = false;
            blueCone.ModelRenderer.Enabled          = false;
            lines.LineRenderer.Enabled              = false;
            planeRedGreen.ModelRenderer.Enabled     = false;
            planeGreenBlue.ModelRenderer.Enabled    = false;
            planeBlueRed.ModelRenderer.Enabled      = false;
            planeRedGreenInv.ModelRenderer.Enabled  = false;
            planeGreenBlueInv.ModelRenderer.Enabled = false;
            planeBlueRedInv.ModelRenderer.Enabled   = false;
            planeAll.LineRenderer.Enabled           = false;
        } // TranslationGizmo
        } // RenderGizmoForPicker

        #endregion

        #region Render Gizmo

        /// <summary>
        /// Render Gizmo.
        /// </summary>
        public void RenderGizmo(GameObject3D gizmoCamera, Control clientArea, EditorViewport.ViewportMode mode)
        {
            #region Find Color

            Color redColor   = Color.Red;
            Color greenColor = new Color(0, 1f, 0);
            Color blueColor  = Color.Blue;

            // If the manipulation is uniform then the axis are not yellow.
            if (!redAxisSelected || !greenAxisSelected || !blueAxisSelected)
            {
                if (redAxisSelected)
                {
                    redColor = Color.Yellow;
                }
                if (greenAxisSelected)
                {
                    greenColor = Color.Yellow;
                }
                if (blueAxisSelected)
                {
                    blueColor = Color.Yellow;
                }
            }

            if (mode == EditorViewport.ViewportMode.Front)
            {
                blueColor = Color.Transparent;
            }
            if (mode == EditorViewport.ViewportMode.Top)
            {
                greenColor = Color.Transparent;
            }
            if (mode == EditorViewport.ViewportMode.Right)
            {
                redColor = Color.Transparent;
            }

            #endregion

            // Calculate the center, scale and orientation of the gizmo.
            Vector3    center;
            Quaternion orientation;
            float      scale;
            GizmoScaleCenterOrientation(selectedObject, gizmoCamera, out scale, out center, out orientation);

            // Calculate the gizmo matrix.
            Matrix transformationMatrix = Matrix.CreateScale(scale);
            transformationMatrix *= Matrix.CreateFromQuaternion(orientation);
            transformationMatrix *= Matrix.CreateTranslation(center);

            // This are the axis line's vertex
            vertices[0] = Vector3.Transform(new Vector3(0, 0, 0), transformationMatrix);
            vertices[1] = Vector3.Transform(new Vector3(1, 0, 0), transformationMatrix);
            vertices[2] = Vector3.Transform(new Vector3(0, 1, 0), transformationMatrix);
            vertices[3] = Vector3.Transform(new Vector3(0, 0, 1), transformationMatrix);

            // The plane used to select all axis.
            Color planeColor;
            if (redAxisSelected && greenAxisSelected && blueAxisSelected)
            {
                planeColor = Color.Yellow;
            }
            else
            {
                planeColor = Color.Gray;
            }

            EngineManager.Device.Viewport = new Viewport(gizmoCamera.Camera.Viewport.X + clientArea.ControlLeftAbsoluteCoordinate,
                                                         gizmoCamera.Camera.Viewport.Y + clientArea.ControlTopAbsoluteCoordinate,
                                                         gizmoCamera.Camera.Viewport.Width, gizmoCamera.Camera.Viewport.Height);
            Vector3 screenPositions = EngineManager.Device.Viewport.Project(vertices[0], gizmoCamera.Camera.ProjectionMatrix, gizmoCamera.Camera.ViewMatrix, Matrix.Identity);
            planeAll.LineRenderer.Vertices[0] = new VertexPositionColor(new Vector3((int)screenPositions.X - RegionSize / 2, (int)screenPositions.Y - RegionSize / 2, 0), planeColor);
            planeAll.LineRenderer.Vertices[1] = new VertexPositionColor(new Vector3((int)screenPositions.X + RegionSize / 2, (int)screenPositions.Y - RegionSize / 2, 0), planeColor);
            planeAll.LineRenderer.Vertices[2] = new VertexPositionColor(new Vector3((int)screenPositions.X + RegionSize / 2, (int)screenPositions.Y - RegionSize / 2, 0), planeColor);
            planeAll.LineRenderer.Vertices[3] = new VertexPositionColor(new Vector3((int)screenPositions.X + RegionSize / 2, (int)screenPositions.Y + RegionSize / 2, 0), planeColor);
            planeAll.LineRenderer.Vertices[4] = new VertexPositionColor(new Vector3((int)screenPositions.X + RegionSize / 2, (int)screenPositions.Y + RegionSize / 2, 0), planeColor);
            planeAll.LineRenderer.Vertices[5] = new VertexPositionColor(new Vector3((int)screenPositions.X - RegionSize / 2, (int)screenPositions.Y + RegionSize / 2, 0), planeColor);
            planeAll.LineRenderer.Vertices[6] = new VertexPositionColor(new Vector3((int)screenPositions.X - RegionSize / 2, (int)screenPositions.Y + RegionSize / 2, 0), planeColor);
            planeAll.LineRenderer.Vertices[7] = new VertexPositionColor(new Vector3((int)screenPositions.X - RegionSize / 2, (int)screenPositions.Y - RegionSize / 2, 0), planeColor);
            LineManager.Begin2D(planeAll.LineRenderer.PrimitiveType);
            for (int j = 0; j < planeAll.LineRenderer.Vertices.Length; j++)
            {
                LineManager.AddVertex(planeAll.LineRenderer.Vertices[j].Position, planeAll.LineRenderer.Vertices[j].Color);
            }
            LineManager.End();

            // Update Axis Lines
            lines.LineRenderer.Vertices[0] = new VertexPositionColor(vertices[0], redColor);
            lines.LineRenderer.Vertices[1] = new VertexPositionColor(vertices[1], redColor);
            lines.LineRenderer.Vertices[2] = new VertexPositionColor(vertices[0], greenColor);
            lines.LineRenderer.Vertices[3] = new VertexPositionColor(vertices[2], greenColor);
            lines.LineRenderer.Vertices[4] = new VertexPositionColor(vertices[0], blueColor);
            lines.LineRenderer.Vertices[5] = new VertexPositionColor(vertices[3], blueColor);
            LineManager.Begin3D(lines.LineRenderer.PrimitiveType, gizmoCamera.Camera.ViewMatrix, gizmoCamera.Camera.ProjectionMatrix);
            for (int j = 0; j < lines.LineRenderer.Vertices.Length; j++)
            {
                LineManager.AddVertex(lines.LineRenderer.Vertices[j].Position, lines.LineRenderer.Vertices[j].Color);
            }
            LineManager.End();

            // Update Cones
            redCone.Transform.LocalMatrix   = Matrix.Identity;
            redCone.Transform.LocalPosition = new Vector3(1, 0, 0);
            redCone.Transform.Rotate(new Vector3(0, 0, -90));
            redCone.Transform.LocalMatrix = redCone.Transform.LocalMatrix * transformationMatrix;
            constantShader.Resource.Parameters["diffuseColor"].SetValue(new Vector3(redColor.R / 255f, redColor.G / 255f, redColor.B / 255f));
            constantShader.Resource.Parameters["worldViewProj"].SetValue(redCone.Transform.WorldMatrix * gizmoCamera.Camera.ViewMatrix * gizmoCamera.Camera.ProjectionMatrix);
            constantShader.Resource.CurrentTechnique.Passes[0].Apply();
            redCone.ModelFilter.Model.Render();

            greenCone.Transform.LocalMatrix   = Matrix.Identity;
            greenCone.Transform.LocalPosition = new Vector3(0, 1, 0);
            greenCone.Transform.LocalMatrix   = greenCone.Transform.LocalMatrix * transformationMatrix;
            constantShader.Resource.Parameters["diffuseColor"].SetValue(new Vector3(greenColor.R / 255f, greenColor.G / 255f, greenColor.B / 255f));
            constantShader.Resource.Parameters["worldViewProj"].SetValue(greenCone.Transform.WorldMatrix * gizmoCamera.Camera.ViewMatrix * gizmoCamera.Camera.ProjectionMatrix);
            constantShader.Resource.CurrentTechnique.Passes[0].Apply();
            greenCone.ModelFilter.Model.Render();

            blueCone.Transform.LocalMatrix   = Matrix.Identity;
            blueCone.Transform.LocalPosition = new Vector3(0, 0, 1);
            blueCone.Transform.Rotate(new Vector3(90, 0, 0));
            blueCone.Transform.LocalMatrix = blueCone.Transform.LocalMatrix * transformationMatrix;
            constantShader.Resource.Parameters["diffuseColor"].SetValue(new Vector3(blueColor.R / 255f, blueColor.G / 255f, blueColor.B / 255f));
            constantShader.Resource.Parameters["worldViewProj"].SetValue(blueCone.Transform.WorldMatrix * gizmoCamera.Camera.ViewMatrix * gizmoCamera.Camera.ProjectionMatrix);
            constantShader.Resource.CurrentTechnique.Passes[0].Apply();
            blueCone.ModelFilter.Model.Render();

            EngineManager.Device.Viewport = new Viewport(0, 0, Screen.Width, Screen.Height);
        } // UpdateRenderingInformation
        } // Update

        #endregion

        #region Render Gizmo For Picker

        /// <summary>
        /// Render the gizmo to the picker.
        /// </summary>
        private void RenderGizmoForPicker(GameObject3D gizmoCamera)
        {
            // Calculate the center, scale and orientation of the gizmo.
            Vector3    center;
            Quaternion orientation;
            float      scale;

            GizmoScaleCenterOrientation(selectedObject, gizmoCamera, out scale, out center, out orientation);

            // Calculate the gizmo matrix.
            Matrix transformationMatrix = Matrix.CreateScale(scale);

            transformationMatrix *= Matrix.CreateFromQuaternion(orientation);
            transformationMatrix *= Matrix.CreateTranslation(center);

            vertices[0] = Vector3.Transform(new Vector3(0, 0, 0), transformationMatrix);
            vertices[1] = Vector3.Transform(new Vector3(1, 0, 0), transformationMatrix);
            vertices[2] = Vector3.Transform(new Vector3(0, 1, 0), transformationMatrix);
            vertices[3] = Vector3.Transform(new Vector3(0, 0, 1), transformationMatrix);
            vertices[4] = Vector3.Transform(new Vector3(1, 1, 0), transformationMatrix);
            vertices[5] = Vector3.Transform(new Vector3(0, 1, 1), transformationMatrix);
            vertices[6] = Vector3.Transform(new Vector3(1, 0, 1), transformationMatrix);

            planeRedGreen.Transform.LocalMatrix  = transformationMatrix;
            planeGreenBlue.Transform.LocalMatrix = transformationMatrix;
            planeBlueRed.Transform.LocalMatrix   = transformationMatrix;
            Picker.RenderObjectToPicker(planeRedGreen, new Color(255, 255, 0));
            Picker.RenderObjectToPicker(planeGreenBlue, new Color(0, 255, 255));
            Picker.RenderObjectToPicker(planeBlueRed, new Color(255, 0, 255));
            // Render a second time but from the other side.
            planeRedGreenInv.Transform.LocalMatrix  = transformationMatrix;
            planeGreenBlueInv.Transform.LocalMatrix = transformationMatrix;
            planeBlueRedInv.Transform.LocalMatrix   = transformationMatrix;
            Picker.RenderObjectToPicker(planeRedGreenInv, new Color(255, 255, 0));
            Picker.RenderObjectToPicker(planeGreenBlueInv, new Color(0, 255, 255));
            Picker.RenderObjectToPicker(planeBlueRedInv, new Color(255, 0, 255));

            EngineManager.Device.Clear(ClearOptions.DepthBuffer, Color.White, 1, 0);
            // Update Axis Lines
            lines.LineRenderer.Vertices[0] = new VertexPositionColor(vertices[0], Color.Red);
            lines.LineRenderer.Vertices[1] = new VertexPositionColor(vertices[1], Color.Red);
            lines.LineRenderer.Vertices[2] = new VertexPositionColor(vertices[0], new Color(0, 255, 0));
            lines.LineRenderer.Vertices[3] = new VertexPositionColor(vertices[2], new Color(0, 255, 0));
            lines.LineRenderer.Vertices[4] = new VertexPositionColor(vertices[0], Color.Blue);
            lines.LineRenderer.Vertices[5] = new VertexPositionColor(vertices[3], Color.Blue);
            Picker.RenderObjectToPicker(lines);

            // Update Cones
            redCone.Transform.LocalMatrix   = Matrix.Identity;
            redCone.Transform.LocalPosition = new Vector3(1, 0, 0);
            redCone.Transform.Rotate(new Vector3(0, 0, -90));
            redCone.Transform.LocalMatrix = redCone.Transform.LocalMatrix * transformationMatrix;
            Picker.RenderObjectToPicker(redCone, Color.Red);

            greenCone.Transform.LocalMatrix   = Matrix.Identity;
            greenCone.Transform.LocalPosition = new Vector3(0, 1, 0);
            greenCone.Transform.LocalMatrix   = greenCone.Transform.LocalMatrix * transformationMatrix;
            Picker.RenderObjectToPicker(greenCone, new Color(0, 255, 0)); // Color.Green is not 0, 255, 0

            blueCone.Transform.LocalMatrix   = Matrix.Identity;
            blueCone.Transform.LocalPosition = new Vector3(0, 0, 1);
            blueCone.Transform.Rotate(new Vector3(90, 0, 0));
            blueCone.Transform.LocalMatrix = blueCone.Transform.LocalMatrix * transformationMatrix;
            Picker.RenderObjectToPicker(blueCone, Color.Blue);

            Vector3 screenPositions = EngineManager.Device.Viewport.Project(vertices[0], gizmoCamera.Camera.ProjectionMatrix, gizmoCamera.Camera.ViewMatrix, Matrix.Identity);

            planeAll.LineRenderer.Vertices[0] = new VertexPositionColor(new Vector3((int)screenPositions.X - RegionSize / 2, (int)screenPositions.Y - RegionSize / 2, 0), Color.White);
            planeAll.LineRenderer.Vertices[1] = new VertexPositionColor(new Vector3((int)screenPositions.X + RegionSize / 2, (int)screenPositions.Y - RegionSize / 2, 0), Color.White);
            planeAll.LineRenderer.Vertices[2] = new VertexPositionColor(new Vector3((int)screenPositions.X + RegionSize / 2, (int)screenPositions.Y - RegionSize / 2, 0), Color.White);
            planeAll.LineRenderer.Vertices[3] = new VertexPositionColor(new Vector3((int)screenPositions.X + RegionSize / 2, (int)screenPositions.Y + RegionSize / 2, 0), Color.White);
            planeAll.LineRenderer.Vertices[4] = new VertexPositionColor(new Vector3((int)screenPositions.X + RegionSize / 2, (int)screenPositions.Y + RegionSize / 2, 0), Color.White);
            planeAll.LineRenderer.Vertices[5] = new VertexPositionColor(new Vector3((int)screenPositions.X - RegionSize / 2, (int)screenPositions.Y + RegionSize / 2, 0), Color.White);
            planeAll.LineRenderer.Vertices[6] = new VertexPositionColor(new Vector3((int)screenPositions.X - RegionSize / 2, (int)screenPositions.Y + RegionSize / 2, 0), Color.White);
            planeAll.LineRenderer.Vertices[7] = new VertexPositionColor(new Vector3((int)screenPositions.X - RegionSize / 2, (int)screenPositions.Y - RegionSize / 2, 0), Color.White);
            Picker.RenderObjectToPicker(planeAll, Color.White);
        } // RenderGizmoForPicker
Beispiel #27
0
 public void Destroy(GameObject3D gameObject3D)
 {
     GameObject3DList.Remove(gameObject3D);
 }
Beispiel #28
0
 public void Add(GameObject3D gameObject3D)
 {
     GameObject3DList.Add(gameObject3D);
 }
        } // DisableGizmo

        #endregion

        #region Update

        /// <summary>
        /// Update.
        /// </summary>
        internal void Update(GameObject3D gizmoCamera, Control clientArea)
        {
            #region Active

            if (Active)
            {
                // If the manipulation is over...
                if (!Mouse.LeftButtonPressed)
                {
                    Active = false;
                    // Store new previous matrix.
                    if (selectedObjects[0].Transform.LocalMatrix != selectedObjectsLocalMatrix[0])
                    {
                        using (Transaction.Create())
                        {
                            for (int i = 0; i < selectedObjects.Count; i++)
                            {
                                // I store the action on the undo system. It seems complex. But it is pretty simple actually.
                                Matrix       oldMatrix    = selectedObjectsLocalMatrix[i];
                                Matrix       newMatrix    = selectedObjects[i].Transform.LocalMatrix;
                                GameObject3D gameObject3D = selectedObjects[i];
                                ActionManager.CallMethod(
                                    // Redo
                                    delegate
                                {
                                    gameObject3D.Transform.LocalMatrix = newMatrix;
                                },
                                    // Undo
                                    delegate
                                {
                                    gameObject3D.Transform.LocalMatrix = oldMatrix;
                                });
                            }
                        }
                    }
                }
                // Transformate object...
                else
                {
                    Vector2 transformationAmount;
                    Vector3 translation = Vector3.Zero;
                    // First we have to know how much to move the object in each axis.
                    if (redAxisSelected)
                    {
                        Calculate2DMouseDirection(selectedObject, gizmoCamera, new Vector3(1, 0, 0), out transformationAmount);
                        translation.X  = (Mouse.DeltaX * transformationAmount.X / 100.0f);
                        translation.X += (Mouse.DeltaY * transformationAmount.Y / 100.0f);
                    }
                    if (greenAxisSelected)
                    {
                        Calculate2DMouseDirection(selectedObject, gizmoCamera, new Vector3(0, 1, 0), out transformationAmount);
                        translation.Y  = (Mouse.DeltaX * transformationAmount.X / 100.0f);
                        translation.Y += (Mouse.DeltaY * transformationAmount.Y / 100.0f);
                    }
                    if (blueAxisSelected)
                    {
                        Calculate2DMouseDirection(selectedObject, gizmoCamera, new Vector3(0, 0, 1), out transformationAmount);
                        translation.Z  = (Mouse.DeltaX * transformationAmount.X / 100.0f);
                        translation.Z += (Mouse.DeltaY * transformationAmount.Y / 100.0f);
                    }
                    // Calculate the scale to do transformation proportional to the camera distance to the object.
                    // The calculations are doing once from only one object to move everything at the same rate.
                    Vector3    center;
                    Quaternion orientation;
                    float      scale;
                    GizmoScaleCenterOrientation(selectedObject, gizmoCamera, out scale, out center, out orientation);
                    // Transform each object.
                    foreach (GameObject3D gameObject3D in selectedObjects)
                    {
                        gameObject3D.Transform.Translate(translation * scale, Space == SpaceMode.Local ? Components.Space.Local : Components.Space.World);
                    }
                }
                if (Keyboard.KeyJustPressed(Keys.Escape))
                {
                    Active = false;
                    // Revert transformation to all selected objects.
                    for (int i = 0; i < selectedObjects.Count; i++)
                    {
                        selectedObjects[i].Transform.LocalMatrix = selectedObjectsLocalMatrix[i];
                    }
                }
            }

            #endregion

            #region Inactive

            else
            {
                if (!Keyboard.KeyPressed(Keys.LeftAlt) && !Keyboard.KeyPressed(Keys.RightAlt))
                {
                    // If we press the left mouse button the manipulator activates.
                    if (Mouse.LeftButtonJustPressed)
                    {
                        Active = true;
                        // Stores initial matrix because maybe the user press escape; i.e. maybe he cancel the transformation.
                        for (int i = 0; i < selectedObjects.Count; i++)
                        {
                            selectedObjectsLocalMatrix[i] = selectedObjects[i].Transform.LocalMatrix;
                        }
                    }

                    // Perform a pick around the mouse pointer.

                    Viewport viewport = new Viewport(gizmoCamera.Camera.Viewport.X + clientArea.ControlLeftAbsoluteCoordinate,
                                                     gizmoCamera.Camera.Viewport.Y + clientArea.ControlTopAbsoluteCoordinate,
                                                     gizmoCamera.Camera.Viewport.Width, gizmoCamera.Camera.Viewport.Height);
                    Picker.BeginManualPicking(gizmoCamera.Camera.ViewMatrix, gizmoCamera.Camera.ProjectionMatrix, viewport);
                    RenderGizmoForPicker(gizmoCamera);
                    Color[] colorArray = Picker.EndManualPicking(new Rectangle(Mouse.Position.X - 5, Mouse.Position.Y - 5, RegionSize, RegionSize));

                    #region Find Selected Axis

                    redAxisSelected   = true;
                    greenAxisSelected = true;
                    blueAxisSelected  = true;
                    bool allAxis = false;
                    for (int i = 0; i < RegionSize * RegionSize; i++)
                    {
                        // This is the order of preference:
                        //  1) All axis.
                        //  2) 1 axis.
                        //  3) 2 axis.

                        if (redAxisSelected && greenAxisSelected && blueAxisSelected)
                        {
                            // X and Y axis.
                            if (colorArray[i].R == 255 && colorArray[i].G == 255 && colorArray[i].B == 0)
                            {
                                redAxisSelected   = true;
                                greenAxisSelected = true;
                                blueAxisSelected  = false;
                            }
                            // X and Z  axis.
                            if (colorArray[i].R == 255 && colorArray[i].G == 0 && colorArray[i].B == 255)
                            {
                                redAxisSelected   = true;
                                greenAxisSelected = false;
                                blueAxisSelected  = true;
                            }
                            // Y and Z axis.
                            if (colorArray[i].R == 0 && colorArray[i].G == 255 && colorArray[i].B == 255)
                            {
                                redAxisSelected   = false;
                                greenAxisSelected = true;
                                blueAxisSelected  = true;
                            }
                        }
                        // X axis.
                        if (colorArray[i].R == 255 && colorArray[i].G == 0 && colorArray[i].B == 0)
                        {
                            redAxisSelected   = true;
                            greenAxisSelected = false;
                            blueAxisSelected  = false;
                        }
                        // Y axis.
                        if (colorArray[i].R == 0 && colorArray[i].G == 255 && colorArray[i].B == 0)
                        {
                            redAxisSelected   = false;
                            greenAxisSelected = true;
                            blueAxisSelected  = false;
                        }
                        // Z axis.
                        if (colorArray[i].R == 0 && colorArray[i].G == 0 && colorArray[i].B == 255)
                        {
                            redAxisSelected   = false;
                            greenAxisSelected = false;
                            blueAxisSelected  = true;
                        }
                        // All axis.
                        if (colorArray[i].R == 255 && colorArray[i].G == 255 && colorArray[i].B == 255)
                        {
                            redAxisSelected   = true;
                            greenAxisSelected = true;
                            blueAxisSelected  = true;
                            allAxis           = true;
                            i = RegionSize * RegionSize; // Or break.
                        }
                    }

                    if (redAxisSelected && greenAxisSelected && blueAxisSelected && !allAxis)
                    {
                        redAxisSelected   = false;
                        greenAxisSelected = false;
                        blueAxisSelected  = false;
                    }

                    #endregion
                }
                else
                {
                    redAxisSelected   = false;
                    greenAxisSelected = false;
                    blueAxisSelected  = false;
                }
            }

            #endregion
        } // Update
Beispiel #30
0
        /// <summary>
        /// Load the resources.
        /// </summary>
        protected override void LoadContent()
        {

            #region Camera
            
            camera = new GameObject3D();
            camera.AddComponent<Camera>();
            camera.AddComponent<SoundListener>();
            camera.Camera.RenderTargetSize = Size.FullScreen;
            camera.Camera.FarPlane = 300;
            camera.Camera.NearPlane = 1f; // Do not place a small value here, you can destroy performance, not just precision.
            camera.Transform.LookAt(new Vector3(0, 0, 15), Vector3.Zero, Vector3.Up);
            WarehouseCameraScript script = (WarehouseCameraScript)camera.AddComponent<WarehouseCameraScript>();
            //script.SetPosition(new Vector3(0, 3, 18), new Vector3(0, 1.5f, 2.2f));
            script.SetPosition(new Vector3(10, 3, 18), new Vector3(0, 1.5f, 3.2f));
            camera.Camera.ClearColor = Color.Black;
            camera.Camera.FieldOfView = 180 / 7f;
            camera.Camera.PostProcess = new PostProcess();
            camera.Camera.PostProcess.ToneMapping.AutoExposureEnabled = false;
            camera.Camera.PostProcess.ToneMapping.LensExposure = -0.5f;
            camera.Camera.PostProcess.ToneMapping.ToneMappingFunction = ToneMapping.ToneMappingFunctionEnumerate.FilmicALU;
            camera.Camera.PostProcess.MLAA.EdgeDetection = MLAA.EdgeDetectionType.Color;
            camera.Camera.PostProcess.MLAA.Enabled = true;
            camera.Camera.PostProcess.Bloom.Enabled = true;
            camera.Camera.PostProcess.Bloom.Threshold = 3f;
            camera.Camera.PostProcess.FilmGrain.Enabled = true;
            camera.Camera.PostProcess.FilmGrain.Strength = 0.15f;
            /*camera.Camera.PostProcess.AdjustLevels.Enabled = true;
            camera.Camera.PostProcess.AdjustLevels.InputGamma = 0.9f;
            camera.Camera.PostProcess.AdjustLevels.InputWhite = 0.95f;*/
            camera.Camera.PostProcess.AnamorphicLensFlare.Enabled = false;
            camera.Camera.PostProcess.ColorCorrection.Enabled = true;
            camera.Camera.PostProcess.ColorCorrection.FirstLookupTable = new LookupTable("LookupTableWarehouse"); // A little more red and blue.
            camera.Camera.AmbientLight = new AmbientLight
            {
                SphericalHarmonicLighting = SphericalHarmonicL2.GenerateSphericalHarmonicFromCubeTexture(new TextureCube("FactoryCatwalkRGBM") { IsRgbm = true, RgbmMaxRange = 50, }),
                Color = new Color(10, 10, 10),
                Intensity = 2f,
                AmbientOcclusionStrength = 1.5f
            };
            //camera.Camera.Sky = new Skydome { Texture = new Texture("HotPursuitSkydome") };
            //camera.Camera.Sky = new Skybox { TextureCube = new TextureCube("FactoryCatwalkRGBM") { IsRgbm = true, RgbmMaxRange = 50, } };
            #if !XBOX
                camera.Camera.AmbientLight.AmbientOcclusion = new HorizonBasedAmbientOcclusion
                {
                    NumberSteps = 12,
                    NumberDirections = 12,
                    Radius = 0.003f, // Bigger values produce more cache misses and you don’t want GPU cache misses, trust me.
                    LineAttenuation = 1.0f,
                    Contrast = 1.1f,
                    AngleBias = 0.1f,
                    Quality = HorizonBasedAmbientOcclusion.QualityType.HighQuality,
                    TextureSize = Size.TextureSize.HalfSize,
                };
            #endif

            #region Test Split Screen
            /*
            camera.Camera.NormalizedViewport = new RectangleF(0, 0, 1, 0.5f);
            camera2 = new GameObject3D();
            camera2.AddComponent<Camera>();
            camera2.Camera.MasterCamera = camera.Camera;
            camera2.Camera.ClearColor = Color.Black;
            camera2.Camera.FieldOfView = 180 / 8.0f;
            camera2.Camera.NormalizedViewport = new RectangleF(0, 0.5f, 1, 0.5f);
            camera2.Transform.LookAt(new Vector3(-5, 5, -15), new Vector3(0, 3, 0), Vector3.Up);
            camera2.Camera.AmbientLight = camera.Camera.AmbientLight;
            camera2.Camera.PostProcess = new PostProcess();
            camera2.Camera.PostProcess.ToneMapping.AutoExposureEnabled = true;
            camera2.Camera.PostProcess.ToneMapping.LensExposure = 0.5f;
            camera2.Camera.PostProcess.ToneMapping.ToneMappingFunction = ToneMapping.ToneMappingFunctionEnumerate.FilmicALU;
            camera2.Camera.PostProcess.MLAA.EdgeDetection = MLAA.EdgeDetectionType.Color;
            camera2.Camera.PostProcess.MLAA.Enabled = true;
            camera2.Camera.PostProcess.Bloom.Enabled = true;
            camera2.Camera.PostProcess.Bloom.Threshold = 3f;
            camera2.Camera.PostProcess.FilmGrain.Enabled = true;
            camera2.Camera.PostProcess.FilmGrain.Strength = 0.15f;
            */
            #endregion

            #endregion
            
            #region Models
            
            #if XBOX
                warehouseWalls = new GameObject3D(new FileModel("Warehouse\\WarehouseWallsXbox"),
                                                  new BlinnPhong
                                                      {
                                                          DiffuseTexture = new Texture("Warehouse\\Warehouse-DiffuseXbox"),
                                                          SpecularTexture = new Texture("Warehouse\\Warehouse-SpecularXbox"),
                                                          SpecularIntensity = 3,
                                                          SpecularPower = 30000,
                                                      });
                warehouseRoof  = new GameObject3D(new FileModel("Warehouse\\WarehouseRoofXbox"),  
                                                  new BlinnPhong
                                                      {
                                                          DiffuseTexture = new Texture("Warehouse\\MetalRoof-DiffuseXbox")
                                                      });
                warehouseRoof1 = new GameObject3D(new FileModel("Warehouse\\WarehouseRoof1Xbox"),
                                                  new BlinnPhong
                                                  {
                                                      DiffuseTexture = new Texture("Warehouse\\MetalRoof2-DiffuseXbox")
                                                  });

                warehouseWood = new GameObject3D(new FileModel("Warehouse\\WarehouseWoodXbox"),
                                                 new BlinnPhong
                                                 {
                                                     DiffuseTexture = new Texture("Warehouse\\Wood-DiffuseXbox")
                                                 });

                warehouseWood2 = new GameObject3D(new FileModel("Warehouse\\WarehouseWood2Xbox"),
                                                  new BlinnPhong
                                                  {
                                                      DiffuseTexture = new Texture("Warehouse\\Wood2-DiffuseXbox")
                                                  });

                warehouseBrokenWindow = new GameObject3D(new FileModel("Warehouse\\WarehouseBrokenWindowXbox"),
                                                 new BlinnPhong
                                                 {
                                                     DiffuseTexture = new Texture("Warehouse\\Window-DiffuseXbox")
                                                 });

                warehouseWindow = new GameObject3D(new FileModel("Warehouse\\WarehouseWindowXbox"),
                                                  new BlinnPhong
                                                  {
                                                      DiffuseTexture = new Texture("Warehouse\\Window-DiffuseXbox")
                                                  });
                warehouseGround = new GameObject3D(new FileModel("Warehouse\\WarehouseGroundXbox"),
                                                  new BlinnPhong
                                                  {
                                                      DiffuseTexture = new Texture("Warehouse\\Ground-DiffuseXbox"),
                                                      NormalTexture = new Texture("Warehouse\\Ground-NormalsXbox"),
                                                      SpecularIntensity = 0.7f
                                                  });
            #else
                warehouseWalls = new GameObject3D(new FileModel("Warehouse\\WarehouseWalls"),
                                                  new BlinnPhong
                                                      {
                                                          DiffuseTexture = new Texture("Warehouse\\Warehouse-Diffuse"),
                                                          SpecularTexture = new Texture("Warehouse\\Warehouse-Specular"),
                                                          SpecularIntensity = 3,
                                                          SpecularPower = 30000,
                                                      });
                warehouseRoof  = new GameObject3D(new FileModel("Warehouse\\WarehouseRoof"),  
                                                  new BlinnPhong
                                                      {
                                                          DiffuseTexture = new Texture("Warehouse\\MetalRoof-Diffuse")
                                                      });
                warehouseRoof1 = new GameObject3D(new FileModel("Warehouse\\WarehouseRoof1"),
                                                  new BlinnPhong
                                                  {
                                                      DiffuseTexture = new Texture("Warehouse\\MetalRoof2-Diffuse")
                                                  });

                warehouseWood = new GameObject3D(new FileModel("Warehouse\\WarehouseWood"),
                                                 new BlinnPhong
                                                 {
                                                     DiffuseTexture = new Texture("Warehouse\\Wood-Diffuse")
                                                 });

                warehouseWood2 = new GameObject3D(new FileModel("Warehouse\\WarehouseWood2"),
                                                  new BlinnPhong
                                                  {
                                                      DiffuseTexture = new Texture("Warehouse\\Wood2-Diffuse")
                                                  });

                warehouseBrokenWindow = new GameObject3D(new FileModel("Warehouse\\WarehouseBrokenWindow"),
                                                 new BlinnPhong
                                                 {
                                                     DiffuseTexture = new Texture("Warehouse\\Window-Diffuse")
                                                 });

                warehouseWindow = new GameObject3D(new FileModel("Warehouse\\WarehouseWindow"),
                                                  new BlinnPhong
                                                  {
                                                      DiffuseTexture = new Texture("Warehouse\\Window-Diffuse")
                                                  });
                warehouseGround = new GameObject3D(new FileModel("Warehouse\\WarehouseGround"),
                                                  new BlinnPhong
                                                  {
                                                      DiffuseTexture = new Texture("Warehouse\\Ground-Diffuse"),
                                                      NormalTexture = new Texture("Warehouse\\Ground-Normals"),
                                                      SpecularIntensity = 0.7f
                                                  });
            #endif

            #endregion
            
            #region Shadows and Lights

            Shadow.DistributeShadowCalculationsBetweenFrames = true;
            
            directionalLight = new GameObject3D();
            directionalLight.AddComponent<DirectionalLight>();
            directionalLight.DirectionalLight.Color = new Color(190, 190, 150);
            directionalLight.DirectionalLight.Intensity = 9.2f;
            directionalLight.Transform.LookAt(new Vector3(0.3f, 0.95f, -0.3f), Vector3.Zero, Vector3.Forward);
            DirectionalLight.Sun = directionalLight.DirectionalLight;
            directionalLight.DirectionalLight.Shadow = new CascadedShadow
            {
                Filter = Shadow.FilterType.PcfPosion,
                LightDepthTextureSize = Size.Square512X512,
                ShadowTextureSize = Size.TextureSize.FullSize, // Lower than this could produce artifacts if the light is too intense.
                DepthBias = 0.0025f,
                FarPlaneSplit1 = 15,
                FarPlaneSplit2 = 40,
                FarPlaneSplit3 = 100,
                //FarPlaneSplit4 = 150
            };
            /*directionalLight.DirectionalLight.Shadow = new BasicShadow
            {
                Filter = Shadow.FilterType.PcfPosion,
                LightDepthTextureSize = Size.Square512X512,
                ShadowTextureSize = Size.TextureSize.FullSize, // Lower than this could produce artifacts if the light is to intense.
                DepthBias = 0.0025f,
                Range = 100,
            };*/
            
            pointLight = new GameObject3D();
            pointLight.AddComponent<PointLight>();
            pointLight.PointLight.Color = new Color(180, 190, 230);
            pointLight.PointLight.Intensity = 0.3f;
            pointLight.PointLight.Range = 60;
            pointLight.Transform.Position = new Vector3(4.8f, 1.5f, 10);
            //pointLight.PointLight.Shadow = new CubeShadow { LightDepthTextureSize = 512, };

            pointLight = new GameObject3D();
            pointLight.AddComponent<PointLight>();
            pointLight.PointLight.Color = new Color(130, 130, 190);
            pointLight.PointLight.Intensity = 0.7f;
            pointLight.PointLight.Range = 60;
            pointLight.Transform.Position = new Vector3(-4.8f, 0, -4);

            /*pointLightClipVolumeTest = new GameObject3D();
            pointLightClipVolumeTest.AddComponent<PointLight>();
            pointLightClipVolumeTest.PointLight.Color = new Color(250, 20, 20);
            pointLightClipVolumeTest.PointLight.Intensity = 2f;
            pointLightClipVolumeTest.PointLight.Range = 60;
            pointLightClipVolumeTest.PointLight.ClipVolume = new FileModel("ClipVolume");
            pointLightClipVolumeTest.PointLight.RenderClipVolumeInLocalSpace = true;
            pointLightClipVolumeTest.Transform.Position = new Vector3(26f, 7, 35);*/

            spotLight = new GameObject3D();
            spotLight.AddComponent<SpotLight>();
            spotLight.SpotLight.Color = new Color(0, 250, 0);
            spotLight.SpotLight.Intensity = 0.5f;
            spotLight.SpotLight.Range = 40; // I always forget to set the light range lower than the camera far plane.
            spotLight.Transform.Position = new Vector3(0, 16, 15);
            spotLight.Transform.Rotate(new Vector3(-80, 0, 0));
            spotLight.SpotLight.LightMaskTexture = new Texture("LightMasks\\TestLightMask");
            /*spotLight.SpotLight.Shadow = new BasicShadow
            {
                Filter = Shadow.FilterType.PcfPosion,
                LightDepthTextureSize = Size.Square512X512,
                ShadowTextureSize = Size.TextureSize.FullSize,
                DepthBias = 0.0005f,
            };*/
            
            #endregion
            
            #region Lamborghini Murcielago LP640
           
            lamborghiniMurcielagoLoader = new LamborghiniMurcielagoLoader();
            lamborghiniMurcielagoLoader.LoadContent();
            lamborghiniMurcielagoLoader.LamborghiniMurcielago.Transform.LocalScale = new Vector3(1.2f, 1.2f, 1.2f);
            lamborghiniMurcielagoLoader.LamborghiniMurcielago.Transform.LocalPosition = new Vector3(0, 1.4f, 2.35f);
            lamborghiniMurcielagoLoader.TiresAngle = -40;
            
            #endregion

            #region Particles
            
            // Pit particles
            GameObject3D particles = new GameObject3D();
            particles.AddComponent<ParticleEmitter>();
            particles.AddComponent<ParticleRenderer>();
            particles.ParticleEmitter.MaximumNumberParticles = 75;
            particles.Transform.LocalPosition = new Vector3(-1.2f, 0, -13);
            particles.ParticleEmitter.Duration = 50f;
            particles.ParticleEmitter.EmitterVelocitySensitivity = 1;
            particles.ParticleEmitter.MinimumHorizontalVelocity = 1;
            particles.ParticleEmitter.MaximumHorizontalVelocity = 2f;
            particles.ParticleEmitter.MinimumVerticalVelocity = 1;
            particles.ParticleEmitter.MaximumVerticalVelocity = 2;
            particles.ParticleRenderer.Texture = new Texture("Particles\\Smoke");
            particles.ParticleRenderer.SoftParticles = true;
            particles.ParticleRenderer.FadeDistance = 25.0f;
            particles.ParticleRenderer.BlendState = BlendState.NonPremultiplied;
            particles.ParticleRenderer.DurationRandomness = 0.1f;
            particles.ParticleRenderer.Gravity = new Vector3(0, 1, 5);
            particles.ParticleRenderer.EndVelocity = 0.75f;
            particles.ParticleRenderer.MinimumColor = Color.Red;
            particles.ParticleRenderer.MaximumColor = Color.White;
            particles.ParticleRenderer.RotateSpeed = new Vector2(-0.3f, 0.25f);
            particles.ParticleRenderer.StartSize = new Vector2(25, 30);
            particles.ParticleRenderer.EndSize = new Vector2(75, 100);
            particles.ParticleRenderer.TilesX = 1;
            particles.ParticleRenderer.TilesY = 1;
            particles.ParticleRenderer.AnimationRepetition = 1;

            particles = new GameObject3D();
            particles.AddComponent<ParticleEmitter>();
            particles.AddComponent<ParticleRenderer>();
            particles.ParticleEmitter.MaximumNumberParticles = 75;
            particles.Transform.LocalPosition = new Vector3(-3.2f, 0, 13);
            particles.ParticleEmitter.Duration = 50f;
            particles.ParticleEmitter.EmitterVelocitySensitivity = 1;
            particles.ParticleEmitter.MinimumHorizontalVelocity = 1;
            particles.ParticleEmitter.MaximumHorizontalVelocity = 2f;
            particles.ParticleEmitter.MinimumVerticalVelocity = 1;
            particles.ParticleEmitter.MaximumVerticalVelocity = 2;
            particles.ParticleRenderer.Texture = new Texture("Particles\\Smoke");
            particles.ParticleRenderer.SoftParticles = true;
            particles.ParticleRenderer.FadeDistance = 25.0f;
            particles.ParticleRenderer.BlendState = BlendState.NonPremultiplied;
            particles.ParticleRenderer.DurationRandomness = 0.1f;
            particles.ParticleRenderer.Gravity = new Vector3(0, 1, -5);
            particles.ParticleRenderer.EndVelocity = 0.75f;
            particles.ParticleRenderer.MinimumColor = Color.Red;
            particles.ParticleRenderer.MaximumColor = Color.White;
            particles.ParticleRenderer.RotateSpeed = new Vector2(-0.2f, 0.2f);
            particles.ParticleRenderer.StartSize = new Vector2(25, 50);
            particles.ParticleRenderer.EndSize = new Vector2(75, 100);
            particles.ParticleRenderer.TilesX = 1;
            particles.ParticleRenderer.TilesY = 1;
            particles.ParticleRenderer.AnimationRepetition = 1;
            
            #endregion

            #region Statistics

            Layer.GetLayerByNumber(26).Name = "Statistics Layer";
            GameObject2D statistics = new GameObject2D();
            statistics.AddComponent<ScriptStatisticsDrawer>();

            #endregion

            #region Legend
            /*
            demoLegend = new GameObject2D();
            var legend = (HudText)demoLegend.AddComponent<HudText>();
            legend.Color = new Color(0.1f, 0.1f, 0.1f, 1f);
            #if XBOX
                legend.Text.Append("A to open the doors\n");
                legend.Text.Append("Left stick to rotate the wheels");
            #else
                legend.Text.Append("Space or A to open the doors\n");
                legend.Text.Append("Left and right cursors or left stick to rotate the wheels\n");
                legend.Text.Append("Left mouse button or right stick to move the camera");
            #endif*/
            
            #endregion
            
        } // Load