Пример #1
0
        public static void Main(string[] arguments)
        {
            if (arguments.Length != 1)
            {
                Console.WriteLine("Expected 1 parameter: path to the file with test case data.");
                return;
            }

            using (var scenarioReader = new ScenarioReader(new StreamReader(arguments[0])))
            {
                foreach (var scenario in scenarioReader.EnumerateScenarios())
                {
                    Utilities.EnsureAllPositionsAreValid(scenario.BombPositions, SpaceSize);

                    var octree = new Octree(SpaceSize);
                    var furthestOctant = octree.GetFurthestOctant(scenario.BombPositions);

                    /*
                    var safestPoint = furthestOctant.Item1.Center;

                    Console.WriteLine("Safest point: ({0}, {1}, {2}), distance to closest bomb: {3}.",
                        Math.Round(safestPoint.X),
                        Math.Round(safestPoint.Y),
                        Math.Round(safestPoint.Z),
                        Math.Round(furthestOctant.Item2));
                    */

                    // Requirement:
                    // Output T integers, one per test case each on its own line, representing the square of distance to the
                    // nearest bomb from the safest point in the cube.
                    Console.WriteLine(Math.Round(furthestOctant.Item2 * furthestOctant.Item2));
                }
            }
        }
Пример #2
0
 public World(GameObject scene, float size, Vector3 center, int maxLevel, float normalExtension, bool progressive = true, Graph.GraphType type = Graph.GraphType.CENTER) {
     space = progressive ? new ProgressiveOctree(size, center - Vector3.one * size / 2, maxLevel) : new Octree(size, center - Vector3.one * size / 2, maxLevel);
     space.BuildFromGameObject(scene, normalExtension);
     spaceGraph = 
         type == Graph.GraphType.CENTER ? space.ToCenterGraph() :
         type == Graph.GraphType.CORNER ? space.ToCornerGraph() : space.ToCrossedGraph();
 }
Пример #3
0
 public void Add(Octree<Volume> octree)
 {
     List<Volume> list = octree.toList();
     foreach (Volume volume in list)
     {
         if( volume.Visible ) Add(volume);
     }
 }
