Exemplo n.º 1
0
        public OcclusionCullingScreen(IServiceLocator services)
            : base(services)
        {
            _sceneNodes = new List <SceneNode>();

            // Create new occlusion buffer with default settings.
            OcclusionBuffer = new OcclusionBuffer(GraphicsService);
            OcclusionBuffer.ProgressiveShadowCasterCulling = true;

            EnableCulling = true;

            // Create a second camera for rendering a top-down view of the scene.
            var topDownPerspective = new PerspectiveProjection();

            topDownPerspective.SetFieldOfView(MathHelper.ToRadians(90), 1, 1, 512);
            _topDownCameraNode           = new CameraNode(new Camera(topDownPerspective));
            _topDownCameraNode.PoseWorld = new Pose(new Vector3F(-10, 120, -10));
            _topDownCameraNode.LookAt(new Vector3F(-10, 0, -10), Vector3F.UnitZ);

            _sceneQuery    = new CustomSceneQuery();
            _debugRenderer = new DebugRenderer(GraphicsService, null, null);

            // The DigitalRune Profiler is used to measure execution times.
            Profiler.SetFormat("Occlusion.Render", 1e3f, "[ms]");
            Profiler.SetFormat("Occlusion.Query", 1e3f, "[ms]");
        }
Exemplo n.º 2
0
        /// <summary>
        /// Creates a graphics mesh with the triangle mesh data of the given shape and the given
        /// diffuse and specular material properties.
        /// </summary>
        /// <param name="contentManager">The contentManager manager.</param>
        /// <param name="graphicsService">The graphics service.</param>
        /// <param name="shape">The shape.</param>
        /// <param name="diffuse">The diffuse material color.</param>
        /// <param name="specular">The specular material color.</param>
        /// <param name="specularPower">The specular power of the material.</param>
        /// <returns>The graphics mesh.</returns>
        public static Mesh CreateMesh(ContentManager contentManager, IGraphicsService graphicsService, Shape shape,
                                      Vector3 diffuse, Vector3 specular, float specularPower)
        {
            // Create a DigitalRune.Geometry.Meshes.TriangleMesh from the shape and
            // convert this to a DigitalRune.Graphics.Mesh.
            TriangleMesh triangleMesh = shape.GetMesh(0.01f, 4);

            Submesh submesh = CreateSubmeshWithTexCoords(
                graphicsService.GraphicsDevice,
                triangleMesh,
                MathHelper.ToRadians(70));

            var mesh = CreateMesh(contentManager, graphicsService, submesh, diffuse, specular, specularPower);

            // Set bounding shape to a box that is equal to the AABB of the shape.
            var aabb     = shape.GetAabb(Pose.Identity);
            var boxShape = new BoxShape(aabb.Extent);
            var center   = aabb.Center;

            if (center.IsNumericallyZero)
            {
                mesh.BoundingShape = boxShape;
            }
            else
            {
                mesh.BoundingShape = new TransformedShape(new GeometricObject(boxShape, new Pose(center)));
            }

            return(mesh);
        }
Exemplo n.º 3
0
        public override void Update(GameTime gameTime)
        {
            // If <Space> is pressed, we fire a shot.
            if (InputService.IsPressed(Keys.Space, true))
            {
                // Get a random angle and a random distance from the target.
                float angle    = _angleDistribution.Next(_random);
                float distance = _distanceDistribution.Next(_random);

                // Create a vector v with the length of distance.
                Vector3 v = new Vector3(0, distance, 0);

                // Rotate v.
                Quaternion rotation = Quaternion.CreateRotationZ(MathHelper.ToRadians(angle));
                v = rotation.Rotate(v);

                // Draw a small cross for the hit.
                var debugRenderer = GraphicsScreen.DebugRenderer2D;
                debugRenderer.DrawLine(
                    _center + v + new Vector3(-10, -10, 0),
                    _center + v + new Vector3(10, 10, 0),
                    Color.Black,
                    true);
                debugRenderer.DrawLine(
                    _center + v + new Vector3(10, -10, 0),
                    _center + v + new Vector3(-10, 10, 0),
                    Color.Black, true);
            }

            base.Update(gameTime);
        }
Exemplo n.º 4
0
        public void GetScreenSizeWithPerspective()
        {
            // Camera
            var projection = new PerspectiveProjection();

            projection.SetFieldOfView(MathHelper.ToRadians(90), 2.0f / 1.0f, 1.0f, 100f);
            var camera     = new Camera(projection);
            var cameraNode = new CameraNode(camera);

            cameraNode.PoseWorld = new Pose(new Vector3(123, 456, -789), Matrix.CreateRotation(new Vector3(1, -2, 3), MathHelper.ToRadians(75)));

            // 2:1 viewport
            var viewport = new Viewport(10, 10, 200, 100);

            // Test object
            var shape           = new SphereShape();
            var geometricObject = new GeometricObject(shape);

            // Empty sphere at camera position.
            shape.Radius         = 0;
            geometricObject.Pose = cameraNode.PoseWorld;
            Vector2F screenSize = GraphicsHelper.GetScreenSize(cameraNode, viewport, geometricObject);

            Assert.AreEqual(0, screenSize.X);
            Assert.AreEqual(0, screenSize.Y);

            // Empty sphere centered at near plane.
            shape.Radius         = 0;
            geometricObject.Pose = cameraNode.PoseWorld * new Pose(new Vector3(0.123f, -0.543f, -1));
            screenSize           = GraphicsHelper.GetScreenSize(cameraNode, viewport, geometricObject);
            Assert.AreEqual(0, screenSize.X);
            Assert.AreEqual(0, screenSize.Y);

            // Create sphere which as a bounding sphere of ~1 unit diameter:
            // Since the bounding sphere is based on the AABB, we need to make the
            // actual sphere a bit smaller.
            shape.Radius = 1 / (2 * (float)Math.Sqrt(3)) + Numeric.EpsilonF;

            // Sphere at camera position.
            geometricObject.Pose = cameraNode.PoseWorld;
            screenSize           = GraphicsHelper.GetScreenSize(cameraNode, viewport, geometricObject);
            Assert.Greater(screenSize.X, 200);
            Assert.Greater(screenSize.Y, 100);

            // Sphere at near plane.
            geometricObject.Pose = cameraNode.PoseWorld * new Pose(new Vector3(0.123f, -0.543f, -1));
            screenSize           = GraphicsHelper.GetScreenSize(cameraNode, viewport, geometricObject);
            Assert.IsTrue(Numeric.AreEqual(screenSize.X, 50.0f, 10f));
            Assert.IsTrue(Numeric.AreEqual(screenSize.Y, 50.0f, 10f));

            // Double distance --> half size
            geometricObject.Pose = cameraNode.PoseWorld * new Pose(new Vector3(0.123f, -0.543f, -2));
            screenSize           = GraphicsHelper.GetScreenSize(cameraNode, viewport, geometricObject);
            Assert.IsTrue(Numeric.AreEqual(screenSize.X, 25.0f, 5f));
            Assert.IsTrue(Numeric.AreEqual(screenSize.Y, 25.0f, 5f));
        }
