Exemple #1
0
        public void DrawOctree(OctTree<TriMesh.Vertex> octree)
        {
            Stack< Cell<TriMesh.Vertex>> cellStack =
                new Stack< Cell<TriMesh.Vertex>>();

            cellStack.Push(octree.Root);

            while (cellStack.Count != 0)
            {
                 Cell<TriMesh.Vertex> cell = cellStack.Pop();

                #region Draw box

                DrawBindBox(cell.Box);

                #endregion

                if (cell.Childrens != null)
                {
                    for (int i = 0; i < cell.Childrens.Length; i++)
                    {
                        cellStack.Push(cell.Childrens[i]);
                    }
                }
            }

            cellStack = null;

            GL.Flush();
        }
    public OctTree <TriangleBound> ConstructSceneOctree(List <TriangleInfo> sceneTriangles, Bounds bound)
    {
        int          count    = 0;
        AABBBoundBox maxBound = new AABBBoundBox(bound);

        _octree = new OctTree <TriangleBound>(maxBound);
        List <TriangleInfo> triangleList = new List <TriangleInfo>(triangleCountInOneGroup);

        foreach (TriangleInfo tri in sceneTriangles)
        {
            triangleList.Add(tri);
            if (triangleList.Count == triangleCountInOneGroup)
            {
                TriangleBound triangleBound = GroupBoundBox(triangleList);

                //boundList.Add(triangleBound);
                if (maxBound.Contains(triangleBound.GetBoundBox()) || maxBound.Overlap(triangleBound.boundBox))
                {
                    _octree.Insert(triangleBound);
                    count++;
                }
                triangleList.Clear();
            }
        }
        if (triangleList.Count != 0)
        {
            _octree.Insert(GroupBoundBox(triangleList));
            count++;
        }

        Debug.Log(count);
        _octree.UpdateTree();
        return(_octree);
    }
        public void DontAddPoint()
        {
            var ut    = new OctTree <object>(BoundingCuboid.Max, 10, new SimpleOctTreeDivisionStrategy <object>());
            var point = new Point3Int <object>(Point3Int.Zero, new object());

            Assert.IsFalse(ut.Points.Contains(point));
        }
Exemple #4
0
 public void MakeDungeon()
 {
     root = new OctTree(totalBounds);
     root.GenerateZones(depth, minRoomSize);
     roomNodeList = new LinkedList <RoomNode> ();
     GenerateRooms(root);
     ConnectRooms();
 }
Exemple #5
0
 public Vertex(OctTree <TCellData, TVertexData> tree, int baseLevel, Vector3 position)
 {
     this.tree      = tree;
     this.baseLevel = baseLevel;
     uid            = tree.getVertexUID;
     data           = new TVertexData();
     connections    = new List <Vertex[]>();
     this.position  = position;
     tree.vertices.Add(this);
 }
Exemple #6
0
 public void SetParams(Vector3 voxelSize, OctTree <TriangleBound> tree)
 {
     _octree    = tree;
     _voxelSize = voxelSize;
     _region    = tree.region;
     _originPos = _region.min;
     _xMax      = Mathf.RoundToInt(_region.size.x / _voxelSize.x);
     _yMax      = Mathf.RoundToInt(_region.size.y / _voxelSize.y);
     _zMax      = Mathf.RoundToInt(_region.size.z / _voxelSize.z);
     _voxels    = new bool[_xMax, _yMax, _zMax];
 }
 public SplitShellWithCurves(Shell shell, Path closedBorder, double precision)
 {
     this.shell        = shell;
     this.closedBorder = closedBorder;
     faceOcttree       = new OctTree <Face>(shell.GetExtent(precision), precision);
     for (int i = 0; i < shell.Faces.Length; i++)
     {
         faceOcttree.AddObject(shell.Faces[i]);
     }
     this.precision = precision;
 }
        public void AddAPointAssertExists(int x, int y, int z)
        {
            var ut        = new OctTree <object>(BoundingCuboid.Max, 10, new SimpleOctTreeDivisionStrategy <object>());
            var point3Int = new Point3Int(x, y, z);

            var point = new Point3Int <object>(point3Int, new object());

            ut.Add(point);

            Assert.Contains(point, ut.Points);
        }
Exemple #9
0
    public void CreateOctree()
    {
        octree = new OctTree <BoxObject>(new AABBBoundBox(-5000f * Vector3.one, 5000f * Vector3.one));
        for (int i = 0; i < collisionObjects.Count; i++)
        {
            octree.Insert(collisionObjects[i]);
        }
        octree.UpdateTree();
        int d = octree.GetMaxTreeDepth();

        Debug.Log(d + " " + Mathf.Pow(8, d) / (d - 1));
    }
 public void Voxelize()
 {
     octree = new OctTree <VoxelBound>(new AABBBoundBox(voxelBoundBox.bounds));
     InitVoxelArray();
     foreach (VoxelBound tBound in _voxelArray)
     {
         octree.Insert(tBound);
     }
     octree.UpdateTree();
     InitTriangleInfoDic();
     IntersectTest();
 }
Exemple #11
0
    private OctTree <T> CreateNode(AABBBoundBox region, List <T> objList)
    {
        if (objList.Count == 0)
        {
            return(null);
        }
        OctTree <T> ret = new OctTree <T>(region, objList);

        ret.parent    = this;
        ret.treeDepth = treeDepth + 1;
        return(ret);
    }
Exemple #12
0
 public Cell(Cell parent, CellVertex index, Vertex[] vertices)
 {
     this.index  = index;
     this.parent = parent;
     level       = parent.level + 1;
     tree        = parent.tree;
     uid         = tree.getCellUID;
     //vertices = new Vertex[CellVerticesNumber];
     children = null;
     data     = new TCellData();
     tree.cells.Add(this);
     this.vertices = vertices;
 }
Exemple #13
0
 // Use this for initialization
 void Start()
 {
     mPointList = new List <Transform>();
     mLineList  = new List <LineRenderer>();
     OT         = FindObjectOfType <OctTree>();
     for (int i = 0; i < PointNum; i++)
     {
         mPointList.Add(GameObject.Instantiate(Point, new Vector3(RandomValue(SpaceScale),
                                                                  RandomValue(SpaceScale),
                                                                  RandomValue(SpaceScale)), Quaternion.identity).transform);
         mLineList.Add(mPointList[i].GetComponent <LineRenderer>());
     }
     OT.GenerateTree(mPointList);
 }
