static void Main(string[] args)
 {
     char[, ,] testMatrix = GetMatrix();
     Cuboid examMain = new Cuboid(testMatrix);
     examMain.EnumerateStars();
     int sum = 0;
     for (int i = 0; i < colorOccurrences.Length; i++)
     {
         sum += colorOccurrences[i];
     }
     Console.WriteLine(sum);
     for (char x = 'A'; x <= 'Z'; x++)
     {
         int currentIndex = CharToIndex(x);
         if (colorOccurrences[currentIndex] != 0)
         {
             Console.WriteLine("{0} {1}", x, colorOccurrences[currentIndex]);
         }
     }
     //Dictionary<char, uint> stars = examMain.Stars;
     //IEnumerable<KeyValuePair<char, uint>> sortedResult = stars.OrderBy(x => x.Key);
     //Console.WriteLine(stars.Sum(x => x.Value));
     //foreach (KeyValuePair<char, uint> star in sortedResult)
     //{
     //    Console.WriteLine("{0} {1}", star.Key, star.Value);
     //}
 }
Пример #2
0
        private void SplitFreeCuboidAlongAxis(
            Cuboid freeCuboid,
            Cuboid placedCuboid,
            bool splitHorizontal)
        {
            var bottom = new Cuboid
            {
                X      = freeCuboid.X,
                Y      = freeCuboid.Y,
                Z      = freeCuboid.Z + placedCuboid.Depth,
                Depth  = freeCuboid.Depth - placedCuboid.Depth,
                Height = placedCuboid.Height
            };

            var right = new Cuboid
            {
                X      = freeCuboid.X + placedCuboid.Width,
                Y      = freeCuboid.Y,
                Z      = freeCuboid.Z,
                Width  = freeCuboid.Width - placedCuboid.Width,
                Height = placedCuboid.Height
            };

            var top = new Cuboid
            {
                X      = freeCuboid.X,
                Y      = freeCuboid.Y + placedCuboid.Height,
                Z      = freeCuboid.Z,
                Height = freeCuboid.Height - placedCuboid.Height,
                Width  = freeCuboid.Width,
                Depth  = freeCuboid.Depth
            };

            if (splitHorizontal)
            {
                bottom.Width = freeCuboid.Width;
                right.Depth  = placedCuboid.Depth;
            }
            else // Split vertically
            {
                bottom.Width = placedCuboid.Width;
                right.Depth  = freeCuboid.Depth;
            }

            // Add new free cuboids.
            if (bottom.Width > 0 && bottom.Height > 0 && bottom.Depth > 0)
            {
                AddFreeCuboid(bottom);
            }
            if (right.Width > 0 && right.Height > 0 && right.Depth > 0)
            {
                AddFreeCuboid(right);
            }
            if (top.Width > 0 && top.Height > 0 && top.Depth > 0)
            {
                AddFreeCuboid(top);
            }
        }
Пример #3
0
        async Task IHandle <SpawnEntity> .Handle(SpawnEntity message)
        {
            var pos = message.Position;
            var bb  = BoundingBox.Item();
            var box = new Cuboid(new Point3d(pos.X, pos.Z, pos.Y), new Size(bb.X, bb.Y, bb.Z));
            await AttachedObject.SetLocalValue(ColliderComponent.ColliderShapeProperty, box);

            CompleteSpawn();
        }
Пример #4
0
        /***************************************************/
        /**** Public Methods - Cuboid                   ****/
        /***************************************************/

        public static bool IsContaining(this Cuboid cuboid, IGeometry geometry, bool acceptOnEdge = true, double tolerance = Tolerance.Distance)
        {
            TransformMatrix transform = Create.OrientationMatrixLocalToGlobal(cuboid.CoordinateSystem);
            IGeometry       globalGeo = geometry.ITransform(transform);
            BoundingBox     geoBox    = globalGeo.IBounds();
            BoundingBox     cuboidBox = cuboid.BoundingBox();

            return(cuboidBox.IsContaining(geoBox, acceptOnEdge, tolerance));
        }
Пример #5
0
        private void RenderAll()
        {
            //dsSetTexture(DS_TEXTURE_NUMBER.DS_WOOD);

            physicsSystem.PhysicsObjects.Stepper(x =>
            {
                dsSetTexture(DS_TEXTURE_NUMBER.DS_WOOD);

                if (x.Shape is Cube <float> )
                {
                    Cube <float> cube = x.Shape as Cube <float>;

                    if (x.IsActive)
                    {
                        dsSetColor(1, 1, 1);
                    }
                    else
                    {
                        dsSetColor(0.5f, 0.5f, 1);
                    }

                    dsDrawBox(cube.Position, To3x4Matrix(cube.Orientation), new Vector <float>(cube.HalfLength * 2, cube.HalfLength * 2, cube.HalfLength * 2));
                }
                else if (x.Shape is Sphere <float> )
                {
                    Sphere <float> sphere = x.Shape as Sphere <float>;

                    if (x.IsActive)
                    {
                        dsSetColor(1, 1, 0);
                    }
                    else
                    {
                        dsSetColor(0.5f, 0.5f, 1);
                    }

                    dsDrawSphere(sphere.Position, To3x4Matrix(sphere.Orientation), sphere.Radius);
                }
                else if (x.Shape is Cuboid <float> )
                {
                    dsSetTexture(DS_TEXTURE_NUMBER.DS_GROUND);

                    Cuboid <float> cuboid = x.Shape as Cuboid <float>;

                    if (x.IsActive)
                    {
                        dsSetColor(.5, .5, .5);
                    }
                    else
                    {
                        dsSetColor(.5, .5, .5);
                    }

                    dsDrawBox(cuboid.Position, To3x4Matrix(cuboid.Orientation), new Vector <float>(cuboid.HalfLength * 2, cuboid.HalfHeight * 2, cuboid.HalfWidth * 2));
                }
            });
        }