Exemplo n.º 5
0
        // In this method, a vector is rotated with a quaternion and a matrix. The result
        // of the two vector rotations are compared.
        private void RotateVector()
        {
            var debugRenderer = GraphicsScreen.DebugRenderer2D;

            debugRenderer.DrawText("----- RotateVector Example:");

            // Create a vector. We will rotate this vector.
            Vector3 v = new Vector3(1, 2, 3);

            // Create another vector which defines the axis of a rotation.
            Vector3 rotationAxis = Vector3.UnitZ;

            // The rotation angle in radians. We want to rotate 50°.
            float rotationAngle = MathHelper.ToRadians(50);

            // ----- Part 1: Rotate a vector with a quaternion.

            // Create a quaternion that represents a 50° rotation around the axis given
            // by rotationAxis.
            Quaternion rotation = Quaternion.CreateFromRotationMatrix(rotationAxis, rotationAngle);

            // Rotate the vector v using the rotation quaternion.
            Vector3 vRotated = rotation.Rotate(v);

            // ----- Part 2: Rotate a vector with a matrix.

            // Create a matrix that represents a 50° rotation around the axis given by
            // rotationAxis.
            Matrix rotationMatrix = Matrix.CreateRotation(rotationAxis, rotationAngle);

            // Rotate the vector v using the rotation matrix.
            Vector3 vRotated2 = rotationMatrix * v;

            // ----- Part 3: Compare the results.
            // The result of both rotations should be identical.
            // Because of numerical errors there can be minor differences in the results.
            // Therefore we use Vector3.AreNumericallyEqual() two check if the results
            // are equal (within a sensible numerical tolerance).
            if (Vector3.AreNumericallyEqual(vRotated, vRotated2))
            {
                debugRenderer.DrawText("Vectors are equal.\n"); // This message is written.
            }
            else
            {
                debugRenderer.DrawText("Vectors are not equal.\n");
            }
        }
        /// <overloads>
        /// <summary>
        /// Initializes a new instance of the <see cref="TerrainMaterialLayer"/> class.
        /// </summary>
        /// </overloads>
        ///
        /// <summary>
        /// Initializes a new instance of the <see cref="TerrainMaterialLayer"/> class with the default
        /// material.
        /// </summary>
        /// <param name="graphicService">The graphic service.</param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="graphicService"/> is <see langword="null"/>.
        /// </exception>
        public TerrainMaterialLayer(IGraphicsService graphicService)
        {
            if (graphicService == null)
            {
                throw new ArgumentNullException("graphicService");
            }

            var effect = graphicService.Content.Load <Effect>("DigitalRune/Terrain/TerrainMaterialLayer");

            Material = new Material
            {
                { "Detail", new EffectBinding(graphicService, effect, null, EffectParameterHint.Material) }
            };

            FadeOutStart            = int.MaxValue;
            FadeOutEnd              = int.MaxValue;
            TileSize                = 1;
            DiffuseColor            = new Vector3(1, 1, 1);
            SpecularColor           = new Vector3(1, 1, 1);
            SpecularPower           = 10;
            Alpha                   = 1;
            DiffuseTexture          = graphicService.GetDefaultTexture2DWhite();
            SpecularTexture         = graphicService.GetDefaultTexture2DBlack();
            NormalTexture           = graphicService.GetDefaultNormalTexture();
            HeightTextureScale      = 1;
            HeightTextureBias       = 0;
            HeightTexture           = graphicService.GetDefaultTexture2DBlack();
            TriplanarTightening     = -1;
            TintStrength            = 1;
            TintTexture             = graphicService.GetDefaultTexture2DWhite();
            BlendThreshold          = 0.5f;
            BlendRange              = 1f;
            BlendHeightInfluence    = 0;
            BlendNoiseInfluence     = 0;
            BlendTextureChannel     = 0;
            BlendTexture            = graphicService.GetDefaultTexture2DWhite();
            NoiseTileSize           = 1;
            TerrainHeightMin        = -1e20f;
            TerrainHeightMax        = +1e20f;
            TerrainHeightBlendRange = 1f;
            TerrainSlopeMin         = -ConstantsF.Pi;
            TerrainSlopeMax         = ConstantsF.Pi;
            TerrainSlopeBlendRange  = MathHelper.ToRadians(10);
        }
Exemplo n.º 7
0
        public void UnprojectTest()
        {
            Viewport viewport = new Viewport(0, 0, 640, 480);
            PerspectiveProjection projection = new PerspectiveProjection();

            projection.SetFieldOfView(MathHelper.ToRadians(60), viewport.AspectRatio, 10, 1000);
            Matrix view = Matrix.CreateLookAt(new Vector3(0, 0, 0), new Vector3(0, 0, -1), Vector3.Up);

            Assert.IsTrue(Vector3.AreNumericallyEqual(new Vector3(0, 0, -10), viewport.Unproject(new Vector3(320, 240, 0), projection, view)));
            Assert.IsTrue(Vector3.AreNumericallyEqual(new Vector3(projection.Left, projection.Top, -10), viewport.Unproject(new Vector3(0, 0, 0), projection, view)));
            Assert.IsTrue(Vector3.AreNumericallyEqual(new Vector3(projection.Right, projection.Top, -10), viewport.Unproject(new Vector3(640, 0, 0), projection, view)));
            Assert.IsTrue(Vector3.AreNumericallyEqual(new Vector3(projection.Left, projection.Bottom, -10), viewport.Unproject(new Vector3(0, 480, 0), projection, view)));
            Assert.IsTrue(Vector3.AreNumericallyEqual(new Vector3(projection.Right, projection.Bottom, -10), viewport.Unproject(new Vector3(640, 480, 0), projection, view)));

            Vector3[] farCorners = new Vector3[4];
            GraphicsHelper.GetFrustumFarCorners(projection, farCorners);
            Assert.IsTrue(Vector3.AreNumericallyEqual((Vector3)farCorners[0], viewport.Unproject(new Vector3(0, 0, 1), projection, view)));
            Assert.IsTrue(Vector3.AreNumericallyEqual((Vector3)farCorners[1], viewport.Unproject(new Vector3(640, 0, 1), projection, view)));
            Assert.IsTrue(Vector3.AreNumericallyEqual((Vector3)farCorners[2], viewport.Unproject(new Vector3(0, 480, 1), projection, view)));
            Assert.IsTrue(Vector3.AreNumericallyEqual((Vector3)farCorners[3], viewport.Unproject(new Vector3(640, 480, 1), projection, view)));
        }