Exemple #14
0
        private Vertex VertexFromPoint(OctTree <Vertex> verticesOctTree, GeoPoint closeTo)
        {
            Vertex[] close = verticesOctTree.GetObjectsFromPoint(closeTo);
            for (int i = 0; i < close.Length; i++)
            {
                if ((close[i].Position | closeTo) == 0.0)
                {
                    return(close[i]);
                }
            }
            Vertex res = new Vertex(closeTo);

            verticesOctTree.AddObject(res);
            return(res);
        }
Exemple #15
0
 public void StartOctTree(float avgRadius)
 {
     narrowPhase = GetComponent <NarrowPhase> ();
     minSize     = avgRadius * 2;
     bounds      = narrowPhase.bounds;
     tmp         = new List <HRigidBody> ();
     for (int i = 0; i < narrowPhase.physicsEngines.Length; i++)
     {
         tmp.Add(narrowPhase.physicsEngines [i]);
     }
     uBounds        = new BoundingBox(new Vector3(0, 0, 0), new Vector3(bounds, bounds, bounds));
     octTree        = new OctTree(uBounds, tmp, narrowPhase, minSize);
     octTree.name   = "root";
     octTree.isRoot = true;
     octTree.BuildTree();
     octTree.GetCollisions();
 }
Exemple #16
0
    void SpawnObjects(OctTree node)
    {
        if (node.roomNode == null)
        {
            foreach (OctTree subNode in node.children)
            {
                SpawnObjects(subNode);
            }
        }
        else
        {
            int uniquesPlaced = 0;

            for (int i = 0; i < oneEachIndices.Length; i++)
            {
                if (oneEachIndices[i] == roomIndex)
                {
                    Vector3 placement = Util.RandomInWidthTwoCube() * 0.33f;
                    placement.y = -1;
                    placement   = Vector3.Scale(node.roomNode.roomBounds.extents, placement);

                    Vector3 facing = Vector3.up * Random.Range(0, 360);
                    Instantiate(mustPlaceOneOfEach[i], placement + node.roomNode.roomBounds.center, Quaternion.Euler(facing));
                    uniquesPlaced++;
                }
            }

            int numObjs = Random.Range(minItems, maxItems + 1);
            numObjs  = Mathf.Min(numObjs, Mathf.FloorToInt(node.roomNode.roomBounds.size.x), Mathf.FloorToInt(node.roomNode.roomBounds.size.z));
            numObjs -= uniquesPlaced;


            if (uniquesPlaced == 0)
            {
                for (int i = 0; i < numObjs; i++)
                {
                    Vector3 placement = Util.RandomInWidthTwoCube();
                    placement = Vector3.Scale(node.roomNode.roomBounds.extents, placement);
                    Vector3 facing = Vector3.up * Random.Range(0, 360);
                    Instantiate(prefabs[weightedSelect()], placement + node.roomNode.roomBounds.center, Quaternion.Euler(facing));
                }
            }
            roomIndex++;
        }
    }
Exemple #17
0
 public void RestartOctTree()
 {
     //count = 0;
     if (build)
     {
         octTree      = new OctTree(uBounds, tmp, narrowPhase, minSize);
         octTree.name = "root";
         octTree.BuildTree();
         //octTree.toString ("");
         octTree.GetCollisions();
     }
     else
     {
         //octTree.toString("");
         octTree.UpdateTree();
         //octTree.toString("");
         octTree.GetCollisions();
     }
 }
Exemple #18
0
    /// <summary>
    /// 获取相交测试结果
    /// </summary>
    /// <returns></returns>
    public bool[,,] GetIntersectionResult()
    {
#if UNITY_EDITOR
        // 遍历场景
        List <TriangleInfo> triangleList = _traverseSceneTriangleStage.RetreiveSceneTriangles();
        //_traverseSceneTriangleStage = null;
        EditorUtility.ClearProgressBar();
        // 构建八叉树
        OctTree <TriangleBound> octree = _octreeSceneStage.ConstructSceneOctree(triangleList, voxelizeBox.bounds);
        //_octreeSceneStage = null;
        EditorUtility.ClearProgressBar();
        // 相交测试W
        _intersectTestStage.SetParams(voxelSize, octree);
        bool[,,] intersectionResult = _intersectTestStage.IntersectTest();
        //_intersectTestStage = null;
        EditorUtility.ClearProgressBar();
        return(intersectionResult);
#endif
        return(null);
    }
Exemple #19
0
    public void GenerateZones(int depth, Vector3 minRoomSize)
    {
        if (depth < 1)
        {
            return;
        }

        if (boundary.extents.x < minRoomSize.x)
        {
            return;
        }
        if (boundary.extents.y < minRoomSize.y)
        {
            return;
        }
        if (boundary.extents.z < minRoomSize.z)
        {
            return;
        }

        Vector3 slice = RandomSlice(minRoomSize);


        for (int oct = 0; oct < 8; oct++)
        {
            Vector3 dir       = OctantDirection(oct);
            Vector3 farCorner = boundary.center + Vector3.Scale(boundary.extents, dir);
            Vector3 size      = Vector3.Scale(farCorner - slice, dir);
            Vector3 center    = slice + Vector3.Scale(size, dir * 0.5f);
            Bounds  newBounds = new Bounds(center, size);
            if (newBounds.size.x >= minRoomSize.x &&
                newBounds.size.y >= minRoomSize.y &&
                newBounds.size.z >= minRoomSize.z)
            {
                children[oct]            = new OctTree(newBounds);
                children[oct].gizmoColor = Color.Lerp(new Color(Mathf.Max(dir.x, 0), Mathf.Max(dir.y, 0), Mathf.Max(dir.z, 0)), gizmoColor, 0.5f);
                children[oct].GenerateZones(depth - 1, minRoomSize);
                childCount++;
            }
        }
    }
        public void GetPointsInBoundingArea(int octMinX, int octMinY, int octMinZ, int octMaxX, int octMaxY, int octMaxZ,
                                            int boundaryMinX, int boundaryMinY, int boundaryMinZ, int boundaryMaxX, int boundaryMaxY, int boundaryMaxZ,
                                            int x, int y, int z,
                                            bool expected)
        {
            var octTreeBoundingBox = new BoundingCuboid(new Point3Int(octMinX, octMinY, octMinZ), new Point3Int(octMaxX, octMaxY, octMaxZ));

            var area = new BoundingCuboid(new Point3Int(boundaryMinX, boundaryMinY, boundaryMinZ), new Point3Int(boundaryMaxX, boundaryMaxY, boundaryMaxZ));

            var obj   = new object();
            var point = new Point3Int <object>(x, y, z, obj);

            var ut = new OctTree <object>(octTreeBoundingBox, 10, new SimpleOctTreeDivisionStrategy <object>());

            ut.Add(point);

            var points = new List <Point3Int <object> >();

            ut.GetPointsWithinBoundary(area, ref points);

            Assert.AreEqual(expected, points.Contains(point));
        }
