public TriangleData(Vector3 p0, Vector3 p1, Vector3 p2, Rigidbody rbObj, HeightField heightField)
    {
        this.point0 = p0;
        this.point1 = p1;
        this.point2 = p2;

        this.heightField = heightField;

        this.center = (p0 + p1 + p2) / 3.0f;

        this.height = Mathf.Abs(this.heightField.DistanceToWater(this.center));

        this.normal = Vector3.Cross(p1 - p0, p2 - p0).normalized;

        this.area = (Vector3.Distance(p1, p0) * Vector3.Distance(p2, p0) * Mathf.Sin(Vector3.Angle(p1 - p0, p2 - p0) * Mathf.Deg2Rad)) / 2f;

        this.velocity = this.GetTriangleVelocity(rbObj);

        //Velocity direction
        this.velocityDir = this.velocity.normalized;

        //Angle between the normal and the velocity
        //Negative if pointing in the opposite direction
        //Positive if pointing in the same direction
        this.cosTheta = Vector3.Dot(this.velocityDir, this.normal);
    }
Exemple #2
0
 private void clearAllLayersToolStripMenuItem_Click(object sender, EventArgs e)
 {
     layerBitmaps.Clear();
     layers.Clear();
     heightField = emptyHeightField;
     UpdateHeightfieldPanel();
 }