Exemplo n.º 8
0
        // This method shows how to safely compare vectors.
        private void CompareVectors()
        {
            var debugRenderer = GraphicsScreen.DebugRenderer2D;

            debugRenderer.DrawText("----- CompareVectors Example:");

            // Define a vector.
            Vector3 v0 = new Vector3(1000, 2000, 3000);

            // Define a rotation quaternion that rotates 360° around the x axis.
            Quaternion rotation = Quaternion.CreateRotationX(MathHelper.ToRadians(360));

            // Rotate v0.
            Vector3 v1 = rotation.Rotate(v0);

            // The rotated vector v1 should be identical to v0 because a 360° rotation
            // should not change the vector. - But due to numerical errors v0 and v1 are
            // not equal.
            if (v0 == v1)
            {
                debugRenderer.DrawText("Vectors are equal.");
            }
            else
            {
                debugRenderer.DrawText("Vectors are not equal."); // This message is written.
            }
            // With Vector3.AreNumericallyEqual() we can check if two vectors are equal
            // when we allow a small numeric tolerance. The tolerance that is applied is
            // Numeric.EpsilonF, e.g. 10^-5.
            if (Vector3.AreNumericallyEqual(v0, v1))
            {
                debugRenderer.DrawText("Vectors are numerically equal.\n"); // This message is written.
            }
            else
            {
                debugRenderer.DrawText("Vectors are not numerically equal.\n");
            }
        }
Exemplo n.º 9
0
        private void CreateGuiControls()
        {
            var panel = SampleFramework.AddOptions("Shadows");

            // ----- Light node controls
            var lightNodePanel = SampleHelper.AddGroupBox(panel, "Light Nodes");

            SampleHelper.AddDropDown(
                lightNodePanel,
                "Light type",
                new[] { "Spotlight", "PointLight" },
                0,
                selectedItem =>
            {
                bool enableSpotlight      = (selectedItem == "Spotlight");
                _spotlightNode.IsEnabled  = enableSpotlight;
                _pointLightNode.IsEnabled = !enableSpotlight;
            });

            SampleHelper.AddSlider(
                lightNodePanel,
                "Range",
                "F2",
                1,
                30,
                10,
                value =>
            {
                _spotlight.Range  = value;
                _pointLight.Range = value;
            });

            SampleHelper.AddSlider(
                lightNodePanel,
                "Y position",
                "F2",
                0,
                10,
                1,
                value =>
            {
                foreach (var node in new[] { _spotlightNode, _pointLightNode })
                {
                    var pose        = node.PoseWorld;
                    pose.Position.Y = value;
                    node.PoseWorld  = pose;
                }
            });

            SampleHelper.AddSlider(
                lightNodePanel,
                "X rotation",
                "F0",
                -90,
                90,
                1,
                value =>
            {
                var pose                 = _spotlightNode.PoseWorld;
                pose.Orientation         = Matrix.CreateRotationX(MathHelper.ToRadians(value));
                _spotlightNode.PoseWorld = pose;
            });

            SampleHelper.AddSlider(
                lightNodePanel,
                "Spotlight angle",
                "F2",
                1,
                89,
                MathHelper.ToDegrees(_spotlight.CutoffAngle),
                value =>
            {
                float angle             = MathHelper.ToRadians(value);
                _spotlight.FalloffAngle = 0.8f * angle;
                _spotlight.CutoffAngle  = angle;
            });

            // ----- Shadow controls
            var shadowPanel = SampleHelper.AddGroupBox(panel, "Shadow");

            SampleHelper.AddSlider(
                shadowPanel,
                "Shadow map resolution",
                "F0",
                16,
                1024,
                _standardShadow.PreferredSize,
                value =>
            {
                _standardShadow.PreferredSize = (int)value;
                _cubeMapShadow.PreferredSize  = (int)value;
            });

            SampleHelper.AddCheckBox(
                shadowPanel,
                "Prefer 16 bit",
                _standardShadow.Prefer16Bit,
                isChecked =>
            {
                _standardShadow.Prefer16Bit = isChecked;
                _cubeMapShadow.Prefer16Bit  = isChecked;
            });

            SampleHelper.AddSlider(
                shadowPanel,
                "Depth bias",
                "F2",
                0,
                10,
                _standardShadow.DepthBias,
                value =>
            {
                _standardShadow.DepthBias = value;
                _cubeMapShadow.DepthBias  = value;
            });

            SampleHelper.AddSlider(
                shadowPanel,
                "Normal offset",
                "F2",
                0,
                10,
                _standardShadow.NormalOffset,
                value =>
            {
                _standardShadow.NormalOffset = value;
                _cubeMapShadow.NormalOffset  = value;
            });

            SampleHelper.AddSlider(
                shadowPanel,
                "Number of samples",
                "F0",
                -1,
                32,
                _standardShadow.NumberOfSamples,
                value =>
            {
                _standardShadow.NumberOfSamples = (int)value;
                _cubeMapShadow.NumberOfSamples  = (int)value;
            });

            SampleHelper.AddSlider(
                shadowPanel,
                "Filter radius",
                "F2",
                0,
                10,
                _standardShadow.FilterRadius,
                value =>
            {
                _standardShadow.FilterRadius = value;
                _cubeMapShadow.FilterRadius  = value;
            });

            SampleHelper.AddSlider(
                shadowPanel,
                "Jitter resolution",
                "F0",
                1,
                10000,
                _standardShadow.JitterResolution,
                value =>
            {
                _standardShadow.JitterResolution = value;
                _cubeMapShadow.JitterResolution  = value;
            });

            SampleFramework.ShowOptionsWindow("Shadows");
        }