Exemple #21
0
    public void GenerateRooms(OctTree tree)
    {
        if (tree.GetChildCount() != 0)
        {
            foreach (OctTree subTree in tree.children)
            {
                if (subTree != null)
                {
                    GenerateRooms(subTree);
                }
            }
        }
        else
        {
            RoomNode newRoom = new RoomNode(tree.boundary);
            newRoom.roomBounds.extents -= Vector3.one * minSeparation;
            newRoom.RandomizeBounds(Vector3.one, minRoomSize, maxRoomSize);
            newRoom.QuantizeBounds(corridorSize);

            /*Vector3 center, extents;
             *
             * extents.x = Mathf.Floor (Random.Range (minRoomSize / 2, tree.boundary.extents.x));
             * extents.y = Mathf.Floor (Random.Range (minRoomSize / 2, tree.boundary.extents.y));
             * extents.z = Mathf.Floor (Random.Range (minRoomSize / 2, tree.boundary.extents.z));
             *
             * center = tree.boundary.center;
             * center.x = Mathf.Round (center.x + Random.Range (extents.x - tree.boundary.extents.x, tree.boundary.extents.x - extents.x));
             * center.y = Mathf.Round (center.y + Random.Range (extents.y - tree.boundary.extents.y, tree.boundary.extents.y - extents.y));
             * center.z = Mathf.Round (center.z + Random.Range (extents.z - tree.boundary.extents.z, tree.boundary.extents.z - extents.z));
             *
             * newRoom.roomBounds.center = center;
             * newRoom.roomBounds.extents = extents;*/

            newRoom.octTreeNode = tree;
            roomNodeList.AddFirst(newRoom);
            tree.roomNode = newRoom;
        }
    }
Exemple #22
0
 // Start is called before the first frame update
 void Start()
 {
     tree = new OctTree(nodeShape);
     ARSessionManager.RegisterChooseCameraConfigurationCallback(ChooseCameraConfiguration);
     ARSessionManager.enabled = true;
 }