Пример #6
0
        public LevelGeometry_Cuboid(XElement xmlElement) : base(xmlElement)
        {
            float   width  = float.Parse(xmlElement.Attribute(WIDTH_ATTRIBUTE_NAME).Value, CultureInfo.InvariantCulture);
            float   height = float.Parse(xmlElement.Attribute(HEIGHT_ATTRIBUTE_NAME).Value, CultureInfo.InvariantCulture);
            float   depth  = float.Parse(xmlElement.Attribute(DEPTH_ATTRIBUTE_NAME).Value, CultureInfo.InvariantCulture);
            Vector3 fbl    = Vector3.Parse(xmlElement.Attribute(FRONT_BOTTOM_LEFT_ATTRIBUTE_NAME).Value);

            this.ShapeDesc = new Cuboid(fbl, width, height, depth);
        }
Пример #7
0
        async Task IHandle <SpawnEntity> .Handle(SpawnEntity message)
        {
            var pos = message.Position;
            var bb  = BoundingBox.Item();
            var box = new Cuboid(new Point3d(pos.X, pos.Z, pos.Y), new Size(bb.X, bb.Y, bb.Z));
            await AttachedObject.SetLocalValue(ColliderComponent.ColliderShapeProperty, box);

            Logger.LogInformation($"Pickup spawn, key: {AttachedObject.GetAddressByPartitionKey()}");
        }
Пример #8
0
 private void AddToShelf(Shelf shelf, Cuboid newCuboid)
 {
     if (shelf.Height < newCuboid.Height)
     {
         throw new ArithmeticException("shelf.Height < newCuboid.Height");
     }
     newCuboid.Y = shelf.StartY;
     _packedCuboids.Add(newCuboid);
 }
Пример #9
0
 internal static global::Topologic.Cell CellByCuboid(Cuboid bhomCuboid)
 {
     return(global::Topologic.Utilities.CellUtility.ByCuboid(
                bhomCuboid.CoordinateSystem.Origin.X, bhomCuboid.CoordinateSystem.Origin.Y, bhomCuboid.CoordinateSystem.Origin.Z,
                bhomCuboid.Length, bhomCuboid.Depth, bhomCuboid.Depth,
                bhomCuboid.CoordinateSystem.Z.X, bhomCuboid.CoordinateSystem.Z.Y, bhomCuboid.CoordinateSystem.Z.Z,
                bhomCuboid.CoordinateSystem.X.X, bhomCuboid.CoordinateSystem.X.Y, bhomCuboid.CoordinateSystem.X.Z,
                bhomCuboid.CoordinateSystem.Y.X, bhomCuboid.CoordinateSystem.Y.Y, bhomCuboid.CoordinateSystem.Y.Z));
 }
Пример #10
0
        public CuboidEditWindow(Cuboid cuboid, ImageControler imageControler, InputFormControler inputFormControler)
        {
            this.inputFormControler = inputFormControler;
            this.imageControler     = imageControler;
            this.cuboid             = cuboid;

            InitializeComponent();
            SetDataToComponents();
        }
        public void PrintTest()
        {
            Cuboid cub = new Cuboid(Color.Red, Color.Yellow, 2, 4, 7, 5);

            string excpected = "Cuboid:\nContourColor:Red\nFillingColor:Yellow\nContourWidth:2\nSideA:4\nSideB:7\nSideC:5\n";
            string actual    = cub.ToString();

            Assert.AreEqual(excpected, actual);
        }
        public void AreaTest()
        {
            Cuboid cub = new Cuboid(Color.Red, Color.Yellow, 2, 1, 2, 3);

            double expected = 22;
            double actual   = cub.Area();

            Assert.AreEqual(expected, actual);
        }
        public void VolumeTest()
        {
            Cuboid cub = new Cuboid(Color.Red, Color.Yellow, 2, 1, 2, 3);

            double expected = 6;
            double actual   = cub.Volume();

            Assert.AreEqual(expected, actual);
        }
Пример #14
0
 public override void CreateColl()
 {
     Vector[] tmp = new Vector[8];
     tmp = MeshVerticisToCubeVerticies(meshF.mesh.vertices);
     for (int i = 0; i < 8; i++)
     {
         tmp[i] = Matrix.TRS((Vector)transform.position + offset, transform.eulerAngles, (Vector)transform.lossyScale + size) * tmp[i];
     }
     cub = new Cuboid(tmp);
 }