Exemple #3
0
        public void MultipleInstancesAreValid()
        {
            using (var physics = CreatePhysicsAndScene())
            {
                // A
                {
                    const int rows = 25, columns = 25;
                    var       samples = HeightFieldTestUtil.CreateSampleGrid(rows, columns);

                    var heightFieldDesc = new HeightFieldDesc()
                    {
                        NumberOfRows    = rows,
                        NumberOfColumns = columns,
                        Samples         = samples
                    };

                    HeightField heightField = physics.Physics.CreateHeightField(heightFieldDesc);
                }

                // B
                {
                    const int rows = 25, columns = 25;
                    var       samples = HeightFieldTestUtil.CreateSampleGrid(rows, columns);

                    var heightFieldDesc = new HeightFieldDesc()
                    {
                        NumberOfRows    = rows,
                        NumberOfColumns = columns,
                        Samples         = samples
                    };

                    HeightField heightField = physics.Physics.CreateHeightField(heightFieldDesc);
                }
            }
        }
    // Start is called before the first frame update
    void Start()
    {
        Filter[] tab = (Filter[])System.Enum.GetValues(typeof(Filter));

        dropdown.ClearOptions();
        List <Dropdown.OptionData> optionList = new List <Dropdown.OptionData>();

        foreach (var item in tab)
        {
            //string itemPrep = item.ToString().ToLowerInvariant().Replace('_',' ');
            optionList.Add(new Dropdown.OptionData(item.ToString()));
        }
        dropdown.AddOptions(optionList);

        slider.SetLimits(0, Hhaut * 2);
        slider.SetValues(Hbas, Hhaut);

        //slider.onValueChanged = ;

        //h saine (blackH) = 26
        //h tour eiffel whiteH = 324
        Box2D box = new Box2D(test.width, test.height);

        hf = new HeightField(test, box, Hbas, Hhaut);

        //meshView.CreateMeshFromsize(MAX_MESH_SIZE, MAX_MESH_SIZE);//255 max pour un mesh (yes merci les terrain qui marche mal)
        meshView.CreateMeshFromsize(test.width, test.height);


        //meshView.createBaseTest();

        StartCoroutine("updateHeigth");
    }
        public void MultipleDisposeCallsDoNotCauseAnException()
        {
            using (var physics = CreatePhysicsAndScene())
            {
                const int rows = 25, columns = 25;
                var       samples = HeightFieldTestUtil.CreateSampleGrid(rows, columns);

                var heightFieldDesc = new HeightFieldDesc()
                {
                    NumberOfRows    = rows,
                    NumberOfColumns = columns,
                    Samples         = samples
                };

                var cooking = physics.Physics.CreateCooking();

                var  stream     = new MemoryStream();
                bool cookResult = cooking.CookHeightField(heightFieldDesc, stream);

                stream.Position = 0;

                HeightField heightField = physics.Physics.CreateHeightField(stream);

                Assert.IsFalse(heightField.Disposed);

                // Dispose
                heightField.Dispose();
                Assert.IsTrue(heightField.Disposed);

                // Dispose again
                heightField.Dispose();
                Assert.IsTrue(heightField.Disposed);
            }
        }
        private void CreateHeightField(Scene scene, Material material)
        {
            const int   rows = 25, columns = 25;
            const float scale = 3;

            var samples = CreateSampleGrid(rows, columns);

            var heightFieldDesc = new HeightFieldDesc()
            {
                NumberOfRows    = rows,
                NumberOfColumns = columns,
                Samples         = samples
            };

            HeightField heightField = scene.Physics.CreateHeightField(heightFieldDesc);

            //

            var rigidActor = scene.Physics.CreateRigidStatic();

            var heightFieldGeom = new HeightFieldGeometry(heightField, MeshGeometryFlag.DoubleSided, 1, scale, scale);

            rigidActor.CreateShape(heightFieldGeom, material);

            rigidActor.GlobalPose = Matrix.Translation(30, 30, -32.5f);

            scene.AddActor(rigidActor);
        }
        private static void IntersectAndReport(HeightField heightfield, Vector3 start, Vector3 end)
        {
            MyIntersector intersector  = new MyIntersector(heightfield);
            Intersection  intersection = intersector.Intersect(start, end);

            Console.WriteLine((intersection != null) ? intersection.Position.ToString() : "no intersection");
        }
        private static void MeasureIntersectionPerformance(HeightField heightfield, Vector3 start, Vector3 end, int iterations)
        {
            Vector3 direction = end - start;

            MyIntersector      intersector = new MyIntersector(heightfield);
            FootprintDebugInfo debugInfo   = new FootprintDebugInfo();
            Intersection       isec        = intersector.Intersect(start, end, ref debugInfo);
            int visitedPixels = debugInfo.VisitedPixels.Count;

            Stopwatch sw = Stopwatch.StartNew();

            for (int i = 0; i < iterations; i++)
            {
                Intersection intersection = intersector.Intersect(start, end);
            }
            sw.Stop();

            Console.WriteLine("Intersection?: {0}", isec != null);
            Console.WriteLine("Ray length: {0:0.0}", direction.Length);
            Console.WriteLine("Visited pixels: {0}", visitedPixels);
            Console.WriteLine("Iterations: {0}", iterations);
            Console.WriteLine("Total time: {0} ms", sw.ElapsedMilliseconds);
            Console.WriteLine("Average time: {0:0.000} ms", sw.ElapsedMilliseconds / (double)iterations);
            double throughput = iterations / ((double)sw.ElapsedMilliseconds * 0.001);

            Console.WriteLine("Throughput: {0:0.000} traversals/s", throughput);
            Console.WriteLine("Throughput of visited pixels: {0:0.000} Mpx/s", throughput * visitedPixels * 1e-6);
        }
        void ReleaseDesignerOutlets()
        {
            if (XField != null)
            {
                XField.Dispose();
                XField = null;
            }

            if (YField != null)
            {
                YField.Dispose();
                YField = null;
            }

            if (WidthField != null)
            {
                WidthField.Dispose();
                WidthField = null;
            }

            if (HeightField != null)
            {
                HeightField.Dispose();
                HeightField = null;
            }
        }
        /// <summary>
        /// If no "Node" instance, this method tries to create one
        /// given the Collide.Shape component in this game object.
        /// </summary>
        /// <returns>True if the node was created - otherwise false.</returns>
        private bool TryInitialize(Shape shape, DebugRenderManager manager)
        {
            if (Node != null)
            {
                return(false);
            }

            Collide.Mesh mesh        = shape as Collide.Mesh;
            HeightField  heightField = shape as HeightField;

            if (mesh != null)
            {
                Node = InitializeMesh(mesh);
            }
            else if (heightField != null)
            {
                Node = InitializeHeightField(heightField);
            }
            else
            {
                Node = PrefabLoader.Instantiate <GameObject>(PrefabName);
                Node.transform.localScale = GetShape().GetScale();
            }

            if (Node != null)
            {
                var renderers = Node.GetComponentsInChildren <Renderer>();
                foreach (var renderer in renderers)
                {
                    renderer.sharedMaterial = manager.ShapeRenderMaterial;
                }
            }

            return(Node != null);
        }
        private void CreateTerrain()
        {
            //Load the height map
            Texture2D heigthMap = Engine.Graphics.CreateTexture2DFromFile("terrain.png");

            //Create the HeightField using the heigth map ,divide the HeightField into and 8x8 grid of sections
            //this will improve culling
            HeightField heigthField = new HeightField(heigthMap, 32, 32);

            heigthField.Materials[0].Diffuse = Color3.FromArgb(System.Drawing.Color.DarkGreen.ToArgb());

            //Uncomment this to texture the terrain
            heigthField.Materials[0].DiffuseMaps = new Texture2D[]
            {
                Engine.Graphics.CreateTexture2DFromFile("grass.jpg")
            };

            //smoot the height field using a 5x5 gaussian kernel with 4 pass
            heigthField.Smoot(5, 4);

            //Create the HeightField node translat it to the center of the scene, then scaling it to 1000 units in X and Z
            Engine.Scene.Create("HeightFieldNode", heigthField,
                                Igneel.Matrix.Translate(-0.5f, 0, -0.5f) *
                                Igneel.Matrix.Scale(1000, 100, 1000));
        }
        private static void TryIntersectionPerformance()
        {
            List <FloatMapImage> layers = new List <FloatMapImage>();

            layers.Add(((Bitmap)Bitmap.FromFile("../../data/2011-05-30_04-50-47_depth_0.png")).ToFloatMap());
            layers.Add(((Bitmap)Bitmap.FromFile("../../data/2011-05-30_04-50-47_depth_1.png")).ToFloatMap());
            layers.Add(((Bitmap)Bitmap.FromFile("../../data/2011-05-30_04-50-47_depth_2.png")).ToFloatMap());
            layers.Add(((Bitmap)Bitmap.FromFile("../../data/2011-05-30_04-50-47_depth_3.png")).ToFloatMap());
            layers.Add(((Bitmap)Bitmap.FromFile("../../data/2011-05-30_04-50-47_depth_4.png")).ToFloatMap());
            HeightField heightfield = new HeightField(layers);
            // no isec
            //Vector3 start = new Vector3(169, 181, 0);
            //Vector3 end = new Vector3(14, 191, 1);
            // isec at layer 4
            //Vector3 start = new Vector3(178, 180, 0);
            //Vector3 end = new Vector3(33, 38, 1);
            // no isec with 5 layers, traversing the filled areas
            //Vector3 start = new Vector3(9, 190, 0);
            //Vector3 end = new Vector3(131, 19, 1);
            Vector3 start      = new Vector3(100, 100, 0);
            Vector3 end        = new Vector3(117.5f, 115.5f, 1);
            int     iterations = 100000;

            MeasureIntersectionPerformance(heightfield, start, end, iterations);
        }