Exemple #23
0
        private void CreateScene()
        {
            int xCount = 40;
            int yCount = 1;
            int zCount = 40;

            float sphereRadius = 10;
            float sphereMargin = 10;

            var sphereMeshGeometry3D = new Ab3d.Meshes.SphereMesh3D(new Point3D(0, 0, 0), sphereRadius, 10).Geometry;

            _oneMeshTriangleIndicesCount = sphereMeshGeometry3D.TriangleIndices.Count;


            PositionNormalTexture[] vertexBuffer;
            int[] indexBuffer;

            var size = new Vector3(xCount * (sphereRadius + sphereMargin), yCount * (sphereRadius + sphereMargin), zCount * (sphereRadius + sphereMargin));

            SubMeshesSample.CreateMultiMeshBuffer(center: new Vector3(0, 0, 0),
                                                  size: size,
                                                  xCount: xCount, yCount: yCount, zCount: zCount,
                                                  meshGeometry3D: sphereMeshGeometry3D,
                                                  vertexBuffer: out vertexBuffer,
                                                  indexBuffer: out indexBuffer);

            _multiMaterialMesh = new SimpleMesh <PositionNormalTexture>(vertexBuffer, indexBuffer,
                                                                        inputLayoutType: InputLayoutType.Position | InputLayoutType.Normal | InputLayoutType.TextureCoordinate);


            // Create all 3 SubMeshes at the beginning.
            // Though at first only the first SubMesh will be rendered (the other two have IndexCount set to 0),
            // this will allow us to simply change the StartIndexLocation and IndexCount of the SubMeshes
            // to show selected part without adding or removing any SubMesh (this would regenerate the RenderingQueues).
            // This way the selection is almost a no-op (only changing a few integer values and rendering the scene again).
            _multiMaterialMesh.SubMeshes = new SubMesh[]
            {
                // First sub-mesh will render triangles from the first to the start of selection (or all triangles if there is no selection)
                new SubMesh("MainSubMesh1")
                {
                    MaterialIndex = 0, StartIndexLocation = 0, IndexCount = indexBuffer.Length
                },

                // Second sub-mesh will render triangles after the selection (this one follows the first on to preserve the same material)
                new SubMesh("MainSubMesh2")
                {
                    MaterialIndex = 0, StartIndexLocation = 0, IndexCount = 0
                },

                // The third sub-mesh will render selected triangles and will use the second material for that.
                new SubMesh("SelectionSubMesh")
                {
                    MaterialIndex = 1, StartIndexLocation = 0, IndexCount = 0
                },
            };

            _disposables.Add(_multiMaterialMesh);

            // Create OctTree from vertexBuffer.
            // This will significantly improve hit testing performance (check this with uncommenting the dxScene.GetClosestHitObject call in OnMouseMouse method).
            _octTree = new OctTree(vertexBuffer, indexBuffer);


            var materials = new Ab3d.DirectX.Material[]
            {
                new Ab3d.DirectX.Materials.StandardMaterial()
                {
                    DiffuseColor = Colors.Green.ToColor3()
                },
                new Ab3d.DirectX.Materials.StandardMaterial()
                {
                    DiffuseColor = Colors.Red.ToColor3()
                }
            };

            _meshObjectNode = new Ab3d.DirectX.MeshObjectNode(_multiMaterialMesh, materials);

            _disposables.Add(_meshObjectNode);

            // Use SceneNodeVisual3D to show SceneNode in DXViewportView
            var sceneNodeVisual3D = new SceneNodeVisual3D(_meshObjectNode);

            MainViewport.Children.Add(sceneNodeVisual3D);
        }
        /// <summary>
        /// Called when a frame is to be drawn to the screen
        /// </summary>
        /// <param name="gameTime">The current time</param>
        public void Render(DwarfTime gameTime)
        {
            if (!ShowingWorld)
            {
                return;
            }
            ValidateShader();
            var frustum     = Camera.GetDrawFrustum();
            var renderables = EnumerateIntersectingObjects(frustum,
                                                           r => r.IsVisible && !ChunkManager.IsAboveCullPlane(r.GetBoundingBox()));

            // Controls the sky fog
            float x = (1.0f - Sky.TimeOfDay);

            x = x * x;
            DefaultShader.FogColor       = new Color(0.32f * x, 0.58f * x, 0.9f * x);
            DefaultShader.LightPositions = LightPositions;

            CompositeLibrary.Render(GraphicsDevice);
            CompositeLibrary.Update();

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

            // Computes the water height.
            float wHeight = WaterRenderer.GetVisibleWaterHeight(ChunkManager, Camera, GraphicsDevice.Viewport,
                                                                lastWaterHeight);

            lastWaterHeight = wHeight;

            // Draw reflection/refraction images
            WaterRenderer.DrawReflectionMap(renderables, gameTime, this, wHeight - 0.1f,
                                            GetReflectedCameraMatrix(wHeight),
                                            DefaultShader, GraphicsDevice);


            #region Draw Selection Buffer.

            if (SelectionBuffer == null)
            {
                SelectionBuffer = new SelectionBuffer(8, GraphicsDevice);
            }

            GraphicsDevice.RasterizerState   = RasterizerState.CullNone;
            GraphicsDevice.DepthStencilState = DepthStencilState.Default;
            GraphicsDevice.BlendState        = BlendState.Opaque;

            Plane slicePlane = WaterRenderer.CreatePlane(SlicePlane, new Vector3(0, -1, 0), Camera.ViewMatrix, false);

            if (SelectionBuffer.Begin(GraphicsDevice))
            {
                // Draw the whole world, and make sure to handle slicing
                DefaultShader.ClipPlane       = new Vector4(slicePlane.Normal, slicePlane.D);
                DefaultShader.ClippingEnabled = true;
                DefaultShader.View            = Camera.ViewMatrix;
                DefaultShader.Projection      = Camera.ProjectionMatrix;
                DefaultShader.World           = Matrix.Identity;

                //GamePerformance.Instance.StartTrackPerformance("Render - Selection Buffer - Chunks");
                ChunkRenderer.RenderSelectionBuffer(DefaultShader, GraphicsDevice, Camera.ViewMatrix);
                //GamePerformance.Instance.StopTrackPerformance("Render - Selection Buffer - Chunks");

                //GamePerformance.Instance.StartTrackPerformance("Render - Selection Buffer - Components");
                ComponentRenderer.RenderSelectionBuffer(renderables, gameTime, ChunkManager, Camera,
                                                        DwarfGame.SpriteBatch, GraphicsDevice, DefaultShader);
                //GamePerformance.Instance.StopTrackPerformance("Render - Selection Buffer - Components");

                //GamePerformance.Instance.StartTrackPerformance("Render - Selection Buffer - Instances");
                InstanceRenderer.Flush(GraphicsDevice, DefaultShader, Camera,
                                       InstanceRenderMode.SelectionBuffer);
                //GamePerformance.Instance.StopTrackPerformance("Render - Selection Buffer - Instances");

                SelectionBuffer.End(GraphicsDevice);
            }


            #endregion



            // Start drawing the bloom effect
            if (GameSettings.Default.EnableGlow)
            {
                bloom.BeginDraw();
            }

            // Draw the sky
            GraphicsDevice.Clear(DefaultShader.FogColor);
            DrawSky(gameTime, Camera.ViewMatrix, 1.0f, DefaultShader.FogColor);

            // Defines the current slice for the GPU
            float level = ChunkManager.World.Master.MaxViewingLevel + 0.25f;
            if (level > VoxelConstants.ChunkSizeY)
            {
                level = 1000;
            }

            SlicePlane = level;
            CaveView   = CaveView * 0.9f + TargetCaveView * 0.1f;
            DefaultShader.WindDirection = Weather.CurrentWind;
            DefaultShader.WindForce     = 0.0005f * (1.0f + (float)Math.Sin(Time.GetTotalSeconds() * 0.001f));
            // Draw the whole world, and make sure to handle slicing
            DefaultShader.ClipPlane       = new Vector4(slicePlane.Normal, slicePlane.D);
            DefaultShader.ClippingEnabled = true;
            //Blue ghost effect above the current slice.
            DefaultShader.GhostClippingEnabled = true;
            Draw3DThings(gameTime, DefaultShader, Camera.ViewMatrix);

            // Now we want to draw the water on top of everything else
            DefaultShader.ClippingEnabled      = true;
            DefaultShader.GhostClippingEnabled = false;

            //ComponentManager.CollisionManager.DebugDraw();

            DefaultShader.View                 = Camera.ViewMatrix;
            DefaultShader.Projection           = Camera.ProjectionMatrix;
            DefaultShader.GhostClippingEnabled = true;
            // Now draw all of the entities in the game
            DefaultShader.ClipPlane       = new Vector4(slicePlane.Normal, slicePlane.D);
            DefaultShader.ClippingEnabled = true;

            if (Debugger.Switches.DrawOcttree)
            {
                foreach (var box in OctTree.EnumerateBounds(frustum))
                {
                    Drawer3D.DrawBox(box.Item2, Color.Yellow, 1.0f / (float)(box.Item1 + 1), false);
                }
            }

            // Render simple geometry (boxes, etc.)
            Drawer3D.Render(GraphicsDevice, DefaultShader, Camera, DesignationDrawer, PlayerFaction.Designations, this);

            DefaultShader.EnableShadows = false;

            DefaultShader.View = Camera.ViewMatrix;

            ComponentRenderer.Render(renderables, gameTime, ChunkManager,
                                     Camera,
                                     DwarfGame.SpriteBatch, GraphicsDevice, DefaultShader,
                                     ComponentRenderer.WaterRenderType.None, lastWaterHeight);
            InstanceRenderer.Flush(GraphicsDevice, DefaultShader, Camera, InstanceRenderMode.Normal);

            if (Master.CurrentToolMode == GameMaster.ToolMode.BuildZone ||
                Master.CurrentToolMode == GameMaster.ToolMode.BuildWall ||
                Master.CurrentToolMode == GameMaster.ToolMode.BuildObject)
            {
                DefaultShader.View       = Camera.ViewMatrix;
                DefaultShader.Projection = Camera.ProjectionMatrix;
                DefaultShader.SetTexturedTechnique();
                GraphicsDevice.BlendState = BlendState.NonPremultiplied;
            }

            WaterRenderer.DrawWater(
                GraphicsDevice,
                (float)gameTime.TotalGameTime.TotalSeconds,
                DefaultShader,
                Camera.ViewMatrix,
                GetReflectedCameraMatrix(wHeight),
                Camera.ProjectionMatrix,
                new Vector3(0.1f, 0.0f, 0.1f),
                Camera,
                ChunkManager);
            ParticleManager.Render(this, GraphicsDevice);
            DefaultShader.ClippingEnabled = false;

            if (GameSettings.Default.EnableGlow)
            {
                bloom.DrawTarget = UseFXAA ? fxaa.RenderTarget : null;

                if (UseFXAA)
                {
                    fxaa.Begin(DwarfTime.LastTime);
                }
                bloom.Draw(gameTime.ToRealTime());
                if (UseFXAA)
                {
                    fxaa.End(DwarfTime.LastTime);
                }
            }
            else if (UseFXAA)
            {
                fxaa.End(DwarfTime.LastTime);
            }

            RasterizerState rasterizerState = new RasterizerState()
            {
                ScissorTestEnable = true
            };


            if (Debugger.Switches.DrawSelectionBuffer)
            {
                SelectionBuffer.DebugDraw(GraphicsDevice.Viewport.Bounds);
            }

            try
            {
                DwarfGame.SafeSpriteBatchBegin(SpriteSortMode.Deferred, BlendState.NonPremultiplied, Drawer2D.PointMagLinearMin,
                                               null, rasterizerState, null, Matrix.Identity);
                //DwarfGame.SpriteBatch.Draw(Shadows.ShadowTexture, Vector2.Zero, Color.White);
                if (IsCameraUnderwater())
                {
                    Drawer2D.FillRect(DwarfGame.SpriteBatch, GraphicsDevice.Viewport.Bounds, new Color(10, 40, 60, 200));
                }

                Drawer2D.Render(DwarfGame.SpriteBatch, Camera, GraphicsDevice.Viewport);

                IndicatorManager.Render(gameTime);
            }
            finally
            {
                DwarfGame.SpriteBatch.End();
            }

            if (Debugger.Switches.DrawComposites)
            {
                Vector2 offset = Vector2.Zero;
                foreach (var composite in CompositeLibrary.Composites)
                {
                    offset = composite.Value.DebugDraw(DwarfGame.SpriteBatch, (int)offset.X, (int)offset.Y);
                }
            }


            Master.Render(Game, gameTime);

            DwarfGame.SpriteBatch.GraphicsDevice.ScissorRectangle =
                DwarfGame.SpriteBatch.GraphicsDevice.Viewport.Bounds;


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

            lock (ScreenshotLock)
            {
                foreach (Screenshot shot in Screenshots)
                {
                    TakeScreenshot(shot.FileName, shot.Resolution);
                }

                Screenshots.Clear();
            }
        }
        private void AddPoint(OctTree <T> blf, OctTree <T> brf, OctTree <T> blb, OctTree <T> brb, OctTree <T> tlf, OctTree <T> trf, OctTree <T> tlb, OctTree <T> trb, Point3Int <T> point, Point3Int center)
        {
            // is on right side
            var point3Int = point.Point;

            if (point3Int.X > center.X)
            {
                // is on top side
                if (point3Int.Y > center.Y)
                {
                    // is on the backside
                    if (point3Int.Z > center.Z)
                    {
                        trb.Add(point);
                    }
                    else
                    {
                        trf.Add(point);
                    }
                }
                else // is on bottom side
                {
                    // is on the backside
                    if (point3Int.Z > center.Z)
                    {
                        brb.Add(point);
                    }
                    else
                    {
                        brf.Add(point);
                    }
                }
            }
            else // is on left side
            {
                // is on top side
                if (point3Int.Y > center.Y)
                {
                    // is on the backside
                    if (point3Int.Z > center.Z)
                    {
                        tlb.Add(point);
                    }
                    else
                    {
                        tlf.Add(point);
                    }
                }
                else // is on bottom side
                {
                    // is on the backside
                    if (point3Int.Z > center.Z)
                    {
                        blb.Add(point);
                    }
                    else
                    {
                        blf.Add(point);
                    }
                }
            }
        }