Пример #15
0
 private void SpatialSnapping(out Vector3 snappingDisplacement)
 {
     snappingDisplacement = Vector3.zero;
     if (m_SpatialPeers != null && m_SpatialPeers.Count > 0)
     {
         var thisCuboid = new Cuboid(m_BoundaryController.GetBoundaryEdges(), m_BoundaryController, m_BoundaryController.OriginalPivot());
         //If not we check if no previous faces were snapping we check if there are snapping faces and try to snap them
         TrySnapFaces(thisCuboid, m_SpatialPeers, out snappingDisplacement);
     }
 }
Пример #16
0
        public override bool Equals(object obj)
        {
            if (!(obj is Cuboid))
            {
                return(false);
            }
            Cuboid c = (Cuboid)obj;

            return(X == c.X && Y == c.Y && Z == c.Z && c.Width == Width && c.Height == Height && Length == c.Length);
        }
Пример #17
0
        private void AddCuboid(double x, double y, double z, Color color,
                               double transX, double transY, double transZ,
                               int degrees, Axis axis)
        {
            Cuboid cuboid = new Cuboid(x, y, z, color);

            cuboid.Rotate(degrees, axis);
            cuboid.Translate(transX, transY, transZ);
            cuboids.Add(cuboid);
        }
 public CurveDesc(Cuboid startingCuboid,
                  float yawRotationRads, float pitchRotationRads, float rollRotationRads,
                  uint numSegments)
 {
     StartingCuboid    = startingCuboid;
     YawRotationRads   = yawRotationRads;
     PitchRotationRads = pitchRotationRads;
     RollRotationRads  = rollRotationRads;
     NumSegments       = numSegments;
 }
Пример #19
0
        private void SplitFreeCuboidAlongAxis(
            Cuboid freeCuboid,
            Cuboid placedCuboid,
            bool splitHorizontal)
        {
            var bottom = new Cuboid();

            bottom.X      = freeCuboid.X;
            bottom.Y      = freeCuboid.Y;
            bottom.Z      = freeCuboid.Z + placedCuboid.Depth;
            bottom.Depth  = freeCuboid.Depth - placedCuboid.Depth;
            bottom.Height = placedCuboid.Height;

            var right = new Cuboid();

            right.X      = freeCuboid.X + placedCuboid.Width;
            right.Y      = freeCuboid.Y;
            right.Z      = freeCuboid.Z;
            right.Width  = freeCuboid.Width - placedCuboid.Width;
            right.Height = placedCuboid.Height;

            var top = new Cuboid();

            top.X      = freeCuboid.X;
            top.Y      = freeCuboid.Y + placedCuboid.Height;
            top.Z      = freeCuboid.Z;
            top.Height = freeCuboid.Height - placedCuboid.Height;
            top.Width  = freeCuboid.Width;
            top.Depth  = freeCuboid.Depth;

            if (splitHorizontal)
            {
                bottom.Width = freeCuboid.Width;
                right.Depth  = placedCuboid.Depth;
            }
            else // Split vertically
            {
                bottom.Width = placedCuboid.Width;
                right.Depth  = freeCuboid.Depth;
            }

            // Add new free cuboids.
            if (bottom.Width > 0 && bottom.Height > 0 && bottom.Depth > 0)
            {
                AddFreeCuboid(bottom);
            }
            if (right.Width > 0 && right.Height > 0 && right.Depth > 0)
            {
                AddFreeCuboid(right);
            }
            if (top.Width > 0 && top.Height > 0 && top.Depth > 0)
            {
                AddFreeCuboid(top);
            }
        }
Пример #20
0
        private void FillCuboid(Cuboid cube)
        {
            foreach (var point in cube.PointsFromBottomToTopSnake())
            {
                var vector      = Vector3D.FromPoint(point);
                var vectorAbove = vector + Vector3D.FromPoint(new Point3D(0, 1, 0));

                MoveBotToPoint(vectorAbove.ToPoint());
                FillVoxelPoint(point);
            }
        }
Пример #21
0
 /// <summary>
 /// Kontrolni metoda pro pridani Kvadru na kreslici platno
 /// </summary>
 /// <returns>Aktualizovany Kvadr</returns>
 internal bool AddCuboidToSceneControl()
 {
     if (Scene.Shapes != null)
     {
         Cuboid c = new Cuboid(new Material(new Vector(0, 0, 0)), new Vector(1.5, -1.5, 0), 1, 1, 1);
         Scene.Shapes.Add(c);
         Scene.shapeCount++;
         return(true);
     }
     return(false);
 }
Пример #22
0
 private static bool StraightPathBoundBoxIntersectsObstacles(Cuboid pathObstacle, Cuboid[] obstacles)
 {
     foreach (var obstacle in obstacles)
     {
         if (pathObstacle.Contains(obstacle.MinPoint))
         {
             return(true);
         }
     }
     return(false);
 }
