Exemplo n.º 1
0
        public void CullMeshes(ref ChunkCoordinate current, ref BoundingFrustum frustum)
        {
            BoundingBox box;
            if (!current.Equals(ref _previous))
            {
                _solidMeshes.Sort((x, y) => x.Position.LengthSquared().CompareTo(y.Position.LengthSquared()));
                _transparentMeshes.Sort((x, y) => -x.Position.LengthSquared().CompareTo(y.Position.LengthSquared()));
            }

            for (int i = 0; i < _solidMeshes.Count; i++)
            {
                _solidMeshes[i].GetBoundingBox(out box);
                if (frustum.Contains(box) != ContainmentType.Disjoint)
                {
                    _solidMeshRenderQueue.Enqueue(_solidMeshes[i]);
                }
            }

            for (int i = 0; i < _transparentMeshes.Count; i++)
            {
               _transparentMeshes[i].GetBoundingBox(out box);
               if (frustum.Contains(box) != ContainmentType.Disjoint)
               {
                   _transparentMeshRenderQueue.Enqueue(_transparentMeshes[i]);
               }
            }
        }
 public FirstPersonCamera(Game game)
     : base(game)
 {
     
     Position = new Vector3(0, 0, 1);
     _viewFrustum = new BoundingFrustum(Matrix.Identity);
 }
Exemplo n.º 3
0
 /// <summary>
 /// Public constructor. Creates a new camera.
 /// </summary>
 /// <param name="world">The world transformation matrix holding the cameras position and orientation.</param>
 /// <param name="projection">The projection transformation matrix specifing the perspective on the world.</param>
 public Camera(Matrix world, Matrix projection)
 {
     _world = world;
     _view = Matrix.Invert(world);
     _projection = projection;
     _frustum = new BoundingFrustum(_view * _projection);
 }
Exemplo n.º 4
0
        public Projector()
            : base()
        {
            const float near = 0.2f;
            const float far = 2.3f;
            const float scale = 1.0f / ScreenDistance * near;
            projection = Matrix.CreatePerspectiveOffCenter(
                scale * Skreen.Left, scale * Skreen.Right,
                scale * -Skreen.Height / 2, scale * Skreen.Height / 2,
                near, far);
            view = Matrix.CreateTranslation(0.0f, -Skreen.Height / 2, -ScreenDistance);

            // this.Width = Screen.PixelWidth;
            // this.Height = Screen.PixelHeight;
            // this.Left = WinScreen.AllScreens.Where(s => s != WinScreen.PrimaryScreen).First().Bounds.Left;
            // this.WindowState = FormWindowState.Maximized;
            // this.FormBorderStyle = FormBorderStyle.None;
            
            var num = Skreen.PixelHeight;
            var frustum = new BoundingFrustum(view * projection);
            var corners = frustum.GetCorners();
            var tpos = corners[4];
            var tray = (corners[7] - corners[4]) / (float)num;
            var bpos = corners[5];
            var bray = (corners[6] - corners[5]) / (float)num;

            SweptPlanes = new Plane[num];
            var projectorPos = Vector3.Zero;//.Invert(this.View).Translation;
            for (int i = 0; i < num; ++i)
                SweptPlanes[i] = new Plane(projectorPos, tpos + (float)i * tray, bpos + (float)i * bray);
        }
Exemplo n.º 5
0
        public override void Draw(BoundingFrustum VisibleArea, Vector3 Position)
        {
            Manager.ResetFor2D();
            MyGame.graphics.GraphicsDevice.RenderState.CullMode = CullMode.None;
            Manager.TexturedEffect.CurrentTechnique = Manager.TexturedEffect.Techniques["TexturedCloud"];
            Manager.TexturedEffect.Parameters["InputTexture"].SetValue(NoiseMap);
            Manager.TexturedEffect.Parameters["ColorMapTexture"].SetValue(ColorMap);
            for (int i = 1; i < 2; i++)
            {
                Matrix transform = Transforms.Rotation
                        * Matrix.CreateScale(Transforms.Scale * 0.75f * i / 3)
                        * Matrix.CreateTranslation(Transforms.Position + Position);
                effect.Parameters["World"].SetValue(transform);
                Manager.TexturedEffect.Parameters["TextureAlphaThreshold"].SetValue(0.33f + 0.27f * i / 3);
                MyGame.graphics.GraphicsDevice.VertexDeclaration = DefaultDeclaration;

                effect.Begin();
                effect.CurrentTechnique.Passes.First<EffectPass>().Begin();
                MyGame.graphics.GraphicsDevice.DrawUserIndexedPrimitives<VertexPositionTexture>(
                    PrimitiveType.TriangleList
                    , ModelVertices
                    , 0
                    , ModelVertices.Length
                    , ModelIndices
                    , 0
                    , ModelIndices.Length / 3);
                effect.CurrentTechnique.Passes.First<EffectPass>().End();
                effect.End();
            }
            Manager.TexturedEffect.Parameters["TextureAlphaThreshold"].SetValue(0.33f);
            base.Draw(VisibleArea, Position);
            MyGame.graphics.GraphicsDevice.RenderState.CullMode = CullMode.CullCounterClockwiseFace;
        }
Exemplo n.º 6
0
        public static void DrawWireframe(PrimitiveDrawer primitiveDrawer,
			Matrix cameraView, Matrix cameraProjection,
			BoundingFrustum frustum, Color color)
        {
            // The points returned correspond to the corners of the BoundingFrustum faces that are
            // perpendicular to the z-axis. The near face is the face with the larger z value, and
            // the far face is the face with the smaller z value. Points 0 to 3 correspond to the
            // near face in a clockwise order starting at its upper-left corner when looking toward
            // the origin from the positive z direction. Points 4 to 7 correspond to the far face
            // in a clockwise order starting at its upper-left corner when looking toward the
            // origin from the positive z direction.
            frustum.GetCorners(Corners);

            FrustumVertices[6].Position = Corners[0];
            FrustumVertices[7].Position = Corners[1];
            FrustumVertices[5].Position = Corners[2];
            FrustumVertices[4].Position = Corners[3];
            FrustumVertices[2].Position = Corners[4];
            FrustumVertices[3].Position = Corners[5];
            FrustumVertices[1].Position = Corners[6];
            FrustumVertices[0].Position = Corners[7];

            primitiveDrawer.Draw(Matrix.Identity, cameraView, cameraProjection, color, null,
                PrimitiveType.LineList, FrustumVertices, WireFrustumIndices, false);
        }
Exemplo n.º 7
0
 public Dof(IRenderContext renderContext)
     : base(renderContext)
 {
     depthMapFormat = DefaultDepthMapFormat;
     Settings = DofSettings.Default;
     cameraFrustum = new BoundingFrustum(Matrix.Identity);
 }
Exemplo n.º 8
0
        public Main()
        {
            graphics = new GraphicsDeviceManager(this);

            graphics.SynchronizeWithVerticalRetrace = false;
            graphics.ApplyChanges();

            resolution = Settings.Default.WindowResolution;

            graphics.PreferredBackBufferWidth = resolution.X;
            graphics.PreferredBackBufferHeight = resolution.Y;

            Content.RootDirectory = "Content";

            camera = new FreeLookCamera(this);
            cameraHandler = new CameraHandler(this);
            fps = new FPS(this);
            hud = new HUD(this);

            Components.Add(camera);
            Components.Add(cameraHandler);
            Components.Add(fps);
            Components.Add(hud);

            Services.AddService(typeof(ICamera), camera);

            fakeViewFrustum = new BoundingFrustum(Matrix.Identity);
        }
        /// <summary>
        /// Draw a bounding frustrum representation
        /// </summary>
        /// <param name="frustum">Frustrum</param>
        /// <param name="camera">Camera</param>
        /// <param name="color">Color</param>
        public static void Draw(BoundingFrustum frustum, BaseCamera camera, Color color)
        {
            if (effect == null)
            {
                effect = new BasicEffect(YnG.GraphicsDevice);
                effect.VertexColorEnabled = true;
                effect.LightingEnabled = false;
            }

            Vector3[] corners = frustum.GetCorners();
            for (int i = 0; i < 8; i++)
            {
                vertices[i].Position = corners[i];
                vertices[i].Color = color;
            }

            effect.View = camera.View;
            effect.Projection = camera.Projection;

            foreach (EffectPass pass in effect.CurrentTechnique.Passes)
            {
                pass.Apply();
                YnG.GraphicsDevice.DrawUserIndexedPrimitives(PrimitiveType.LineList, vertices, 0, 8, indices, 0, indices.Length / 2);
            }
        }
Exemplo n.º 10
0
        public void Draw(GameTime gameTime, BoundingFrustum VisibleArea)
        {
            if (units.Count > 0)
            {
                VertexPositionColor[] display = new VertexPositionColor[units.Count * 2];
                int[] pointIndex = new int[units.Count];
                for (int i = 0; i < units.Count; i++)
                {
                    display[i * 2] = new VertexPositionColor(units[i].Position, DisplayColor);
                    pointIndex[i] = i * 2;
                    if (units[i].Target != null)
                    {
                        display[i * 2 + 1] = new VertexPositionColor(units[i].Target.Position, DisplayColor);
                    }
                    else
                    {
                        display[i * 2 + 1] = display[i * 2];
                    }
                }

                Manager.ResetFor3D();
                MyGame.graphics.GraphicsDevice.VertexDeclaration = UnitDeclaration;
                MyGame.graphics.GraphicsDevice.RenderState.PointSize = 5.0f;
                Manager.OrdinaryEffect.CurrentTechnique = Manager.OrdinaryEffect.Techniques["Ordinary"];
                Manager.OrdinaryEffect.Parameters["World"].SetValue(Matrix.Identity);
                Manager.OrdinaryEffect.Begin();
                Manager.OrdinaryEffect.CurrentTechnique.Passes.First<EffectPass>().Begin();
                MyGame.graphics.GraphicsDevice.DrawUserPrimitives<VertexPositionColor>(PrimitiveType.LineList, display, 0, display.Length / 2);
                MyGame.graphics.GraphicsDevice.DrawUserIndexedPrimitives<VertexPositionColor>(PrimitiveType.PointList, display, 0, display.Length
                    , pointIndex, 0, pointIndex.Length);
                Manager.OrdinaryEffect.CurrentTechnique.Passes.First<EffectPass>().End();
                Manager.OrdinaryEffect.End();
            }
        }