Exemple #13
0
        public void MultipleDisposeCallsDoNotCauseAnException()
        {
            using (var physics = CreatePhysicsAndScene())
            {
                const int rows = 25, columns = 25;
                var       samples = HeightFieldTestUtil.CreateSampleGrid(rows, columns);

                var heightFieldDesc = new HeightFieldDesc()
                {
                    NumberOfRows    = rows,
                    NumberOfColumns = columns,
                    Samples         = samples
                };

                HeightField heightField = physics.Physics.CreateHeightField(heightFieldDesc);

                Assert.IsFalse(heightField.Disposed);

                // Dispose
                heightField.Dispose();
                Assert.IsTrue(heightField.Disposed);

                // Dispose again
                heightField.Dispose();
                Assert.IsTrue(heightField.Disposed);
            }
        }
Exemple #14
0
 private void executeGeneratorToolStripMenuItem_Click(object sender, EventArgs e)
 {
     if (Document.SelectedRender != null && Document.ContainsGenerator((string)generatorListBox.SelectedItem))
     {
         HeightRender.Generator generator = Document.GetGenerator((string)generatorListBox.SelectedItem);
         if (generator != null && MessageBox.Show("Applying a generator will modify or replace the current height map. This action cannot be undone.\n\nWould you like to continue?", "Apply Generator", MessageBoxButtons.YesNo) == DialogResult.Yes)
         {
             lock (undoQueue) undoQueue.Clear();
             lock (redoQueue) redoQueue.Clear();
             HeightField field = Document.SelectedRender.HeightField;
             lock (field)
             {
                 try
                 {
                     for (int u = 0; u < field.Width; u++)
                     {
                         for (int v = 0; v < field.Height; v++)
                         {
                             field[u, v] = (float)generator(u, v, field);
                         }
                     }
                 }
                 catch (Exception ex)
                 {
                     MessageBox.Show(ex.Message, "There was a runtime error with your generator script.");
                 }
                 finally
                 {
                     UpdateRender();
                 }
             }
         }
     }
 }
Exemple #15
0
        private void CreateHeightField(Scene scene, Material material)
        {
            const int   rows = 25, columns = 25;
            const float scale = 3;

            var samples = CreateSampleGrid(rows, columns);

            var heightFieldDesc = new HeightFieldDesc()
            {
                NumberOfRows    = rows,
                NumberOfColumns = columns,
                Samples         = samples
            };

            var cooking = scene.Physics.CreateCooking();

            var  stream     = new MemoryStream();
            bool cookResult = cooking.CookHeightField(heightFieldDesc, stream);

            stream.Position = 0;

            HeightField heightField = scene.Physics.CreateHeightField(stream);

            //

            var rigidActor = scene.Physics.CreateRigidStatic();

            var heightFieldGeom = new HeightFieldGeometry(heightField, MeshGeometryFlag.DoubleSided, 1, scale, scale);

            rigidActor.CreateShape(heightFieldGeom, material);

            rigidActor.GlobalPose = Matrix4x4.CreateTranslation(30, 30, -32.5f);

            scene.AddActor(rigidActor);
        }