Пример #23
0
 public IEnumerable <TagCompound> GetWithin(Cuboid area)
 {
     foreach (TagCompound e in _entities)
     {
         Position pos = Entity.GetPosition(e);
         if (area.Contains(pos.X, pos.Y, pos.Z))
         {
             yield return(e);
         }
     }
 }
Пример #24
0
        public override Value Evaluate(FSharpList <Value> args)
        {
            CoordinateSystem cs = (CoordinateSystem)((Value.Container)args[0]).Item;
            double           w  = ((Value.Number)args[1]).Item;
            double           l  = ((Value.Number)args[2]).Item;
            double           h  = ((Value.Number)args[3]).Item;

            _solid = Cuboid.by_lengths(cs, w, l, h);

            return(Value.NewContainer(_solid));
        }
Пример #25
0
            public static void Main(string[] args)
            {
                Cuboid vol = new Cuboid(10, 20, 30);

                Console.WriteLine("\n Volume:" + vol.Volume());
                Console.WriteLine("\n Surface Area:" + vol.Surface());



                Console.ReadKey();
            }
Пример #26
0
        public void SaveAndLoad()
        {
            _model = new EpicModel("test");
            var cuboid = Cuboid.CreateCuboid();

            cuboid.Name = "Cuboid1";
            cuboid.AddAnchor("a1");
            cuboid.AddAnchor("a2");
            cuboid.Position = new Vector3(1, 1, 0);

            var cuboid2 = Cuboid.CreateCuboid();

            cuboid2.Name = "Cuboid2";
            var a3 = cuboid2.AddAnchor("a3");

            cuboid2.AddAnchor("a4");
            a3.Position = new Vector3(1, 1, 0);

            a3.Rotation = new Vector3(1.0f, 2.0f, 3.0f);

            cuboid.Pivot.SetParent(a3);

            _model.ModelParts.Add(cuboid);
            _model.ModelParts.Add(cuboid2);
            _model.ModelParts.Add(cuboid.Clone());

            var animation = _model.GetAnimation(AnimationType.Drop, true);

            animation.AddFrame().Time = 0.123f;
            animation.AddFrame().Time = 0.265f;
            animation.AddFrame().Time = 0.384f;

            var animation2 = _model.GetAnimation(AnimationType.Death3, true);

            animation2.AddFrame().Time = 0.464f;
            animation2.AddFrame().Time = 0.519f;
            animation2.AddFrame().Time = 0.694f;

            var materialTranslator = new TestMaterialTranslator();

            var memoryStream = new MemoryStream(4096);

            var binaryWriter = new BinaryWriter(memoryStream);
            var writer       = new EpicModelWriter(materialTranslator);

            writer.Write(binaryWriter, _model);

            memoryStream.Position = 0;

            var binaryReader = new BinaryReader(memoryStream);
            var reader       = new EpicModelReader(materialTranslator, binaryReader);

            _readModel = reader.Read("test");
        }
Пример #27
0
    public override Geometry GenerateGeometry()
    {
        Cuboid cuboid = new Cuboid();

        cuboid.Constructor = new CuboidConstructor(cuboid);
        cuboid.Assistor    = new Assistor(cuboid);
        cuboid.Implement   = new Implement(cuboid);
        cuboid.Init();

        return(cuboid);
    }
Пример #28
0
    public static bool CuboidVsPlaneCollision(Cuboid a, Plane b, out CollisionData collision)
    {
        Vector3 planeNormal = b.normal;
        Vector3 extents     = a.extents;
        Vector3 center      = a.center;

        float fRadius = Mathf.Abs(planeNormal.x * extents.x) + Mathf.Abs(planeNormal.y * extents.y) + Mathf.Abs(planeNormal.z * extents.z);

        Sphere sphere = new Sphere(center, fRadius);

        return(SphereVsPlaneCollision(sphere, b, out collision));
    }
        public Box BoxToSpeckle(Cuboid box, string units = null)
        {
            var u     = units ?? ModelUnits;
            var plane = PlaneToSpeckle(box.ContextCoordinateSystem.XYPlane, u);

            // Todo: Check for cubes that are offset from the plane origin to ensure correct positioning.
            var boxToSpeckle = new Box(plane, new Interval(-box.Width / 2, box.Width / 2), new Interval(-box.Length / 2, box.Length / 2), new Interval(-box.Height / 2, box.Height / 2), u);

            boxToSpeckle.volume = box.Volume;
            boxToSpeckle.area   = box.Area;
            return(boxToSpeckle);
        }
Пример #30
0
        /// <summary>
        /// Return the bounding surface of the input surface
        /// </summary>
        /// <param name="surface"></param>
        /// <search></search>
        public static Autodesk.DesignScript.Geometry.Surface BoundingSurface(this Autodesk.DesignScript.Geometry.Surface surface)
        {
            Autodesk.DesignScript.Geometry.BoundingBox bb = surface.BoundingBox;
            Cuboid c = bb.ToCuboid();

            Autodesk.DesignScript.Geometry.Surface srf = (c.Explode())[0] as Autodesk.DesignScript.Geometry.Surface;

            bb.Dispose();
            c.Dispose();

            return(srf);
        }