Exemplo n.º 11
0
        public void UpdateFromBoundingFrustum(BoundingFrustum sourceBoundingFrustum)
        {
            #region Create the lines if necessary

            if (mLines.Count == 0)
            {
                for (int i = 0; i < NumberOfLines; i++)
                {
                    Line line = ShapeManager.AddLine();
                    mLines.Add(line);
                }
            }

            #endregion

            Vector3[] corners = sourceBoundingFrustum.GetCorners();

            mLines[0].SetFromAbsoluteEndpoints(corners[0], corners[1]);
            mLines[1].SetFromAbsoluteEndpoints(corners[1], corners[2]);
            mLines[2].SetFromAbsoluteEndpoints(corners[2], corners[3]);
            mLines[3].SetFromAbsoluteEndpoints(corners[3], corners[0]);

            mLines[4].SetFromAbsoluteEndpoints(corners[4], corners[5]);
            mLines[5].SetFromAbsoluteEndpoints(corners[5], corners[6]);
            mLines[6].SetFromAbsoluteEndpoints(corners[6], corners[7]);
            mLines[7].SetFromAbsoluteEndpoints(corners[7], corners[4]);

            mLines[8].SetFromAbsoluteEndpoints(corners[0], corners[4]);
            mLines[9].SetFromAbsoluteEndpoints(corners[1], corners[5]);
            mLines[10].SetFromAbsoluteEndpoints(corners[2], corners[6]);
            mLines[11].SetFromAbsoluteEndpoints(corners[3], corners[7]);


            sourceBoundingFrustum.Near.ToString();
        }
Exemplo n.º 12
0
 public void Draw(DoubleVector3 cameraLocation, BoundingFrustum originBasedViewFrustum, Matrix originBasedViewMatrix, Matrix projectionMatrix)
 {
     foreach (var face in _faces)
     {
         face.Draw(cameraLocation, originBasedViewFrustum, originBasedViewMatrix, projectionMatrix);
     }
 }
Exemplo n.º 13
0
        /// <summary>
        /// Project a point into 2D space
        /// </summary>
        public static Vector2 Project(BoundingFrustum VisibleArea, Vector3 Point)
        {
            //Acquires the frustum of the area of the screen in view.
            //Then it stores the corners of the area.
            Vector3[] corners = VisibleArea.GetCorners();
            Ray ray = new Ray(Point, Point - Manager.CameraFocus - Manager.CameraLocation);

            float? DistanceToFar = ray.Intersects(VisibleArea.Far);
            float? DistanceToNear = ray.Intersects(VisibleArea.Near);
            Vector3 ScreenCoord;
            if (DistanceToFar.HasValue)
            {
                ScreenCoord = ray.Position + ray.Direction * DistanceToFar.Value;
                ScreenCoord = new Vector3(
                    Vector3.Dot(
                        Vector3.Normalize(corners[5] - corners[4])
                        , ScreenCoord - corners[4])
                    / (corners[5] - corners[4]).Length()
                    , Vector3.Dot(
                        Vector3.Normalize(corners[7] - corners[4])
                        , ScreenCoord - corners[4])
                    / (corners[7] - corners[4]).Length()
                    , 0);
            }
            else
            {
                //Make sure this is off the screen
                return Vector2.One * (Manager.GameWindow.Width + Manager.GameWindow.Height);
            }
            return new Vector2(ScreenCoord.X * Manager.GameWindow.Width, ScreenCoord.Y * Manager.GameWindow.Height);
        }
Exemplo n.º 14
0
        /// <summary>
        /// Unproject a screen coordinate into a ray
        /// </summary>
        public static Ray Unproject(Vector2 Point)
        {
            //Acquires the frustum of the area of the screen in view
            //Then it stores the corners of the area
            BoundingFrustum VisibleArea = new BoundingFrustum(Manager.View * Manager.Projection);
            Vector3[] corners = VisibleArea.GetCorners();
            Vector3 Position = new Vector3(Point, 0.0f);
            Ray ray = new Ray();

            //Point on the near plane of the visible area
            ray.Position =
                corners[0] * (1 - Position.X) * (1 - Position.Y)
                + corners[1] * Position.X * (1 - Position.Y)
                + corners[2] * Position.X * Position.Y
                + corners[3] * (1 - Position.X) * Position.Y;
            Position =
                corners[4] * (1 - Position.X) * (1 - Position.Y)
                + corners[5] * Position.X * (1 - Position.Y)
                + corners[6] * Position.X * Position.Y
                + corners[7] * (1 - Position.X) * Position.Y;
            //Direction between the two points
            ray.Direction = Vector3.Normalize(Position - ray.Position);

            return ray;
        }
Exemplo n.º 15
0
 /// <summary>
 /// Public constructor. Creates a new default camera.
 /// </summary>
 public Camera()
 {
     _world = Matrix.CreateTranslation(Vector3.Backward * 500f);
     _view = Matrix.Invert(_world);
     _projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 16f / 9f, 0.1f, 1000f);
     _frustum = new BoundingFrustum(_view * _projection);
 }
 public SingleScreenSpaceShadow(IRenderContext context)
     : base(context)
 {
     lspsmLightCamera = new LspsmLightCamera();
     lightCameraFrustum = new BoundingFrustum(Matrix.Identity);
     shadowCasters = new List<Actor>();
 }
        public void Draw(
            ref BoundingFrustum boundingFrustum,
            Effect effect,
            ref Color vertexColor)
        {
            var coners = boundingFrustum.GetCorners();
            var vertices = new VertexPositionColor[8];
            for (int i = 0; i < 8; i++)
            {
                vertices[i].Position = coners[i];
                vertices[i].Color = vertexColor;
            }

            foreach (EffectPass pass in effect.CurrentTechnique.Passes)
            {
                pass.Apply();
                graphicsDevice.DrawUserIndexedPrimitives<VertexPositionColor>(
                    PrimitiveType.LineList,
                    vertices,
                    0,
                    8,
                    indices,
                    0,
                    primitiveCount);
            }
        }
Exemplo n.º 18
0
        public void CalibrateExtrinsics(PointF[] imagePoints, MCvPoint3D32f[] worldPoints)
        {
            if (Intrinsics == null)
                throw new Exception("Intrinsics of camera are still unknown, unable to calibrate extrinsic paramters.");
            
            Extrinsics = CameraCalibration.FindExtrinsicCameraParams2(worldPoints, imagePoints, Intrinsics);

            InitializeWorldAndViewMatrices();
            BoundingFrustum = new BoundingFrustum(View * Projection);

            using (var img = new Image<Bgr, byte>(ImageWidth, ImageHeight))
            {
                foreach (var p in imagePoints)
                    img.Draw(new Cross2DF(p, 20, 20), new Bgr(255, 0, 255), 1);

                var projectedCorners = CameraCalibration.ProjectPoints(worldPoints, Extrinsics, Intrinsics);
                foreach (var p in projectedCorners)
                    img.Draw(new Cross2DF(p, 6, 6), new Bgr(255, 255, 0), 1);

                var und = Intrinsics.Undistort(img);

                img.Save(Path.Combine(Global.TmpDir, "reproject.png"));
                und.Save(Path.Combine(Global.TmpDir, "undistorted.png"));
            }
        }
Exemplo n.º 19
0
        public Camera(String ID, Vector3 Position, Vector3 Target)
        {
            this.ID = ID;
            this.Position = Position;
            this.Target = Target;
            this.Up = Vector3.Up;
            Updateable = true;

            this.NearPlane = GameApplication.Instance.NearPlane;
            this.FarPlane = GameApplication.Instance.FarPlane;
            this.AspectRatio = (float)GameApplication.Instance.GetGraphics().Viewport.Width /
                            (float)GameApplication.Instance.GetGraphics().Viewport.Height;
            this.FieldOfView = MathHelper.PiOver4;

            // create the view matrix
            View = Matrix.CreateLookAt(this.Position, this.Target, this.Up);

            // create projection matrix
            Projection = Utils.CreateProjectionMatrix();

            Frustum = new BoundingFrustum(Matrix.Multiply(View, Projection));

            // add the camera to the camera manager
            CameraManager.Instance.AddCamera(this.ID, this);
        }
Exemplo n.º 20
0
        public Selection(Settings settings, IVisibleRanges visibleRanges)
        {
            this.settings = settings;
            VisibleRanges = visibleRanges;

            Frustum = new BoundingFrustum(Matrix.Identity);
            selectedNodes = new SelectedNode[MaxSelectedNodeCount];
        }
Exemplo n.º 21
0
        public CDLODSelection(CDLODSettings settings, ICDLODVisibleRanges visibleRanges)
        {
            Settings = settings;
            VisibleRanges = visibleRanges;

            Frustum = new BoundingFrustum(Matrix.Identity);
            selectedNodes = new CDLODSelectedNode[MaxSelectedNodeCount];
        }
Exemplo n.º 22
0
        public FrustumRenderer(Game game, BoundingFrustum frustum, string debugName = null)
        {
            this.game = game;
            this.debugName = debugName ?? "FrustumRenderer " + Debug.NextObjectId;

            line = new LineRenderer(game, 12, this.debugName);
            UpdateFrustum(frustum);
        }
Exemplo n.º 23
0
        public Camera()
        {
            inputManager = InputManager.GetInstance();

            frustum = new BoundingFrustum(view * projection);

            UpdateProjection();
        }
Exemplo n.º 24
0
 public static void VisitTree(OctCell root, BoundingFrustum frustum, Action<OctCell> callback)
 {
     if (frustum.Intersects(root.Bounds))
     {
         if (root.Leaf) callback(root);
         else foreach (var child in root.Children) VisitTree(child, frustum, callback);
     }
 }
Exemplo n.º 25
0
 public void Update(IViewProject viewProject)
 {
     View = viewProject.View;
     Projection = viewProject.Projection;
     
     BoundingFrustum = new BoundingFrustum(View * Projection);
     World = Matrix.Invert(View);
 }
Exemplo n.º 26
0
 /// <summary>
 /// Creates a Fast Frustum from a bounding frustum
 /// </summary>
 /// <param name="source">Bounding Frustum</param>
 public FastFrustum(BoundingFrustum source)
 {
     _nearNormal = source.Near.Normal; _nearD = source.Near.D;
     _leftNormal = source.Left.Normal; _leftD = source.Left.D;
     _rightNormal = source.Right.Normal; _rightD = source.Right.D;
     _bottomNormal = source.Bottom.Normal; _bottomD = source.Bottom.D;
     _topNormal = source.Top.Normal; _topD = source.Top.D;
 }
Exemplo n.º 27
0
 public void Draw(DoubleVector3 cameraLocation, BoundingFrustum originBasedViewFrustum, Matrix originBasedViewMatrix, Matrix projectionMatrix)
 {
     // TODO: better spec coverage here
     if (IsAboveHorizonToCamera && IsVisibleToCamera(cameraLocation, originBasedViewFrustum))
     {
         _renderer.Draw(_locationRelativeToPlanet, cameraLocation, originBasedViewMatrix, projectionMatrix);
     }
 }
Exemplo n.º 28
0
 public AvatarBase(Game game, string label) : base(game) {
     Label = label;
     Orientation = Quaternion.Identity;
     RotationSpeed *= 3f;
     ForwardSpeed *= 5f;
     _viewFrustum = new BoundingFrustum(Matrix.Identity);
     _clippingFrustum = new BoundingFrustum(Matrix.Identity);
 }