Exemple #26
0
        public static void Initialize(float initialChunkSize, int initialMaxDepth, int nodeCapacity, Vector3 center)
        {
            initialChunkSize = initialChunkSize / 2;

            tree = new OctTree<ITransformable>(nodeCapacity, initialMaxDepth, new List<ITransformable>(), new BoundingBox(new Vector3(-initialChunkSize) + center, new Vector3(initialChunkSize) + center));
        }
        public void AddPointsExceedCapacityAssertEndUpInRightOct()
        {
            var obj = new object();
            var blf = new Point3Int <object>(-2, -2, -2, obj);
            var brf = new Point3Int <object>(2, -2, -2, obj);

            var blb = new Point3Int <object>(-2, -2, 2, obj);
            var brb = new Point3Int <object>(2, -2, 2, obj);

            var ulf = new Point3Int <object>(-2, 2, -2, obj);
            var urf = new Point3Int <object>(2, 2, -2, obj);

            var ulb = new Point3Int <object>(-2, 2, 2, obj);
            var urb = new Point3Int <object>(2, 2, 2, obj);

            var magicNumber9 = new Point3Int <object>(0, 0, 0, obj);

            var ut = new OctTree <object>(BoundingCuboid.Max, 8, new SimpleOctTreeDivisionStrategy <object>());

            ut.Add(blf);
            ut.Add(brf);
            ut.Add(blb);
            ut.Add(brb);
            ut.Add(ulf);
            ut.Add(urf);
            ut.Add(ulb);
            ut.Add(urb);

            Assert.IsNotNull(ut.Points);
            Assert.AreEqual(8, ut.Points.Length);
            Assert.IsNull(ut.ULF);
            Assert.IsNull(ut.URF);
            Assert.IsNull(ut.ULB);
            Assert.IsNull(ut.URB);
            Assert.IsNull(ut.BLF);
            Assert.IsNull(ut.BRF);
            Assert.IsNull(ut.BLB);
            Assert.IsNull(ut.BRB);

            ut.Add(magicNumber9);

            Assert.IsNull(ut.Points);
            Assert.IsNotNull(ut.ULF);
            Assert.IsNotNull(ut.URF);
            Assert.IsNotNull(ut.ULB);
            Assert.IsNotNull(ut.URB);
            Assert.IsNotNull(ut.BLF);
            Assert.IsNotNull(ut.BRF);
            Assert.IsNotNull(ut.BLB);
            Assert.IsNotNull(ut.BRB);

            Assert.IsTrue(ut.BLF.Points.Contains(blf));
            Assert.Contains(brf, ut.BRF.Points);
            Assert.Contains(blb, ut.BLB.Points);
            Assert.Contains(brb, ut.BRB.Points);

            Assert.Contains(urf, ut.URF.Points);
            Assert.Contains(ulf, ut.ULF.Points);
            Assert.Contains(ulb, ut.ULB.Points);
            Assert.Contains(urb, ut.URB.Points);

            Assert.Contains(magicNumber9, ut.BLF.Points);
        }