Пример #4
0
 public override QuantizedImage Quantize(ImageBase image, int maxColors)
 {
     colors = NumUtils.Clamp(maxColors, 1, 255);
     if (octree == null){
         octree = new Octree(GetBitsNeededForColorDepth(maxColors));
     }
     return base.Quantize(image, maxColors);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="OctreeCuller"/> class.
 /// </summary>
 /// <param name="worldSize">Size of the world.</param>
 /// <param name="loose">The loose.</param>
 /// <param name="maxDepth">The max depth.</param>
 /// <param name="center">The center.</param>
 /// <param name="DebugDrawer">The debug drawer. We strong recomend you to DONT JUST this DebugDrawer for nothing anymore, if you need, create another</param>
 public OctreeCuller(float worldSize, float loose, int maxDepth, Vector3 center, DebugShapesDrawer DebugDrawer = null)
 {
     oct = new Octree<IObject>(worldSize, loose, maxDepth, center);
     if (DebugDrawer != null)
     {
         DebugDrawer.DrawAllShapesEachFrame = false;
         oct.DebugDraw = DebugDrawer;                
     }            
 }        
 public void setData(Octree tree, int count, Vector3[] voxMins, uint[] voxMats, Octree.GPUVOX[] voxs, Vector3 min, int octreeSize)
 {
     i_Tree = tree;
     i_Count = count;
     i_VoxMins = voxMins;
     i_VoxMaterials = voxMats;
     i_Voxs = voxs;
     i_Min = min;
     i_Size = octreeSize;
 }
        /// <summary>
        /// Construct the octree quantizer
        /// </summary>
        /// <remarks>
        /// The Octree quantizer is a two pass algorithm. The initial pass sets up the octree,
        /// the second pass quantizes a color based on the nodes in the tree
        /// </remarks>
        public OctreeQuantizer(BitDepth pBitDepth)
            : base(false)
        {
            var maxColors = GetMaxColors(pBitDepth);
            var maxColorBits = GetMaxColorBits(pBitDepth);

            _octree = new Octree(maxColorBits);

            _maxColors = maxColors;
        }
		/// <summary>
		/// Construct the octree quantizer
		/// </summary>
		/// <remarks>
		/// The Octree quantizer is a two pass algorithm. The initial pass sets up the octree,
		/// the second pass quantizes a color based on the nodes in the tree
		/// </remarks>
		/// <param name="maxColors">The maximum number of colors to return</param>
		/// <param name="maxColorBits">The number of significant bits</param>
		public OctreeQuantizer ( int maxColors , int maxColorBits ) : base ( false )
		{
			if ( maxColors > 255 )
				throw new ArgumentOutOfRangeException ( "maxColors" , maxColors , "The number of colors should be less than 256" ) ;

			if ( ( maxColorBits < 1 ) | ( maxColorBits > 8 ) )
				throw new ArgumentOutOfRangeException ( "maxColorBits" , maxColorBits , "This should be between 1 and 8" ) ;

			// Construct the octree
			_octree = new Octree ( maxColorBits  ) ;
			_maxColors = maxColors ;
		}
Пример #9
0
        static void Main(string[] args)
        {

            var root = OctreeNode<object>.Filled(Vect3.Zero, 5, 0, new object());
            
            var tree = new Octree<object>(root.Split());

            using (var win = new Window<object>(tree, node => Color.Blue))
            {
                win.Run();
                Console.ReadLine();
            }
        }
Пример #10
0
        public static Octree<Volume> Generate( int width, int depth )
        {
            Octree<Volume> octree = new Octree<Volume>(new Volume(new Vector3(0,0,0), new Vector3(width, 64, depth), new Color()), Volume.AddHandler, Volume.RemoveHandler, Volume.SearchHandler, Volume.SetRootHandler, Volume.RemoveAllHandler);

            List<Vector3> coords = new List<Vector3>();
            int hills = rand.Next(10);
            int height = 0;
            for (int i = 0; i < hills; i++)
            {
                coords.Add( new Vector3( rand.Next(width), 0, rand.Next(depth)));
            }
            System.Drawing.Color c = System.Drawing.Color.LawnGreen;
            int r, g, b;
            for (int i = 0; i < width; i++)
            {
                for (int j = 0; j < depth; j++)
                {
                    octree.Add(
                                new Volume(
                                new Vector3(i, 0, j),
                                new Vector3(1, 1, 1),
                                new Color(c.R, c.G, c.B))
                                );
                }
            }
            foreach (Vector3 coord in coords)
            {
                for (int x = -10; x < 10; x++)
                {
                    for (int z = -10; z < 10; z++)
                    {
                        c = System.Drawing.Color.LawnGreen;
                        r = (int)(0.1f * (float)height * (int)c.R);
                        g = (int)c.G;
                        b = (int)(0.1f * (float)height * (int)c.B);

                        if (r > 255) r = 255; if (g > 255) g = 255; if (b > 255) b = 255;
                        height = Math.Min(20 - Math.Abs(z), 20 - Math.Abs(x));
                        c = System.Drawing.Color.FromArgb(r, g, b);
                        octree.Add(
                            new Volume(
                            new Vector3(coord.X + x, height, coord.Z + z),
                            new Vector3(1, 1, 1),
                            new Color(c.R, c.G, c.B))
                            );
                    }
                }
            }

            return octree;
        }
Пример #11
0
 public World( int size )
 {
     RemoveQueue = Queue.Synchronized(new Queue());
     AddQueue = Queue.Synchronized(new Queue());
     faceBatch = new FaceBatch<VertexPositionNormalColor>();
     octree = new Octree<WorldVolume>(new WorldVolume(new Vector3(-(int)Math.Pow(2.0f, size) / 2, -(int)Math.Pow(2.0f, size) / 2, -(int)Math.Pow(2.0f, size) / 2),
                                             new Vector3((int)Math.Pow(2.0f, size), (int)Math.Pow(2.0f, size), (int)Math.Pow(2.0f, size)),
                                             new Color()),
                                             WorldVolume.AddHandler,
                                             WorldVolume.RemoveHandler,
                                             WorldVolume.SearchHandler,
                                             WorldVolume.SetRootHandler, WorldVolume.RemoveAllHandler);
     thread = new Thread(new ThreadStart(Do));
 }
Пример #12
0
        private void firstPass(Octree tree, BitmapData data, int width, int height)
        {
            byte* srcRow = (byte*)data.Scan0.ToPointer();
            Int32* srcPxl;

            for (int row = 0; row < height; ++row)
            {
                srcPxl = (Int32*)srcRow;
                for (int col = 0; col < width; ++col, ++srcPxl)
                    tree.addColor((Color32*)srcPxl);

                srcRow += data.Stride;
            }
        }
Пример #13
0
		protected override async void Start()
		{
			base.Start();
			Input.SubscribeToKeyDown(k => { if (k.Key == Key.Esc) Exit(); });
			Input.SubscribeToTouchEnd(OnTouched);

			// 3D scene with Octree
			var scene = new Scene(Context);
			octree = scene.CreateComponent<Octree>();

			// Camera
			var cameraNode = scene.CreateChild(name: "camera");
			cameraNode.Position = new Vector3(10, 14, 10);
			cameraNode.Rotation = new Quaternion(-0.121f, 0.878f, -0.305f, -0.35f);
			camera = cameraNode.CreateComponent<Camera>();

			// Light
			Node lightNode = cameraNode.CreateChild(name: "light");
			var light = lightNode.CreateComponent<Light>();
			light.LightType = LightType.Point;
			light.Range = 100;
			light.Brightness = 1.3f;

			// Viewport
			var viewport = new Viewport(Context, scene, camera, null);
			Renderer.SetViewport(0, viewport);
			viewport.SetClearColor(new Color(0.4f, 0.4f, 0.4f));

			plotNode = scene.CreateChild();
			var baseNode = plotNode.CreateChild().CreateChild();
			var plane = baseNode.CreateComponent<StaticModel>();
			plane.Model = ResourceCache.GetModel("Models/Plane.mdl");

			int size = 5;
			baseNode.Scale = new Vector3(size * 1.5f, 1, size * 1.5f);
			for (var i = 0f; i < size * 1.5f; i += 1.5f)
			{
				for (var j = 0f; j < size * 1.5f; j += 1.5f)
				{
					var boxNode = plotNode.CreateChild();
					boxNode.Position = new Vector3(size / 2f - i + 0.5f, 0, size / 2f - j + 0.5f);
					var box = new Bar(h => Math.Round(h, 1).ToString(), new Color(Sample.NextRandom(), Sample.NextRandom(), Sample.NextRandom(), 0.9f));
					boxNode.AddComponent(box);
					box.Value = (Math.Abs(i) + Math.Abs(j) + 1) / 2f;
				}
			}
			await plotNode.RunActionsAsync(new EaseBackOut(new RotateBy(2f, 0, 360, 0)));
			movementsEnabled = true;
		}
Пример #14
0
    public Chunk()
    {
        int primModCount = 300;
        primitiveMods = new DensityPrimitive[primModCount];

        //primitiveMods[0] = new DensityPrimitive(1, 0, new Vector3 (20, 20, 0), new Vector3(10, 10, 10));
        //primitiveMods[1] = new DensityPrimitive(0, 1, new Vector3 (20, 25, 0), new Vector3(5, 3, 5));

        vertices = new List<Vector3>();
        normals = new List<Vector3>();
        indices = new List<int>();

        tree = new Octree();
        meshObject = null;
        voxelMesh = null;
        meshObject = (GameObject) GameObject.Instantiate(Resources.Load("ChunkMesh"), Vector3.zero, Quaternion.identity);
    }
Пример #15
0
        /// <summary>
        /// Construct the octree quantizer
        /// </summary>
        /// <remarks>
        /// The Octree quantizer is a two pass algorithm. The initial pass sets up the octree,
        /// the second pass quantizes a color based on the nodes in the tree
        /// </remarks>
        /// <param name="maxColors">The maximum number of colors to return</param>
        /// <param name="maxColorBits">The number of significant bits</param>
        /// <param name="enableTransparency">If true, then one color slot in the palette will be reserved for transparency. 
        /// Any color passed through QuantizePixel which does not have an alpha of 255 will use this color slot.
        /// If false, then all colors should have an alpha of 255. Otherwise the results may be unpredictable.</param>
        public OctreeQuantizer(int maxColors, bool enableTransparency) 
            : base(false)
        {
            if (maxColors > 256)
            {
                throw new ArgumentOutOfRangeException("maxColors", maxColors, "The number of colors should be 256 or less");
            }

            if (maxColors < 2)
            {
                throw new ArgumentOutOfRangeException("maxColors", maxColors, "The number of colors must be 2 or more");
            }

            this.octree = new Octree(8); // 8-bits per color
            this.enableTransparency = enableTransparency;
            this.maxColors = maxColors - (this.enableTransparency ? 1 : 0); // subtract 1 if enableTransparency is true
        }
Пример #16
0
                /// <summary>
                /// Construct the node
                /// </summary>
                /// <param name="level">The level in the tree = 0 - 7</param>
                /// <param name="colorBits">The number of significant color bits in the image</param>
                /// <param name="octree">The tree to which this node belongs</param>
                public OctreeNode(int level, int colorBits, Octree octree)
                {
                    // Construct the new node
                    leaf = (level == colorBits);

                    red = green = blue = 0;

                    // If a leaf, increment the leaf count
                    if (leaf)
                    {
                        octree.Leaves++;
                    }
                    else
                    {
                        // Otherwise add this to the reducible nodes
                        nextReducible = octree.ReducibleNodes[level];
                        octree.ReducibleNodes[level] = this;
                        children = new OctreeNode[8];
                    }
                }
Пример #17
0
    private void SubDivide()
    {
        Vector3 newSize = (boundary.size / 2);
        Vector3 offset  = newSize / 2;

        for (int x = 0; x < 2; x++)
        {
            for (int y = 0; y < 2; y++)
            {
                for (int z = 0; z < 2; z++)
                {
                    Vector3    point   = boundary.center + new Vector3(x * newSize.x, y * newSize.y, z * newSize.z) - offset;
                    AABB       bb      = new AABB(point, newSize);
                    Octree <T> subtree = new Octree <T>(bb, capacity);
                    subtrees.Add(subtree);
                }
            }
        }
        divided = true;
    }
Пример #18
0
        public AbstractPreviewScene()
        {
            var bbox = new BoundingBox(new Vector3(-1000, -1000, -1000), new Vector3(1000, 1000, 1000));

            _scene.Value = new Scene();
            _octree      = Scene.CreateComponent <Octree>();
            _octree.SetSize(bbox, 10);
            Zone = Scene.CreateComponent <Zone>();
            Zone.SetBoundingBox(bbox);
            _cameraNode.Value      = new Node();
            Camera                 = CameraNode.CreateComponent <Camera>();
            Camera.Fov             = 45.0f;
            Camera.AspectRatio     = 1;
            Camera.AutoAspectRatio = false;
            CameraNode.Position    = new Vector3(10, 10, 5);
            CameraNode.LookAt(Vector3.Zero, Vector3.Up);
            PreviewContainer = new Node();
            Scene.AddChild(PreviewContainer);
            Scene.AddChild(CameraNode);
        }
Пример #19
0
        internal static uint AddNewNormal(IList <Vector3> target, Vector3 normal, Octree <MeshSpatialInfo> mergeTree)
        {
            target.Add(normal);
            uint index = (uint)target.Count - 1;

            if (mergeTree != null)
            {
                OctreeResult <MeshSpatialInfo> info;
                if (mergeTree.GetAt(normal, out info))
                {
                    info.Entry.Normal = index;
                }
                else
                {
                    mergeTree.Add(new MeshSpatialInfo(null, index), normal);
                }
            }

            return(index);
        }
Пример #20
0
        public static void TestSaving(GameSave gameSave, string saveName)
        {
            var octree         = new Octree(gameSave, new BitArray(new[] { false, false }), new byte[] { 1 });
            var blockTypeTable = new BlockTypeTable(gameSave,
                                                    new[]
            {
                new StringBlock(gameSave, "Block 0"),
                new StringBlock(gameSave, "Block 1"),
                new StringBlock(gameSave, "Block 2"),
                new StringBlock(gameSave, "Block 2")
            },
                                                    new[] { 0, 0, 0, 1 });
            var chunk      = new Chunk(gameSave, blockTypeTable, new[] { octree });
            var chunkTable = new ChunkTable(gameSave, new[] { 0 }, new[] { 0 }, new[] { chunk });
            var mainIndex  = new SavedStateIndex(gameSave, DateTime.UtcNow.Ticks, new StringBlock(gameSave, saveName),
                                                 chunkTable);
            var header = new Header(gameSave, mainIndex);

            header.Write(true);
        }
Пример #21
0
        internal static uint AddNewVertex(IList <Vector3> target, Vector3 vertex, Octree <MeshSpatialInfo> mergeTree)
        {
            target.Add(vertex);
            uint index = (uint)target.Count - 1;

            if (mergeTree != null)
            {
                OctreeResult <MeshSpatialInfo> info;
                if (mergeTree.GetAt(vertex, out info))
                {
                    info.Entry.Vertex = index;
                }
                else
                {
                    mergeTree.Add(new MeshSpatialInfo(index), vertex);
                }
            }

            return(index);
        }
Пример #22
0
        /// <summary>
        /// Initialize the physic world with the geometric detail of map.
        /// </summary>
        /// <param name="map">The base to create the physic world.</param>
        private void Initialize(Map.Map map)
        {
            List <JVector> vertices = new List <JVector>();
            List <TriangleVertexIndices> indices = new List <TriangleVertexIndices>();

            for (uint i = 0; i < map.Width; i++)
            {
                for (uint j = 0; j < map.Length; j++)
                {
                    for (uint k = 0; k < map.Height; k++)
                    {
                        int   pos   = 0;
                        Block block = map.GetBlock(new Vector3(i, j, k));
                        block.CreateColisions();
                        foreach (JVector vertice in block.CollisionVertices)
                        {
                            vertices.Add(vertice);
                            pos++;
                        }

                        int newPos = vertices.Count - pos;
                        foreach (TriangleVertexIndices indice in block.CollisionTriangles)
                        {
                            TriangleVertexIndices t = new TriangleVertexIndices(indice.I0 + newPos, indice.I1 + newPos, indice.I2 + newPos);
                            indices.Add(t);
                        }
                    }
                }
            }

            //ToDo: The vertices list has duplicated vertices. In the worst case each vertices has 4 different instantiation.
            //Probably some performance can be expected by remove the duplicated ones.
            //However it is also necessary to update the indies List with the correct positions.

            Octree            tree  = new Octree(vertices, indices);
            TriangleMeshShape shape = new TriangleMeshShape(tree);
            RigidBody         body  = new RigidBody(shape);

            body.IsStatic = true;
            world.AddBody(body);
        }
Пример #23
0
        /// <summary>
        /// Construct the octree quantizer
        /// </summary>
        /// <remarks>
        /// The Octree quantizer is a two pass algorithm. The initial pass sets up the octree,
        /// the second pass quantizes a color based on the nodes in the tree
        /// </remarks>
        /// <param name="maxColors">The maximum number of colors to return</param>
        /// <param name="maxColorBits">The number of significant bits</param>
        public OctreeQuantizer(int maxColors, int maxColorBits)
            : base(false)
        {
            if (maxColors > 255)
            {
                throw new ArgumentOutOfRangeException("maxColors", maxColors, "The number of colors should be less than 256");
            }

            if (maxColors < 2)
            {
                throw new ArgumentOutOfRangeException("maxColors", maxColors, "The number of colors must be 2 or more");
            }

            if ((maxColorBits < 1) |(maxColorBits > 8))
            {
                throw new ArgumentOutOfRangeException("maxColorBits", maxColorBits, "This should be between 1 and 8");
            }

            _octree = new Octree(maxColorBits);
            _maxColors = maxColors;
        }
Пример #24
0
        public override void OnAttachedToNode(Node node)
        {
            base.OnAttachedToNode(node);
            Application.Input.TouchEnd   += Input_TouchEnd;
            Application.Input.TouchBegin += Input_TouchBegin;

            cubeNode          = node.CreateChild();
            cubeNode.Position = new Vector3(1000, 1000, 1000);
            cubeNode.SetScale(0.02f);
            var box = cubeNode.CreateComponent <Box>();

            box.Color = Color.White;

            var moveAction = new MoveBy(0.5f, new Vector3(0, 0.005f, 0));

            cubeNode.RunActionsAsync(new RepeatForever(new RotateBy(1f, 0, 120, 0)));
            cubeNode.RunActionsAsync(new RepeatForever(moveAction, moveAction.Reverse()));

            camera = Scene.GetChildrenWithComponent <Camera>(true).First().GetComponent <Camera>();
            octree = Scene.GetComponent <Octree>(true);
        }
Пример #25
0
        /// <summary>
        /// Construct the octree quantizer
        /// </summary>
        /// <remarks>
        /// The Octree quantizer is a two pass algorithm. The initial pass sets up the octree,
        /// the second pass quantizes a color based on the nodes in the tree
        /// </remarks>
        /// <param name="maxColors">The maximum number of colors to return</param>
        /// <param name="maxColorBits">The number of significant bits</param>
        public OctreeQuantizer(int maxColors, int maxColorBits)
            : base(false)
        {
            if (maxColors > 255)
            {
                throw new ArgumentOutOfRangeException("maxColors", maxColors, "The number of colors should be less than 256");
            }

            if (maxColors < 2)
            {
                throw new ArgumentOutOfRangeException("maxColors", maxColors, "The number of colors must be 2 or more");
            }

            if ((maxColorBits < 1) | (maxColorBits > 8))
            {
                throw new ArgumentOutOfRangeException("maxColorBits", maxColorBits, "This should be between 1 and 8");
            }

            _octree    = new Octree(maxColorBits);
            _maxColors = maxColors;
        }
        public void OctreeBuild_buildFromPtList_originOK()
        {
            List <Vector3> vectorList = new List <Vector3>();

            for (int i = 0; i <= 10; i++)
            {
                for (int j = 0; j <= 10; j++)
                {
                    for (int k = 0; k <= 10; k++)
                    {
                        vectorList.Add(new Vector3(i * 1.0, j * 1.0, k * 1.0));
                    }
                }
            }
            Octree <SurfacePoint> Octree = OctreeBuilder <SurfacePoint> .Build(vectorList, .1);


            Assert.AreEqual(0, Octree.Origin.X, .001);
            Assert.AreEqual(0, Octree.Origin.Y, .001);
            Assert.AreEqual(0, Octree.Origin.Z, .001);
        }
    private void split()
    {
        float newSize = size / 2f;

        childs[0] = new Octree(level + 1, new Vector3(center.x - newSize / 2f, center.y + newSize / 2f, center.z + newSize / 2f), newSize);
        childs[1] = new Octree(level + 1, new Vector3(center.x + newSize / 2f, center.y + newSize / 2f, center.z + newSize / 2f), newSize);
        childs[2] = new Octree(level + 1, new Vector3(center.x - newSize / 2f, center.y - newSize / 2f, center.z + newSize / 2f), newSize);
        childs[3] = new Octree(level + 1, new Vector3(center.x + newSize / 2f, center.y - newSize / 2f, center.z + newSize / 2f), newSize);
        childs[4] = new Octree(level + 1, new Vector3(center.x - newSize / 2f, center.y + newSize / 2f, center.z - newSize / 2f), newSize);
        childs[5] = new Octree(level + 1, new Vector3(center.x + newSize / 2f, center.y + newSize / 2f, center.z - newSize / 2f), newSize);
        childs[6] = new Octree(level + 1, new Vector3(center.x - newSize / 2f, center.y - newSize / 2f, center.z - newSize / 2f), newSize);
        childs[7] = new Octree(level + 1, new Vector3(center.x + newSize / 2f, center.y - newSize / 2f, center.z - newSize / 2f), newSize);


        /*
         * childs[4] = new Octree(level + 1, new Vector3(center.x - newSize / 2f, center.y + newSize / 2f, center.z - newSize / 2f), newSize);
         * childs[5] = new Octree(level + 1, new Vector3(center.x + newSize / 2f, center.y + newSize / 2f, center.z - newSize / 2f), newSize);
         * childs[6] = new Octree(level + 1, new Vector3(center.x - newSize / 2f, center.y - newSize / 2f, center.z - newSize / 2f), newSize);
         * childs[7] = new Octree(level + 1, new Vector3(center.x + newSize / 2f, center.y - newSize / 2f, center.z - newSize / 2f), newSize);
         */
    }
                /// <summary>
                /// Construct the node
                /// </summary>
                /// <param name="level">The level in the tree = 0 - 7</param>
                /// <param name="colorBits">The number of significant color bits in the image</param>
                /// <param name="octree">The tree to which this node belongs</param>
                public OctreeNode(int level, int colorBits, Octree octree)
                {
                    _leaf = (level == colorBits);

                    _red        = _green = _blue = 0;
                    _pixelCount = 0;

                    if (_leaf)
                    {
                        octree.Leaves++;
                        _nextReducible = null;
                        _children      = null;
                    }
                    else
                    {
                        var repNodes = octree.ReducibleNodes();
                        _nextReducible  = repNodes[level];
                        repNodes[level] = this;
                        _children       = new OctreeNode[8];
                    }
                }
        public void Octree_getNormal_normalOK()
        {
            List <Vector3> vectorList = new List <Vector3>();

            for (int i = 0; i <= 100; i++)
            {
                for (int j = 0; j <= 100; j++)
                {
                    vectorList.Add(new Vector3(i * .1, j * .1, i * .1));
                }
            }
            Octree <SurfacePoint> Octree = OctreeBuilder <SurfacePoint> .Build(vectorList, .1);

            var     pt     = new SurfacePoint(new Vector3(5, 5, 1));
            Vector3 normal = Octree.GetNormalAt(pt.Position);

            normal.Normalize();
            Assert.AreEqual(-.707, normal.X, .01);
            Assert.AreEqual(0.0, normal.Y, .01);
            Assert.AreEqual(.707, normal.Z, .01);
        }
Пример #30
0
        Octree mOctree;      //which Octree this node belongs too

        //Methods
        public OctreeNode(Octree owner, Vector3 position, float size, int depth, int ParentIndex, OctreeNode parent)
        {
            mOctree = owner;
            //Increase the number of nodes now
            mOctree.mNumberNodes += 1;

            //Debug.Log("Current Index = " + mOctree.mNumberNodes + " ,parent = " + ParentIndex);

            mSDF = new SDF_Struct();

            mSDF.mPosition = position;
            mSDF.mSize     = size;

            mNodeDepth   = depth;
            mParentIndex = ParentIndex;
            mParent      = parent;
            mNodeIndex   = mOctree.mNumberNodes; //this node was just created so it's the newest one

            //for now arrbitrary values here
            mSDF.mPoint    = new Vector3(999999.9f, 999999.9f, 999999.9f);
            mSDF.mDistance = 999999.9f;//Mathf.Infinity;
            mInsideMesh    = false;

            mAABB       = new AABB();
            mAABB.Max.x = position.x + size;
            mAABB.Max.y = position.y + size;
            mAABB.Max.z = position.z + size;
            mAABB.Min.x = position.x - size;
            mAABB.Min.y = position.y - size;
            mAABB.Min.z = position.z - size;

            //check if Node intersects with scene geometry AABBs
            mHasGeo = HasGeo();

            //Lowest level dept = -1
            if (mHasGeo && mNodeDepth >= 0)
            {
                SubDivide();
            }
        }
Пример #31
0
    void Start()
    {
        thisTransform = transform;
        mesh          = GetComponent <MeshFilter>().mesh;
        tris          = mesh.triangles;
        verts         = mesh.vertices;
        normals       = mesh.normals;
        Vector3 corner1 = verts[0];
        Vector3 corner2 = verts[0];

        foreach (Vector3 vert in verts)
        {
            corner1 = Vector3.Min(corner1, vert);
            corner2 = Vector3.Max(corner2, vert);
        }
        o = new Octree(new Box(corner1, corner2));
        for (int i = 0; i < tris.Length / 3; i++)
        {
            o.AddTriangle(i);
        }
        randState = UnityEngine.Random.state;
    }
Пример #32
0
        async void CreateScene()
        {
            Input.SubscribeToTouchEnd(OnTouched);

            scene  = new Scene();
            octree = scene.CreateComponent <Octree> ();


            body          = scene.CreateChild();
            body.Position = new Vector3(0, -1.5f, 4);
            body.Rotation = new Quaternion(0, 180, 0);
            body.SetScale(1f);

            AnimatedModel modelObject = body.CreateComponent <AnimatedModel>();

            modelObject.Model    = ResourceCache.GetModel("Ninja/Kachujin.mdl");
            modelObject.Material = ResourceCache.GetMaterial("Ninja/Kachujin.xml");

            lA = body.GetChild("LeftArm", true);
            rA = body.GetChild("RightArm", true);
            lL = body.GetChild("LeftUpLeg", true);
            rL = body.GetChild("RightUpLeg", true);
            await lA.RunActionsAsync(new EaseOut(new RotateBy(1f, -80f, 0f, 0f), 3));

            await rA.RunActionsAsync(new EaseOut(new RotateBy(1f, -80f, 0f, 0f), 3));


            Node light = scene.CreateChild(name: "light");

            light.SetDirection(new Vector3(0.4f, -0.5f, 0.3f));
            light.CreateComponent <Light>();

            Node cameraNode = scene.CreateChild(name: "camera");

            camera = cameraNode.CreateComponent <Camera>();

            Renderer.SetViewport(0, new Viewport(scene, camera, null));
            Renderer.GetViewport(0).SetClearColor(Color.White);
        }
        public void Octree_getpointsInboxfromSearchBox_pointsOK()
        {
            List <Vector3> vectorList = new List <Vector3>();

            for (int i = 0; i <= 100; i++)
            {
                for (int j = 0; j <= 100; j++)
                {
                    vectorList.Add(new Vector3(i * .1, j * .1, 1.0));
                }
            }
            Octree <SurfacePoint> Octree = OctreeBuilder <SurfacePoint> .Build(vectorList, .1);

            Vector3             searchPoint  = new Vector3(5, 6, 3);
            Vector3             direction    = new Vector3(0, 0, 1);
            Ray                 ray          = new Ray(searchPoint, direction);
            double              searchRadius = Octree.MeshSize * 3;
            var                 searchBox    = BoundingBoxBuilder.GetSearchCylinder(Octree.BoundingBox, searchPoint, direction, searchRadius);
            List <SurfacePoint> points       = Octree.GetPointsInsideBox(searchBox);

            Assert.AreNotEqual(0, points.Count);
        }
Пример #34
0
        protected override Shape MakeShape()
        {
            var mf = GetComponent<MeshFilter>();
            var mesh = mf.mesh;
            if (mesh == null) { Debug.Log("No Mesh found!"); return null; }

            if (IsTrigger || Convex)
            {
                Convex = IsTrigger;
                return new ConvexHullShape(GetComponent<MeshFilter>().mesh.vertices.Select(vert => vert.ConvertToJVector()).ToList());
            }
            var positions = new List<JVector>();
            var indices = new List<TriangleVertexIndices>();

            var vertices = mesh.vertices;
            var count = mesh.vertices.Length;
            var scale = transform.lossyScale;
            for (var i = 0; i < count; i++)
            {
                var v = vertices[i];
                v.x *= scale.x;
                v.y *= scale.y;
                v.z *= scale.z;

                positions.Add(new JVector(v.x, v.y, v.z));
            }

            count = mesh.triangles.Length;
            var triangles = mesh.triangles;
            for (var i = 0; i < count; i += 3)
            {
                indices.Add(new TriangleVertexIndices(triangles[i], triangles[i + 2], triangles[i + 1]));
            }

            var octree = new Octree(positions, indices);
            octree.BuildOctree();

            return new TriangleMeshShape(octree);
        }
Пример #35
0
        public void AllLeavesPutAtRoot()
        {
            Octree <int> tree = new Octree <int>(1, new Bounds(-10, -20, -30, 10, 20, 30));

            tree.Insert(1, new Bounds(-9, -19, -29, 9, 19, 29));
            tree.Insert(2, new Bounds(-9, -19, -29, 9, 19, 29));
            tree.Insert(3, new Bounds(-9, -19, -29, 9, 19, 29));
            tree.Insert(4, new Bounds(-9, -19, -29, 9, 19, 29));

            Assert.IsTrue(tree.CountBranches() == 1);

            Assert.AreEqual(tree.SearchBounds(new Bounds(-9, -19, -29, 9, 19, 29)).Count(), 4, "Found all items.");
            Assert.AreEqual(tree.SearchPoint(0, 0, 0).Count(), 4, "All or around this point.");
            Assert.AreEqual(tree.FindCollisions(1).Count(), 3, "Don't find the item we are starting from.");
            Assert.AreEqual(tree.Count, 4, "Have the right count.");

            tree.Remove(3);
            Assert.AreEqual(tree.SearchBounds(new Bounds(-9, -19, -29, 9, 19, 29)).Count(), 3, "Found all items.");
            Assert.AreEqual(tree.SearchPoint(0, 0, 0).Count(), 3, "All or around this point.");
            Assert.AreEqual(tree.FindCollisions(1).Count(), 2, "Don't find the item we are starting from.");
            Assert.AreEqual(tree.Count, 3, "Have the right count.");
        }
Пример #36
0
    static void Mem()
    {
        Vector3 startPoint  = new Vector3();
        float   minSize     = 0.01f;
        float   defaultSize = 1.0f;
        Vector3 boundsMin   = new Vector3(-5, -5, -5);
        Vector3 boundsMax   = new Vector3(5, 5, 5);
        int     iterations  = 50000;

        int[]         checkpoints = new int[] { 10000, 20000, 30000, 40000, 50000 };
        System.Random rand        = new System.Random();

        Console.WriteLine("Created Octree... bounds: {0} to {1}, minSize: {2}, defaultSize: {3}, value type: {4}",
                          pointToStr(boundsMin), pointToStr(boundsMax), minSize, defaultSize, typeof(byte));

        long baseMem = GC.GetTotalMemory(false);

        Octree <byte> octree = new Octree <byte>(startPoint, minSize, defaultSize);

        for (int i = 1; i <= iterations; i++)
        {
            octree.set(randomPoint(boundsMin, boundsMax, rand), default(byte), true);

            for (int j = 0; j < checkpoints.Length; j++)
            {
                long memUse = GC.GetTotalMemory(false) - baseMem;
                if (i == checkpoints[j])
                {
                    Console.WriteLine("Checkpoint... Points added: {0}, Mem: {1} (Octree estimate: {2}), " +
                                      "Components: {3} ({4} / Component) Voxels: {5} ({6} / Voxel), " +
                                      "Non-null Voxels: {7} ({8} / Non-null Voxel)",
                                      i, MemToStr(memUse), MemToStr(octree.memSize),
                                      octree.numComponents, MemToStr(memUse / octree.numComponents),
                                      octree.numVoxels, MemToStr(memUse / octree.numVoxels),
                                      octree.numNonNullVoxels, MemToStr(memUse / octree.numNonNullVoxels));
                }
            }
        }
    }
Пример #37
0
            /// <summary>
            /// Initializes the basic level structure.
            /// </summary>
            /// <returns>LevelManager with initialized based level structure.</returns>
            protected LevelManager InitializeLevel()
            {
                //Before level is asociated with screen, the global try/catch will not dispose of the screen
                Scene  scene  = null;
                Octree octree = null;

                try
                {
                    scene = new Scene(Game.Context)
                    {
                        UpdateEnabled = false
                    };
                    octree = scene.CreateComponent <Octree>();
                    var physics = scene.CreateComponent <PhysicsWorld>();

                    physics.Enabled = true;

                    LoadSceneParts(scene);
                }
                catch (Exception e)
                {
                    Urho.IO.Log.Write(LogLevel.Error, $"Screen creation failed with: {e.Message}");
                    octree?.Dispose();
                    scene?.RemoveAllChildren();
                    scene?.Remove();
                    scene?.Dispose();
                    throw;
                }

                var levelNode = scene.CreateChild("LevelNode");

                levelNode.Enabled = false;
                CurrentLevel      = new LevelManager(levelNode, LevelRep, Game, octree, EditorMode);
                levelNode.AddComponent(CurrentLevel);

                CurrentLevel.Plugin = GetPlugin(CurrentLevel);

                return(CurrentLevel);
            }
Пример #38
0
        public void ItemRetrieval_Raycast()
        {
            var treeBounds = new AABB(Vector3.zero, new Vector3(distanceOfSideOfTreeFromCentre, distanceOfSideOfTreeFromCentre * 2, distanceOfSideOfTreeFromCentre));
            var octree     = new Octree <TestObject>(minNodeWidth, treeBounds);

            var testObject = new TestObject(new Vector3(treeBounds.center.x, treeBounds.center.x + treeBounds.extents.y / 2, treeBounds.center.z));

            Assert.IsTrue(octree.Insert(testObject));

            var testRayInitial = new Ray(testObject.AABB.center, Vector3.right);
            var testRaySecond  = new Ray(new Vector3(treeBounds.center.x, treeBounds.center.x - treeBounds.extents.y / 2, treeBounds.center.z), Vector3.right);

            bool RayCastTest_UT(TestObject item, Ray ray)
            {
                return(item.AABB.RayIntersects(ray));
            }

            {
                octree.Raycast(testRayInitial, RayCastTest_UT, out var expectInsertedItem);

                Assert.AreEqual(1, expectInsertedItem.Count, "Expected to find item just inserted and nothing else");
                Assert.IsTrue(expectInsertedItem.Contains(testObject), "Expected to find item just inserted");

                octree.Raycast(testRaySecond, RayCastTest_UT, out var expectedEmpty);
                Assert.IsTrue(!expectedEmpty.Any(), "Found item in area where there should be no items");
            }

            octree.EditItem(testObject, obj => obj.AABB = new AABB(new Vector3(treeBounds.center.x, treeBounds.center.x - treeBounds.extents.y / 2, treeBounds.center.z), obj.AABB.extents));

            {
                octree.Raycast(testRaySecond, RayCastTest_UT, out var expectInsertedItem);

                Assert.AreEqual(1, expectInsertedItem.Count, "Expected to find item just inserted and nothing else");
                Assert.IsTrue(expectInsertedItem.Contains(testObject), "Expected to find item just inserted");

                octree.Raycast(testRayInitial, RayCastTest_UT, out var expectedEmpty);
                Assert.IsTrue(!expectedEmpty.Any(), "Found item in area where there should be no items");
            }
        }
Пример #39
0
        public static void Write(this Octree octree, BinaryWriter binaryWriter)
        {
            int octreeDataLength = 0;

            var octreeData = octree.data;

            if (octreeData != null)
            {
                octreeDataLength = octreeData.Length;
            }

            binaryWriter.Write(Convert.ToUInt16(octreeDataLength / 4));

            if (octreeData != null)
            {
#if BelowZero
                binaryWriter.Write(octreeData.ToArray());
#else
                binaryWriter.Write(octreeData.Array, octreeData.Offset, octreeDataLength);
#endif
            }
        }
Пример #40
0
 public void AddColor(Color2 pixel, int colorBits, int level, Octree octree)
 {
     if (leaf)
     {
         Increment(pixel);
         octree.TrackPrevious(this);
     }
     else
     {
         int    shift      = 7 - level;
         byte[] components = pixel.ToBytes();
         int    index      = ((components[2] & Mask[level]) >> (shift - 2)) | ((components[1] & Mask[level]) >> (shift - 1)) |
                             ((components[0] & Mask[level]) >> shift);
         OctreeNode child = children[index];
         if (child == null)
         {
             child           = new OctreeNode(level + 1, colorBits, octree);
             children[index] = child;
         }
         child.AddColor(pixel, colorBits, level + 1, octree);
     }
 }
Пример #41
0
 public void AddColor(Color32 pixel, int colorBits, int level, Octree octree)
 {
     if (_leaf)
     {
         Increment(pixel);
         octree.TrackPrevious(this);
     }
     else
     {
         int shift = 7 - level;
         int index = ((pixel.Red & mask[level]) >> (shift - 2)) |
                     ((pixel.Green & mask[level]) >> (shift - 1)) |
                     ((pixel.Blue & mask[level]) >> (shift));
         OctreeNode child = _children[index];
         if (null == child)
         {
             child            = new OctreeNode(level + 1, colorBits, octree);
             _children[index] = child;
         }
         child.AddColor(pixel, colorBits, level + 1, octree);
     }
 }
Пример #42
0
    public static double SunShineSim(TreeModel treeModel, PhotosyntheticModels type)
    {
        double biomass = 0.0;

        switch (type)
        {
        case PhotosyntheticModels.LightResponse:
            Octree octree = Octree.Build(treeModel);
            biomass =
                octree == null?         //无模型,说明未出苗
                MaizeParams.SEED_BIOMASS : DailySunShineSimluation(treeModel, DateTime.Now, 119, 26, octree, 0.1f, 100, 100);
            if (octree != null)
            {
                octree.Clear();
            }
            break;

        default:
            GameObject go = treeModel.TreeModelInstance;

            if (go != null)
            {
                Mesh.AddBoxColliderInParent(go);
            }

            biomass =
                treeModel.GetLeafIndexes().Count != 0 ?         //无叶片,说明未出苗
                BeerRule.BiomassCal(treeModel) / FunctionSim.ComputeDaysInGC(treeModel) : MaizeParams.SEED_BIOMASS;
            break;
        }

        if (biomass != MaizeParams.SEED_BIOMASS)
        {
            biomass *= EnvironmentEffect.TemperatureStressFactor(treeModel) * EnvironmentEffect.WaterStressFactor(treeModel) * EnvironmentEffect.SunshineStress(treeModel);
        }

        return(biomass);
    }
Пример #43
0
        void CreateScene()
        {
            scene = new Scene();
            octree = scene.CreateComponent<Octree>();

            rootNode = scene.CreateChild(name: "Root");

            var earthNode = rootNode.CreateChild(name: "Earth");
            var earth = earthNode.CreateComponent<Sphere>();
            earth.Color = Urho.Color.Blue;
            earthNode.SetScale(4f);
            earth.SetMaterial(Material.FromImage("earth3.jpg"));

            cameraNode = scene.CreateChild();
            camera = cameraNode.CreateComponent<Camera>();
            cameraNode.Position = new Vector3((float)9.5, (float)9.90, 10) / 1.75f;
            cameraNode.Rotation = new Quaternion(-0.121f, 0.878f, -0.305f, -0.35f);

            Node lightNode = cameraNode.CreateChild();
            var light = lightNode.CreateComponent<Light>();
            light.LightType = LightType.Point;
            light.Range = 100;
            light.Brightness = 1.3f;

            var markersNode = rootNode.CreateChild();

            var positions = new Dictionary<string, float[]> {
                { "tokyo", new float[] { 35.683333f, 139.683333f }},//tokyo
                { "amsterdam", new float[] { 52.366667f, 4.900000f } },//amsterdam
                { "delhi", new float[] { 28.538336f, -81.379234f } },//orlando
                { "orlando", new float[] { 28.293155f, 76.919282f } },//delhi
            };


            foreach (var row in positions.Keys)
                AddMarker(markersNode,
                          lat: positions[row][0],
                          lon: positions[row][1], id: row);

            AutoRotate();
        }
Пример #44
0
        public static void AddCollision(this DynamicPrimitive dynamicPrimitive, Microsoft.Xna.Framework.Graphics.Model model, Matrix?world, Color color)
        {
            if (bones == null || bones.Length < model.Bones.Count)
            {
                bones = new Matrix[model.Bones.Count];
            }

            model.CopyAbsoluteBoneTransformsTo(bones);

            Matrix transform = world.HasValue ? world.Value : Matrix.Identity;

            ModelTag tag = model.Tag as ModelTag;

            // Add collision tree
            if (tag != null && tag.Collision != null)
            {
                transform = bones[model.Meshes[0].ParentBone.Index] * transform;
                Octree <bool> tree = tag.Collision.CollisionTree;

                tree.Traverse(node =>
                {
                    if (!node.hasChildren && node.value)
                    {
                        dynamicPrimitive.AddSolidBox(node.bounds, transform, color);
                    }
                    return(TraverseOptions.Continue);
                });
            }
            // Add collision sphere
            else
            {
                for (int i = 0; i < model.Meshes.Count; ++i)
                {
                    var mesh = model.Meshes[i];
                    dynamicPrimitive.AddSolidSphere(mesh.BoundingSphere, 18, bones[mesh.ParentBone.Index] * transform, color);
                }
            }
        }
Пример #45
0
        /// <summary>
        /// Constructor takes the variables and processes the image
        /// </summary>
        /// <param name="image">The image to reduce</param>
        /// <param name="maxColors">The maximum number of colors to use value must be between 2 and 255</param>
        public ReduceColor(Bitmap image, int maxColors)
        {
            if (maxColors < 2 || maxColors > 255)
                throw new ArgumentOutOfRangeException("maxColors", maxColors, "The maximum number of colors should be between 2 and 255");

            int maxColorBits = 8;
            for (int i = 1, j = 2; i < 9; ++i, j *= 2)
            {
                if (maxColors <= j)
                {
                    maxColorBits = i;
                    break;
                }
            }

            Octree tree = new Octree(maxColorBits);
            Rectangle bounds = new Rectangle(0, 0, image.Width, image.Height);
            Bitmap copy = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppArgb);
            Bitmap output = new Bitmap(image.Width, image.Height, PixelFormat.Format8bppIndexed);

            using (Graphics g = Graphics.FromImage(copy))
            {
                g.PageUnit = GraphicsUnit.Pixel;
                g.DrawImageUnscaled(image, bounds);
            }

            BitmapData imgData = null;
            try
            {
                imgData = copy.LockBits(bounds, ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
                firstPass(tree, imgData, image.Width, image.Height);
                output.Palette = palette(tree, output.Palette, maxColors);
                secondPass(tree, imgData, output, image.Width, image.Height, bounds, maxColors);
            }
            finally { copy.UnlockBits(imgData); }

            _rst = output;
        }
Пример #46
0
                /// <summary>
                /// Initializes a new instance of the <see cref="OctreeNode"/> class.
                /// </summary>
                /// <param name="level">The level in the tree = 0 - 7.</param>
                /// <param name="colorBits">The number of significant color bits in the image.</param>
                /// <param name="octree">The tree to which this node belongs.</param>
                public OctreeNode(int level, int colorBits, Octree octree)
                {
                    // Construct the new node
                    this.leaf = level == colorBits;

                    this.red        = this.green = this.blue = 0;
                    this.pixelCount = 0;

                    // If a leaf, increment the leaf count
                    if (this.leaf)
                    {
                        octree.Leaves++;
                        this.NextReducible = null;
                        this.children      = null;
                    }
                    else
                    {
                        // Otherwise add this to the reducible nodes
                        this.NextReducible           = octree.ReducibleNodes[level];
                        octree.ReducibleNodes[level] = this;
                        this.children = new OctreeNode[8];
                    }
                }
Пример #47
0
                /// <summary>
                /// Construct the node
                /// </summary>
                /// <param name="level">The level in the tree = 0 - 7</param>
                /// <param name="colorBits">The number of significant color bits in the image</param>
                /// <param name="octree">The tree to which this node belongs</param>
                public OctreeNode(int level, int colorBits, Octree octree)
                {
                    // Construct the new node
                    _leaf = (level == colorBits);

                    _red        = _green = _blue = 0;
                    _pixelCount = 0;

                    // If a leaf, increment the leaf count
                    if (_leaf)
                    {
                        octree.Leaves++;
                        _nextReducible = null;
                        _children      = null;
                    }
                    else
                    {
                        // Otherwise add this to the reducible nodes
                        _nextReducible = octree.ReducibleNodes[level];
                        octree.ReducibleNodes[level] = this;
                        _children = new OctreeNode[8];
                    }
                }
Пример #48
0
        protected override void OnUpdate(float timeStep)
        {
            base.OnUpdate(timeStep);
            var ray           = Camera.GetScreenRay(0.5f, 0.5f);
            var raycastResult = Octree.RaycastSingle(ray);

            if (raycastResult != null)
            {
                var pos = raycastResult.Value.Position;
                if (!raycastResult.Value.Node.Name.StartsWith("RulerPoint"))
                {
                    pointerNode.Position = pos;
                    cursorPos            = pos;
                }
            }
            else
            {
                cursorPos = null;
            }

            textNode.LookAt(CameraNode.Position, Vector3.UnitY);
            textNode.Rotate(new Quaternion(0, 180, 0));
        }
Пример #49
0
        public Window()
            : base(1280, 720, new GraphicsMode(32, 0, 0, 4), "OpenCAD")
        {
            stl = new STL("Models/elephant.stl", Color.Green, STLType.Binary);

            var s1 = new Sphere {Center = Vect3.Zero, Radius = 4};
            var s2 = new Sphere {Center = new Vect3(0,5,0), Radius = 4};
            var t1 = new Octree<Voxel>(Vect3.Zero, 32.0);
            var t2 = new Octree<Voxel>(Vect3.Zero, 32.0);

            Test2(t1, node => s1.Intersects(node.AABB));
            Test(t2, stl.Elements);

            _tree = t1.Union(t2);

            //_tree.Test(node => sphere.Intersects(node.AABB),maxLevel);
            //Test2(t, node => sphere.Intersects(node.AABB));

            //t[0].Clear();
            //t[0].Clear();
            //Test(_tree,stl.Elements);
            //create from stl
            //foreach (var tri in stl.Elements)
            //{
            //    Intersect(_tree, tri);
            //}

            VSync = VSyncMode.On;

            _camera = new Camera();
            Mouse.WheelChanged += (sender, args) =>
                {
                    _camera.View = _camera.View * Mat4.Translate(0, 0, args.DeltaPrecise * -10.0);
                    //_camera.Eye += new Vect3(0, 0, args.DeltaPrecise * -10.0);
                    // Console.WriteLine(_camera.Eye);
                };
        }
Пример #50
0
        /// <summary>
        /// Does the quantize.
        /// </summary>
        /// <param name="bitmapSource">The bitmap source.</param>
        /// <param name="pixelFormat">The pixel format.</param>
        /// <param name="useDither">if set to <c>true</c> [use dither].</param>
        /// <returns>The quantized image with the recalculated color palette.</returns>
        private static Bitmap DoQuantize(Bitmap bitmapSource, PixelFormat pixelFormat, bool useDither)
        {
            // We use these values a lot
            int width = bitmapSource.Width;
            int height = bitmapSource.Height;
            Rectangle sourceRect = Rectangle.FromLTRB(0, 0, width, height);

            Bitmap bitmapOptimized = null;

            try
            {
                // Create a bitmap with the same dimensions and the desired format
                bitmapOptimized = new Bitmap(width, height, pixelFormat);

                // Lock the bits of the source image for reading.
                // we will need to write if we do the dither.
                BitmapData bitmapDataSource = bitmapSource.LockBits(
                    sourceRect,
                    ImageLockMode.ReadWrite,
                    PixelFormat.Format32bppArgb);

                try
                {
                    // Perform the first pass, which generates the octree data
                    // Create an Octree
                    Octree octree = new Octree(pixelFormat);

                    // Stride might be negative, indicating inverted row order.
                    // Allocate a managed buffer for the pixel data, and copy it from the unmanaged pointer.
                    int strideSource = Math.Abs(bitmapDataSource.Stride);
                    byte[] sourceDataBuffer = new byte[strideSource * height];
                    Marshal.Copy(bitmapDataSource.Scan0, sourceDataBuffer, 0, sourceDataBuffer.Length);

                    // We could skip every other row and/or every other column when sampling the colors
                    // of the source image, rather than hitting every other pixel. It doesn't seem to
                    // degrade the resulting image too much. But it doesn't really help the performance
                    // too much because the majority of the time seems to be spent in other places.

                    // For every row
                    int rowStartSource = 0;
                    for (int ndxRow = 0; ndxRow < height; ndxRow += 1)
                    {
                        // For each column
                        for (int ndxCol = 0; ndxCol < width; ndxCol += 1)
                        {
                            // Add the color (4 bytes per pixel - ARGB)
                            Pixel pixel = GetSourcePixel(sourceDataBuffer, rowStartSource, ndxCol);
                            octree.AddColor(pixel);
                        }

                        rowStartSource += strideSource;
                    }

                    // Get the optimized colors
                    Color[] colors = octree.GetPaletteColors();

                    // Set the palette from the octree
                    ColorPalette palette = bitmapOptimized.Palette;
                    for (var ndx = 0; ndx < palette.Entries.Length; ++ndx)
                    {
                        // Use the colors we calculated
                        // for the rest, just set to transparent
                        palette.Entries[ndx] = (ndx < colors.Length)
                            ? colors[ndx]
                            : Color.Transparent;
                    }

                    bitmapOptimized.Palette = palette;

                    // Lock the bits of the optimized bitmap for writing.
                    // we will also need to read if we are doing 1bpp or 4bpp
                    BitmapData bitmapDataOutput = bitmapOptimized.LockBits(sourceRect, ImageLockMode.ReadWrite, pixelFormat);
                    try
                    {
                        // Create a managed array for the destination bytes given the desired color depth
                        // and marshal the unmanaged data to the managed array
                        int strideOutput = Math.Abs(bitmapDataOutput.Stride);
                        byte[] bitmapOutputBuffer = new byte[strideOutput * height];

                        // For each source pixel, compute the appropriate color index
                        rowStartSource = 0;
                        int rowStartOutput = 0;

                        for (int ndxRow = 0; ndxRow < height; ++ndxRow)
                        {
                            // For each column
                            for (int ndxCol = 0; ndxCol < width; ++ndxCol)
                            {
                                // Get the source color
                                Pixel pixel = GetSourcePixel(sourceDataBuffer, rowStartSource, ndxCol);

                                // Get the closest palette index
                                int paletteIndex = octree.GetPaletteIndex(pixel);

                                // If we want to dither and this isn't the transparent pixel
                                if (useDither && pixel.Alpha != 0)
                                {
                                    // Calculate the error
                                    Color paletteColor = colors[paletteIndex];
                                    int deltaRed = pixel.Red - paletteColor.R;
                                    int deltaGreen = pixel.Green - paletteColor.G;
                                    int deltaBlue = pixel.Blue - paletteColor.B;

                                    // Propagate the dither error.
                                    // we'll use a standard Floyd-Steinberg matrix (1/16):
                                    // | 0 0 0 |
                                    // | 0 x 7 |
                                    // | 3 5 1 |

                                    // Make sure we're not on the right-hand edge
                                    if (ndxCol + 1 < width)
                                    {
                                        DitherSourcePixel(sourceDataBuffer, rowStartSource, ndxCol + 1, deltaRed, deltaGreen, deltaBlue, 7);
                                    }

                                    // Make sure we're not already on the bottom row
                                    if (ndxRow + 1 < height)
                                    {
                                        int nextRow = rowStartSource + strideSource;

                                        // Make sure we're not on the left-hand column
                                        if (ndxCol > 0)
                                        {
                                            // Down one row, but back one pixel
                                            DitherSourcePixel(sourceDataBuffer, nextRow, ndxCol - 1, deltaRed, deltaGreen, deltaBlue, 3);
                                        }

                                        // pixel directly below us
                                        DitherSourcePixel(sourceDataBuffer, nextRow, ndxCol, deltaRed, deltaGreen, deltaBlue, 5);

                                        // Make sure we're not on the right-hand column
                                        if (ndxCol + 1 < width)
                                        {
                                            // Down one row, but right one pixel
                                            DitherSourcePixel(sourceDataBuffer, nextRow, ndxCol + 1, deltaRed, deltaGreen, deltaBlue, 1);
                                        }
                                    }
                                }

                                // Set the bitmap index based on the format
                                switch (pixelFormat)
                                {
                                    case PixelFormat.Format8bppIndexed:
                                        // Each byte is a palette index
                                        bitmapOutputBuffer[rowStartOutput + ndxCol] = (byte)paletteIndex;
                                        break;

                                    case PixelFormat.Format4bppIndexed:
                                        // Each byte contains two pixels
                                        bitmapOutputBuffer[rowStartOutput + (ndxCol >> 1)] |= ((ndxCol & 1) == 1)
                                            ? (byte)(paletteIndex & 0x0f) // lower nibble
                                            : (byte)(paletteIndex << 4);  // upper nibble
                                        break;

                                    case PixelFormat.Format1bppIndexed:
                                        // Each byte contains eight pixels
                                        if (paletteIndex != 0)
                                        {
                                            bitmapOutputBuffer[rowStartOutput + (ndxCol >> 3)] |= (byte)(0x80 >> (ndxCol & 0x07));
                                        }

                                        break;
                                }
                            }

                            rowStartSource += strideSource;
                            rowStartOutput += strideOutput;
                        }

                        // Now copy the calculated pixel bytes from the managed array to the unmanaged bitmap
                        Marshal.Copy(bitmapOutputBuffer, 0, bitmapDataOutput.Scan0, bitmapOutputBuffer.Length);
                    }
                    finally
                    {
                        bitmapOptimized.UnlockBits(bitmapDataOutput);
                        bitmapDataOutput = null;
                    }
                }
                finally
                {
                    bitmapSource.UnlockBits(bitmapDataSource);
                    bitmapDataSource = null;
                }
            }
            catch (Exception)
            {
                // If any exception is thrown, dispose of the bitmap object
                // we've been working on before we rethrow and bail
                if (bitmapOptimized != null)
                {
                    bitmapOptimized.Dispose();
                }

                throw;
            }

            // Caller is responsible for disposing of this bitmap!
            return bitmapOptimized;
        }
Пример #51
0
                /// <summary>Initializes a new instance of the <see cref="OctreeNode"/> class. Constructor</summary>
                /// <param name="level">level for this node</param>
                /// <param name="octree">owning octree</param>
                internal OctreeNode(int level, Octree octree)
                {
                    this.nodeOctree = octree;
                    this.nodeLevel = level;

                    // Since there are only eight levels, if we get to level 7
                    // We automatically make this a leaf node
                    this.nodeIsLeaf = level == 7;

                    if (!this.nodeIsLeaf)
                    {
                        // Create the child array
                        this.nodeChildNodes = new OctreeNode[8];

                        // Add it to the tree's reducible node list
                        this.nodeOctree.AddReducibleNode(this);
                    }
                }
Пример #52
0
                /// <summary>
                /// Initializes a new instance of the <see cref="OctreeNode"/> class. 
                /// </summary>
                /// <param name="level">
                /// The level in the tree = 0 - 7
                /// </param>
                /// <param name="colorBits">
                /// The number of significant color bits in the image
                /// </param>
                /// <param name="octree">
                /// The tree to which this node belongs
                /// </param>
                public OctreeNode(int level, int colorBits, Octree octree)
                {
                    // Construct the new node
                    this.leaf = level == colorBits;

                    this.red = this.green = this.blue = 0;
                    this.pixelCount = 0;

                    // If a leaf, increment the leaf count
                    if (this.leaf)
                    {
                        octree.Leaves++;
                        this.nextReducible = null;
                        this.children = null;
                    }
                    else
                    {
                        // Otherwise add this to the reducible nodes
                        this.nextReducible = octree.ReducibleNodes[level];
                        octree.ReducibleNodes[level] = this;
                        this.children = new OctreeNode[8];
                    }
                }
Пример #53
0
                /// <summary>
                /// Add a color into the tree
                /// </summary>
                /// <param name="pixel">
                /// The color
                /// </param>
                /// <param name="colorBits">
                /// The number of significant color bits
                /// </param>
                /// <param name="level">
                /// The level in the tree
                /// </param>
                /// <param name="octree">
                /// The tree to which this node belongs
                /// </param>
                public void AddColor(Color32* pixel, int colorBits, int level, Octree octree)
                {
                    // Update the color information if this is a leaf
                    if (this.leaf)
                    {
                        this.Increment(pixel);

                        // Setup the previous node
                        octree.TrackPrevious(this);
                    }
                    else
                    {
                        // Go to the next level down in the tree
                        int shift = 7 - level;
                        int index = ((pixel->R & Mask[level]) >> (shift - 2)) |
                                    ((pixel->G & Mask[level]) >> (shift - 1)) |
                                    ((pixel->B & Mask[level]) >> shift);

                        OctreeNode child = this.children[index];

                        if (null == child)
                        {
                            // Create a new child node & store in the array
                            child = new OctreeNode(level + 1, colorBits, octree);
                            this.children[index] = child;
                        }

                        // Add the color to the child node
                        child.AddColor(pixel, colorBits, level + 1, octree);
                    }
                }
Пример #54
0
                /// <summary>
                /// Construct the node
                /// </summary>
                /// <param name="level">The level in the tree = 0 - 7</param>
                /// <param name="colorBits">The number of significant color bits in the image</param>
                /// <param name="octree">The tree to which this node belongs</param>
                public OctreeNode(int level, int colorBits, Octree octree)
                {
                    // Construct the new node
                    _leaf = (level == colorBits);

                    _red = _green = _blue = 0;
                    _pixelCount = 0;

                    // If a leaf, increment the leaf count
                    if (_leaf)
                    {
                        octree.Leaves++;
                        _nextReducible = null;
                        _children = null;
                    }
                    else
                    {
                        // Otherwise add this to the reducible nodes
                        _nextReducible = octree.ReducibleNodes[level];
                        octree.ReducibleNodes[level] = this;
                        _children = new OctreeNode[8];
                    }
                }
Пример #55
0
        private byte processPxl(Octree tree, Color32* pxl, int maxColors)
        {
            byte idx = (byte)maxColors;
            if (pxl->Alpha > 0)
                idx = (byte)tree.paletteIndex(pxl);

            return idx;
        }
Пример #56
0
        private void secondPass(Octree tree, BitmapData data, Bitmap output, int width, int height, Rectangle bounds, int maxColors)
        {
            BitmapData outData = null;
            try
            {
                outData = output.LockBits(bounds, ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
                byte* srcRow = (byte*)data.Scan0.ToPointer();
                Int32* srcPxl = (Int32*)srcRow;
                Int32* prvPxl = srcPxl;

                byte* dstRow = (byte*)outData.Scan0.ToPointer();
                byte* dstPxl = dstRow;

                byte pxlValue = processPxl(tree, (Color32*)srcPxl, maxColors);
                *dstPxl = pxlValue;

                for (int row = 0; row < height; ++row)
                {
                    srcPxl = (Int32*)srcRow;
                    dstPxl = dstRow;

                    for (int col = 0; col < width; ++col, ++srcPxl, ++dstPxl)
                    {
                        if (*prvPxl == *srcPxl)
                        {
                            pxlValue = processPxl(tree, (Color32*)srcPxl, maxColors);
                            prvPxl = srcPxl;
                        }
                        *dstPxl = pxlValue;
                    }

                    srcRow += data.Stride;
                    dstRow += outData.Stride;
                }
            }
            finally { output.UnlockBits(outData); }
        }
Пример #57
0
                /// <summary>
                /// Add a color into the tree
                /// </summary>
                /// <param name="pixel">The color</param>
                /// <param name="colorBits">The number of significant color bits</param>
                /// <param name="level">The level in the tree</param>
                /// <param name="octree">The tree to which this node belongs</param>
                public void addColor(Color32* pixel, int colorBits, int level, Octree octree)
                {
                    // Update the color information if this is a leaf
                    if (_leaf)
                    {
                        inc(pixel);
                        // Setup the previous node
                        octree.trackPrevious(this);
                    }
                    else
                    {
                        // Go to the next level down in the tree
                        int shift = 7 - level;
                        int index = ((pixel->Red & mask[level]) >> (shift - 2)) |
                           ((pixel->Green & mask[level]) >> (shift - 1)) |
                           ((pixel->Blue & mask[level]) >> (shift));

                        OctreeNode child = _children[index];

                        if (child == null)
                        {
                            // Create a new child node & store in the array
                            child = new OctreeNode(level + 1, colorBits, octree);
                            _children[index] = child;
                        }

                        // Add the color to the child node
                        child.addColor(pixel, colorBits, level + 1, octree);
                    }
                }
Пример #58
0
 /// <summary>
 /// Creates a new istance if the TriangleMeshShape class.
 /// </summary>
 /// <param name="octree">The octree which holds the triangles
 /// of a mesh.</param>
 public TriangleMeshShape(Octree octree)
 {
     this.octree = octree;
     UpdateShape();
 }
Пример #59
0
 public void Setup()
 {
     _box = new ThreeDimensionalBoundingBox(10, 10, 10, 10);
     _tree = new Octree<TestObject>(_box, 2);
 }
Пример #60
-1
        private ColorPalette palette(Octree tree, ColorPalette old, int maxColors)
        {
            ArrayList palette = tree.palette(maxColors - 1);
            for (int i = 0; i < palette.Count; ++i)
                old.Entries[i] = (Color)palette[i];

            old.Entries[maxColors] = Color.FromArgb(0, 0, 0, 0);
            return old;
        }