Exemplo n.º 29
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="view"></param>
		/// <param name="projection"></param>
		/// <param name="frustum"></param>
		/// <param name="min"></param>
		/// <param name="max"></param>
		/// <returns></returns>
		bool GetFrustumExtent ( Matrix view, Matrix projection, Rectangle viewport, BoundingFrustum frustum, out Vector4 min, out Vector4 max )
		{
			min = max	=	Vector4.Zero;

			var znear	=	projection.M34 * projection.M43 / projection.M33;
			
			var viewPoints = frustum.GetCorners()
					.Select( p0 => Vector3.TransformCoordinate( p0, view ) )
					.ToArray();

			//var dr		=	Game.GetService<DebugRender>();

			var lines = new[]{
				new Line( viewPoints[0], viewPoints[1] ),
				new Line( viewPoints[1], viewPoints[2] ),
				new Line( viewPoints[2], viewPoints[3] ),
				new Line( viewPoints[3], viewPoints[0] ),
														
				new Line( viewPoints[4], viewPoints[5] ),
				new Line( viewPoints[5], viewPoints[6] ),
				new Line( viewPoints[6], viewPoints[7] ),
				new Line( viewPoints[7], viewPoints[4] ),
													
				new Line( viewPoints[0], viewPoints[4] ),
				new Line( viewPoints[1], viewPoints[5] ),
				new Line( viewPoints[2], viewPoints[6] ),
				new Line( viewPoints[3], viewPoints[7] ),
			};

			lines = lines.Where( line => line.Clip(znear) ).ToArray();

			if (!lines.Any()) {
				return false;
			}

			var projPoints = new List<Vector3>();
			
			foreach ( var line in lines ) {
				projPoints.Add( Vector3.TransformCoordinate( line.A, projection ) );
				projPoints.Add( Vector3.TransformCoordinate( line.B, projection ) );
			}

			min.X	=	projPoints.Min( p => p.X );
			min.Y	=	projPoints.Max( p => p.Y );
			min.Z	=	projPoints.Min( p => p.Z );

			max.X	=	projPoints.Max( p => p.X );
			max.Y	=	projPoints.Min( p => p.Y );
			max.Z	=	projPoints.Max( p => p.Z );

			min.X	=	( min.X *  0.5f + 0.5f ) * viewport.Width;
			min.Y	=	( min.Y * -0.5f + 0.5f ) * viewport.Height;

			max.X	=	( max.X *  0.5f + 0.5f ) * viewport.Width;
			max.Y	=	( max.Y * -0.5f + 0.5f ) * viewport.Height;

			return true;
		} 
Exemplo n.º 30
0
        /// <summary>
        /// Create terrain at <paramref name="position"/>
        /// </summary>
        /// <param name="position"></param>
        /// <param name="textures"></param>
        /// <param name="device"></param>
        /// <param name="scale"></param>
        /// <param name="Content"></param>
        /// <param name="camera"></param>
        public QuadTree(Vector3 position, List<Texture2D> textures, GraphicsDevice device, int scale, ContentManager Content, GameCamera.FreeCamera camera)
        {
            shadow = new LightsAndShadows.Shadow();
            light = new LightsAndShadows.Light(0.7f, 0.4f, new Vector3(513, 100, 513));

            ViewFrustrum = new BoundingFrustum(camera.View * camera.Projection);
             //  Model model = Content.Load<Model>("Models/stone2");
              //  this.model = new LoadModel(model, Vector3.One, Vector3.Up, new Vector3(1), device);
            this.textures = textures;
            effect = Content.Load<Effect>("Effects/MultiTextured");
            effect2 = Content.Load<Effect>("Effects/Shadows");
            Device = device;

            _position = position;
            _topNodeSize = textures[4].Width - 1;

            _vertices = new MapRender(textures[4],scale);
            _buffers = new BufferManager(_vertices.Vertices, device);
            _rootNode = new QuadNode(NodeType.FullNode, _topNodeSize, 1, null, this, 0);

            //Construct an array large enough to hold all of the indices we'll need.
            Indices = _vertices.indices;

            envBilbList.Add(new EnvBilb(textures[6], textures[5], device, Content, scale));
             foreach (EnvBilb pass in envBilbList)
            {
                pass.GenerateObjPositions(_vertices.Vertices, _vertices.TerrainWidth, _vertices.TerrainLength, _vertices.heightData);
                pass.CreateBillboardVerticesFromList();
            }

            /*
            envModelList.Add(new EnvModel(textures[6], model, device, Content, scale));

               foreach (EnvModel pass1 in envModelList)
            {
                pass1.GenerateObjPositions(_vertices.Vertices, _vertices.TerrainWidth, _vertices.TerrainLength, _vertices.heightData);
                pass1.CreateModelFromList();
            }
             * */

               effect.Parameters["xTexture0"].SetValue(textures[1]);
               effect.Parameters["xTexture1"].SetValue(textures[0]);
               effect.Parameters["xTexture2"].SetValue(textures[2]);
               effect.Parameters["xTexture3"].SetValue(textures[3]);
               effect.Parameters["xTexture5"].SetValue(textures[7]);
               Matrix worldMatrix = Matrix.Identity;
               effect.Parameters["xWorld"].SetValue(worldMatrix);
               effect.Parameters["xEnableLighting"].SetValue(true);
               effect.Parameters["xAmbient"].SetValue(light.Ambient);
               effect.Parameters["xLightPower"].SetValue(light.LightPower);

               effect.Parameters["Ground"].SetValue(textures[7]);
               effect.Parameters["GroundText0"].SetValue(textures[8]);
               effect.Parameters["GroundText1"].SetValue(textures[9]);
               effect.Parameters["GroundText2"].SetValue(textures[10]);

               _rootNode.EnforceMinimumDepth();
        }
Exemplo n.º 31
0
 public static void AddBoundingFrustum(BoundingFrustum frustum, Color color)
 {
     AddBoundingFrustum(frustum, color, 0f);
 }
Exemplo n.º 32
0
 public abstract void GetVisibleMeshes(BoundingFrustum frustum, List <Mesh.SubMesh> visibleSubMeshes);
Exemplo n.º 33
0
        private void RenderSet(List <IRenderable> renderables, GraphicsDevice device, CommandList commandList, RenderingContext context, Vector3 location, BoundingFrustum frustum)
        {
            var transparent = new List <IRenderable>();

            foreach (var renderable in renderables)
            {
                if (renderable.IsActive && renderable.IsVisible(frustum))
                {
                    if (renderable.Transparent)
                    {
                        transparent.Add(renderable);
                    }
                    else
                    {
                        renderable.Render(device, commandList, context);
                    }
                }
            }

            if (transparent.Any())
            {
                var sorted = transparent.OrderBy(r => Vector3.DistanceSquared(location, r.Position));
                foreach (var renderable in sorted)
                {
                    renderable.Render(device, commandList, context);
                }
            }
        }
Exemplo n.º 34
0
        public bool Cull(ref BoundingFrustum visibleFrustum)
        {
            var boundingSphere = new BoundingSphere((_centeredBounds.Center * (Scale.X)) + Position, _centeredBounds.Radius * Scale.X);

            return(visibleFrustum.Contains(boundingSphere) == ContainmentType.Disjoint);
        }
Exemplo n.º 35
0
 public bool Intersects(BoundingFrustum frustum)
 {
     return((frustum.Contains(this.boundingSphere) == ContainmentType.Contains) ||
            (frustum.Contains(this.boundingSphere) == ContainmentType.Intersects));
 }
Exemplo n.º 36
0
        public void GenerateFloor(GraphicsDevice gd, WorldRC world, Blueprint bp, bool justTexture)
        {
            var dim = FLOOR_RES_PER_TILE * FLOOR_TILES;
            var tex = new RenderTarget2D(gd, dim * 3, dim * 2, false, SurfaceFormat.Color, DepthFormat.Depth24);

            gd.SetRenderTarget(tex);
            gd.Clear(Color.TransparentBlack);
            var lookat = Matrix.CreateLookAt(new Vector3(bp.Width * 1.5f, 200, bp.Height * 1.5f), new Vector3(bp.Width * 1.5f, 0, bp.Height * 1.5f), new Vector3(0, 0, 1));
            var baseO  = Matrix.CreateOrthographic(FLOOR_TILES * 3f, FLOOR_TILES * 3f, 0, 400);

            var oldLevel = world.State.SilentLevel;

            for (int i = 0; i < bp.Stories + 1; i++)
            {
                world.State.SilentLevel = (sbyte)(i + 1);
                var x      = i % 3;
                var y      = i / 3;
                var offMat = Matrix.CreateScale(1 / 3f, 1 / 2f, 1f) * Matrix.CreateTranslation(-1 + ((x + 0.5f) * 2 / 3f), 1 - ((y + 0.5f) * 2 / 2f), 0);

                gd.RasterizerState  = Scissor;
                gd.ScissorRectangle = new Rectangle(dim * x + 1, dim * y + 1, dim - 2, dim - 2);

                if (i == bp.Stories)
                {
                    var effect = WorldContent.RCObject;
                    gd.BlendState = BlendState.NonPremultiplied;
                    var vp = lookat * baseO * offMat;
                    effect.Parameters["ViewProjection"].SetValue(vp);
                    var frustrum = new BoundingFrustum(lookat * baseO);

                    effect.CurrentTechnique = effect.Techniques["Draw"];

                    var objs = bp.Objects.Where(o => o.Level == 1 && frustrum.Intersects(((ObjectComponentRC)o).GetBounds())).OrderBy(o => ((ObjectComponentRC)o).SortDepth(vp));
                    foreach (var obj in objs)
                    {
                        obj.Draw(gd, world.State);
                    }
                }
                else
                {
                    var floors = new HashSet <sbyte>();
                    floors.Add((sbyte)i);
                    var mat = baseO * offMat;
                    bp.Terrain.DrawCustom(gd, world.State, lookat, mat, 1, floors);
                    if (i == 0)
                    {
                        bp.Terrain.DrawMask(gd, world.State, lookat, mat);
                    }

                    var effect = WorldContent.RCObject;
                    gd.BlendState = BlendState.NonPremultiplied;
                    var vp = lookat * baseO * offMat;
                    effect.Parameters["ViewProjection"].SetValue(vp);
                    var frustrum = new BoundingFrustum(lookat * baseO);

                    effect.CurrentTechnique = effect.Techniques["Draw"];

                    var objs = bp.Objects.Where(o => o.Level == i + 1 && frustrum.Intersects(((ObjectComponentRC)o).GetBounds())).OrderBy(o => ((ObjectComponentRC)o).SortDepth(vp));
                    foreach (var obj in objs)
                    {
                        obj.Draw(gd, world.State);
                    }

                    if (RoofOnFloor)
                    {
                        //gd.DepthStencilState = DepthStencilState.None;
                        gd.DepthStencilState = DepthStencilState.Default;
                        if (i > 0)
                        {
                            bp.RoofComp.DrawOne(gd, lookat, mat, world.State, i - 1);
                        }
                        if (i == bp.Stories - 1)
                        {
                            bp.RoofComp.DrawOne(gd, lookat, mat, world.State, i);
                        }
                        gd.DepthStencilState = DepthStencilState.Default;
                    }
                }
            }
            world.State.SilentLevel = oldLevel;

            /*
             * using (var fs = new FileStream(@"C:\Users\Rhys\Desktop\floor.png", FileMode.Create, FileAccess.Write))
             *  tex.SaveAsPng(fs, tex.Width, tex.Height);
             */

            if (!justTexture)
            {
                var vertDiv = GROUND_SUBDIV + 1;
                var inc     = FLOOR_TILES / (float)GROUND_SUBDIV;
                var invDiv  = 1 / (float)GROUND_SUBDIV;
                var basepos = new Vector2(bp.Width - FLOOR_TILES, bp.Height - FLOOR_TILES) / 2;
                var basetc  = new Vector2(1 / 3f, 1 / 2f);
                FloorVerts = new VertexPositionTexture[vertDiv * vertDiv];

                //output vertices
                int verti = 0;
                for (int y = 0; y < vertDiv; y++)
                {
                    for (int x = 0; x < vertDiv; x++)
                    {
                        var pos    = basepos + new Vector2(x * inc, y * inc);
                        var height = bp.InterpAltitude(new Vector3(pos, 0));
                        FloorVerts[verti++] = new VertexPositionTexture(new Vector3(pos.X, height, pos.Y), basetc - new Vector2(x * invDiv / 3, y * invDiv / 2));
                    }
                }

                //output indices
                int indi = 0;

                FloorIndices = new int[GROUND_SUBDIV * GROUND_SUBDIV * 6];
                for (int y = 0; y < GROUND_SUBDIV; y++)
                {
                    for (int x = 0; x < GROUND_SUBDIV; x++)
                    {
                        var baseVert = x + y * vertDiv;
                        FloorIndices[indi++] = baseVert + 1 + vertDiv;
                        FloorIndices[indi++] = baseVert + 1;
                        FloorIndices[indi++] = baseVert;

                        FloorIndices[indi++] = baseVert;
                        FloorIndices[indi++] = baseVert + vertDiv;
                        FloorIndices[indi++] = baseVert + 1 + vertDiv;
                    }
                }
            }
            FloorTexture = tex;
            gd.SetRenderTarget(null);
        }