Exemplo n.º 10
0
    // Creates a lot of random objects.
    private void CreateRandomObjects()
    {
      var random = new Random();

      var isFirstHeightField = true;

      int currentShape = 0;
      int numberOfObjects = 0;
      while (true)
      {
        numberOfObjects++;
        if (numberOfObjects > ObjectsPerType)
        {
          currentShape++;
          numberOfObjects = 0;
        }

        Shape shape;
        switch (currentShape)
        {
          case 0:
            // Box
            shape = new BoxShape(ObjectSize, ObjectSize * 2, ObjectSize * 3);
            break;
          case 1:
            // Capsule
            shape = new CapsuleShape(0.3f * ObjectSize, 2 * ObjectSize);
            break;
          case 2:
            // Cone
            shape = new ConeShape(1 * ObjectSize, 2 * ObjectSize);
            break;
          case 3:
            // Cylinder
            shape = new CylinderShape(0.4f * ObjectSize, 2 * ObjectSize);
            break;
          case 4:
            // Sphere
            shape = new SphereShape(ObjectSize);
            break;
          case 5:
            // Convex hull of several points.
            ConvexHullOfPoints hull = new ConvexHullOfPoints();
            hull.Points.Add(new Vector3(-1 * ObjectSize, -2 * ObjectSize, -1 * ObjectSize));
            hull.Points.Add(new Vector3(2 * ObjectSize, -1 * ObjectSize, -0.5f * ObjectSize));
            hull.Points.Add(new Vector3(1 * ObjectSize, 2 * ObjectSize, 1 * ObjectSize));
            hull.Points.Add(new Vector3(-1 * ObjectSize, 2 * ObjectSize, 1 * ObjectSize));
            hull.Points.Add(new Vector3(-1 * ObjectSize, 0.7f * ObjectSize, -0.6f * ObjectSize));
            shape = hull;
            break;
          case 6:
            // A composite shape: two boxes that form a "T" shape.
            var composite = new CompositeShape();
            composite.Children.Add(
              new GeometricObject(
                new BoxShape(ObjectSize, 3 * ObjectSize, ObjectSize),
                new Pose(new Vector3(0, 0, 0))));
            composite.Children.Add(
              new GeometricObject(
                new BoxShape(2 * ObjectSize, ObjectSize, ObjectSize),
                new Pose(new Vector3(0, 2 * ObjectSize, 0))));
            shape = composite;
            break;
          case 7:
            shape = new CircleShape(ObjectSize);
            break;
          case 8:
            {
              var compBvh = new CompositeShape();
              compBvh.Children.Add(new GeometricObject(new BoxShape(0.5f, 1, 0.5f), new Pose(new Vector3(0, 0.5f, 0), Matrix.Identity)));
              compBvh.Children.Add(new GeometricObject(new BoxShape(0.8f, 0.5f, 0.5f), new Pose(new Vector3(0.5f, 0.7f, 0), Matrix.CreateRotationZ(-MathHelper.ToRadians(15)))));
              compBvh.Children.Add(new GeometricObject(new SphereShape(0.3f), new Pose(new Vector3(0, 1.15f, 0), Matrix.Identity)));
              compBvh.Children.Add(new GeometricObject(new CapsuleShape(0.2f, 1), new Pose(new Vector3(0.6f, 1.15f, 0), Matrix.CreateRotationX(0.3f))));
              compBvh.Partition = new AabbTree<int>();
              shape = compBvh;
              break;
            }
          case 9:
            CompositeShape comp = new CompositeShape();
            comp.Children.Add(new GeometricObject(new BoxShape(0.5f * ObjectSize, 1 * ObjectSize, 0.5f * ObjectSize), new Pose(new Vector3(0, 0.5f * ObjectSize, 0), Quaternion.Identity)));
            comp.Children.Add(new GeometricObject(new BoxShape(0.8f * ObjectSize, 0.5f * ObjectSize, 0.5f * ObjectSize), new Pose(new Vector3(0.3f * ObjectSize, 0.7f * ObjectSize, 0), Quaternion.CreateRotationZ(-MathHelper.ToRadians(45)))));
            comp.Children.Add(new GeometricObject(new SphereShape(0.3f * ObjectSize), new Pose(new Vector3(0, 1.15f * ObjectSize, 0), Quaternion.Identity)));
            shape = comp;
            break;
          case 10:
            shape = new ConvexHullOfPoints(new[]
            {
              new Vector3(-1 * ObjectSize, -2 * ObjectSize, -1 * ObjectSize),
              new Vector3(2 * ObjectSize, -1 * ObjectSize, -0.5f * ObjectSize),
              new Vector3(1 * ObjectSize, 2 * ObjectSize, 1 * ObjectSize),
              new Vector3(-1 * ObjectSize, 2 * ObjectSize, 1 * ObjectSize),
              new Vector3(-1 * ObjectSize, 0.7f * ObjectSize, -0.6f * ObjectSize)
            });
            break;
          case 11:
            ConvexHullOfShapes shapeHull = new ConvexHullOfShapes();
            shapeHull.Children.Add(new GeometricObject(new SphereShape(0.3f * ObjectSize), new Pose(new Vector3(0, 2 * ObjectSize, 0), Matrix.Identity)));
            shapeHull.Children.Add(new GeometricObject(new BoxShape(1 * ObjectSize, 2 * ObjectSize, 3 * ObjectSize), Pose.Identity));
            shape = shapeHull;
            break;
          case 12:
            shape = Shape.Empty;
            break;
          case 13:
            var numberOfSamplesX = 10;
            var numberOfSamplesZ = 10;
            var samples = new float[numberOfSamplesX * numberOfSamplesZ];
            for (int z = 0; z < numberOfSamplesZ; z++)
              for (int x = 0; x < numberOfSamplesX; x++)
                samples[z * numberOfSamplesX + x] = (float)(Math.Cos(z / 3f) * Math.Sin(x / 2f) * BoxSize / 6);
            HeightField heightField = new HeightField(0, 0, 2 * BoxSize, 2 * BoxSize, samples, numberOfSamplesX, numberOfSamplesZ);
            shape = heightField;
            break;
          //case 14:
          //shape = new LineShape(new Vector3(0.1f, 0.2f, 0.3f), new Vector3(0.1f, 0.2f, -0.3f).Normalized);
          //break;            
          case 15:
            shape = new LineSegmentShape(
              new Vector3(0.1f, 0.2f, 0.3f), new Vector3(0.1f, 0.2f, 0.3f) + 3 * ObjectSize * new Vector3(0.1f, 0.2f, -0.3f));
            break;
          case 16:
            shape = new MinkowskiDifferenceShape
            {
              ObjectA = new GeometricObject(new SphereShape(0.1f * ObjectSize)),
              ObjectB = new GeometricObject(new BoxShape(1 * ObjectSize, 2 * ObjectSize, 3 * ObjectSize))
            };
            break;
          case 17:
            shape = new MinkowskiSumShape
            {
              ObjectA = new GeometricObject(new SphereShape(0.1f * ObjectSize)),
              ObjectB = new GeometricObject(new BoxShape(1 * ObjectSize, 2 * ObjectSize, 3 * ObjectSize)),
            };
            break;
          case 18:
            shape = new OrthographicViewVolume(0, ObjectSize, 0, ObjectSize, ObjectSize / 2, ObjectSize * 2);
            break;
          case 19:
            shape = new PerspectiveViewVolume(MathHelper.ToRadians(60f), 16f / 10, ObjectSize / 2, ObjectSize * 3);
            break;
          case 20:
            shape = new PointShape(0.1f, 0.3f, 0.2f);
            break;
          case 21:
            shape = new RayShape(new Vector3(0.2f, 0, -0.12f), new Vector3(1, 2, 3).Normalized, ObjectSize * 2);
            break;
          case 22:
            shape = new RayShape(new Vector3(0.2f, 0, -0.12f), new Vector3(1, 2, 3).Normalized, ObjectSize * 2)
            {
              StopsAtFirstHit = true
            };
            break;
          case 23:
            shape = new RectangleShape(ObjectSize, ObjectSize * 2);
            break;
          case 24:
            shape = new TransformedShape(
              new GeometricObject(
                new BoxShape(1 * ObjectSize, 2 * ObjectSize, 3 * ObjectSize),
                new Pose(new Vector3(0.1f, 1, -0.2f))));
            break;
          case 25:
            shape = new TriangleShape(
              new Vector3(ObjectSize, 0, 0), new Vector3(0, ObjectSize, 0), new Vector3(ObjectSize, ObjectSize, ObjectSize));
            break;
          //case 26:
          //  {
          //    // Create a composite object from which we get the mesh.
          //    CompositeShape compBvh = new CompositeShape();
          //    compBvh.Children.Add(new GeometricObject(new BoxShape(0.5f, 1, 0.5f), new Pose(new Vector3(0, 0.5f, 0), Matrix.Identity)));
          //    compBvh.Children.Add(
          //      new GeometricObject(
          //        new BoxShape(0.8f, 0.5f, 0.5f),
          //        new Pose(new Vector3(0.5f, 0.7f, 0), Matrix.CreateRotationZ(-(float)MathHelper.ToRadians(15)))));
          //    compBvh.Children.Add(new GeometricObject(new SphereShape(0.3f), new Pose(new Vector3(0, 1.15f, 0), Matrix.Identity)));
          //    compBvh.Children.Add(
          //      new GeometricObject(new CapsuleShape(0.2f, 1), new Pose(new Vector3(0.6f, 1.15f, 0), Matrix.CreateRotationX(0.3f))));

          //    TriangleMeshShape meshBvhShape = new TriangleMeshShape { Mesh = compBvh.GetMesh(0.01f, 3) };
          //    meshBvhShape.Partition = new AabbTree<int>();
          //    shape = meshBvhShape;
          //    break;
          //  }
          //case 27:
          //  {
          //    // Create a composite object from which we get the mesh.
          //    CompositeShape compBvh = new CompositeShape();
          //    compBvh.Children.Add(new GeometricObject(new BoxShape(0.5f, 1, 0.5f), new Pose(new Vector3(0, 0.5f, 0), Quaternion.Identity)));
          //    compBvh.Children.Add(
          //      new GeometricObject(
          //        new BoxShape(0.8f, 0.5f, 0.5f),
          //        new Pose(new Vector3(0.5f, 0.7f, 0), Quaternion.CreateRotationZ(-(float)MathHelper.ToRadians(15)))));
          //    compBvh.Children.Add(new GeometricObject(new SphereShape(0.3f), new Pose(new Vector3(0, 1.15f, 0), Quaternion.Identity)));
          //    compBvh.Children.Add(
          //      new GeometricObject(new CapsuleShape(0.2f, 1), new Pose(new Vector3(0.6f, 1.15f, 0), Quaternion.CreateRotationX(0.3f))));

          //    TriangleMeshShape meshBvhShape = new TriangleMeshShape { Mesh = compBvh.GetMesh(0.01f, 3) };
          //    meshBvhShape.Partition = new AabbTree<int>();
          //    shape = meshBvhShape;
          //    break;
          //  }
          case 28:
            shape = new ConvexPolyhedron(new[]
            {
              new Vector3(-1 * ObjectSize, -2 * ObjectSize, -1 * ObjectSize),
              new Vector3(2 * ObjectSize, -1 * ObjectSize, -0.5f * ObjectSize),
              new Vector3(1 * ObjectSize, 2 * ObjectSize, 1 * ObjectSize),
              new Vector3(-1 * ObjectSize, 2 * ObjectSize, 1 * ObjectSize),
              new Vector3(-1 * ObjectSize, 0.7f * ObjectSize, -0.6f * ObjectSize)
            });
            break;
          case 29:
            return;
          default:
            currentShape++;
            continue;
        }

        // Create an object with the random shape, pose, color and velocity.
        Pose randomPose = new Pose(
          random.NextVector3(-BoxSize + ObjectSize * 2, BoxSize - ObjectSize * 2),
          random.NextQuaternion());
        var newObject = new MovingGeometricObject
        {
          Pose = randomPose,
          Shape = shape,
          LinearVelocity = random.NextQuaternion().Rotate(new Vector3(MaxLinearVelocity, 0, 0)),
          AngularVelocity = random.NextQuaternion().Rotate(Vector3.Forward)
                            * RandomHelper.Random.NextFloat(0, MaxAngularVelocity),
        };

        if (RandomHelper.Random.NextBool())
          newObject.LinearVelocity = Vector3.Zero;
        if (RandomHelper.Random.NextBool())
          newObject.AngularVelocity = Vector3.Zero;

        if (shape is LineShape || shape is HeightField)
        {
          // Do not move lines or the height field.
          newObject.LinearVelocity = Vector3.Zero;
          newObject.AngularVelocity = Vector3.Zero;
        }

        // Create only 1 heightField!
        if (shape is HeightField)
        {
          if (isFirstHeightField)
          {
            isFirstHeightField = true;
            newObject.Pose = new Pose(new Vector3(-BoxSize, -BoxSize, -BoxSize));
          }
          else
          {
            currentShape++;
            numberOfObjects = 0;
            continue;
          }
        }

        // Add collision object to collision domain.
        _domain.CollisionObjects.Add(new CollisionObject(newObject));

        //co.Type = CollisionObjectType.Trigger;
        //co.Name = "Object" + shape.GetType().Name + "_" + i;
      }
    }
 public override void Update(GameTime gameTime)
 {
     if (_avatarPose == null)
     {
         if (_avatarRenderer.State == AvatarRendererState.Ready)
         {
             _avatarPose = new AvatarPose(_avatarRenderer);
             AnimationService.StartAnimation(_walkAnimation, _avatarPose).AutoRecycle();
         }
     }
     else
     {
         // Update pose of attached baseball bat.
         // The offset of the baseball bat origin to the bone origin (in bone space)
         Pose offset = new Pose(new Vector3(0.01f, 0.05f, 0.0f), Matrix.CreateRotationY(MathHelper.ToRadians(-20)));
         // The bone position in model space
         SrtTransform bonePose = _avatarPose.SkeletonPose.GetBonePoseAbsolute((int)AvatarBone.SpecialRight);
         // The baseball bat matrix in world space
         _baseballBatMeshNode.PoseWorld = _pose * (Pose)bonePose * offset;
     }
 }