Exemple #16
0
        public void SetupHeightField()
        {
            _physics = CreatePhysicsAndScene();

            const int rows = 25, columns = 40;
            var       samples = HeightFieldTestUtil.CreateSampleGrid(rows, columns);

            var heightFieldDesc = new HeightFieldDesc()
            {
                NumberOfRows        = rows,
                NumberOfColumns     = columns,
                Samples             = samples,
                Thickness           = 4.2f,
                ConvexEdgeThreshold = 6.6f,
                Flags = HeightFieldFlag.NoBoundaryEdges
            };

            var cooking = _physics.Physics.CreateCooking();

            var  stream     = new MemoryStream();
            bool cookResult = cooking.CookHeightField(heightFieldDesc, stream);

            stream.Position = 0;

            _heightField = _physics.Physics.CreateHeightField(stream);

            Assert.IsNotNull(_heightField);
            Assert.IsFalse(_heightField.Disposed);
        }
    void GenerateMap()
    {
        var startTime = DateTime.Now;

        points = BlueNoiseGenerator.PoissonDiscSampling(rMin, rMax, 30, mapSize);
        List <Vertex> scaffolding = BlueNoiseGenerator.Scaffolding(mapSize);

        points.AddRange(scaffolding);

        var duration = DateTime.Now - startTime;

        Debug.Log("SeedPoints Done in " + duration.TotalSeconds + "s");
        startTime = DateTime.Now;

        List <Triangle> convexPoly = Triangulation.TriangulateConvexPolygon(scaffolding);

        triangles = Triangulation.TriangleSplittingAlgorithm(points, convexPoly);
        //triangles = Triangulation.IncrementalAlgorithm(points);

        duration = DateTime.Now - startTime;
        Debug.Log("Triangulation Done in " + duration.TotalSeconds + "s");
        startTime = DateTime.Now;

        triangles = DelaunayTriangulation.MakeTriangulationDelaunay(triangles);

        duration = DateTime.Now - startTime;
        Debug.Log("Delaunayification Done in " + duration.TotalSeconds + "s");
        startTime = DateTime.Now;

        triangles = DelaunayTriangulation.FillInNeighbours(triangles);

        duration = DateTime.Now - startTime;
        Debug.Log("Neighbours Done in " + duration.TotalSeconds + "s");
        startTime = DateTime.Now;

        // fill heightmap into y coordinates
        points = HeightField.PerlinIsland(points, mapSize, 0.1f, 0.7f, 4f, 3f, 6);

        duration = DateTime.Now - startTime;
        Debug.Log("Heightmap Done in " + duration.TotalSeconds + "s");
        startTime = DateTime.Now;

        triangles = Voronoi.GenerateCentroids(triangles, points);

        duration = DateTime.Now - startTime;
        Debug.Log("Centroids Done in " + duration.TotalSeconds + "s");
        startTime = DateTime.Now;

        cells = CellMeshCreator.SpawnMeshes(points, cell);

        duration = DateTime.Now - startTime;
        Debug.Log("Meshes Done in " + duration.TotalSeconds + "s");

        var camHeight = mapSize * 0.5f / Mathf.Tan(Camera.main.fieldOfView * 0.5f * Mathf.Deg2Rad);

        Camera.main.transform.position = new Vector3(mapSize / 2, camHeight * 1.1f, mapSize / 2);

        //DebugDraw();
    }
        public void CreateHeightfieldTest()
        {
            int rows    = 25;
            int columns = 25;

            HeightFieldSample[] samples = new HeightFieldSample[rows * columns];
            for (int r = 0; r < rows; r++)
            {
                for (int c = 0; c < columns; c++)
                {
                    // Put a z and x curve together
                    double h = Math.Sin(c) * Math.Cos(r) * short.MaxValue;

                    HeightFieldSample sample = new HeightFieldSample()
                    {
                        Height           = (short)h,
                        MaterialIndex0   = 0,
                        MaterialIndex1   = 1,
                        TessellationFlag = 0
                    };

                    samples[r * columns + c] = sample;
                }
            }

            HeightFieldDescription heightFieldDesc = new HeightFieldDescription()
            {
                NumberOfRows    = rows,
                NumberOfColumns = columns
            };

            heightFieldDesc.SetSamples(samples);

            using (CreateCoreAndScene())
            {
                HeightField heightField = this.Core.CreateHeightField(heightFieldDesc);

                //

                HeightFieldShapeDescription heightFieldShapeDesc = new HeightFieldShapeDescription()
                {
                    HeightField  = heightField,
                    HoleMaterial = 2,
                    // The max height of our samples is short.MaxValue and we want it to be 1
                    HeightScale = 1.0f / (float)short.MaxValue,
                    RowScale    = 3,
                    ColumnScale = 3
                };
                heightFieldShapeDesc.LocalPosition = new Vector3(-0.5f * rows * 1 * heightFieldShapeDesc.RowScale, 0, -0.5f * columns * 1 * heightFieldShapeDesc.ColumnScale);

                ActorDescription actorDesc = new ActorDescription()
                {
                    GlobalPose = Matrix.Translation(100, 0, 0),
                    Shapes     = { heightFieldShapeDesc }
                };

                Actor actor = this.Scene.CreateActor(actorDesc);
            }
        }