Exemplo n.º 37
0
        public void Render(GraphicsDevice device, Effect effect)
        {
            device.BlendState = BlendState.AlphaBlend;
            effect.Parameters["VP"].SetValue(camera.view * camera.projection);

            effect.Parameters["alpha"].SetValue(1);
            effect.Parameters["ambient"].SetValue(Color.LawnGreen.ToVector4());
            List<Cell> cellsToKeep = new List<Cell>();

            foreach (Virus virus in this.viruses)
            {
                if (virus.target != null)
                    cellsToKeep.Add(virus.target);
                Matrix[] transforms = new Matrix[virus.model.Bones.Count];
                virus.model.CopyAbsoluteBoneTransformsTo(transforms);
                foreach (ModelMesh mesh in virus.model.Meshes)
                {
                    foreach (ModelMeshPart meshpart in mesh.MeshParts)
                    {
                        effect.Parameters["W"].SetValue(transforms[mesh.ParentBone.Index] * Matrix.CreateRotationX(virus.rotation.X) * Matrix.CreateRotationY(virus.rotation.Y) * Matrix.CreateRotationZ(virus.rotation.Z) * Matrix.CreateTranslation(virus.position));
                        meshpart.Effect = effect;
                        foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                        {
                            pass.Apply();
                            mesh.Draw();
                        }
                    }
                }
            }

            BoundingFrustum f = camera.frustum;
            if (worldFade > 0)
            {
                effect.Parameters["alpha"].SetValue(worldFade);
                effect.Parameters["ambient"].SetValue(Color.IndianRed.ToVector4());
                for (int x = 0; x < tunnelLength; x++)
                {
                    for (int a = 0; a < tunnelDensity; a++)
                    {
                        if (f.Intersects(walls[x, a].sphere))
                        {
                            Matrix[] transforms = new Matrix[walls[x, a].model.Bones.Count];
                            walls[x, a].model.CopyAbsoluteBoneTransformsTo(transforms);
                            foreach (ModelMesh mesh in walls[x, a].model.Meshes)
                            {
                                foreach (ModelMeshPart meshpart in mesh.MeshParts)
                                {
                                    effect.Parameters["W"].SetValue(transforms[mesh.ParentBone.Index] * Matrix.CreateTranslation(walls[x, a].position));
                                    meshpart.Effect = effect;
                                    foreach (EffectPass pass in effect.CurrentTechnique.Passes)
                                    {
                                        pass.Apply();
                                        mesh.Draw();
                                    }
                                }
                            }
                        }
                    }
                }
            }

            if (flipCellFaces)
                device.RasterizerState = RasterizerState.CullClockwise;
            else
                device.RasterizerState = RasterizerState.CullCounterClockwise;
            foreach (Cell cell in this.cells)
            {
                if (f.Intersects(cell.sphere))
                {
                    bool c=false;
                    foreach (Cell cl in cellsToKeep)
                    {
                        if (cl == cell)
                        {
                            c = true;
                            break;
                        }
                    }
                    if (c)
                        effect.Parameters["alpha"].SetValue(cell.alpha);
                    else
                        effect.Parameters["alpha"].SetValue(worldFade);
                    // cell body
                    effect.Parameters["ambient"].SetValue(Color.CornflowerBlue.ToVector4());
                    cell.drawSphere(1, Vector3.Zero, effect);
                    // nucleus
                    effect.Parameters["ambient"].SetValue(Color.Black.ToVector4());
                    cell.drawSphere(.4f, Vector3.Zero, effect);
                    // ribosomes
                    effect.Parameters["ambient"].SetValue(Color.Orange.ToVector4());
                    foreach (Vector3 v in cell.ribosomes)
                    {
                        cell.drawSphere(.025f, v, effect);
                    }
                }
            }
            device.RasterizerState = RasterizerState.CullCounterClockwise;
        }
Exemplo n.º 38
0
        public void Render(
            GraphicsDevice gd,
            CommandList rc,
            SceneContext sc,
            RenderPasses pass,
            BoundingFrustum frustum,
            Vector3 viewPosition,
            RenderQueue renderQueue,
            List <CullRenderable> cullRenderableList,
            List <Renderable> renderableList,
            Comparer <RenderItemIndex> comparer,
            bool threaded)
        {
            renderQueue.Clear();

            cullRenderableList.Clear();
            CollectVisibleObjects(ref frustum, pass, cullRenderableList);
            renderQueue.AddRange(cullRenderableList, viewPosition);

            renderableList.Clear();
            CollectFreeObjects(pass, renderableList);
            renderQueue.AddRange(renderableList, viewPosition);

            if (comparer == null)
            {
                renderQueue.Sort();
            }
            else
            {
                renderQueue.Sort(comparer);
            }

            foreach (Renderable renderable in renderQueue)
            {
                renderable.Render(gd, rc, sc, pass);
            }

            if (threaded)
            {
                lock (_allPerFrameRenderablesSet)
                {
                    foreach (CullRenderable thing in cullRenderableList)
                    {
                        _allPerFrameRenderablesSet.Add(thing);
                    }
                    foreach (Renderable thing in renderableList)
                    {
                        _allPerFrameRenderablesSet.Add(thing);
                    }
                }
            }
            else
            {
                foreach (CullRenderable thing in cullRenderableList)
                {
                    _allPerFrameRenderablesSet.Add(thing);
                }
                foreach (Renderable thing in renderableList)
                {
                    _allPerFrameRenderablesSet.Add(thing);
                }
            }
        }