Exemple #28
0
        public Cell(OctTree <TCellData, TVertexData> tree, Vector3 position, float size)
        {
            this.tree = tree;
            level     = 0;
            uid       = tree.getCellUID;
            vertices  = new Vertex[CellVerticesNumber];
            children  = null;
            data      = new TCellData();
            tree.cells.Add(this);

            //     7---4    7       Py
            //    /   /|    |       |
            //   3---0 5    6---5   6---Px
            //   |   |/    /       /
            //   2---1    2       Pz

            /*    Nx  Ny  Nz  Px  Py  Pz
             * 0  3   1   4
             * 1  2       5       0
             * 2          6   1   3
             * 3      2   7   0
             * 4  7   5               0
             * 5  6               4   1
             * 6              5   7   2
             * 7      6       4       3
             */

            vertices[0] = new Vertex(tree, level, new Vector3(size, size, size));
            vertices[1] = new Vertex(tree, level, new Vector3(size, 0f, size));
            vertices[2] = new Vertex(tree, level, new Vector3(0f, 0f, size));
            vertices[3] = new Vertex(tree, level, new Vector3(0f, size, size));
            vertices[4] = new Vertex(tree, level, new Vector3(size, size, 0f));
            vertices[5] = new Vertex(tree, level, new Vector3(size, 0f, 0f));
            vertices[6] = new Vertex(tree, level, new Vector3(0f, 0f, 0f));
            vertices[7] = new Vertex(tree, level, new Vector3(0f, size, 0f));

            //                                             Nx           Ny           Nz           Px           Py           Pz
            vertices[0].AddConnectionLevel(new Vertex[6] {
                vertices[3], vertices[1], vertices[4], null, null, null
            }, level);
            vertices[1].AddConnectionLevel(new Vertex[6] {
                vertices[2], null, vertices[5], null, vertices[0], null
            }, level);
            vertices[2].AddConnectionLevel(new Vertex[6] {
                null, null, vertices[6], vertices[1], vertices[3], null
            }, level);
            vertices[3].AddConnectionLevel(new Vertex[6] {
                null, vertices[2], vertices[7], vertices[0], null, null
            }, level);
            vertices[4].AddConnectionLevel(new Vertex[6] {
                vertices[7], vertices[5], null, null, null, vertices[0]
            }, level);
            vertices[5].AddConnectionLevel(new Vertex[6] {
                vertices[6], null, null, null, vertices[4], vertices[1]
            }, level);
            vertices[6].AddConnectionLevel(new Vertex[6] {
                null, null, null, vertices[5], vertices[7], vertices[2]
            }, level);
            vertices[7].AddConnectionLevel(new Vertex[6] {
                null, vertices[6], null, vertices[4], null, vertices[3]
            }, level);
        }
    // Start is called before the first frame update
    void Start()
    {
        OctTree <string, TestDataClass> .OctTreeNode root = new OctTree <string, TestDataClass> .OctTreeNode(Vector3.zero, new Vector3(50.0f, 50.0f, 50.0f));

        m_octTree = new OctTree <string, TestDataClass>(root);

        Profiler.BeginSample("generate octtree");
        m_octTree.GenerateTree(4);
        Profiler.EndSample();

        List <TestDataClass> dataList = new List <TestDataClass>(100);

        for (int i = 0; i < dataList.Capacity; ++i)
        {
            TestDataClass testData = new TestDataClass();
            testData.Key      = "testString" + i.ToString();
            testData.Position = new Vector3(Random.Range(-25.0f, 25.0f), Random.Range(-25.0f, 25.0f), Random.Range(-25.0f, 25.0f));

            dataList.Add(testData);
        }

        m_pointCloud = new PointCloud <TestDataClass>(dataList);
        m_octTree.AddPointCloudData(m_pointCloud);
        //m_ray = new Ray(Vector3.zero, Vector3.up);
        //m_cachedResults = m_octTree.QueryAgainstNodesRay(m_ray, 3);

        m_trajectory = new Trajectory();

        Vector3 origin = Vector3.zero;
        Vector3 dir    = Vector3.up;
        float   time   = 0.0f;

        for (int i = 0; i < 50; ++i)
        {
            Ray ray = new Ray(origin, dir);
            m_trajectory.AddSegment(time, ray);

            time   += 0.5f;
            origin += dir;
            dir     = new Vector3(Random.Range(-5.0f, 5.0f), Random.Range(-10.0f, 10.0f), Random.Range(5.0f, 5.0f)).normalized;
        }

        Profiler.BeginSample("Query result");
        m_cachedResults = new List <CachedResult>();
        foreach (var segment in m_trajectory.TrajectorySegments.Values)
        {
            var result = m_octTree.QueryAgainstNodesRay(segment.Ray, 4);

            if (result.Count > 0)
            {
                m_cachedResults.Add(new CachedResult
                {
                    Time   = segment.Time,
                    Result = result
                });
            }
        }
        Profiler.EndSample();

        m_testPlayer = FindObjectOfType <TestPlayer>();
    }