Exemplo n.º 12
0
    public LdrSkySample(Microsoft.Xna.Framework.Game game)
      : base(game)
    {
      SampleFramework.IsMouseVisible = false;
      var delegateGraphicsScreen = new DelegateGraphicsScreen(GraphicsService)
      {
        RenderCallback = Render,
      };
      GraphicsService.Screens.Insert(0, delegateGraphicsScreen);

      // Add a custom game object which controls the camera.
      _cameraObject = new CameraObject(Services);
      GameObjectService.Objects.Add(_cameraObject);


      var spriteFont = UIContentManager.Load<SpriteFont>("UI Themes/BlendBlue/Default");
      _debugRenderer = new DebugRenderer(GraphicsService, spriteFont);

      _cieSkyFilter = new CieSkyFilter(GraphicsService);
      _cieSkyFilter.Exposure = 5;
      _cieSkyFilter.Strength = 0.9f;

      _gradientSky = new GradientSkyNode();
      //_gradientSky.GroundColor = new Vector4(0, 0, 1, 1);
      //_gradientSky.ZenithColor = new Vector4(0, 0, 1, 1);
      //_gradientSky.FrontColor = new Vector4(0, 0, 1, 1);
      //_gradientSky.BackColor = new Vector4(0, 0, 1, 1);
      //_gradientSky.FrontZenithShift = 0.3f;
      //_gradientSky.FrontGroundShift = 0.1f;
      //_gradientSky.BackGroundShift = 0.1f;
      _gradientSky.CieSkyStrength = 0;

      _gradientTextureSky = new GradientTextureSkyNode();
      _gradientTextureSky.TimeOfDay = _time.TimeOfDay;
      _gradientTextureSky.Color = new Vector4(1);
      _gradientTextureSky.FrontTexture = ContentManager.Load<Texture2D>("Sky/GradientSkyFront");
      _gradientTextureSky.BackTexture = ContentManager.Load<Texture2D>("Sky/GradientSkyBack");
      _gradientTextureSky.CieSkyStrength = 1;

      _scatteringSky = new ScatteringSkyNode();
      _scatteringSky.SunIntensity *= 2;
      _scatteringSky.BetaMie *= 2;
      _scatteringSky.GMie = 0.75f;
      _scatteringSky.ScaleHeight = _scatteringSky.AtmosphereHeight * 0.25f;

      InitializeStarfield();

      _cloudMapRenderer = new CloudMapRenderer(GraphicsService);
      _skyRenderer = new SkyRenderer(GraphicsService);

      _milkyWay = ContentManager.Load<TextureCube>("Sky/MilkyWay");
      _milkyWaySkybox = new SkyboxNode(_milkyWay) { Color = new Vector3(0.05f) };

      _sun = new SkyObjectNode
      {
        GlowColor0 = new Vector3(1, 1, 1) * 5,
        GlowExponent0 = 4000,

        //GlowColor1 = new Vector3(0.4f) * 0.1f,
        //GlowExponent1 = 100
      };

      _moon = new SkyObjectNode
      {
        Texture = new PackedTexture(ContentManager.Load<Texture2D>("Sky/Moon")),
        SunLight = new Vector3(1, 1, 1) * 1,
        AmbientLight = new Vector3(0.001f) * 1,
        LightWrap = 0.1f,
        LightSmoothness = 1,
        AngularDiameter = new Vector2F(MathHelper.ToRadians(5)),

        GlowColor0 = new Vector3(0.005f * 0),
        GlowCutoffThreshold = 0.001f,
        GlowExponent0 = 100
      };

      var cloudMap = new LayeredCloudMap
      {
        Density = 10,
        Coverage = 0.5f,
        Size = 1024,
      };
      var scale = CreateScale(0.2f);
      cloudMap.Layers[0] = new CloudMapLayer(null, scale * CreateScale(1), -0.5f, 1, 0.011f * 0);
      cloudMap.Layers[1] = new CloudMapLayer(null, scale * CreateScale(1.7f), -0.5f, 1f / 2f, 0.017f * 0);
      cloudMap.Layers[2] = new CloudMapLayer(null, scale * CreateScale(3.97f), -0.5f, 1f / 4f, 0.033f * 0);
      cloudMap.Layers[3] = new CloudMapLayer(null, scale * CreateScale(8.1f), -0.5f, 1f / 8f, 0.043f * 0);
      cloudMap.Layers[4] = new CloudMapLayer(null, scale * CreateScale(16, 17), -0.5f, 1f / 16f, 0.051f * 0);
      cloudMap.Layers[5] = new CloudMapLayer(null, scale * CreateScale(32, 31), -0.5f, 1f / 32f, 0.059f * 0);
      cloudMap.Layers[6] = new CloudMapLayer(null, scale * CreateScale(64, 67), -0.5f, 1f / 64f, 0.067f * 0);
      cloudMap.Layers[7] = new CloudMapLayer(null, scale * CreateScale(128, 127), -0.5f, 1f / 128f, 0.081f * 0);
      _cloudLayerNode = new CloudLayerNode(cloudMap)
      {
        ForwardScatterScale = 2.5f,
        ForwardScatterOffset = 0.3f,
        TextureMatrix = CreateScale(0.5f),
        SkyCurvature = 0.9f,
        NumberOfSamples = 16,
      };

      _ephemeris = new Ephemeris();
      // Approx. location of Ternberg: Latitude = 48, Longitude = 15, Altitude = 300
      _ephemeris.Latitude = 0;
      _ephemeris.Longitude = 15;
      _ephemeris.Altitude = 300;

      //_time = new DateTime(2013, 5, 1, 17, 17, 0, 0);
      _time = DateTime.Now;
#else
      _time = new DateTimeOffset(2013, 5, 1, 12, 0, 0, 0, TimeSpan.Zero);
      //_time = DateTimeOffset.UtcNow;

      UpdateEphemeris();

      _milkyWaySkybox.DrawOrder = 0;
      _starfield.DrawOrder = 1;
      _sun.DrawOrder = 2;
      _moon.DrawOrder = 3;
      _scatteringSky.DrawOrder = 4;
      _gradientSky.DrawOrder = 4;
      _gradientTextureSky.DrawOrder = 4;
      _cloudLayerNode.DrawOrder = 5;

      _skyNodes = new SceneNode[]
      {
        _milkyWaySkybox,
        _starfield, 
        _sun, 
        _moon,
        _scatteringSky,
        //_gradientSky,
        //_gradientTextureSky,
        _cloudLayerNode,
      };

      var graphicsDevice = GraphicsService.GraphicsDevice;
      _skybox = new SkyboxNode(
        new RenderTargetCube(graphicsDevice, 512, false, SurfaceFormat.Color, DepthFormat.None))
      {
        Encoding = ColorEncoding.Rgbm,
      };

      _hdrFilter = new HdrFilter(GraphicsService)
      {
        MinExposure = 0.5f,
        MaxExposure = 2,
        BloomIntensity = 1,
        BloomThreshold = 0.6f,
        AdaptionSpeed = 100,
      };

      _colorEncoder = new ColorEncoder(GraphicsService)
      {
        SourceEncoding = ColorEncoding.Rgb,
        TargetEncoding = _skybox.Encoding,
      };
    }