Пример #31
0
    public CuboidLengthConditionState(Tool tool, Condition condition, Geometry geometry) : base(tool, condition)
    {
        if (condition is CuboidLengthCondition)
        {
            this.condition = (CuboidLengthCondition)condition;
        }

        if (geometry is Cuboid)
        {
            this.geometry = (Cuboid)geometry;
        }
    }
Пример #32
0
        /**
             * Checks if the frustum of this camera intersects the given Cuboid.
             *
             * @param c The cuboid to check the frustum against.
             * @return True if the frustum intersects the cuboid.
             */
        public bool intersects(Cuboid c)
        {
            Vector3[] vertices = c.getVertices();
                for (int i = 0; i < 6; i++)
                {
                    if (frustum[i, 0] * (vertices[0].X - position.X) + frustum[i, 1] * (vertices[0].Y - position.Y) + frustum[i, 2] * (vertices[0].Z - position.Z) + frustum[i, 3] > 0)
                    {
                        continue;
                    }

                    if (frustum[i, 0] * (vertices[1].X - position.X) + frustum[i, 1] * (vertices[1].Y - position.Y) + frustum[i, 2] * (vertices[1].Z - position.Z) + frustum[i, 3] > 0)
                    {
                        continue;
                    }

                    if (frustum[i, 0] * (vertices[2].X - position.X) + frustum[i, 1] * (vertices[2].Y - position.Y) + frustum[i, 2] * (vertices[2].Z - position.Z) + frustum[i, 3] > 0)
                    {
                        continue;
                    }

                    if (frustum[i, 0] * (vertices[3].X - position.X) + frustum[i, 1] * (vertices[3].Y - position.Y) + frustum[i, 2] * (vertices[3].Z - position.Z) + frustum[i, 3] > 0)
                    {
                        continue;
                    }

                    if (frustum[i, 0] * (vertices[4].X - position.X) + frustum[i, 1] * (vertices[4].Y - position.Y) + frustum[i, 2] * (vertices[4].Z - position.Z) + frustum[i, 3] > 0)
                    {
                        continue;
                    }

                    if (frustum[i, 0] * (vertices[5].X - position.X) + frustum[i, 1] * (vertices[5].Y - position.Y) + frustum[i, 2] * (vertices[5].Z - position.Z) + frustum[i, 3] > 0)
                    {
                        continue;
                    }

                    if (frustum[i, 0] * (vertices[6].X - position.X) + frustum[i, 1] * (vertices[6].Y - position.Y) + frustum[i, 2] * (vertices[6].Z - position.Z) + frustum[i, 3] > 0)
                    {
                        continue;
                    }

                    if (frustum[i, 0] * (vertices[7].X - position.X) + frustum[i, 1] * (vertices[7].Y - position.Y) + frustum[i, 2] * (vertices[7].Z - position.Z) + frustum[i, 3] > 0)
                    {
                        continue;
                    }
                    return false;
                }

                return true;
        }
Пример #33
0
        private static void Main()
        {
            // Throws Exception correctly
            //Console.WriteLine(FileUtilities.GetFileExtension("example"));

            Console.WriteLine(FileUtilities.GetFileExtension("example.pdf"));
            Console.WriteLine(FileUtilities.GetFileExtension("example.new.pdf"));

            Console.WriteLine(FileUtilities.GetFileNameWithoutExtension("example"));
            Console.WriteLine(FileUtilities.GetFileNameWithoutExtension("example.pdf"));
            Console.WriteLine(FileUtilities.GetFileNameWithoutExtension("example.new.pdf"));

            I2Dimentional firstPoint2D = new Point2D(1, -2);
            I2Dimentional secondPoint2D = new Point2D(3, 4);
            Console.WriteLine(
                "Distance in the 2D space = {0:f2}",
                MathUtilities.CalculateDistance2D(firstPoint2D, secondPoint2D));

            I3Dimentional firstPoint3D = new Point3D(5, 2, -1);
            I3Dimentional secondPoint3D = new Point3D(3, -6, 4);
            Console.WriteLine(
                "Distance in the 3D space = {0:f2}",
                MathUtilities.CalculateDistance3D(firstPoint3D, secondPoint3D));

            ICuboid cuboid = new Cuboid(3,4,5);
            Console.WriteLine(
                "Volume = {0:f2}",
                MathUtilities.CalculateCuboidVolume(cuboid));

            Console.WriteLine(
                "Diagonal XYZ = {0:f2}",
                MathUtilities.CalculateCuboidDiagonal(cuboid));

            I3Dimentional thirdPoint3D = new Point3D(3, 4, 5);
            Console.WriteLine(
                "Diagonal XY = {0:f2}",
                MathUtilities.CalculateRectangleDiagonal(thirdPoint3D.X, thirdPoint3D.Y));

            Console.WriteLine(
                "Diagonal XZ = {0:f2}",
                MathUtilities.CalculateRectangleDiagonal(thirdPoint3D.X, thirdPoint3D.Z));

            Console.WriteLine(
                "Diagonal YZ = {0:f2}",
                MathUtilities.CalculateRectangleDiagonal(thirdPoint3D.Y, thirdPoint3D.Z));
        }