Exemple #30
0
    public void GenerateRooms(OctTree tree)
    {
        if (tree.GetChildCount () != 0) {
                        foreach (OctTree subTree in tree.children) {
                                if (subTree != null) {
                                        GenerateRooms (subTree);
                                }
                        }
                } else {
                        RoomNode newRoom = new RoomNode (tree.boundary);
                        newRoom.roomBounds.extents -= Vector3.one * minSeparation;
                        newRoom.RandomizeBounds (Vector3.one, minRoomSize, maxRoomSize);
                        newRoom.QuantizeBounds (corridorSize);
                        /*Vector3 center, extents;

                        extents.x = Mathf.Floor (Random.Range (minRoomSize / 2, tree.boundary.extents.x));
                        extents.y = Mathf.Floor (Random.Range (minRoomSize / 2, tree.boundary.extents.y));
                        extents.z = Mathf.Floor (Random.Range (minRoomSize / 2, tree.boundary.extents.z));

                        center = tree.boundary.center;
                        center.x = Mathf.Round (center.x + Random.Range (extents.x - tree.boundary.extents.x, tree.boundary.extents.x - extents.x));
                        center.y = Mathf.Round (center.y + Random.Range (extents.y - tree.boundary.extents.y, tree.boundary.extents.y - extents.y));
                        center.z = Mathf.Round (center.z + Random.Range (extents.z - tree.boundary.extents.z, tree.boundary.extents.z - extents.z));

                        newRoom.roomBounds.center = center;
                        newRoom.roomBounds.extents = extents;*/

                        newRoom.octTreeNode = tree;
                        roomNodeList.AddFirst (newRoom);
                        tree.roomNode = newRoom;
                }
    }
        public void SubDivide(Point3Int <T>[] existingPoints,
                              Point3Int <T> newPoint,
                              BoundingCuboid boundary,
                              out OctTree <T> tlf,
                              out OctTree <T> trf,
                              out OctTree <T> tlb,
                              out OctTree <T> trb,
                              out OctTree <T> blf,
                              out OctTree <T> brf,
                              out OctTree <T> blb,
                              out OctTree <T> brb)
        {
            int maxItems = existingPoints.Length;
            var center   = boundary.CenterPoint();

            //blf
            var minBlf = boundary.LowerLeft;
            var mzxBlf = center;

            blf = new OctTree <T>(new BoundingCuboid(minBlf, mzxBlf), maxItems, this);

            //brf
            var minBrf = new Point3Int(center.X, boundary.LowerLeft.Y, boundary.LowerLeft.Z);
            var maxBrf = new Point3Int(boundary.UpperRight.X, center.Y, center.Z);

            brf = new OctTree <T>(new BoundingCuboid(minBrf, maxBrf), maxItems, this);

            //blb
            var minBlb = new Point3Int(boundary.LowerLeft.X, boundary.LowerLeft.Y, center.Z);
            var maxBlb = new Point3Int(center.X, center.Y, boundary.UpperRight.Z);

            blb = new OctTree <T>(new BoundingCuboid(minBlb, maxBlb), maxItems, this);

            //brb
            var minBrb = new Point3Int(center.X, boundary.LowerLeft.Y, center.Z);
            var maxBrb = new Point3Int(boundary.UpperRight.X, center.Y, boundary.UpperRight.Z);

            brb = new OctTree <T>(new BoundingCuboid(minBrb, maxBrb), maxItems, this);

            //tlf
            var minTlf = new Point3Int(boundary.LowerLeft.X, center.Y, boundary.LowerLeft.Z);
            var maxTlf = new Point3Int(center.X, boundary.UpperRight.Y, center.Z);

            tlf = new OctTree <T>(new BoundingCuboid(minTlf, maxTlf), maxItems, this);

            //trf
            var minTrf = new Point3Int(center.X, center.Y, boundary.LowerLeft.Z);
            var maxTrf = new Point3Int(boundary.UpperRight.X, boundary.UpperRight.Y, center.Z);

            trf = new OctTree <T>(new BoundingCuboid(minTrf, maxTrf), maxItems, this);

            //tlb
            var minTlb = new Point3Int(boundary.LowerLeft.X, center.Y, center.Z);
            var maxTlb = new Point3Int(center.X, boundary.UpperRight.Y, boundary.UpperRight.Z);

            tlb = new OctTree <T>(new BoundingCuboid(minTlb, maxTlb), maxItems, this);

            //trb
            var minTrb = center;
            var maxTrb = boundary.UpperRight;

            trb = new OctTree <T>(new BoundingCuboid(minTrb, maxTrb), maxItems, this);

            foreach (var point3Int in existingPoints)
            {
                AddPoint(blf, brf, blb, brb, tlf, trf, tlb, trb, point3Int, center);
            }

            AddPoint(blf, brf, blb, brb, tlf, trf, tlb, trb, newPoint, center);
        }
Exemple #32
0
 public void MakeDungeon()
 {
     root = new OctTree (totalBounds);
             root.GenerateZones (depth, minRoomSize);
             roomNodeList = new LinkedList<RoomNode> ();
             GenerateRooms (root);
             ConnectRooms ();
 }
Exemple #33
0
	// Use this for initialization
	void Start () {
		tree = new OctTree(totalBounds);
		tree.GenerateZones(depth,minRoomSize);
	}