Exemplo n.º 13
0
        public FacialAnimationSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            _graphicsScreen = new DeferredGraphicsScreen(Services)
            {
                DrawReticle = false
            };
            GraphicsService.Screens.Insert(0, _graphicsScreen);
            Services.Register(typeof(DebugRenderer), null, _graphicsScreen.DebugRenderer);
            Services.Register(typeof(IScene), null, _graphicsScreen.Scene);

            // Add a game object which adds some GUI controls for the deferred graphics
            // screen to the Options window.
            GameObjectService.Objects.Add(new DeferredGraphicsOptionsObject(Services));

            // Use a fixed camera.
            var projection = new PerspectiveProjection();

            projection.SetFieldOfView(
                ConstantsF.PiOver4,
                GraphicsService.GraphicsDevice.Viewport.AspectRatio,
                0.1f,
                10);
            var cameraNode = new CameraNode(new Camera(projection));

            cameraNode.LookAt(new Vector3(0.15f, 0.15f, 0.5f), new Vector3(0.1f, 0.15f, 0), Vector3.Up);
            _graphicsScreen.Scene.Children.Add(cameraNode);
            _graphicsScreen.ActiveCameraNode = cameraNode;

            // Lighting setup:
            var keyLight = new LightNode(new Spotlight {
                DiffuseIntensity = 0.6f, SpecularIntensity = 0.4f
            });

            keyLight.LookAt(new Vector3(-2, 2, 2), new Vector3(), Vector3.Up);
            _graphicsScreen.Scene.Children.Add(keyLight);

            var backLight = new LightNode(new Spotlight {
                DiffuseIntensity = 0.3f, SpecularIntensity = 0.3f
            });

            backLight.LookAt(new Vector3(1, 0.5f, -2), new Vector3(), Vector3.Up);
            _graphicsScreen.Scene.Children.Add(backLight);

            var fillLight = new LightNode(new AmbientLight {
                HemisphericAttenuation = 1, Intensity = 0.1f
            });

            _graphicsScreen.Scene.Children.Add(fillLight);

            // The scene does not have a proper background. That's why the exposure is a
            // bit off. --> Reduce the max exposure.
            var hdrFilter = _graphicsScreen.PostProcessors.OfType <HdrFilter>().First();

            hdrFilter.MaxExposure = 6;

            // Load the customized "Sintel" model (original: Durian Open Movie Project - http://www.sintel.org/).
            var model = ContentManager.Load <ModelNode>("Sintel/Sintel-Head").Clone();

            model.PoseWorld = new Pose(new Vector3(0, 0, 0), Matrix.CreateRotationY(MathHelper.ToRadians(10)) * Matrix.CreateRotationX(-MathHelper.ToRadians(90)));
            _graphicsScreen.Scene.Children.Add(model);

            // The model consists of a root node and a mesh node.
            //  ModelNode "Sintel-Head"
            //    MeshNode "Sintel"
            _sintel = (MeshNode)model.Children[0];

            // The model contains two skeletal animations:
            // - "MOUTH-open" is just a single frame.
            // - "Test" is a short animation (250 frames).

            // In the Options window, we will add a slider to move the jaw.
            // Slider.Value = 0 ... mouth closed (default)
            _mouthClosedPose = SkeletonPose.Create(_sintel.Mesh.Skeleton);
            // Slider.Value = 1 ... mouth open (copied from the "MOUTH-open" animation)
            SkeletonKeyFrameAnimation mouthOpen = _sintel.Mesh.Animations["MOUTH-open"];

            _mouthOpenPose = SkeletonPose.Create(_sintel.Mesh.Skeleton);
            mouthOpen.GetValue(TimeSpan.Zero, ref _mouthOpenPose, ref _mouthOpenPose, ref _mouthOpenPose);

            // Turn the "Test" animation into an endless loop.
            _skeletalAnimation = new AnimationClip <SkeletonPose>(_sintel.Mesh.Animations["Test"])
            {
                Duration     = TimeSpan.MaxValue,
                LoopBehavior = LoopBehavior.Cycle
            };

            // Mesh has several morph targets for facial animation, which are imported
            // automatically via the content pipeline. Unfortunately, the XNA content
            // pipeline cannot import morph target animations automatically.
            // In this demo, we will create a morph target animation in code.
            _morphingAnimation = CreateMorphingAnimation();

            CreateGuiControls();
        }