Exemplo n.º 39
0
        private void RenderAllSingleThread(GraphicsDevice gd, CommandList cl, SceneContext sc)
        {
            float     depthClear  = gd.IsDepthRangeZeroToOne ? 0f : 1f;
            Matrix4x4 cameraProj  = Camera.ProjectionMatrix;
            Vector4   nearLimitCS = Vector4.Transform(new Vector3(0, 0, -_nearCascadeLimit), cameraProj);
            Vector4   midLimitCS  = Vector4.Transform(new Vector3(0, 0, -_midCascadeLimit), cameraProj);
            Vector4   farLimitCS  = Vector4.Transform(new Vector3(0, 0, -_farCascadeLimit), cameraProj);

            cl.UpdateBuffer(sc.DepthLimitsBuffer, 0, new DepthCascadeLimits
            {
                NearLimit = nearLimitCS.Z,
                MidLimit  = midLimitCS.Z,
                FarLimit  = farLimitCS.Z
            });

            cl.UpdateBuffer(sc.LightInfoBuffer, 0, sc.DirectionalLight.GetInfo());

            Vector3 lightPos = sc.DirectionalLight.Transform.Position - sc.DirectionalLight.Direction * 1000f;

            // Near
            cl.PushDebugGroup("Shadow Map - Near Cascade");
            Matrix4x4 viewProj0 = UpdateDirectionalLightMatrices(
                gd,
                sc,
                Camera.NearDistance,
                _nearCascadeLimit,
                sc.ShadowMapTexture.Width,
                out BoundingFrustum lightFrustum);

            cl.UpdateBuffer(sc.LightViewProjectionBuffer0, 0, ref viewProj0);
            cl.SetFramebuffer(sc.NearShadowMapFramebuffer);
            cl.SetFullViewports();
            cl.ClearDepthStencil(depthClear);
            Render(gd, cl, sc, RenderPasses.ShadowMapNear, lightFrustum, lightPos, _renderQueues[0], _cullableStage[0], _renderableStage[0], null, false);
            cl.PopDebugGroup();

            // Mid
            cl.PushDebugGroup("Shadow Map - Mid Cascade");
            Matrix4x4 viewProj1 = UpdateDirectionalLightMatrices(
                gd,
                sc,
                _nearCascadeLimit,
                _midCascadeLimit,
                sc.ShadowMapTexture.Width,
                out lightFrustum);

            cl.UpdateBuffer(sc.LightViewProjectionBuffer1, 0, ref viewProj1);
            cl.SetFramebuffer(sc.MidShadowMapFramebuffer);
            cl.SetFullViewports();
            cl.ClearDepthStencil(depthClear);
            Render(gd, cl, sc, RenderPasses.ShadowMapMid, lightFrustum, lightPos, _renderQueues[0], _cullableStage[0], _renderableStage[0], null, false);
            cl.PopDebugGroup();

            // Far
            cl.PushDebugGroup("Shadow Map - Far Cascade");
            Matrix4x4 viewProj2 = UpdateDirectionalLightMatrices(
                gd,
                sc,
                _midCascadeLimit,
                _farCascadeLimit,
                sc.ShadowMapTexture.Width,
                out lightFrustum);

            cl.UpdateBuffer(sc.LightViewProjectionBuffer2, 0, ref viewProj2);
            cl.SetFramebuffer(sc.FarShadowMapFramebuffer);
            cl.SetFullViewports();
            cl.ClearDepthStencil(depthClear);
            Render(gd, cl, sc, RenderPasses.ShadowMapFar, lightFrustum, lightPos, _renderQueues[0], _cullableStage[0], _renderableStage[0], null, false);
            cl.PopDebugGroup();

            // Reflections
            cl.PushDebugGroup("Planar Reflection Map");
            cl.SetFramebuffer(sc.ReflectionFramebuffer);
            float fbWidth  = sc.ReflectionFramebuffer.Width;
            float fbHeight = sc.ReflectionFramebuffer.Height;

            cl.SetViewport(0, new Viewport(0, 0, fbWidth, fbHeight, 0, 1));
            cl.SetFullViewports();
            cl.SetFullScissorRects();
            cl.ClearColorTarget(0, RgbaFloat.Black);
            cl.ClearDepthStencil(depthClear);

            // Render reflected scene.
            Matrix4x4  planeReflectionMatrix = Matrix4x4.CreateReflection(MirrorMesh.Plane);
            CameraInfo camInfo = new CameraInfo();

            camInfo.CameraLookDirection       = Vector3.Normalize(Vector3.Reflect(_camera.LookDirection, MirrorMesh.Plane.Normal));
            camInfo.CameraPosition_WorldSpace = Vector3.Transform(_camera.Position, planeReflectionMatrix);
            cl.UpdateBuffer(sc.CameraInfoBuffer, 0, ref camInfo);

            Matrix4x4 view = sc.Camera.ViewMatrix;

            view = planeReflectionMatrix * view;
            cl.UpdateBuffer(sc.ViewMatrixBuffer, 0, view);

            Matrix4x4 projection = _camera.ProjectionMatrix;

            cl.UpdateBuffer(sc.ReflectionViewProjBuffer, 0, view * projection);

            BoundingFrustum cameraFrustum = new BoundingFrustum(view * projection);

            Render(gd, cl, sc, RenderPasses.ReflectionMap, cameraFrustum, _camera.Position, _renderQueues[0], _cullableStage[0], _renderableStage[0], null, false);

            cl.GenerateMipmaps(sc.ReflectionColorTexture);
            cl.PopDebugGroup();

            // Main scene
            cl.PushDebugGroup("Main Scene Pass");
            cl.SetFramebuffer(sc.MainSceneFramebuffer);
            fbWidth  = sc.MainSceneFramebuffer.Width;
            fbHeight = sc.MainSceneFramebuffer.Height;
            cl.SetViewport(0, new Viewport(0, 0, fbWidth, fbHeight, 0, 1));
            cl.SetFullViewports();
            cl.SetFullScissorRects();
            cl.ClearDepthStencil(depthClear);
            sc.UpdateCameraBuffers(cl); // Re-set because reflection step changed it.
            cameraFrustum = new BoundingFrustum(_camera.ViewMatrix * _camera.ProjectionMatrix);
            Render(gd, cl, sc, RenderPasses.Standard, cameraFrustum, _camera.Position, _renderQueues[0], _cullableStage[0], _renderableStage[0], null, false);
            cl.PopDebugGroup();
            cl.PushDebugGroup("Transparent Pass");
            Render(gd, cl, sc, RenderPasses.AlphaBlend, cameraFrustum, _camera.Position, _renderQueues[0], _cullableStage[0], _renderableStage[0], null, false);
            cl.PopDebugGroup();
            cl.PushDebugGroup("Overlay");
            Render(gd, cl, sc, RenderPasses.Overlay, cameraFrustum, _camera.Position, _renderQueues[0], _cullableStage[0], _renderableStage[0], null, false);
            cl.PopDebugGroup();

            if (sc.MainSceneColorTexture.SampleCount != TextureSampleCount.Count1)
            {
                cl.ResolveTexture(sc.MainSceneColorTexture, sc.MainSceneResolvedColorTexture);
            }

            cl.PushDebugGroup("Duplicator");
            cl.SetFramebuffer(sc.DuplicatorFramebuffer);
            fbWidth  = sc.DuplicatorFramebuffer.Width;
            fbHeight = sc.DuplicatorFramebuffer.Height;
            cl.SetFullViewports();
            Render(gd, cl, sc, RenderPasses.Duplicator, new BoundingFrustum(), _camera.Position, _renderQueues[0], _cullableStage[0], _renderableStage[0], null, false);
            cl.PopDebugGroup();

            cl.PushDebugGroup("Swapchain Pass");
            cl.SetFramebuffer(gd.SwapchainFramebuffer);
            fbWidth  = gd.SwapchainFramebuffer.Width;
            fbHeight = gd.SwapchainFramebuffer.Height;
            cl.SetFullViewports();
            Render(gd, cl, sc, RenderPasses.SwapchainOutput, new BoundingFrustum(), _camera.Position, _renderQueues[0], _cullableStage[0], _renderableStage[0], null, false);
            cl.PopDebugGroup();

            cl.End();

            _resourceUpdateCL.Begin();
            foreach (Renderable renderable in _allPerFrameRenderablesSet)
            {
                renderable.UpdatePerFrameResources(gd, _resourceUpdateCL, sc);
            }
            _resourceUpdateCL.End();

            gd.SubmitCommands(_resourceUpdateCL);
            gd.SubmitCommands(cl);
        }
Exemplo n.º 40
0
        private Matrix4x4 UpdateDirectionalLightMatrices(
            GraphicsDevice gd,
            SceneContext sc,
            float near,
            float far,
            uint shadowMapWidth,
            out BoundingFrustum lightFrustum)
        {
            Vector3        lightDir = sc.DirectionalLight.Direction;
            Vector3        viewDir  = sc.Camera.LookDirection;
            Vector3        viewPos  = sc.Camera.Position;
            Vector3        unitY    = Vector3.UnitY;
            FrustumCorners cameraCorners;

            if (gd.IsDepthRangeZeroToOne)
            {
                FrustumHelpers.ComputePerspectiveFrustumCorners(
                    ref viewPos,
                    ref viewDir,
                    ref unitY,
                    sc.Camera.FieldOfView,
                    far,
                    near,
                    sc.Camera.AspectRatio,
                    out cameraCorners);
            }
            else
            {
                FrustumHelpers.ComputePerspectiveFrustumCorners(
                    ref viewPos,
                    ref viewDir,
                    ref unitY,
                    sc.Camera.FieldOfView,
                    near,
                    far,
                    sc.Camera.AspectRatio,
                    out cameraCorners);
            }

            // Approach used: http://alextardif.com/ShadowMapping.html

            Vector3 frustumCenter = Vector3.Zero;

            frustumCenter += cameraCorners.NearTopLeft;
            frustumCenter += cameraCorners.NearTopRight;
            frustumCenter += cameraCorners.NearBottomLeft;
            frustumCenter += cameraCorners.NearBottomRight;
            frustumCenter += cameraCorners.FarTopLeft;
            frustumCenter += cameraCorners.FarTopRight;
            frustumCenter += cameraCorners.FarBottomLeft;
            frustumCenter += cameraCorners.FarBottomRight;
            frustumCenter /= 8f;

            float radius        = (cameraCorners.NearTopLeft - cameraCorners.FarBottomRight).Length() / 2.0f;
            float texelsPerUnit = shadowMapWidth / (radius * 2.0f);

            Matrix4x4 scalar = Matrix4x4.CreateScale(texelsPerUnit, texelsPerUnit, texelsPerUnit);

            Vector3 baseLookAt = -lightDir;

            Matrix4x4 lookat = Matrix4x4.CreateLookAt(Vector3.Zero, baseLookAt, Vector3.UnitY);

            lookat = scalar * lookat;
            Matrix4x4.Invert(lookat, out Matrix4x4 lookatInv);

            frustumCenter   = Vector3.Transform(frustumCenter, lookat);
            frustumCenter.X = (int)frustumCenter.X;
            frustumCenter.Y = (int)frustumCenter.Y;
            frustumCenter   = Vector3.Transform(frustumCenter, lookatInv);

            Vector3 lightPos = frustumCenter - (lightDir * radius * 2f);

            Matrix4x4 lightView = Matrix4x4.CreateLookAt(lightPos, frustumCenter, Vector3.UnitY);

            Matrix4x4 lightProjection = Util.CreateOrtho(
                gd,
                gd.IsDepthRangeZeroToOne,
                -radius * _lScale,
                radius * _rScale,
                -radius * _bScale,
                radius * _tScale,
                -radius * _nScale,
                radius * _fScale);

            Matrix4x4 viewProjectionMatrix = lightView * lightProjection;

            lightFrustum = new BoundingFrustum(viewProjectionMatrix);
            return(viewProjectionMatrix);
        }