Exemple #34
0
    public void GenerateZones(int depth, Vector3 minRoomSize)
    {
        if(depth < 1) return;

        if(boundary.extents.x < minRoomSize.x) return;
        if(boundary.extents.y < minRoomSize.y) return;
        if(boundary.extents.z < minRoomSize.z) return;

        Vector3 slice = RandomSlice(minRoomSize);

        for(int oct = 0; oct < 8; oct ++)
        {
            Vector3 dir = OctantDirection(oct);
            Vector3 farCorner = boundary.center + Vector3.Scale(boundary.extents,dir);
            Vector3 size = Vector3.Scale(farCorner - slice,dir);
            Vector3 center = slice + Vector3.Scale(size, dir * 0.5f);
            Bounds newBounds = new Bounds(center,size);
            if(newBounds.size.x >= minRoomSize.x
                && newBounds.size.y >= minRoomSize.y
                && newBounds.size.z >= minRoomSize.z)
            {
                children[oct] = new OctTree(newBounds);
                children[oct].gizmoColor = Color.Lerp(new Color(Mathf.Max(dir.x, 0),Mathf.Max(dir.y, 0),Mathf.Max(dir.z, 0)),gizmoColor,0.5f);
                children[oct].GenerateZones(depth - 1, minRoomSize);
                childCount ++;
            }

        }
    }
Exemple #35
0
        public Shell[] Read(string fileName)
        {
            List <Shell> res = new List <Shell>();

            using (sr = new StreamReader(fileName)) // may throw exceptions like "file not found" etc.
            {
                char[] head = new char[5];
                int    read = sr.ReadBlock(head, 0, 5);
                if (read != 5)
                {
                    throw new ApplicationException("cannot read from file");
                }
                if (new string(head) == "solid")
                {
                    isASCII = true;
                }
                else
                {
                    isASCII = false;
                }
            }
            if (isASCII)
            {
                sr = new StreamReader(fileName);
                string title = sr.ReadLine();
            }
            else
            {
                br = new BinaryReader(File.Open(fileName, FileMode.Open));
                br.ReadBytes(80);
                uint nrtr = br.ReadUInt32();
            }
            OctTree <Vertex> verticesOctTree = null;
            triangle         tr;
            int           cnt      = 0;
            Set <Face>    allFaces = new Set <Face>();
            GeoObjectList dbgl     = new GeoObjectList();

            do
            {
                tr = GetNextTriangle();
                if (tr == null)
                {
                    break;
                }
                if (verticesOctTree == null)
                {
                    verticesOctTree = new OctTree <Vertex>(new BoundingCube(tr.p1, tr.p2, tr.p3), 1e-6);
                }
                try
                {
                    PlaneSurface ps = new PlaneSurface(tr.p1, tr.p2, tr.p3);
                    Vertex       v1 = VertexFromPoint(verticesOctTree, tr.p1);
                    Vertex       v2 = VertexFromPoint(verticesOctTree, tr.p2);
                    Vertex       v3 = VertexFromPoint(verticesOctTree, tr.p3);
                    Edge         e1 = Vertex.SingleConnectingEdge(v1, v2);
                    if (e1 != null && e1.SecondaryFace != null)
                    {
                    }
                    if (e1 == null || e1.SecondaryFace != null)
                    {
                        e1 = new Edge(Line.TwoPoints(v1.Position, v2.Position), v1, v2);
                    }
                    Edge e2 = Vertex.SingleConnectingEdge(v2, v3);
                    if (e2 != null && e2.SecondaryFace != null)
                    {
                    }
                    if (e2 == null || e2.SecondaryFace != null)
                    {
                        e2 = new Edge(Line.TwoPoints(v2.Position, v3.Position), v2, v3);
                    }
                    Edge e3 = Vertex.SingleConnectingEdge(v3, v1);
                    if (e3 != null && e3.SecondaryFace != null)
                    {
                    }
                    if (e3 == null || e3.SecondaryFace != null)
                    {
                        e3 = new Edge(Line.TwoPoints(v3.Position, v1.Position), v3, v1);
                    }
                    dbgl.Add(Line.TwoPoints(v1.Position, v2.Position));
                    dbgl.Add(Line.TwoPoints(v2.Position, v3.Position));
                    dbgl.Add(Line.TwoPoints(v3.Position, v1.Position));
                    Face fc = Face.Construct();
                    fc.Surface = ps;
                    //Line2D l1 = new Line2D(ps.Plane.Project(tr.p1), ps.Plane.Project(tr.p2));
                    //Line2D l2 = new Line2D(ps.Plane.Project(tr.p2), ps.Plane.Project(tr.p3));
                    //Line2D l3 = new Line2D(ps.Plane.Project(tr.p3), ps.Plane.Project(tr.p1));
                    //if (e1.PrimaryFace == null) e1.SetPrimary(fc, l1, true);
                    //else e1.SetSecondary(fc, l1, false);
                    //if (e2.PrimaryFace == null) e2.SetPrimary(fc, l2, true);
                    //else e2.SetSecondary(fc, l2, false);
                    //if (e3.PrimaryFace == null) e3.SetPrimary(fc, l3, true);
                    //else e3.SetSecondary(fc, l3, false);
                    e1.SetFace(fc, e1.Vertex1 == v1);
                    e2.SetFace(fc, e2.Vertex1 == v2);
                    e3.SetFace(fc, e3.Vertex1 == v3);
                    fc.Set(ps, new Edge[][] { new Edge[] { e1, e2, e3 } });
                    allFaces.Add(fc);
                    ++cnt;
                }
                catch (ModOpException)
                {
                    // empty triangle, plane construction failed
                }
            } while (tr != null);
            while (!allFaces.IsEmpty())
            {
                Shell part = Shell.CollectConnected(allFaces);
#if DEBUG
                // TODO: some mechanism to tell whether and how to reverse engineer the stl file
                double precision;
                if (numnum == 0)
                {
                    precision = part.GetExtent(0.0).Size * 1e-5;
                }
                else
                {
                    precision = Math.Pow(10, -numdec / (double)(numnum));  // numdec/numnum is average number of decimal places
                }
                part.ReconstructSurfaces(precision);
#endif
                res.Add(part);
            }
            return(res.ToArray());
        }
Exemple #36
0
 // Use this for initialization
 void Start()
 {
     tree = new OctTree(totalBounds);
     tree.GenerateZones(depth, minRoomSize);
 }