Exemple #19
0
        public void Cleanup()
        {
            _heightField.Dispose();
            _heightField = null;

            _physics.Dispose();
            _physics = null;
        }
		public void Cleanup()
		{
			_heightField.Dispose();
			_heightField = null;

			_physics.Dispose();
			_physics = null;
		}
        public ContentPipelineHeightFieldSample(Microsoft.Xna.Framework.Game game)
            : base(game)
        {
            // Add basic force effects.
            Simulation.ForceEffects.Add(new Gravity());
            Simulation.ForceEffects.Add(new Damping());

            // Load height field model and add it to the graphics scene.
            _heightFieldModelNode = ContentManager.Load <ModelNode>("HeightField/TerrainHeights").Clone();
            GraphicsScreen.Scene.Children.Add(_heightFieldModelNode);

            // The UserData contains the collision shape of type HeightField.
            HeightField heightField = (HeightField)_heightFieldModelNode.UserData;

            _heightFieldModelNode.PoseWorld = new Pose(new Vector3F(-heightField.WidthX / 2, 0, -heightField.WidthZ / 2));

            // Create rigid body.
            _heightFieldBody = new RigidBody(heightField, null, null)
            {
                MotionType = MotionType.Static,
                Pose       = _heightFieldModelNode.PoseWorld,

                // The PhysicsSample class should not draw the height field.
                UserData = "NoDraw",
            };
            Simulation.RigidBodies.Add(_heightFieldBody);

            // Distribute a few spheres and boxes across the landscape.
            SphereShape sphereShape = new SphereShape(0.5f);

            for (int i = 0; i < 30; i++)
            {
                Vector3F position = RandomHelper.Random.NextVector3F(-30, 30);
                position.Y = 20;

                RigidBody body = new RigidBody(sphereShape)
                {
                    Pose = new Pose(position)
                };
                Simulation.RigidBodies.Add(body);
            }

            BoxShape boxShape = new BoxShape(1, 1, 1);

            for (int i = 0; i < 30; i++)
            {
                Vector3F position = RandomHelper.Random.NextVector3F(-30, 30);
                position.Y = 20;

                RigidBody body = new RigidBody(boxShape)
                {
                    Pose = new Pose(position)
                };
                Simulation.RigidBodies.Add(body);
            }
        }
Exemple #22
0
        /// <summary>
        /// If no "Node" instance, this method tries to create one
        /// given the Collide.Shape component in this game object.
        /// </summary>
        /// <returns>True if the node was created - otherwise false.</returns>
        private bool TryInitialize(Shape shape, DebugRenderManager manager)
        {
            if (Node != null)
            {
                return(false);
            }

            Collide.Mesh   mesh           = shape as Collide.Mesh;
            HeightField    heightField    = shape as HeightField;
            Cone           cone           = shape as Cone;
            HollowCone     hollowCone     = shape as HollowCone;
            HollowCylinder hollowCylinder = shape as HollowCylinder;

            if (mesh != null)
            {
                Node = InitializeMesh(mesh);
            }
            else if (heightField != null)
            {
                Node = InitializeHeightField(heightField);
            }
            else if (hollowCone != null)
            {
                Node = new GameObject(PrefabName);
                Node.AddComponent <MeshRenderer>().sharedMaterial = manager.ShapeRenderMaterial;
                Node.AddComponent <MeshFilter>().sharedMesh       = ShapeVisualHollowCone.GenerateMesh(shape);
            }
            else if (hollowCylinder != null)
            {
                Node = new GameObject(PrefabName);
                Node.AddComponent <MeshRenderer>().sharedMaterial = manager.ShapeRenderMaterial;
                Node.AddComponent <MeshFilter>().sharedMesh       = ShapeVisualHollowCylinder.GenerateMesh(shape);
            }
            else if (cone != null)
            {
                Node = new GameObject(PrefabName);
                Node.AddComponent <MeshRenderer>().sharedMaterial = manager.ShapeRenderMaterial;
                Node.AddComponent <MeshFilter>().sharedMesh       = ShapeVisualCone.GenerateMesh(shape);
            }
            else
            {
                Node = PrefabLoader.Instantiate <GameObject>(PrefabName);
                Node.transform.localScale = GetShape().GetScale();
            }

            if (Node != null)
            {
                var renderers = Node.GetComponentsInChildren <Renderer>();
                foreach (var renderer in renderers)
                {
                    renderer.sharedMaterial = manager.ShapeRenderMaterial;
                }
            }

            return(Node != null);
        }
Exemple #23
0
        public override DRModelNodeContent Process(Texture2DContent input, ContentProcessorContext context)
        {
            HeightField        heightField = CreateHeightFieldFromTexture(input);
            DRModelNodeContent model       = CreateModel(input, context, heightField);

            // The content processor returns a ModelNode. The HeightField shape is stored
            // in ModelNode.UserData.
            model.UserData = heightField;

            return(model);
        }
        public void TrySimpleHeightfield1x1WithPerpendicularRay()
        {
            FloatMapImage data = new FloatMapImage(1, 1, PixelFormat.Greyscale);

            data.Image[0, 0, 0] = 0.5f;
            HeightField heightfield = new HeightField(new[] { data });

            Vector3 start = new Vector3(0.1f, 0.1f, 0.25f);
            Vector3 end   = new Vector3(0.1f, 0.1f, 0.75f);

            IntersectAndReport(heightfield, start, end);
        }
Exemple #25
0
    public UpdateObjMesh(GameObject floatObject, GameObject sea)
    {
        objTrans    = floatObject.GetComponent <Transform> ();
        objRB       = floatObject.GetComponent <Rigidbody> ();
        heightField = sea.GetComponent <HeightField> ();
        Mesh mesh = floatObject.GetComponent <MeshFilter> ().mesh;

        verArr       = mesh.vertices;
        triArr       = mesh.triangles;
        verCount     = mesh.vertexCount;
        verArrGlobal = new Vector3[verCount];
        verHeight    = new float[verCount];
        isSubmerged  = false;
    }