Exemplo n.º 41
0
        private void RenderAllMultiThreaded(GraphicsDevice gd, CommandList cl, SceneContext sc)
        {
            float     depthClear  = gd.IsDepthRangeZeroToOne ? 0f : 1f;
            Matrix4x4 cameraProj  = Camera.ProjectionMatrix;
            Vector4   nearLimitCS = Vector4.Transform(new Vector3(0, 0, -_nearCascadeLimit), cameraProj);
            Vector4   midLimitCS  = Vector4.Transform(new Vector3(0, 0, -_midCascadeLimit), cameraProj);
            Vector4   farLimitCS  = Vector4.Transform(new Vector3(0, 0, -_farCascadeLimit), cameraProj);
            Vector3   lightPos    = sc.DirectionalLight.Transform.Position - sc.DirectionalLight.Direction * 1000f;

            _resourceUpdateCL.Begin();
            CommandList[] cls = new CommandList[5];
            for (int i = 0; i < cls.Length; i++)
            {
                cls[i] = gd.ResourceFactory.CreateCommandList(); cls[i].Begin();
            }

            _resourceUpdateCL.UpdateBuffer(sc.DepthLimitsBuffer, 0, new DepthCascadeLimits
            {
                NearLimit = nearLimitCS.Z,
                MidLimit  = midLimitCS.Z,
                FarLimit  = farLimitCS.Z
            });

            _resourceUpdateCL.UpdateBuffer(sc.LightInfoBuffer, 0, sc.DirectionalLight.GetInfo());

            _allPerFrameRenderablesSet.Clear();
            _tasks[0] = Task.Run(() =>
            {
                // Near
                Matrix4x4 viewProj0 = UpdateDirectionalLightMatrices(
                    gd,
                    sc,
                    Camera.NearDistance,
                    _nearCascadeLimit,
                    sc.ShadowMapTexture.Width,
                    out BoundingFrustum lightFrustum0);
                cls[1].UpdateBuffer(sc.LightViewProjectionBuffer0, 0, ref viewProj0);

                cls[1].SetFramebuffer(sc.NearShadowMapFramebuffer);
                cls[1].SetViewport(0, new Viewport(0, 0, sc.ShadowMapTexture.Width, sc.ShadowMapTexture.Height, 0, 1));
                cls[1].SetScissorRect(0, 0, 0, sc.ShadowMapTexture.Width, sc.ShadowMapTexture.Height);
                cls[1].ClearDepthStencil(depthClear);
                Render(gd, cls[1], sc, RenderPasses.ShadowMapNear, lightFrustum0, lightPos, _renderQueues[0], _cullableStage[0], _renderableStage[0], null, true);
            });

            _tasks[1] = Task.Run(() =>
            {
                // Mid
                Matrix4x4 viewProj1 = UpdateDirectionalLightMatrices(
                    gd,
                    sc,
                    _nearCascadeLimit,
                    _midCascadeLimit,
                    sc.ShadowMapTexture.Width,
                    out var lightFrustum1);
                cls[2].UpdateBuffer(sc.LightViewProjectionBuffer1, 0, ref viewProj1);

                cls[2].SetFramebuffer(sc.MidShadowMapFramebuffer);
                cls[2].SetViewport(0, new Viewport(0, 0, sc.ShadowMapTexture.Width, sc.ShadowMapTexture.Height, 0, 1));
                cls[2].SetScissorRect(0, 0, 0, sc.ShadowMapTexture.Width, sc.ShadowMapTexture.Height);
                cls[2].ClearDepthStencil(depthClear);
                Render(gd, cls[2], sc, RenderPasses.ShadowMapMid, lightFrustum1, lightPos, _renderQueues[1], _cullableStage[1], _renderableStage[1], null, true);
            });

            _tasks[2] = Task.Run(() =>
            {
                // Far
                Matrix4x4 viewProj2 = UpdateDirectionalLightMatrices(
                    gd,
                    sc,
                    _midCascadeLimit,
                    _farCascadeLimit,
                    sc.ShadowMapTexture.Width,
                    out var lightFrustum2);
                cls[3].UpdateBuffer(sc.LightViewProjectionBuffer2, 0, ref viewProj2);

                cls[3].SetFramebuffer(sc.FarShadowMapFramebuffer);
                cls[3].SetViewport(0, new Viewport(0, 0, sc.ShadowMapTexture.Width, sc.ShadowMapTexture.Height, 0, 1));
                cls[3].SetScissorRect(0, 0, 0, sc.ShadowMapTexture.Width, sc.ShadowMapTexture.Height);
                cls[3].ClearDepthStencil(depthClear);
                Render(gd, cls[3], sc, RenderPasses.ShadowMapFar, lightFrustum2, lightPos, _renderQueues[2], _cullableStage[2], _renderableStage[2], null, true);
            });

            _tasks[3] = Task.Run(() =>
            {
                // Reflections
                cls[4].SetFramebuffer(sc.ReflectionFramebuffer);
                float scWidth  = sc.ReflectionFramebuffer.Width;
                float scHeight = sc.ReflectionFramebuffer.Height;
                cls[4].SetViewport(0, new Viewport(0, 0, scWidth, scHeight, 0, 1));
                cls[4].SetFullViewports();
                cls[4].SetFullScissorRects();
                cls[4].ClearColorTarget(0, RgbaFloat.Black);
                cls[4].ClearDepthStencil(depthClear);

                // Render reflected scene.
                Matrix4x4 planeReflectionMatrix = Matrix4x4.CreateReflection(MirrorMesh.Plane);
                CameraInfo camInfo                = new CameraInfo();
                camInfo.CameraLookDirection       = Vector3.Normalize(Vector3.Reflect(_camera.LookDirection, MirrorMesh.Plane.Normal));
                camInfo.CameraPosition_WorldSpace = Vector3.Transform(_camera.Position, planeReflectionMatrix);
                cls[4].UpdateBuffer(sc.CameraInfoBuffer, 0, ref camInfo);

                Matrix4x4 view = sc.Camera.ViewMatrix;
                view           = planeReflectionMatrix * view;
                cls[4].UpdateBuffer(sc.ViewMatrixBuffer, 0, view);

                Matrix4x4 projection = _camera.ProjectionMatrix;
                cls[4].UpdateBuffer(sc.ReflectionViewProjBuffer, 0, view * projection);

                BoundingFrustum cameraFrustum = new BoundingFrustum(view * projection);
                Render(gd, cls[4], sc, RenderPasses.ReflectionMap, cameraFrustum, _camera.Position, _renderQueues[3], _cullableStage[3], _renderableStage[3], null, true);

                cl.GenerateMipmaps(sc.ReflectionColorTexture);

                // Main scene
                cls[4].SetFramebuffer(sc.MainSceneFramebuffer);
                scWidth  = sc.MainSceneFramebuffer.Width;
                scHeight = sc.MainSceneFramebuffer.Height;
                cls[4].SetViewport(0, new Viewport(0, 0, scWidth, scHeight, 0, 1));
                cls[4].SetScissorRect(0, 0, 0, (uint)scWidth, (uint)scHeight);
                cls[4].ClearColorTarget(0, RgbaFloat.Black);
                cls[4].ClearDepthStencil(depthClear);
                sc.UpdateCameraBuffers(cls[4]);
                cameraFrustum = new BoundingFrustum(_camera.ViewMatrix * _camera.ProjectionMatrix);
                Render(gd, cls[4], sc, RenderPasses.Standard, cameraFrustum, _camera.Position, _renderQueues[3], _cullableStage[3], _renderableStage[3], null, true);
                Render(gd, cls[4], sc, RenderPasses.AlphaBlend, cameraFrustum, _camera.Position, _renderQueues[3], _cullableStage[3], _renderableStage[3], null, true);
                Render(gd, cls[4], sc, RenderPasses.Overlay, cameraFrustum, _camera.Position, _renderQueues[3], _cullableStage[3], _renderableStage[3], null, true);
            });

            Task.WaitAll(_tasks);

            foreach (Renderable renderable in _allPerFrameRenderablesSet)
            {
                renderable.UpdatePerFrameResources(gd, _resourceUpdateCL, sc);
            }
            _resourceUpdateCL.End();
            gd.SubmitCommands(_resourceUpdateCL);

            for (int i = 0; i < cls.Length; i++)
            {
                cls[i].End(); gd.SubmitCommands(cls[i]); cls[i].Dispose();
            }

            if (sc.MainSceneColorTexture.SampleCount != TextureSampleCount.Count1)
            {
                cl.ResolveTexture(sc.MainSceneColorTexture, sc.MainSceneResolvedColorTexture);
            }

            cl.SetFramebuffer(sc.DuplicatorFramebuffer);
            uint fbWidth  = sc.DuplicatorFramebuffer.Width;
            uint fbHeight = sc.DuplicatorFramebuffer.Height;

            cl.SetViewport(0, new Viewport(0, 0, fbWidth, fbHeight, 0, 1));
            cl.SetViewport(1, new Viewport(0, 0, fbWidth, fbHeight, 0, 1));
            cl.SetScissorRect(0, 0, 0, fbWidth, fbHeight);
            cl.SetScissorRect(1, 0, 0, fbWidth, fbHeight);
            Render(gd, cl, sc, RenderPasses.Duplicator, new BoundingFrustum(), _camera.Position, _renderQueues[0], _cullableStage[0], _renderableStage[0], null, false);

            cl.SetFramebuffer(gd.SwapchainFramebuffer);
            fbWidth  = gd.SwapchainFramebuffer.Width;
            fbHeight = gd.SwapchainFramebuffer.Height;
            cl.SetViewport(0, new Viewport(0, 0, fbWidth, fbHeight, 0, 1));
            cl.SetScissorRect(0, 0, 0, fbWidth, fbHeight);
            Render(gd, cl, sc, RenderPasses.SwapchainOutput, new BoundingFrustum(), _camera.Position, _renderQueues[0], _cullableStage[0], _renderableStage[0], null, false);

            cl.End();
            gd.SubmitCommands(cl);
        }
Exemplo n.º 42
0
        /// <summary>
        /// Creates bounding sphere from bounding frustum.
        /// Implementation taken from XNA source, replace IEnumerable with array
        /// </summary>
        /// <param name="frustum">The bounding frustum.</param>
        /// <param name="corners">Temporary memory to save corner when getting from frustum.</param>
        /// <returns>BoundingSphere</returns>
        public static BoundingSphere ToBoundingSphere(this BoundingFrustum frustum, Vector3[] corners)
        {
            float          num;
            float          num2;
            Vector3        vector2;
            float          num4;
            float          num5;
            BoundingSphere sphere;
            Vector3        vector5;
            Vector3        vector6;
            Vector3        vector7;
            Vector3        vector8;
            Vector3        vector9;

            if (corners.Length < 8)
            {
                throw new ArgumentException("Corners length must be at least 8");
            }

            frustum.GetCorners(corners);

            Vector3 vector4 = vector5 = vector6 = vector7 = vector8 = vector9 = corners[0];

            for (int i = 0; i < corners.Length; i++)
            {
                Vector3 vector = corners[i];

                if (vector.X < vector4.X)
                {
                    vector4 = vector;
                }
                if (vector.X > vector5.X)
                {
                    vector5 = vector;
                }
                if (vector.Y < vector6.Y)
                {
                    vector6 = vector;
                }
                if (vector.Y > vector7.Y)
                {
                    vector7 = vector;
                }
                if (vector.Z < vector8.Z)
                {
                    vector8 = vector;
                }
                if (vector.Z > vector9.Z)
                {
                    vector9 = vector;
                }
            }
            Vector3.Distance(ref vector5, ref vector4, out num5);
            Vector3.Distance(ref vector7, ref vector6, out num4);
            Vector3.Distance(ref vector9, ref vector8, out num2);
            if (num5 > num4)
            {
                if (num5 > num2)
                {
                    Vector3.Lerp(ref vector5, ref vector4, 0.5f, out vector2);
                    num = num5 * 0.5f;
                }
                else
                {
                    Vector3.Lerp(ref vector9, ref vector8, 0.5f, out vector2);
                    num = num2 * 0.5f;
                }
            }
            else if (num4 > num2)
            {
                Vector3.Lerp(ref vector7, ref vector6, 0.5f, out vector2);
                num = num4 * 0.5f;
            }
            else
            {
                Vector3.Lerp(ref vector9, ref vector8, 0.5f, out vector2);
                num = num2 * 0.5f;
            }
            for (int i = 0; i < corners.Length; i++)
            {
                Vector3 vector10 = corners[i];

                Vector3 vector3;
                vector3.X = vector10.X - vector2.X;
                vector3.Y = vector10.Y - vector2.Y;
                vector3.Z = vector10.Z - vector2.Z;
                float num3 = vector3.Length();
                if (num3 > num)
                {
                    num      = (num + num3) * 0.5f;
                    vector2 += (Vector3)((1f - (num / num3)) * vector3);
                }
            }
            sphere.Center = vector2;
            sphere.Radius = num;
            return(sphere);
        }
Exemplo n.º 43
0
 private void ComputeMatrices()
 {
     this.ViewProjection        = this.View * this.Projection;
     this.Frustum               = new BoundingFrustum(this.ViewProjection);
     this.InverseViewProjection = Matrix.Invert(this.ViewProjection);
 }