Пример #34
0
        private void AddLevelWalls()
        {
            var hitBoxExtraSize = new Vector3(0f, 0f, 100f);
            var wallTop = new Cuboid(Vector3.Zero, new Vector3(400f, 20f, 20f))
            {
                Position = TopLeftBound, 
                Color = Color4.Red
            };
            wallTop.AddHitBox("wallTop", wallTop.Min - hitBoxExtraSize, wallTop.Max + hitBoxExtraSize);

            var wallLeft = new Cuboid(Vector3.Zero, new Vector3(20f, 400f, 20f))
            {
                Position = TopLeftBound,
                Color = Color4.AliceBlue
            };
            wallLeft.AddHitBox("wallLeft", wallLeft.Min - hitBoxExtraSize, wallLeft.Max + hitBoxExtraSize);

            var wallRight = new Cuboid(Vector3.Zero, new Vector3(20f, 400f, 20f))
            {
                Position = TopRightBound,
                Color = Color4.AliceBlue
            };
            wallRight.AddHitBox(
                "wallRight", wallRight.Min - hitBoxExtraSize, wallRight.Max + hitBoxExtraSize);

            var wallBottom = new Cuboid(Vector3.Zero, new Vector3(400f, 20f, 20f))
            {
                Position = BottomLeftBound,
                Color = Color4.AliceBlue
            };
            wallBottom.AddHitBox(
                "wallBottom", wallBottom.Min - hitBoxExtraSize, wallBottom.Max + hitBoxExtraSize);

            Engine.SpawnObject("wallTop", wallTop);
            Engine.SpawnObject("wallLeft", wallLeft);
            Engine.SpawnObject("wallRight", wallRight);
            Engine.SpawnObject("wallBottom", wallBottom);
        }
 // Проверяет, совпадают ли три размера части с тремя размерами другой части
 public bool CompareDimensions(Cuboid target)
 {
     return
         target.depth == depth ?
             target.width == width ?
                 target.hight == hight :
                 target.width == hight ?
                     target.hight == width : false :
         target.depth == width ?
             target.width == depth ?
                 target.hight == hight :
                 target.width == hight ?
                     target.hight == depth : false :
         target.depth == hight ?
             target.width == depth ?
                 target.hight == width :
                 target.width == width ?
                     target.hight == depth : false :
         false;
 }
Пример #36
0
        private static bool HandleTriplet(int x, int y, int z, int dimensionLimit, HashSet<Cuboid> cuboids)
        {
            if (y > dimensionLimit)
            {
                return true;
            }
            long p1 = z * z;

            for (int j = 1; j < x; j++)
            {
                if (j <= dimensionLimit && x - j <= dimensionLimit)
                {
                    long a = j;
                    long b = (x - j);
                    if (a <= dimensionLimit && b <= dimensionLimit)
                    {
                        //long p1 = (a + b) * (a + b) + y * y;
                        long p2 = (a + y) * (a + y) + b * b;
                        long p3 = (y + b) * (y + b) + a * a;
                        if (p1 <= p2 && p1 <= p3)
                        {
                            var cuboid = new Cuboid((short)j, (short)(x - j), (short)y);
                            if (!cuboids.Contains(cuboid))
                            {
                                cuboids.Add(cuboid);
                                if (cuboids.Count >= LIMIT)
                                {
                                    return false;
                                }
                            }
                        }
                    }
                }
            }
            return true;
        }