Exemple #26
0
        public DebugRendererSample(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);

            // Load a sprite font.
            var spriteFont = UIContentManager.Load <SpriteFont>("UI Themes/BlendBlue/Default");

            // Create a new debug renderer.
            _debugRenderer = new DebugRenderer(GraphicsService, spriteFont)
            {
                DefaultColor = Color.White,
            };

            // A normal XNA model.
            _xnaModel = ContentManager.Load <Model>("Saucer3/saucer");

            // A DigitalRune model.
            _modelNode           = ContentManager.Load <ModelNode>("Dude/Dude").Clone();
            _modelNode.PoseLocal = new Pose(new Vector3F(6, 0, -7));

            // Create a geometric object with a height field shape.
            var numberOfSamplesX = 20;
            var numberOfSamplesZ = 20;
            var samples          = new float[numberOfSamplesX * numberOfSamplesZ];

            for (int z = 0; z < numberOfSamplesZ; z++)
            {
                for (int x = 0; x < numberOfSamplesX; x++)
                {
                    samples[z * numberOfSamplesX + x] = 1.0f + (float)(Math.Cos(z / 2f) * Math.Sin(x / 2f) * 1.0f);
                }
            }
            HeightField heightField = new HeightField(0, 0, 120, 120, samples, numberOfSamplesX, numberOfSamplesZ);

            _geometricObject = new GeometricObject(heightField, new Pose(new Vector3F(5, 0, -5)))
            {
                Scale = new Vector3F(0.01f, 0.05f, 0.02f),
            };
        }
        public void MultipleInstancesAreValid()
        {
            using (var physics = CreatePhysicsAndScene())
            {
                // A
                {
                    const int rows = 25, columns = 25;
                    var       samples = HeightFieldTestUtil.CreateSampleGrid(rows, columns);

                    var heightFieldDesc = new HeightFieldDesc()
                    {
                        NumberOfRows    = rows,
                        NumberOfColumns = columns,
                        Samples         = samples
                    };

                    var cooking = physics.Physics.CreateCooking();

                    var  stream     = new MemoryStream();
                    bool cookResult = cooking.CookHeightField(heightFieldDesc, stream);

                    stream.Position = 0;

                    HeightField heightField = physics.Physics.CreateHeightField(stream);
                }

                // B
                {
                    const int rows = 25, columns = 25;
                    var       samples = HeightFieldTestUtil.CreateSampleGrid(rows, columns);

                    var heightFieldDesc = new HeightFieldDesc()
                    {
                        NumberOfRows    = rows,
                        NumberOfColumns = columns,
                        Samples         = samples
                    };

                    var cooking = physics.Physics.CreateCooking();

                    var  stream     = new MemoryStream();
                    bool cookResult = cooking.CookHeightField(heightFieldDesc, stream);

                    stream.Position = 0;

                    HeightField heightField = physics.Physics.CreateHeightField(stream);
                }
            }
        }
Exemple #28
0
        // Modify the terrain height values to add the road to the terrain.
        private void ClampTerrainToRoad()
        {
            // We have to manipulate the height and normal texture of each tile which contains the road.
            foreach (var tile in _terrainObject.TerrainNode.Terrain.Tiles)
            {
                // Get the current height texture of the tile and extract the heights into a float array.
                var     heightTexture = tile.HeightTexture;
                float[] heights       = TerrainHelper.GetTextureLevelSingle(heightTexture, 0);

                // Create a temporary height field.
                var heightField = new HeightField(
                    tile.OriginX,
                    tile.OriginZ,
                    tile.WidthX,
                    tile.WidthZ,
                    heights,
                    heightTexture.Width,
                    heightTexture.Height);

                // Change the height values of the height field.
                TerrainRoadLayer.ClampTerrainToRoad(heightField, _roadPath, 8, 30, 10, 0.1f);

                // Rebuild the height texture.
                TerrainHelper.CreateHeightTexture(
                    GraphicsService.GraphicsDevice,
                    heights,
                    heightTexture.Width,
                    heightTexture.Height,
                    false,
                    ref heightTexture);

                // Rebuild the normal texture.
                var normalTexture = tile.NormalTexture;
                TerrainHelper.CreateNormalTexture(
                    GraphicsService.GraphicsDevice,
                    heights,
                    heightTexture.Width,
                    heightTexture.Height,
                    tile.CellSize,
                    false,
                    ref normalTexture);

                // Get rigid body that represents this tile.
                var rigidBody = Simulation.RigidBodies.First(body => body.UserData == tile);

                // Update the height values of the collision detection height field.
                ((HeightField)rigidBody.Shape).SetSamples(heights, heightTexture.Width, heightTexture.Height);
            }
        }