Exemplo n.º 44
0
        public void GenerateWalls(GraphicsDevice gd, WorldRC world, Blueprint bp, bool justTexture)
        {
            //generate wall geometry and texture.
            if (!justTexture)
            {
                foreach (var room in bp.Rooms)
                {
                    //add walls for each outside room.
                    if (room.Base == room.RoomID && room.IsOutside)
                    {
                        var walls = new List <Vector2[]>(room.WallLines);
                        walls.AddRange(room.FenceLines);
                        foreach (var wall in walls)
                        {
                            var facadeWall = new LotFacadeWall(wall, room);
                            AddToBin(facadeWall);
                        }
                    }
                }
            }

            //ok, allocate the texture for the wall.
            var tex = new RenderTarget2D(gd, MAX_WALL_WIDTH * WALL_WIDTH, CeilToFour(Math.Max(1, WallBins.Count * (WALL_HEIGHT + GAP * 2) - GAP * 2)), false, SurfaceFormat.Color, DepthFormat.Depth24);

            gd.SetRenderTarget(tex);
            gd.DepthStencilState = DepthStencilState.Default;
            gd.Clear(Color.TransparentBlack);
            //ace, let's draw each wall

            var oldLevel = world.State.Level;

            world.State.SilentLevel    = bp.Stories;
            world.State.ZeroWallOffset = true;
            var cuts = bp.Cutaway;

            bp.Cutaway = new bool[cuts.Length];
            bp.WCRC?.Generate(gd, world.State, false);

            int wallCount = 0;
            int bini      = 0;

            foreach (var bin in WallBins)
            {
                var yPos = bini * (WALL_HEIGHT + GAP * 2);
                var xPos = 0;
                foreach (var wall in bin.Walls)
                {
                    wallCount++;
                    //get a camera for this wall first
                    //create a look at matrix for the wall. first find a camera point at one side of the wall,
                    //then create an orthographic projection with the size of the wall in mind.

                    var ctr   = (wall.Points[0] + wall.Points[1]) / (2 * 16);
                    var rNorm = wall.Points[1] - wall.Points[0];
                    rNorm = new Vector2(rNorm.Y, -rNorm.X);
                    rNorm.Normalize();
                    //which side is "outside"?
                    //check one side. assume the other is outside if we fail
                    var testPos = (ctr + rNorm * 0.6f).ToPoint();
                    if (testPos.X >= 0 && testPos.X < bp.Width && testPos.Y >= 0 && testPos.Y < bp.Height)
                    {
                        var room = bp.RoomMap[wall.Room.Floor][testPos.X + testPos.Y * bp.Width];
                        if (!bp.Rooms[bp.Rooms[(ushort)room].Base].IsOutside)
                        {
                            rNorm *= -1;
                        }
                    }

                    var height = (wall.Room.Floor + 0.5f) * 2.95f * 3 + bp.InterpAltitude(new Vector3(ctr, 0)) * 3f + 0.2f;
                    var camp   = (ctr + rNorm) * 3;
                    var objp   = ctr * 3;
                    var lookat = Matrix.CreateLookAt(new Vector3(camp.X, height, camp.Y), new Vector3(objp.X, height, objp.Y), Vector3.Up);
                    var ortho  = Matrix.CreateOrthographic(3 * wall.PhysicalLength, 2.90f * 3, 0, 6);

                    //rescale our camera matrix to render to the correct part of the render target. Apply scissor test for that area.
                    var rect = new Rectangle(xPos + (wall.EffectiveLength - (wall.Length + GAP)), yPos, wall.Length, WALL_HEIGHT);
                    gd.RasterizerState  = Scissor;
                    gd.ScissorRectangle = rect;

                    var trans = Matrix.CreateScale((rect.Width / ((float)tex.Width)), (rect.Height / ((float)tex.Height)), 1) *
                                Matrix.CreateTranslation((-(rect.X * -2 - wall.Length) / (float)tex.Width) - 1f, (-(rect.Y * 2 + WALL_HEIGHT - 2) / (float)tex.Height) + 1f, 0);

                    var frustrum = new BoundingFrustum(lookat * ortho);
                    ortho = ortho * trans;

                    //draw the walls and objects for this wall segment. this is a little slow right now.
                    var effect = WorldContent.RCObject;
                    gd.BlendState = BlendState.NonPremultiplied;
                    var vp = lookat * ortho;
                    effect.Parameters["ViewProjection"].SetValue(vp);

                    bp.WCRC?.Draw(gd, world.State);

                    effect.CurrentTechnique = effect.Techniques["Draw"];

                    var objs = bp.Objects.Where(x => x.Level >= wall.Room.Floor - 5 && frustrum.Intersects(((ObjectComponentRC)x).GetBounds()))
                               .OrderBy(x => ((ObjectComponentRC)x).SortDepth(vp));
                    foreach (var obj in objs)
                    {
                        obj.Draw(gd, world.State);
                    }

                    xPos += wall.EffectiveLength;
                }
                bini++;
            }
            gd.RasterizerState = RasterizerState.CullNone;

            bp.Cutaway = cuts;
            bp.WCRC?.Generate(gd, world.State, false);
            world.State.ZeroWallOffset = false;
            world.State.SilentLevel    = oldLevel;

            //generate wall geometry
            var data = new Color[tex.Width * tex.Height];

            tex.GetData(data);

            var verts   = new VertexPositionTexture[wallCount * 4];
            var indices = new int[wallCount * 6];

            bini = 0;
            var verti = 0;
            var indi  = 0;

            foreach (var bin in WallBins)
            {
                var xInt = 0;
                var yInt = bini * (WALL_HEIGHT + GAP * 2);
                var yPos = bini * (WALL_HEIGHT + GAP * 2) / (float)tex.Height;
                var xPos = 0f;
                var div  = WALL_HEIGHT / (float)tex.Height;
                foreach (var wall in bin.Walls)
                {
                    var rect = new Rectangle(xInt + (wall.EffectiveLength - (wall.Length + GAP)), yInt, wall.Length, WALL_HEIGHT);
                    BleedRect(data, rect, tex.Width, tex.Height);

                    if (!justTexture)
                    {
                        var ctr     = (wall.Points[0] + wall.Points[1]) / (2 * 16);
                        var off     = (wall.EffectiveLength - (wall.Length + GAP)) / (float)tex.Width;
                        var height1 = ((wall.Room.Floor) * 2.95f + bp.InterpAltitude(new Vector3(ctr, 0)));
                        var height2 = height1 + 2.95f;
                        var pt1     = wall.Points[0] / 16f;
                        var pt2     = wall.Points[1] / 16f;
                        verts[verti++] = new VertexPositionTexture(new Vector3(pt1.X, height2, pt1.Y), new Vector2(xPos + off, yPos));
                        verts[verti++] = new VertexPositionTexture(new Vector3(pt2.X, height2, pt2.Y), new Vector2(xPos + off + wall.Length / (float)tex.Width, yPos));
                        verts[verti++] = new VertexPositionTexture(new Vector3(pt2.X, height1, pt2.Y), new Vector2(xPos + off + wall.Length / (float)tex.Width, (yPos + div)));
                        verts[verti++] = new VertexPositionTexture(new Vector3(pt1.X, height1, pt1.Y), new Vector2(xPos + off, (yPos + div)));

                        indices[indi++] = verti - 2;
                        indices[indi++] = verti - 3;
                        indices[indi++] = verti - 4;

                        indices[indi++] = verti - 4;
                        indices[indi++] = verti - 1;
                        indices[indi++] = verti - 2;

                        xInt += wall.EffectiveLength;
                        xPos += wall.EffectiveLength / (float)tex.Width;
                    }
                }
                bini++;
            }

            //using (var fs = new FileStream(@"C:\Users\Rhys\Desktop\walls.png", FileMode.Create, FileAccess.Write))
            //    tex.SaveAsPng(fs, tex.Width, tex.Height);

            tex.SetData(data);

            if (!justTexture)
            {
                WallTarget  = tex;
                WallVerts   = verts;
                WallIndices = indices;
            }
        }
Exemplo n.º 45
0
 public List <T> GetIntersectingElements(BoundingFrustum frustum)
 {
     return(_root.GetIntersectingElements(frustum));
 }
Exemplo n.º 46
0
 public Camera()
 {
     view            = projection = viewprojection = Matrix.Identity;
     boundingfrustum = new BoundingFrustum(viewprojection);
 }
Exemplo n.º 47
0
 protected virtual bool CheckBoundingFrustum(ref BoundingFrustum viewFrustum)
 {
     return(viewFrustum.Intersects(ref boundsWithTransform));
 }
Exemplo n.º 48
0
 /// <summary>
 /// Renders the outline of a bounding frustum
 /// </summary>
 /// <param name="frustum">Bounding frustum to render</param>
 /// <param name="color">Color of the frustum lines</param>
 public void DrawWireFrustum(BoundingFrustum frustum, Color color)
 {
     DrawWireShape(frustum.GetCorners(), cubeIndices, color);
 }
Exemplo n.º 49
0
        public void RunMainLoop(Panel Panel, MainForm.MainForm mainForm)
        {
            RenderLoop.Run(Panel, () =>
            {
                if (dontRender)
                {
                    return;
                }

                //Resizing
                if (Device.MustResize)
                {
                    Device.Resize();
                    Camera.ProjectionMatrix.AspectRatio = (float)Panel.Width / Panel.Height;
                }

                mainForm.KeyboardController();
                mainForm.SetToolStripStatusLabel(Camera + " FPS: " + $"{SharpFps.StatFPS:0.0000}");

                //clear color
                Device.Clear(backgroundColor);

                //Set matrices
                viewProjection = Camera.ViewMatrix.GetViewMatrix() * Camera.ProjectionMatrix.GetProjectionMatrix();
                frustum        = new BoundingFrustum(viewProjection);

                mainForm.TexturePatternEditor.Animate();

                if (ShowCollision)
                {
                    foreach (var c in mainForm.CollisionEditorDict.Values)
                    {
                        c.RenderCollisionModel(this);
                    }
                    mainForm.LevelEditor.RenderShadowCollisionModel(this);
                }
                else
                {
                    mainForm.LevelEditor.RenderLevelModel(this);
                }

                if (ShowChunkBoxes)
                {
                    mainForm.LevelEditor.visibilityFunctions.RenderChunkModels(this);
                }

                if (ShowObjects == CheckState.Checked)
                {
                    foreach (var l in mainForm.LayoutEditorDict.Values)
                    {
                        l.RenderSetObjects(this, true);
                    }
                }
                else if (ShowObjects == CheckState.Indeterminate)
                {
                    foreach (var l in mainForm.LayoutEditorDict.Values)
                    {
                        l.RenderSetObjects(this, false);
                    }
                }

                if (ShowCameras)
                {
                    mainForm.CameraEditor.RenderCameras(this);
                }

                if (ShowStartPositions)
                {
                    mainForm.ConfigEditor.RenderStartPositions(this);
                }

                if (ShowSplines)
                {
                    mainForm.ConfigEditor.SplineEditor.RenderSplines(this);
                    mainForm.LevelEditor.shadowSplineEditor.RenderSplines(this);
                }

                if (ShowQuadtree)
                {
                    foreach (var c in mainForm.CollisionEditorDict.Values)
                    {
                        c.RenderQuadtree(this);
                    }
                }

                //present
                Device.Present();
                SharpFps.EndFrame();
            });

            //release resources

            whiteDefault.Dispose();
            mainForm.LevelEditor.bspRenderer.Dispose();
            TextureManager.DisposeTextures();
            dffRenderer.Dispose();
            foreach (var c in mainForm.CollisionEditors)
            {
                c.DisposeRenderStuff();
            }
            mainForm.ConfigEditor.SplineEditor.DisposeSplines();

            Cube.Dispose();
            Pyramid.Dispose();
            Cylinder.Dispose();
            Sphere.Dispose();

            basicBuffer.Dispose();
            basicShader.Dispose();

            defaultBuffer.Dispose();
            defaultShader.Dispose();

            collisionBuffer.Dispose();
            collisionShader.Dispose();

            tintedBuffer.Dispose();
            tintedShader.Dispose();

            Device.Dispose();
        }