Exemplo n.º 14
0
        // OnLoad() is called when the GameObject is added to the IGameObjectService.
        protected override void OnLoad()
        {
            var graphicsService   = _services.GetInstance <IGraphicsService>();
            var gameObjectService = _services.GetInstance <IGameObjectService>();

            // Check if the game object manager has another ProceduralObject instance.
            var otherProceduralObject = gameObjectService.Objects
                                        .OfType <ProceduralObject>()
                                        .FirstOrDefault(o => o != this);
            Mesh mesh;

            if (otherProceduralObject != null)
            {
                // This ProceduralObject is not the first. We re-use rigid body data and
                // the mesh from the existing instance.
                var otherBody = otherProceduralObject._rigidBody;
                _rigidBody = new RigidBody(otherBody.Shape, otherBody.MassFrame, otherBody.Material);
                mesh       = otherProceduralObject._meshNode.Mesh;
            }
            else
            {
                // This is the first ProceduralObject instance. We create a new rigid body
                // and a new mesh.
                var shape = new MinkowskiSumShape(new GeometricObject(new SphereShape(0.05f)), new GeometricObject(new BoxShape(0.5f, 0.5f, 0.5f)));
                _rigidBody = new RigidBody(shape);

                // Create a DigitalRune.Geometry.Meshes.TriangleMesh from the RigidBody's
                // shape and convert this to a DigitalRune.Graphics.Mesh.
                var triangleMesh = _rigidBody.Shape.GetMesh(0.01f, 4);
                mesh = new Mesh {
                    Name = "ProceduralObject"
                };
                var submesh = CreateSubmeshWithTexCoords(graphicsService.GraphicsDevice, triangleMesh, MathHelper.ToRadians(70));
                mesh.Submeshes.Add(submesh);

                // Next, we need a material. We can load a predefined material (*.drmat file)
                // with the content manager.
                //var material = content.Load<Material>("Default");

                // Alternatively, we can load some effects and build the material here:
                Material material = new Material();

                // We need an EffectBinding for each render pass.
                // The "Default" pass uses a BasicEffectBinding (which is an EffectBinding
                // for the XNA BasicEffect).
                // Note: The "Default" pass is not used by the DeferredLightingScreen, so
                // we could ignore this pass in this sample project.
                BasicEffectBinding defaultEffectBinding = new BasicEffectBinding(graphicsService, null)
                {
                    LightingEnabled    = true,
                    TextureEnabled     = true,
                    VertexColorEnabled = false
                };
                defaultEffectBinding.Set("Texture", graphicsService.GetDefaultTexture2DWhite());
                defaultEffectBinding.Set("DiffuseColor", new Vector3(1, 1, 1));
                defaultEffectBinding.Set("SpecularColor", new Vector3(1, 1, 1));
                defaultEffectBinding.Set("SpecularPower", 100f);
                material.Add("Default", defaultEffectBinding);

                // EffectBinding for the "ShadowMap" pass.
                // Note: EffectBindings which are used in a Material must be marked with
                // the EffectParameterHint Material.
                var           content = _services.GetInstance <ContentManager>();
                EffectBinding shadowMapEffectBinding = new EffectBinding(
                    graphicsService,
                    content.Load <Effect>("DigitalRune\\Materials\\ShadowMap"),
                    null,
                    EffectParameterHint.Material);
                material.Add("ShadowMap", shadowMapEffectBinding);

                // EffectBinding for the "GBuffer" pass.
                EffectBinding gBufferEffectBinding = new EffectBinding(
                    graphicsService,
                    content.Load <Effect>("DigitalRune\\Materials\\GBuffer"),
                    null,
                    EffectParameterHint.Material);
                gBufferEffectBinding.Set("SpecularPower", 100f);
                material.Add("GBuffer", gBufferEffectBinding);

                // EffectBinding for the "Material" pass.
                EffectBinding materialEffectBinding = new EffectBinding(
                    graphicsService,
                    content.Load <Effect>("DigitalRune\\Materials\\Material"),
                    null,
                    EffectParameterHint.Material);
                materialEffectBinding.Set("DiffuseTexture", graphicsService.GetDefaultTexture2DWhite());
                materialEffectBinding.Set("DiffuseColor", new Vector3(1, 1, 1));
                materialEffectBinding.Set("SpecularColor", new Vector3(1, 1, 1));
                material.Add("Material", materialEffectBinding);

                // Assign this material to the submesh.
                submesh.SetMaterial(material);
            }

            // Create a scene graph node for the mesh.
            _meshNode = new MeshNode(mesh);

            // Set a random pose.
            var randomPosition = new Vector3F(
                RandomHelper.Random.NextFloat(-10, 10),
                RandomHelper.Random.NextFloat(2, 5),
                RandomHelper.Random.NextFloat(-20, 0));

            _rigidBody.Pose     = new Pose(randomPosition, RandomHelper.Random.NextQuaternionF());
            _meshNode.PoseWorld = _rigidBody.Pose;

            // Add mesh node to scene graph.
            var scene = _services.GetInstance <IScene>();

            scene.Children.Add(_meshNode);

            // Add rigid body to the physics simulation.
            var simulation = _services.GetInstance <Simulation>();

            simulation.RigidBodies.Add(_rigidBody);
        }