Exemple #29
0
 private void addLayerToolStripMenuItem_Click(object sender, EventArgs e)
 {
     if (openFileDialog.ShowDialog() == DialogResult.OK)
     {
         foreach (var fileName in openFileDialog.FileNames)
         {
             Bitmap newLayerBitmap = (Bitmap)Bitmap.FromFile(fileName);
             layerBitmaps.Add(newLayerBitmap);
             layers.Add(newLayerBitmap.ToFloatMap());
         }
         heightField = new HeightField(layers.ToArray());
         selectedIntersector.HeightField = heightField;
         UpdateHeightfieldPanel();
     }
 }
        public void TrySimpleHeightfield2x2()
        {
            FloatMapImage data = new FloatMapImage(2, 2, PixelFormat.Greyscale);

            data.Image[0, 0, 0] = 0.5f;
            data.Image[0, 1, 0] = 0.5f;
            data.Image[1, 0, 0] = 0.5f;
            data.Image[1, 1, 0] = 0.5f;
            HeightField heightfield = new HeightField(new[] { data });

            Vector3 start = new Vector3(0.5f, 1.5f, 0.0f);
            Vector3 end   = new Vector3(2, 2, 1);

            IntersectAndReport(heightfield, start, end);
        }
Exemple #31
0
        public void HeightFieldWithHoles()
        {
            float[,] array = new float[2, 3];
            array[0, 0]    = float.NaN;
            array[0, 1]    = 1;
            array[0, 2]    = float.NaN;
            array[1, 0]    = float.NaN;
            array[1, 1]    = 4;
            array[1, 2]    = float.NaN;

            HeightField heightField = new HeightField(0, 0, 10, 20, _samples, 3, 8);

            // Check if returned values do not contain NaN.
            Assert.IsTrue(Numeric.IsFinite(heightField.InnerPoint.Y));
            Assert.IsTrue(Numeric.IsFinite(heightField.GetAabb(Pose.Identity).Extent.Length));
        }
Exemple #32
0
        public void Clone()
        {
            float[] array = new float[6] { 0, 1, 2, 3, 4, 5, };

              HeightField heightField = new HeightField(100, 200, 1.23f, 45.6f, array, 2, 3);
              HeightField clone = heightField.Clone() as HeightField;
              Assert.IsNotNull(clone);
              Assert.AreNotSame(heightField.Samples, clone.Samples);
              Assert.AreEqual(heightField.OriginX, clone.OriginX);
              Assert.AreEqual(heightField.OriginZ, clone.OriginZ);
              Assert.AreEqual(heightField.WidthX, clone.WidthX);
              Assert.AreEqual(heightField.WidthZ, clone.WidthZ);
              Assert.AreEqual(heightField.Depth, clone.Depth);
              Assert.AreEqual(heightField.NumberOfSamplesX, clone.NumberOfSamplesX);
              Assert.AreEqual(heightField.NumberOfSamplesZ, clone.NumberOfSamplesZ);
              Assert.AreEqual(heightField.GetAabb(Pose.Identity).Minimum, clone.GetAabb(Pose.Identity).Minimum);
              Assert.AreEqual(heightField.GetAabb(Pose.Identity).Maximum, clone.GetAabb(Pose.Identity).Maximum);
        }
		public void SetupHeightField()
		{
			_physics = CreatePhysicsAndScene();

			const int rows = 25, columns = 40;
			var samples = HeightFieldTestUtil.CreateSampleGrid(rows, columns);

			var heightFieldDesc = new HeightFieldDesc()
			{
				NumberOfRows = rows,
				NumberOfColumns = columns,
				Samples = samples,
				Thickness = 4.2f,
				ConvexEdgeThreshold = 6.6f,
				Flags = HeightFieldFlag.NoBoundaryEdges
			};

			_heightField = _physics.Physics.CreateHeightField(heightFieldDesc);

			Assert.IsNotNull(_heightField);
			Assert.IsFalse(_heightField.Disposed);
		}
Exemple #34
0
 public void Setup()
 {
     _samples = new float [] { 0, 1, 2,
                         3, 4, 2,
                         1, 0, 1,
                         2, 2, 2,
                         5, 3, 2,
                         1, 2, 1,
                         2, 0, 3,
                        -1, 0, 2 };
       _field = new HeightField
       {
     OriginX = 1000,
     OriginZ = 2000,
     WidthX = 100,
     WidthZ = 200,
       };
       _field.SetSamples(_samples, 3, 8);
 }
Exemple #35
0
        public void HeightFieldWithHoles()
        {
            float[,] array = new float[2, 3];
              array[0, 0] = float.NaN;
              array[0, 1] = 1;
              array[0, 2] = float.NaN;
              array[1, 0] = float.NaN;
              array[1, 1] = 4;
              array[1, 2] = float.NaN;

              HeightField heightField = new HeightField(0, 0, 10, 20, _samples, 3, 8);

              // Check if returned values do not contain NaN.
              Assert.IsTrue(Numeric.IsFinite(heightField.InnerPoint.Y));
              Assert.IsTrue(Numeric.IsFinite(heightField.GetAabb(Pose.Identity).Extent.Length));
        }