Exemplo n.º 50
0
 public abstract void DoPreFrameWork(BoundingFrustum frustum);
 protected override bool CheckBoundingFrustum(ref BoundingFrustum boundingFrustum)
 {
     return(true);
 }
        public BoundingFrustum CreateBoundingFrustum()
        {
            BoundingFrustum boundingFrustum = new BoundingFrustum(Matrix.Identity);

            return(boundingFrustum);
        }
Exemplo n.º 53
0
 public bool Cull(ref BoundingFrustum visibleFrustum)
 {
     return(false);
 }
Exemplo n.º 54
0
 public Light()
 {
     _boundingSphere = new BoundingSphere(_transform.Translation, _radius);
     _frustum        = new BoundingFrustum(Matrix.Identity);
     UpdateSpotValues();
 }
Exemplo n.º 55
0
        private bool IsBoxInFrustum(Vector3 bMin, Vector3 bMax, BoundingFrustum Frustum)
        {
            Vector3 NearPoint;

            Plane[] plane = new Plane[6];
            plane[0] = frustum.Bottom;
            plane[1] = frustum.Far;
            plane[2] = frustum.Left;
            plane[3] = frustum.Near;
            plane[4] = frustum.Right;
            plane[5] = frustum.Top;


            for (int i = 0; i < 6; i++)
            {
                if (plane[i].Normal.X > 0.0f)
                {
                    if (plane[i].Normal.Y > 0.0f)//
                    {
                        if (plane[i].Normal.Z > 0.0f)
                        {
                            NearPoint.X = bMin.X; NearPoint.Y = bMin.Y; NearPoint.Z = bMin.Z;
                        }
                        else
                        {
                            NearPoint.X = bMin.X; NearPoint.Y = bMin.Y; NearPoint.Z = bMax.Z;
                        }
                    }
                    else
                    {
                        if (plane[i].Normal.Z > 0.0f)
                        {
                            NearPoint.X = bMin.X; NearPoint.Y = bMax.Y; NearPoint.Z = bMin.Z;
                        }
                        else
                        {
                            NearPoint.X = bMin.X; NearPoint.Y = bMax.Y; NearPoint.Z = bMax.Z;
                        }
                    }
                }
                else
                {
                    if (plane[i].Normal.Y > 0.0f)
                    {
                        if (plane[i].Normal.Z > 0.0f)
                        {
                            NearPoint.X = bMax.X; NearPoint.Y = bMin.Y; NearPoint.Z = bMin.Z;
                        }
                        else
                        {
                            NearPoint.X = bMax.X; NearPoint.Y = bMin.Y; NearPoint.Z = bMax.Z;
                        }
                    }
                    else
                    {
                        if (plane[i].Normal.Z > 0.0f)
                        {
                            NearPoint.X = bMax.X; NearPoint.Y = bMax.Y; NearPoint.Z = bMin.Z;
                        }
                        else
                        {
                            NearPoint.X = bMax.X; NearPoint.Y = bMax.Y; NearPoint.Z = bMax.Z;
                        }
                    }
                }

                // near extreme point is outside, and thus
                // the AABB is totally outside the polyhedron

                float dotProduct;
                Vector3.Dot(ref plane[i].Normal, ref NearPoint, out dotProduct);
                if (dotProduct + plane[i].D > 0)
                {
                    return(false);
                }
            }
            return(true);
        }
Exemplo n.º 56
0
 public abstract void GetShadowCasters(BoundingFrustum frustum, List <Mesh.SubMesh> visibleSubMeshes);
Exemplo n.º 57
0
        protected void GénérerFrustum()
        {
            Matrix vueProjection = Vue * Projection;

            Frustum = new BoundingFrustum(vueProjection);
        }
Exemplo n.º 58
0
 /// <summary>
 /// View frustum test.
 /// </summary>
 /// <param name="viewFrustum">The frustum.</param>
 /// <returns></returns>
 public virtual bool TestViewFrustum(ref BoundingFrustum viewFrustum)
 {
     return(true);
 }
Exemplo n.º 59
0
 public abstract void GetVisibleLights(BoundingFrustum frustum, List <Light> visibleLights);
Exemplo n.º 60
0
        public void Draw(GameTime gameTime, bool underWater)
        {
            BoundingFrustum viewFrustrum = new BoundingFrustum(Game.Camera.View * Game.Camera.Projection);

            // _game.GraphicsDevice.VertexDeclaration = _vertexDeclaration;
            // _game.GraphicsDevice.RenderState.CullMode = CullMode.CullCounterClockwiseFace;

            /*_game.GraphicsDevice.RenderState.DepthBufferEnable = true;
             * _game.GraphicsDevice.RenderState.DepthBufferWriteEnable = true;
             * _game.GraphicsDevice.RenderState.AlphaBlendEnable = false;
             */

            _game.GraphicsDevice.RasterizerState = RasterizerState.CullCounterClockwise;

            _game.GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            _game.GraphicsDevice.BlendState        = BlendState.Opaque;



            _solidBlockEffect.Parameters["World"].SetValue(Matrix.Identity);
            _solidBlockEffect.Parameters["View"].SetValue(Game.Camera.View);
            _solidBlockEffect.Parameters["Projection"].SetValue(Game.Camera.Projection);
            _solidBlockEffect.Parameters["CameraPosition"].SetValue(Game.Camera.Position);
            _solidBlockEffect.Parameters["AmbientColor"].SetValue(Color.White.ToVector4());
            _solidBlockEffect.Parameters["AmbientIntensity"].SetValue(0.8f);
            _solidBlockEffect.Parameters["FogColor"].SetValue(Color.SkyBlue.ToVector4());
            //_solidBlockEffect.Parameters["FogNear"].SetValue(WorldSettings.FOGNEAR);
            //_solidBlockEffect.Parameters["FogFar"].SetValue(WorldSettings.FOGFAR);
            _solidBlockEffect.Parameters["BlockTexture"].SetValue(_textureAtlas);

            //_solidBlockEffect.Parameters["RippleTime"].SetValue(rippleTime*2);

            //if (underWater)
            //{
            //    _solidBlockEffect.Parameters["RippleAmount"].SetValue(0.2f);
            //}
            //else
            //{
            //    _solidBlockEffect.Parameters["RippleAmount"].SetValue(0f);
            //}

            _regionsDrawn = 0;
            //_solidBlockEffect.Begin();
            foreach (EffectPass pass in _solidBlockEffect.CurrentTechnique.Passes)
            {
                pass.Apply();
                for (int x = 0; x < REGIONRATIOWIDTH; x++)
                {
                    for (int y = 0; y < REGIONRATIOHEIGHT; y++)
                    {
                        for (int z = 0; z < REGIONRATIOLENGTH; z++)
                        {
                            Region region = _regions[x, y, z];
                            if (region.BoundingBox.Intersects(viewFrustrum))
                            {
                                if (region.Dirty)
                                {
                                    region.Build();
                                }
                                if (region.SolidVertexBuffer != null)
                                {
                                    _regionsDrawn++;

                                    //string debugOutput = ;
                                    DebugInfo.Data = "region vertex buffer: " + region.SolidVertexBuffer.VertexCount;


                                    //_game.GraphicsDevice.Vertices[0].SetSource(region.SolidVertexBuffer, 0, VertexPositionTextureShade.SizeInBytes);
                                    _game.GraphicsDevice.SetVertexBuffer(region.SolidVertexBuffer);
                                    //_game.GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, (region.SolidVertexBuffer.SizeInBytes / VertexPositionTextureShade.SizeInBytes) / 3);
                                    _game.GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, region.SolidVertexBuffer.VertexCount / 3);
                                }
                            }
                        }
                    }
                }
                //pass.End();
            }
            //_solidBlockEffect.End();

            /*if (!underWater)
             * {
             *
             *  rippleTime += 0.1f;
             *
             *  //_game.GraphicsDevice.RenderState.AlphaBlendEnable = true;
             *  //_game.GraphicsDevice.RenderState.SourceBlend = Blend.SourceAlpha;
             *  //_game.GraphicsDevice.RenderState.DestinationBlend = Blend.InverseSourceAlpha;
             *
             *  _game.GraphicsDevice.BlendState = BlendState.AlphaBlend;
             *
             *  _waterBlockEffect.Parameters["World"].SetValue(Matrix.Identity);
             *  _waterBlockEffect.Parameters["View"].SetValue(Game.Camera.View);
             *  _waterBlockEffect.Parameters["Projection"].SetValue(Game.Camera.Projection);
             *  _waterBlockEffect.Parameters["CameraPosition"].SetValue(Game.Camera.Position);
             *  _waterBlockEffect.Parameters["AmbientColor"].SetValue(Color.White.ToVector4());
             *  _waterBlockEffect.Parameters["AmbientIntensity"].SetValue(0.8f);
             *  _waterBlockEffect.Parameters["FogColor"].SetValue(Color.SkyBlue.ToVector4());
             *  _waterBlockEffect.Parameters["RippleTime"].SetValue(rippleTime);
             *  //_waterBlockEffect.Parameters["FogNear"].SetValue(WorldSettings.FOGNEAR);
             *  //_waterBlockEffect.Parameters["FogFar"].SetValue(WorldSettings.FOGFAR);
             *  _waterBlockEffect.Parameters["BlockTexture"].SetValue(_textureAtlas);
             *
             *  //_waterBlockEffect.Begin();
             *  foreach (EffectPass pass in _waterBlockEffect.CurrentTechnique.Passes)
             *  {
             *      //pass.Begin();
             *      pass.Apply();
             *      for (int x = 0; x < REGIONRATIOWIDTH; x++)
             *      {
             *          for (int y = 0; y < REGIONRATIOHEIGHT; y++)
             *          {
             *              for (int z = 0; z < REGIONRATIOLENGTH; z++)
             *              {
             *                  Region region = _regions[x, y, z];
             *                  if (region.BoundingBox.Intersects(viewFrustrum))
             *                  {
             *                      if (region.Dirty) region.Build();
             *                  }
             *                  if (region.WaterVertexBuffer != null)
             *                  {
             *                      _regionsDrawn++;
             *                     // _game.GraphicsDevice.Vertices[0].SetSource(region.WaterVertexBuffer, 0, VertexPositionTextureShade.SizeInBytes);
             *                      _game.GraphicsDevice.SetVertexBuffer(region.WaterVertexBuffer);
             *                      //_game.GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, (region.WaterVertexBuffer.SizeInBytes / VertexPositionTextureShade.SizeInBytes) / 3);
             *                      _game.GraphicsDevice.DrawPrimitives(PrimitiveType.TriangleList, 0, (region.WaterVertexBuffer.VertexCount) / 3);
             *
             *                  }
             *              }
             *          }
             *      }
             *     // pass.End();
             *  }
             * // _waterBlockEffect.End();
             * }*/

            //_game.GraphicsDevice.RenderState.AlphaBlendEnable = false;
            _game.GraphicsDevice.BlendState = BlendState.Opaque;
        }