Пример #37
0
        public override Octree<UInt16> Generate( int x, int y, int z, int size, int resolution = 1 )
        {
            Octree<UInt16> octree = base.Generate( x, y, z, size, resolution );

            Random rand = new Random( Seed );

            UInt16 empty = BlockManager.GetID( "Core_Empty" );
            UInt16[] sand = new UInt16[ 15 ];
            UInt16[] rock = new UInt16[ 15 ];

            for ( int i = 0; i < 15; ++i )
            {
                sand[ i ] = BlockManager.GetID( "MarsMiner_Sand", i );
                rock[ i ] = BlockManager.GetID( "MarsMiner_Rock", i );
            }

            Face[] slopeFaces = new Face[] { Face.Front, Face.Left, Face.Back, Face.Right };
            UInt16 boulder = BlockManager.GetID( "MarsMiner_Boulder" );

            int min = System.Math.Min( myMinHilly, myMinPlains );
            int gradRange = 2;

            octree.SetCuboid( x, 0, z, size, System.Math.Min( myMinHilly, myMinPlains ), size, rock[ 14 ] );

            if ( y + size >= min )
            {
                int hillDiff = ( myMaxHilly - myMinHilly ) / 2;
                int hillMid = myMinHilly + hillDiff;
                int plainDiff = ( myMinPlains - myMaxPlains ) / 2;
                int plainMid = myMaxPlains + plainDiff;

                int maxCount = size / resolution;
                double hres = resolution / 2.0;

                int[,] heightmap = new int[ maxCount + gradRange * 2, maxCount + gradRange * 2 ];
                double[,] gradmap = new double[ maxCount, maxCount ];

                for( int i = 0; i < maxCount + gradRange * 2; ++ i )
                {
                    double dx = ( x + ( i - gradRange ) * resolution + hres ) / 256.0;
                    for( int j = 0; j < maxCount + gradRange * 2; ++ j )
                    {
                        double dy = ( z + ( j - gradRange ) * resolution + hres ) / 256.0;
                        double hillVal = Tools.Clamp( myHillyNoise.GetValue( dx, dy, 0.5 ) * hillDiff + hillMid, myMinHilly, myMaxHilly );
                        double plainVal = Tools.Clamp( myHillyNoise.GetValue( dx, dy, 0.5 ) * plainDiff + plainMid, myMinPlains, myMaxPlains );
                        double trans = Tools.Clamp( ( myTransNoise.GetValue( dx, dy, 0.5 ) + 1.0 ) / 2.0, 0.0, 1.0 );
                        //trans *= trans;

                        int val = (int) System.Math.Floor( trans * hillVal + ( 1 - trans ) * plainVal );

                        heightmap[ i, j ] = val / resolution * resolution;
                    }
                }

                for ( int i = 0; i < maxCount; ++i )
                {
                    for ( int j = 0; j < maxCount; ++j )
                    {
                        double grad = 0;

                        for ( int gx = -gradRange; gx <= gradRange; ++gx )
                        {
                            for ( int gy = -gradRange; gy <= gradRange; ++gy )
                            {
                                if( gx == 0 && gy == 0 )
                                    continue;

                                double dist = System.Math.Sqrt( gx * gx + gy * gy );

                                int diff = heightmap[ i + gradRange + gx, j + gradRange + gy ]
                                    - heightmap[ i + gradRange, j + gradRange ];

                                grad += System.Math.Abs( diff ) / dist;
                            }
                        }

                        gradmap[ i, j ] = grad;
                    }
                }

                Cuboid rcuboid = new Cuboid( 0, 0, 0, resolution, 1, resolution );
                Cuboid scuboid = new Cuboid( 0, 0, 0, 1, 1, 1 );

                int[,] prev = null;

                for ( int count = 1; count <= maxCount; count <<= 1 )
                {
                    int res = size / count;
                    hres = res / 2.0;
                    int[,] cur = new int[ count, count ];

                    int sca = res / resolution;

                    rcuboid.Width = res;
                    rcuboid.Depth = res;

                    scuboid.Width = res;
                    scuboid.Height = res;
                    scuboid.Depth = res;

                    for ( int nx = 0; nx < count; ++nx )
                    {
                        int rx = x + nx * res;
                        int px = nx >> 1;

                        for ( int nz = 0; nz < count; ++nz )
                        {
                            int rz = z + nz * res;
                            int pz = nz >> 1;

                            int realHeight = heightmap[ nx * sca + gradRange, nz * sca + gradRange ];
                            int height = realHeight / res * res;

                            cur[ nx, nz ] = height;

                            int prevHeight = ( count == 1 ? 0 : prev[ px, pz ] );

                            rcuboid.X = rx;
                            rcuboid.Z = rz;

                            rcuboid.Bottom = System.Math.Min( height, prevHeight );
                            rcuboid.Top = System.Math.Max( height, prevHeight );

                            if( height > prevHeight )
                                octree.SetCuboid( rcuboid, rock[ 14 ] );
                            else
                                octree.SetCuboid( rcuboid, empty );

                            if ( ( res == 1 || ( resolution > 1 && height == realHeight ) )
                                && gradmap[ nx, nz ] <= 8.0 * res )
                            {
                                scuboid.X = rx;
                                scuboid.Y = height - res;
                                scuboid.Z = rz;

                                octree.SetCuboid( scuboid, sand[ 14 ] );
                            }
                        }
                    }

                    prev = cur;
                }

                for ( int colxi = 0; colxi < size / resolution; ++colxi )
                {
                    int colx = colxi * resolution + x;

                    for ( int colzi = 0; colzi < size / resolution; ++colzi )
                    {
                        int colz = colzi * resolution + z;

                        int height = heightmap[ colxi + gradRange, colzi + gradRange ];

                        OctreeLeaf<UInt16> curLeaf =
                        octree.FindNode( colx, height - resolution, colz, resolution )
                            as OctreeLeaf<UInt16>;

                        if ( curLeaf != null && curLeaf.Value != empty )
                        {
                            int[] ns = new int[]
                            {
                                heightmap[ colxi + gradRange - 1, colzi + gradRange + 1 ],
                                heightmap[ colxi + gradRange + 0, colzi + gradRange + 1 ],
                                heightmap[ colxi + gradRange + 1, colzi + gradRange + 1 ],
                                heightmap[ colxi + gradRange - 1, colzi + gradRange + 0 ],
                                heightmap[ colxi + gradRange + 1, colzi + gradRange + 0 ],
                                heightmap[ colxi + gradRange - 1, colzi + gradRange - 1 ],
                                heightmap[ colxi + gradRange + 0, colzi + gradRange - 1 ],
                                heightmap[ colxi + gradRange + 1, colzi + gradRange - 1 ]
                            };

                            bool[] bs = new bool[ 8 ];
                            for ( int i = 0; i < 8; ++i )
                                bs[ i ] = ns[ i ] >= height;

                            int index = 0;

                            if ( bs[ 5 ] && ( bs[ 3 ] && bs[ 6 ] ) )
                                index |= 1 << 0;
                            if ( bs[ 7 ] && ( bs[ 4 ] && bs[ 6 ] ) )
                                index |= 1 << 1;
                            if ( bs[ 0 ] && ( bs[ 1 ] && bs[ 3 ] ) )
                                index |= 1 << 2;
                            if ( bs[ 2 ] && ( bs[ 1 ] && bs[ 4 ] ) )
                                index |= 1 << 3;

                            if ( index > 0 )
                                octree.SetCuboid(
                                    colx, height - resolution, colz,
                                    resolution, resolution, resolution,
                                    (UInt16) ( curLeaf.Value + index - 15 ) );
                        }
                    }
                }
            }

            return octree;
        }
 // Проверяет, содержат ли множества цветов части и указанной другой части
 // одинаковые наборы элементов
 public bool CompareColors(Cuboid target)
 {
     char[] targetColors = new char[6];
     target.colors.CopyTo(targetColors, 0);
     for (int i = 0; i < 6; i++)
     {
         if (!targetColors.FindAndReplace(colors[i], ' '))
         {
             return false;
         }
     }
     return true;
 }
 private static int Search(Cuboid target)
 {
     for (int i = 0; i < pieces.Length; i++)
         if (!pieces[i].IsPlaceFound &&
             pieces[i].CompareDimensions(target) &&
             pieces[i].CompareColors(target))
         {
             return i;
         }
     throw new Exception("Applicable piece not found");
 }
    // Функция для инициализации всех частей, заполнения списка частей,
    // определения расстояний между разрезами и занесением их в списки
    private static void GetPiecesAndCuts()
    {
        int lastX = -1, lastY = -1, lastZ = -1;
        for (int i = 0; i < n; i++)
        {
            Cuboid piece = new Cuboid();
            piece.Init();
            // Проверяем положение, которое занимает новая часть
            switch (piece.SpecialPosition)
            {
                // Часть не содержит никакую ось
                case 'N':
                    break;

                // Часть содержит начало координат
                // Добавляем соответсвующие ее размеры в начало списков,
                // описывающих расстояния между разрезами
                case 'F':
                    cutX.AddFirst(piece.GetDimension(0, 2));
                    cutY.AddFirst(piece.GetDimension(4, 2));
                    cutZ.AddFirst(piece.GetDimension(0, 4));
                    break;

                // Часть содержит ось X
                // Добавляем в список, описывающий расстояния между разрезами,
                // перпендикулярными оси X длину ребра, лежащего на этой оси
                case 'X':
                    cutX.AddLast(piece.GetDimension(0, 2));
                    break;
                case 'Y':
                    cutY.AddLast(piece.GetDimension(4, 2));
                    break;
                case 'Z':
                    cutZ.AddLast(piece.GetDimension(0, 4));
                    break;

                // Часть является последней по оси X, т.е. самой правой
                case 'R':
                    lastX = i;
                    break;
                case 'B':
                    lastY = i;
                    break;
                case 'U':
                    lastZ = i;
                    break;
            }
            pieces[i] = piece;
        }
        if (lastX != -1)
            cutX.AddLast(pieces[lastX].GetDimension(0, 2));
        if (lastY != -1)
            cutY.AddLast(pieces[lastY].GetDimension(4, 2));
        if (lastZ != -1)
            cutZ.AddLast(pieces[lastZ].GetDimension(0, 4));
    }
 // Проверяет, совпадает ли часть с указанным описанием, т.е. повернута ли
 // она как нужно. Поскольку множества цветов и размеров заведомо совпадают
 // с таковыми у описания, то достаточно проверить равенства 5 цветов из 6
 // и 2 размеров из 3.
 private bool IsAppropriate(Cuboid target)
 {
     return
         colors[0] == target.colors[0] &&
         colors[1] == target.colors[1] &&
         colors[2] == target.colors[2] &&
         colors[3] == target.colors[3] &&
         colors[4] == target.colors[4] &&
         depth == target.depth &&
         hight == target.hight;
 }
 // Поворачивает часть до полного совпадения с указанным описанием
 public void Rotate(Cuboid target)
 {
     for (int i = 0; i < 4; i++)
     {
         for (int j = 0; j < 4; j++)
         {
             if (IsAppropriate(target))
             {
                 return;
             }
             RotateFrontIsFixed();
         }
         RotateDownIsFixed();
     }
     RotateFrontIsFixed();
     RotateDownIsFixed();
     for (int j = 0; j < 2; j++)
     {
         for (int i = 0; i < 4; i++)
         {
             if (IsAppropriate(target))
             {
                 return;
             }
             RotateFrontIsFixed();
         }
         RotateDownIsFixed();
         RotateDownIsFixed();
     }
     throw new Exception("An unexpected error occurred");
 }