Exemple #36
0
    private Detour.AtavismNavTile BuildTileMesh(int tx, int ty, RecastVertex min, RecastVertex max)
    {
        Config.Width = Config.TileSize + Config.BorderSize * 2;
        Config.Height = Config.TileSize + Config.BorderSize * 2;
        Config.MinBounds = min;
        Config.MaxBounds = max;
        Config.MinBounds.X -= Config.BorderSize * Config.CellSize;
        Config.MinBounds.Z -= Config.BorderSize * Config.CellSize;

        Config.MaxBounds.X += Config.BorderSize * Config.CellSize;
        Config.MaxBounds.Z += Config.BorderSize * Config.CellSize;

        HeightField heightfield = new HeightField(Config.Width, Config.Height, Config.MinBounds.ToArray(), Config.MaxBounds.ToArray(), Config.CellSize, Config.CellHeight);

        short[] triAreas = new short[Geometry.ChunkyTriMesh.MaxTrisPerChunk];

        float[] tbmin = new float[2], tbmax = new float[2];
        tbmin[0] = Config.MinBounds.X;
        tbmin[1] = Config.MinBounds.Z;

        tbmax[0] = Config.MaxBounds.X;
        tbmax[1] = Config.MaxBounds.Z;

        int[] cid = new int[512];

        int ncid = Geometry.ChunkyTriMesh.GetChunksOverlappingRect(tbmin, tbmax, ref cid, 512);

        if (ncid == 0)
            return null;

        for (int i = 0; i < ncid; i++)
        {
            ChunkyTriMeshNode node = Geometry.ChunkyTriMesh.Nodes[cid[i]];
            int[] tris = new int[node.n * 3];
            Array.Copy(Geometry.ChunkyTriMesh.Tris, node.i * 3, tris, 0, node.n * 3);
            List<int> ctris = new List<int>(tris);
            int nctris = node.n;

            Array.Clear(triAreas, 0, triAreas.Length);
            Geometry.MarkWalkableTriangles(Config.WalkableSlopeAngle, ctris, nctris, ref triAreas);

            heightfield.RasterizeTriangles(Geometry, ctris, nctris, triAreas, Config.WalkableClimb);
        }

        heightfield.FilterLowHangingWalkableObstacles(Config.WalkableClimb);
        heightfield.FilterLedgeSpans(Config.WalkableHeight, Config.WalkableClimb);
        heightfield.FilterWalkableLowHeightSpans(Config.WalkableHeight);

        CompactHeightfield compactHeightfield = new CompactHeightfield(Config.WalkableHeight, Config.WalkableClimb, heightfield);
        compactHeightfield.ErodeWalkableArea(Config.WalkableRadius);

        // optional convex volumes

        compactHeightfield.BuildDistanceField();
        compactHeightfield.BuildRegions(Config.BorderSize, Config.MinRegionArea, Config.MergeRegionArea);

        ContourSet contourSet = new ContourSet(compactHeightfield, Config.MaxSimplificationError, Config.MaxEdgeLength);

        if (contourSet.NConts == 0)
            return null;

        PolyMesh polyMesh = new PolyMesh(contourSet, Config.MaxVertexesPerPoly);

        DetailPolyMesh detailPolyMesh = new DetailPolyMesh(polyMesh, compactHeightfield, Config.DetailSampleDistance,
                                                            Config.DetailSampleMaxError);

        // Convert the Areas and Flags for path weighting
        for (int i = 0; i < polyMesh.NPolys; i++)
        {

            if (polyMesh.Areas[i] == Geometry.WalkableArea)
            {
                polyMesh.Areas[i] = 0; // Sample_polyarea_ground
                polyMesh.Flags[i] = 1; // Samply_polyflags_walk
            }
        }
        NavMeshCreateParams param = new NavMeshCreateParams
        {
            Verts = polyMesh.Verts,
            VertCount = polyMesh.NVerts,
            Polys = polyMesh.Polys,
            PolyAreas = polyMesh.Areas,
            PolyFlags = polyMesh.Flags,
            PolyCount = polyMesh.NPolys,
            Nvp = polyMesh.Nvp,
            DetailMeshes = detailPolyMesh.Meshes,
            DetailVerts = detailPolyMesh.Verts,
            DetailVertsCount = detailPolyMesh.NVerts,
            DetailTris = detailPolyMesh.Tris,
            DetailTriCount = detailPolyMesh.NTris,

            // Off Mesh data
            OffMeshConVerts = Geometry.OffMeshConnectionVerts.ToArray(),
            OffMeshConRad = Geometry.OffMeshConnectionRadii.ToArray(),
            OffMeshConDir = Geometry.OffMeshConnectionDirections.ToArray(),
            OffMeshConAreas = Geometry.OffMeshConnectionAreas.ToArray(),
            OffMeshConFlags = Geometry.OffMeshConnectionFlags.ToArray(),
            OffMeshConUserId = Geometry.OffMeshConnectionIds.ToArray(),
            OffMeshConCount = (int)Geometry.OffMeshConnectionCount,
            // end off mesh data

            WalkableHeight = Config.WalkableHeight,
            WalkableRadius = Config.WalkableRadius,
            WalkableClimb = Config.WalkableClimb,
            BMin = new float[] { polyMesh.BMin[0], polyMesh.BMin[1], polyMesh.BMin[2] },
            BMax = new float[] { polyMesh.BMax[0], polyMesh.BMax[1], polyMesh.BMax[2] },
            Cs = polyMesh.Cs,
            Ch = polyMesh.Ch,
            BuildBvTree = true,
            TileX = tx,
            TileY = ty,
            TileLayer = 0
        };
        return new Detour.AtavismNavTile(param);
    }