/// <summary>
        /// is the given point inside the path tube?
        /// </summary>
        /// <param name="pathway"></param>
        /// <param name="point"></param>
        /// <returns></returns>
        public static bool IsInsidePath(this IPathway pathway, Vector3 point)
		{
			float outside;
			Vector3 tangent;
            pathway.MapPointToPath(point, out tangent, out outside);
			return outside < 0;
		}
 public static void ResetLocalSpace(out Vector3 forward, out Vector3 side, out Vector3 up, out Vector3 position)
 {
     forward = -Vector3.UnitZ;
     side = Vector3.UnitX;
     up = Vector3.UnitY;
     position = Vector3.Zero;
 }
        static int AddStaticBody(Simulation simulation, System.Numerics.Vector3 position, BepuUtilities.Quaternion rotation, object shapeType)
        {
            switch (shapeType)
            {
            case IBoxDetection boxDetection:
                IBoxDetection box      = shapeType as IBoxDetection;
                var           boxShape = new Box(box.GetSize().x, box.GetSize().y, box.GetSize().z);
                return(simulation.Statics.Add(new StaticDescription(new System.Numerics.Vector3(position.X, position.Y, position.Z),
                                                                    new BepuUtilities.Quaternion(rotation.X, rotation.Y, rotation.Z, rotation.W),
                                                                    new CollidableDescription(simulation.Shapes.Add(boxShape), 0.01f))));

            case ISphereDetection sphereDetection:
                ISphereDetection sphere = shapeType as ISphereDetection;
                var sphereShape         = new Sphere(sphere.GetRadius());
                return(simulation.Statics.Add(new StaticDescription(new System.Numerics.Vector3(position.X, position.Y, position.Z),
                                                                    new BepuUtilities.Quaternion(rotation.X, rotation.Y, rotation.Z, rotation.W),
                                                                    new CollidableDescription(simulation.Shapes.Add(sphereShape), 0.01f))));

            case ICapsuleDetection capsuleDetection:
                ICapsuleDetection capsule = shapeType as ICapsuleDetection;
                var capsuleShape          = new Capsule(capsule.GetRadius(), capsule.GetHeight());
                return(simulation.Statics.Add(new StaticDescription(new System.Numerics.Vector3(position.X, position.Y, position.Z),
                                                                    new BepuUtilities.Quaternion(rotation.X, rotation.Y, rotation.Z, rotation.W),
                                                                    new CollidableDescription(simulation.Shapes.Add(capsuleShape), 0.01f))));

            default:
                throw new System.ArgumentException(message: CouldNotInitializeMessage, nameof(shapeType));
            }
        }
        public void Draw(RenderTarget target, RenderStates states)
        {
            if (VertexArray == null || VertexArray.Length == 0 || VertexArray.Length % 4 != 0)
            {
                return;
            }

            System.Numerics.Vector3    Location = GetLocation_WorldSpace();
            System.Numerics.Quaternion Rotation = GetRotation_WorldSpace(); //TODO: Get the rotation out of this quat
            System.Numerics.Vector3    Scale    = GetScale_WorldSpace();

            Transform tf = Transform.Identity;

            tf.Translate(Location.X, Location.Y);
            //tf.Scale(Scale.X, Scale.Y);

            states.Transform *= tf;

            if (Texture.Loaded)
            {
                states.Texture = Texture.Get <Texture>();
            }

            target.Draw(VertexArray, PrimitiveType, states);
        }
        /**
         * Face breaker for EDGE-FACE-FACE / FACE-FACE-EDGE
         *
         * @param facePos face position on the faces array
         * @param newPos1 new vertex position
         * @param newPos2 new vertex position
         * @param endVertex vertex used for the split
         */
        private void breakFaceInFour(int facePos, Point3d newPos1, Point3d newPos2, Vertex endVertex)
        {
            Face face = faces[facePos];

            faces.RemoveAt(facePos);

            Vertex vertex1 = addVertex(newPos1, face.v1.getColor(), Vertex.BOUNDARY);
            Vertex vertex2 = addVertex(newPos2, face.v1.getColor(), Vertex.BOUNDARY);

            if (endVertex.equals(face.v1))
            {
                addFace(face.v1, vertex1, vertex2);
                addFace(vertex1, face.v2, vertex2);
                addFace(face.v2, face.v3, vertex2);
                addFace(face.v3, face.v1, vertex2);
            }
            else if (endVertex.equals(face.v2))
            {
                addFace(face.v2, vertex1, vertex2);
                addFace(vertex1, face.v3, vertex2);
                addFace(face.v3, face.v1, vertex2);
                addFace(face.v1, face.v2, vertex2);
            }
            else
            {
                addFace(face.v3, vertex1, vertex2);
                addFace(vertex1, face.v1, vertex2);
                addFace(face.v1, face.v2, vertex2);
                addFace(face.v2, face.v3, vertex2);
            }
        }
        /**
         * Face breaker for EDGE-EDGE-EDGE
         *
         * @param facePos face position on the faces array
         * @param newPos1 new vertex position
         * @param newPos2 new vertex position
         * @param splitEdge edge that will be split
         */
        private void breakFaceInThree(int facePos, Point3d newPos1, Point3d newPos2, int splitEdge)
        {
            Face face = faces[facePos];

            faces.RemoveAt(facePos);

            Vertex vertex1 = addVertex(newPos1, face.v1.getColor(), Vertex.BOUNDARY);
            Vertex vertex2 = addVertex(newPos2, face.v1.getColor(), Vertex.BOUNDARY);

            if (splitEdge == 1)
            {
                addFace(face.v1, vertex1, face.v3);
                addFace(vertex1, vertex2, face.v3);
                addFace(vertex2, face.v2, face.v3);
            }
            else if (splitEdge == 2)
            {
                addFace(face.v2, vertex1, face.v1);
                addFace(vertex1, vertex2, face.v1);
                addFace(vertex2, face.v3, face.v1);
            }
            else
            {
                addFace(face.v3, vertex1, face.v2);
                addFace(vertex1, vertex2, face.v2);
                addFace(vertex2, face.v1, face.v2);
            }
        }
Exemple #7
0
        public override bool PlaceBlock(Level world, Player player, BlockCoordinates blockCoordinates, BlockFace face, Vector3 faceCoords)
        {
            Metadata = (byte) face;

            world.SetBlock(this);
            return true;
        }
            private static VECTOR3 _GetMainAxis(ReadOnlySpan <PointNode> nodes)
            {
                if (nodes.Length < 2)
                {
                    return(VECTOR3.UnitX);
                }
                if (nodes.Length == 2)
                {
                    var d = new POINT3(nodes[1].Point - nodes[0].Point);

                    // calculate a vector perpendicular to D
                    var a = VECTOR3.Cross(d.XYZ, d.DominantAxis == 0 ? VECTOR3.UnitY : VECTOR3.UnitX);

                    System.Diagnostics.Debug.Assert(a != VECTOR3.Zero);

                    return(a);
                }

                var axis = VECTOR3.Zero;

                for (int i = 2; i < nodes.Length; i++)
                {
                    var ab = nodes[i - 2].Point - nodes[i - 1].Point;
                    var ac = nodes[i - 1].Point - nodes[i - 0].Point;
                    axis += VECTOR3.Cross(ab, ac);
                }

                return(VECTOR3.Normalize(axis));
            }
Exemple #9
0
 public Mesh(string fileName = null)
 {
     Filename = fileName;
     MinVertex = new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity);
     MaxVertex = new Vector3(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity);
     SubMeshes = new List<SubMesh>();
 }
Exemple #10
0
        public override void UseItem(Level world, Player player, BlockCoordinates targetCoordinates, BlockFace face, Vector3 faceCoords)
        {
            //if (player.GameMode != GameMode.Creative)
            //{
            //	Item itemStackInHand = player.Inventory.GetItemInHand();
            //	itemStackInHand.Count--;

            //	if (itemStackInHand.Count <= 0)
            //	{
            //		// set empty
            //		player.Inventory.Slots[player.Inventory.Slots.IndexOf(itemStackInHand)] = new ItemAir();
            //	}
            //}

            _block.Coordinates = GetNewCoordinatesFromFace(targetCoordinates, face);
            _block.Metadata = (byte) Metadata;

            if ((player.GetBoundingBox() - 0.01f).Intersects(_block.GetBoundingBox()))
            {
                Log.Debug("Can't build where you are standing: " + _block.GetBoundingBox());
                return;
            }
            if (!_block.CanPlace(world, face)) return;

            if (_block.PlaceBlock(world, player, targetCoordinates, face, faceCoords)) return; // Handled

            world.SetBlock(_block);
        }
        /// <summary>
        /// how far outside path tube is the given point?  (negative is inside)
        /// </summary>
        /// <param name="pathway"></param>
        /// <param name="point"></param>
        /// <returns></returns>
        public static float HowFarOutsidePath(this IPathway pathway, Vector3 point)
		{
			float outside;
			Vector3 tangent;
            pathway.MapPointToPath(point, out tangent, out outside);
			return outside;
		}
Exemple #12
0
        private bool CreateVector3(string label, ref Num.Vector3 v, MinMaxDescription minMax)
        {
            switch (minMax.Type)
            {
            case MinMaxDescriptionType.ZeroToOne:
                return(ImGui.SliderFloat3(label, ref v, 0, 1));

            case MinMaxDescriptionType.MinusOneToOne:
                return(ImGui.SliderFloat3(label, ref v, -1, 1));

            case MinMaxDescriptionType.ZeroToInfinity:
                return(ImGui.DragFloat3(label, ref v, this.DragSpeed, 0, float.MaxValue));

            case MinMaxDescriptionType.Custom:
                if ((minMax.Max - minMax.Min) < SliderDragThreshold)
                {
                    return(ImGui.SliderFloat3(label, ref v, minMax.Min, minMax.Max));
                }
                return(ImGui.DragFloat3(label, ref v, this.DragSpeed, minMax.Min, minMax.Max));

            case MinMaxDescriptionType.MinusInfinityToInfinity:
            default:
                return(ImGui.DragFloat3(label, ref v, this.DragSpeed));
            }
        }
Exemple #13
0
 public Mesh(string filename, List<SubMesh> subMeshes)
 {
     Filename = filename;
     MinVertex = new Vector3(float.PositiveInfinity, float.PositiveInfinity, float.PositiveInfinity);
     MaxVertex = new Vector3(float.NegativeInfinity, float.NegativeInfinity, float.NegativeInfinity);
     SubMeshes = subMeshes;
 }
Exemple #14
0
        public void Render(Renderer renderer)
        {
            SFMLRenderer sfmlRenderer = renderer as SFMLRenderer;

            System.Numerics.Vector3    Location = GetLocation_WorldSpace();
            System.Numerics.Quaternion Rotation = GetRotation_WorldSpace(); //TODO: Get the rotation out of this quat
            System.Numerics.Vector3    Scale    = GetScale_WorldSpace();


            Transform tf = Transform.Identity;

            tf.Translate(Location.X, Location.Y);
            tf.Scale(Scale.X, Scale.Y);

            RenderStates RS = RenderStates.Default;

            RS.Transform = tf;

            SFMLEngine engine = Engine.Instance as SFMLEngine;

            if (Texture.Loaded)
            {
                //Texture.Get<Sprite>().Position = new Vector2f(Location.X, Location.Y);
                engine?.Window.Draw(Texture.Get <Sprite>(), RS);
            }
        }
Exemple #15
0
        // 000 001 010 011 100
        public override bool PlaceBlock(Level world, Player player, BlockCoordinates blockCoordinates, BlockFace face, Vector3 faceCoords)
        {
            byte direction = player.GetDirection();

            byte upper = (byte) ((faceCoords.Y > 0.5 && face != BlockFace.Up) || face == BlockFace.Down ? 0x04 : 0x00);

            switch (direction)
            {
                case 0:
                    Metadata = (byte) (0 | upper);
                    break;
                case 1:
                    Metadata = (byte) (2 | upper);
                    break;
                case 2:
                    Metadata = (byte) (1 | upper);
                    break;
                case 3:
                    Metadata = (byte) (3 | upper);
                    break;
            }

            world.SetBlock(this);
            return true;
        }
Exemple #16
0
        private void ReadFile(string filename)
        {
            try
            {   // Open the text file using a stream reader.
                using (StreamReader sr = new StreamReader(filename))
                {
                    // Read the stream to a string, and write the string to the console.
                    //String line = sr.ReadToEnd();
                    while (sr.Peek() >= 0)
                    {
                        //Console.WriteLine(sr.ReadLine());
                        var line  = sr.ReadLine();
                        var words = line.Split(' ');

                        var point  = new SN.Vector3(Int32.Parse(words[0]), Int32.Parse(words[1]), Int32.Parse(words[2]));
                        var shapes = new SN.Vector3(Int32.Parse(words[3]), Int32.Parse(words[4]), Int32.Parse(words[5]));
                        var block  = new Block(point, shapes);
                        this.blocks.Add(block);
                    }
                }
            }
            catch (IOException e)
            {
                Console.WriteLine("The file could not be read:");
                Console.WriteLine(e.Message);
            }
        }
Exemple #17
0
        public override bool PlaceBlock(Level world, Player player, BlockCoordinates blockCoordinates, BlockFace face, Vector3 faceCoords)
        {
            byte direction = player.GetDirection();

            switch (face)
            {
                case BlockFace.South: // ok
                    Metadata = 0;
                    break;
                case BlockFace.North:
                    Metadata = 1;
                    break;
                case BlockFace.West:
                    Metadata = 2;
                    break;
                case BlockFace.East: // ok
                    Metadata = 3;
                    break;
            }

            Log.Warn($"Direction={direction}, face={face}, metadata={Metadata}");

            world.SetBlock(this);

            return true;
        }
    //get the average of all values between two timestamps
    public Vector3 GetAverageBetween(long from, long to)
    {
        lock (this)
        {
            CleanUp();
            Vector3 sum   = new Vector3();
            int     count = 0;
            foreach (TimeStampedVector tsv in m_data)
            {
                //Console.WriteLine("timestamp: " + tsv.m_timeStamp);

                if (tsv.m_timeStamp < from)
                {
                    continue;
                }
                if (tsv.m_timeStamp > to)
                {
                    break;
                }
                count++;
                sum += tsv.m_data;
            }
            sum /= count;
            return(sum);
        }
    }
Exemple #19
0
 internal Character(int unitId, string name, Bepu bepu, System.Numerics.Vector3 startPosition) : base(unitId, name, startPosition)
 {
     this.bepu = bepu;
     collider.isPassThrough = false;
     collider.type          = Collider.Type.Characer;
     moveSpeed = walkSpeed;
 }
Exemple #20
0
        private void drawoXYZ()
        {
            SN.Vector3 oz = new SN.Vector3(0, 0, 600);
            SN.Vector3 oy = new SN.Vector3(0, 600, 0);
            SN.Vector3 ox = new SN.Vector3(600, 0, 0);

            List <SN.Vector3> l = new List <SN.Vector3>();

            l.Add(ox);
            l.Add(oy);
            l.Add(oz);

            foreach (SN.Vector3 axe in l)
            {
                var        p3d  = camera.ComputePointOnPlane(axe);
                var        oo3d = camera.ComputePointOnPlane(new SN.Vector3(0, 0, 0));
                SN.Vector2 p    = new SN.Vector2(p3d.X, p3d.Y);
                SN.Vector2 oo   = new SN.Vector2(oo3d.X, oo3d.Y);
                Color      c    = Color.Red;
                if (axe.Y > 0)
                {
                    c = Color.Yellow;
                }
                else if (axe.Z > 0)
                {
                    c = Color.Green;
                }

                this.DrawLine(oo, p, c);
                // this.DrawLine(oo,new SN.Vector2(300,0), Color.Pink);
            }
        }
        /**
         * Method used to add a vertex properly for internal methods
         *
         * @param pos vertex position
         * @param color vertex color
         * @param status vertex status
         * @return the vertex inserted (if a similar vertex already exists, this is returned)
         */
        private Vertex addVertex(Point3d pos, Vector4 color, int status)
        {
            int i;
            //if already there is an equal vertex, it is not inserted
            Vertex vertex = new Vertex(pos, color, status);

            for (i = 0; i < vertices.Count; i++)
            {
                if (vertex.equals(vertices[i]))
                {
                    break;
                }
            }
            if (i == vertices.Count)
            {
                vertices.Add(vertex);
                return(vertex);
            }
            else
            {
                vertex = vertices[i];
                vertex.setStatus(status);
                return(vertex);
            }
        }
Exemple #22
0
        public LocalSpace(Vector3 up, Vector3 forward, Vector3 position)
		{
			Up = up;
			Forward = forward;
            Position = position;
			SetUnitSideFromForwardAndUp();
		}
		// Given an arbitrary point ("A"), returns the nearest point ("P") on
		// this path.  Also returns, via output arguments, the path tangent at
		// P and a measure of how far A is outside the Pathway's "tube".  Note
		// that a negative distance indicates A is inside the Pathway.
        public virtual Vector3 MapPointToPath(Vector3 point, out Vector3 tangent, out float outside)
		{
            float minDistance = float.MaxValue;
            Vector3 onPath = Vector3.Zero;
			tangent = Vector3.Zero;

			// loop over all segments, find the one nearest to the given point
			for (int i = 1; i < PointCount; i++)
			{
			    Vector3 chosen;
                float d = PointToSegmentDistance(point, Points[i - 1], Points[i], Tangents[i], Lengths[i], out chosen);
				if (d < minDistance)
				{
					minDistance = d;
                    onPath = chosen;
                    tangent = Tangents[i];
				}
			}

			// measure how far original point is outside the Pathway's "tube"
			outside = Vector3.Distance(onPath, point) - Radius;

			// return point on path
			return onPath;
		}
Exemple #24
0
        private static Colour RayColour(Ray r, Hittable world, int depth)
        {
            // If we've exceeded the ray bounce limit, no more light is gathered.
            if (depth <= 0)
            {
                return(Colour.Zero);
            }

            HitRecord rec = new HitRecord();

            if (world.Hit(r, 0.001f, float.PositiveInfinity, ref rec))
            {
                Ray    scattered   = new Ray();
                Colour attenuation = new Colour();
                if (rec.Mat.Scatter(ref r, ref rec, ref attenuation, ref scattered))
                {
                    return(attenuation * RayColour(scattered, world, depth - 1));
                }
                return(Colour.Zero);
            }
            Vector3 unitDirection = Vector3.Normalize(r.Direction);
            float   t             = 0.5f * (unitDirection.Y + 1f);

            return((1f - t) * Colour.One + t * new Colour(0.5f, 0.7f, 1.0f));
        }
Exemple #25
0
        public override void UseItem(Level world, Player player, BlockCoordinates blockCoordinates, BlockFace face, Vector3 faceCoords)
        {
            if (player.GameMode != GameMode.Creative)
            {
                Item itemStackInHand = player.Inventory.GetItemInHand();
                itemStackInHand.Count--;

                if (itemStackInHand.Count <= 0)
                {
                    // set empty
                    player.Inventory.Slots[player.Inventory.Slots.IndexOf(itemStackInHand)] = new ItemAir();
                }
            }

            var coor = GetNewCoordinatesFromFace(blockCoordinates, face);
            Chest chest = new Chest
            {
                Coordinates = coor,
            };

            if (!chest.CanPlace(world, face)) return;

            chest.PlaceBlock(world, player, coor, face, faceCoords);

            // Then we create and set the sign block entity that has all the intersting data

            ChestBlockEntity chestBlockEntity = new ChestBlockEntity
            {
                Coordinates = coor
            };

            world.SetBlockEntity(chestBlockEntity);
        }
Exemple #26
0
        public override bool PlaceBlock(Level world, Player player, BlockCoordinates blockCoordinates, BlockFace face, Vector3 faceCoords)
        {
            if (face == BlockFace.Down) return true;

            switch (face)
            {
                case BlockFace.Up:
                    Metadata = 5;
                    break;
                case BlockFace.East:
                    Metadata = 4;
                    break;
                case BlockFace.West:
                    Metadata = 3;
                    break;
                case BlockFace.North:
                    Metadata = 2;
                    break;
                case BlockFace.South:
                    Metadata = 1;
                    break;
            }

            world.SetBlock(this);
            return true;
        }
Exemple #27
0
		// Convert an AnatomyEngine mesh to a Godot mesh:
		public GodotMeshConverter(UVMesh mesh)
		{
			// Initialize the arrays that are needed:
			Godot.Collections.Array arrays = new Godot.Collections.Array();
			arrays.Resize((int)Mesh.ArrayType.Max);
			
			int vertexCount = mesh.VertexList.Count;
			
			Godot.Vector3[] normal_array = new Godot.Vector3[vertexCount];
			Godot.Vector3[] vertex_array = new Godot.Vector3[vertexCount];
			
			// Populate the arrays from the input mesh data:
			for (int i = 0; i < vertexCount; i++)
			{
				Numerics.Vector3 vertex = mesh.VertexList[i].Position;
				Numerics.Vector3 normal = mesh.VertexList[i].Normal;
				vertex_array[i] = new Godot.Vector3(vertex.X, vertex.Y, vertex.Z);
				normal_array[i] = new Godot.Vector3(normal.X, normal.Y, normal.Z);
			}
			
			// The index list doesn't need to be converted:
			int[] index_array = mesh.IndexList.ToArray();
			
			// Put the data arrays in a larger array for Godot to understand what the arrays represent:
			arrays[(int)Mesh.ArrayType.Vertex] = vertex_array;
			arrays[(int)Mesh.ArrayType.Normal] = normal_array;
			arrays[(int)Mesh.ArrayType.Index] = index_array;
			
			// Finally, upload the mesh to GPU:
			this.AddSurfaceFromArrays(Mesh.PrimitiveType.Triangles, arrays);
		}
Exemple #28
0
        private void InterpolateKeys(double animationTime, AnimationLayer layer, ref Quaternion rotation, ref Vector3 translation, ref Vector3 scale, PRSKey prsKey, PRSKey nextPrsKey)
        {
            var nextTime = (nextPrsKey.Time < prsKey.Time
                ? (nextPrsKey.Time + Animation.Duration)
                : nextPrsKey.Time);

            var blend = ( float )(animationTime / nextTime);

            if (prsKey.HasRotation)
            {
                rotation = Quaternion.Slerp(prsKey.Rotation, nextPrsKey.Rotation, blend);
            }

            if (prsKey.HasPosition)
            {
                translation = Vector3.Lerp(prsKey.Position * layer.PositionScale,
                                           nextPrsKey.Position * layer.PositionScale,
                                           blend);
            }

            if (prsKey.HasScale)
            {
                scale = Vector3.Lerp(prsKey.Scale * layer.ScaleScale,
                                     nextPrsKey.Scale * layer.ScaleScale,
                                     blend);
            }
        }
            private static void _Fill(Span <PointNode> nodes, ReadOnlySpan <VECTOR3> points, float diameter, bool closed)
            {
                System.Diagnostics.Debug.Assert(points.Length > 1);
                System.Diagnostics.Debug.Assert(points[0] != points[points.Length - 1]);

                var joinPoint = closed ? VECTOR3.Normalize(points[points.Length - 1] - points[0]) : VECTOR3.Zero;

                for (int i = 0; i < nodes.Length; i++)
                {
                    nodes[i].Point    = points[i];
                    nodes[i].Diameter = diameter;

                    var prevDir = i > 0 ? VECTOR3.Normalize(points[i - 1] - points[i]) : joinPoint;
                    var nextDir = i < points.Length - 1 ? VECTOR3.Normalize(points[i] - points[i + 1]) : joinPoint;

                    var angle = POINT3.AngleInRadians(prevDir, nextDir);
                    nodes[i].Angle     = float.IsNaN(angle) ? 0 : angle;
                    nodes[i].Direction = -VECTOR3.Normalize(prevDir + nextDir);
                    nodes[i].Axis      = VECTOR3.Normalize(VECTOR3.Cross(prevDir, nextDir));

                    if (float.IsNaN(nodes[i].Axis.X))
                    {
                        nodes[i].Axis = VECTOR3.Zero;
                    }
                }
            }
 /// <summary>
 /// Constructs a Vector4 from the given Vector3 and a W component.
 /// </summary>
 /// <param name="value">The vector to use as the X, Y, and Z components.</param>
 /// <param name="w">The W component.</param>
 public Vector4(Vector3 value, Single w)
 {
     X = value.X;
     Y = value.Y;
     Z = value.Z;
     W = w;
 }
            private readonly void _FillSection(Span <POINT3> points, int divisions, VECTOR3 mainAxis)
            {
                var r = _AdjustNGonRadius(Diameter / 2, divisions);

                var nz = Direction;
                var ny = VECTOR3.Cross(nz, mainAxis);
                var nx = VECTOR3.Cross(ny, nz);

                nx = VECTOR3.Normalize(nx);
                ny = VECTOR3.Normalize(ny);

                var nt = this.GetScale(4);

                for (int i = 0; i < divisions; ++i)
                {
                    var angle = -PI * 2 * i / divisions;

                    #if NETSTANDARD2_1_OR_GREATER
                    var p = nx * MathF.Cos(angle) + ny * MathF.Sin(angle) * nt;
                    #else
                    var p = nx * (float)Math.Cos(angle) + ny * (float)Math.Sin(angle) * nt;
                    #endif

                    points[i] = Point + p * r;
                }

                POINT3.DebugAssertIsFinite(points);
            }
Exemple #32
0
        public static double GetPlayerDistance(System.Numerics.Vector3 myLoc, System.Numerics.Vector3 enemyLoc)
        {
            double dist = System.Math.Sqrt(System.Math.Pow(enemyLoc.X - myLoc.X, 2) + System.Math.Pow(enemyLoc.Y - myLoc.Y, 2) + System.Math.Pow(enemyLoc.Z - myLoc.Z, 2));

            dist *= 0.01905F;
            return(dist);
        }
Exemple #33
0
 private Vector3 NumCross(Vector3 first, Vector3 second)
 {
     Num.Vector3 vec1   = new Num.Vector3(first.X, first.Y, first.Z);
     Num.Vector3 vec2   = new Num.Vector3(second.X, second.Y, second.Z);
     Num.Vector3 result = Num.Vector3.Cross(vec1, vec2);
     return(new Vector3(result.X, result.Y, result.Z));
 }
Exemple #34
0
        private static HittableList RandomScene()
        {
            HittableList world = new HittableList();

            Material groundMat = new Lambertian(new Colour(0.5f, 0.5f, 0.5f));

            world.Add(new Sphere(new Point3(0, -1000, 0), 1000, groundMat));

            for (int a = -11; a < 11; a++)
            {
                for (int b = -11; b < 11; b++)
                {
                    double chooseMat = random.NextDouble();
                    Point3 centre    = new Point3((float)(a + 0.9 * random.NextDouble()), 0.2f, (float)(b + 0.9 * random.NextDouble()));

                    if ((centre - new Point3(4, 0.2f, 0)).Length() > 0.9f)
                    {
                        Material sphereMat;
                        float    radius = random.NextDouble() / 10f + 0.15f;
                        centre.Y = radius;
                        if (chooseMat < 0.8f)
                        {
                            // Diffuse
                            Colour albedo = RandVector(0, 1) * RandVector(0, 1);
                            sphereMat = new Lambertian(albedo);
                            world.Add(new Sphere(centre, radius, sphereMat));
                        }
                        else if (chooseMat < 0.95)
                        {
                            // Metal
                            Colour albedo = RandVector(0.5f, 1);
                            float  fuzz   = (float)(random.NextDouble() / 2);
                            sphereMat = new Metal(albedo, fuzz);
                            world.Add(new Sphere(centre, radius, sphereMat));
                        }
                        else
                        {
                            // Glass
                            sphereMat = new Dielectric(RandFloat(1.3f, 1.7f));
                            world.Add(new Sphere(centre, radius, sphereMat));
                        }
                    }
                }
            }

            Material material1 = new Dielectric(1.5f);

            world.Add(new Sphere(new Point3(0, 1, 0), 1.0f, material1));

            Material material2 = new Lambertian(new Colour(0.4f, 0.2f, 0.1f));

            world.Add(new Sphere(new Point3(-4, 1, 0), 1.0f, material2));

            Material material3 = new Metal(new Colour(0.7f, 0.6f, 0.5f), 0.0f);

            world.Add(new Sphere(new Point3(4, 1, 0), 1.0f, material3));

            return(world);
        }
Exemple #35
0
 public UnturnedPlayerDamagedEvent(IPlayer player, EDeathCause deathCause, ELimb limb, IUser damageDealer, Vector3 direction, float damage, float times, EventExecutionTargetContext executionTarget = EventExecutionTargetContext.Sync, bool global = true) : base(player, damage, damageDealer, executionTarget, global)
 {
     DeathCause = deathCause;
     Limb       = limb;
     Direction  = direction;
     Damage     = damage;
     Times      = times;
 }
Exemple #36
0
 public UnturnedPlayerDamagedEvent(IPlayer player, EDeathCause deathCause, ELimb limb, IUser damageDealer, Vector3 direction, float damage, float times) : base(player, damage, damageDealer)
 {
     DeathCause = deathCause;
     Limb       = limb;
     Direction  = direction;
     Damage     = damage;
     Times      = times;
 }
Exemple #37
0
        /// <summary>
        /// Gets the distance from the plane to the point.
        /// </summary>
        /// <param name="plane"></param>
        /// <param name="point"></param>
        /// <returns></returns>
        public static float Distance(this Plane plane, Vector3 point)
        {
            //http://stackoverflow.com/questions/4436160/distance-to-a-plane

            float dot = Vector3.Dot(plane.Normal, point);
            float value = dot + plane.D;
            return value;
        }
Exemple #38
0
        private bool WithinArea(Vector3 location)
        {
            var differenceFromCenter = this.Position - location;
            var uLength = Util.Projection(differenceFromCenter, uDirection);
            var vLength = Util.Projection(differenceFromCenter, vDirection);

            return uLength.Magnitude() <= width / 2f && vLength.Magnitude() <= height / 2f;
        }
Exemple #39
0
 /// <summary>
 ///
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="myItem"></param>
 /// <returns></returns>
 public bool ContainsPoint(System.Numerics.Vector3 myItem)
 {
     foreach (var A in this.IterateDataNodes(delegate(IAABBNode myNode) { return(myNode.Bounds.Contains(myItem) == ContainmentType.Contains); }, Root))
     {
         return(true);
     }
     return(false);
 }
Exemple #40
0
        public static Matrix4x4 Right(this Matrix4x4 matrix, Vector3 value)
        {
            matrix.M11 = value.X;
            matrix.M12 = value.Y;
            matrix.M13 = value.Z;

            return matrix;
        }
Exemple #41
0
 internal Unit(int unitId, string name, System.Numerics.Vector3 startPosition)
 {
     Console.WriteLine("start position");
     this.startPosition = new System.Numerics.Vector3(startPosition.X, startPosition.Y + (size.Y / 2f), startPosition.Z);
     collider.type      = Collider.Type.Unit;
     this.name          = name;
     this.unitId        = unitId;
 }
Exemple #42
0
        public SimpleVertex(Vector3 position, Vector3 normal, Color4f color)
        {
            this.Color = color;
            this.Normal = Vector3.Normalize(normal);
            this.Position = position;

            this.__packing = 0f;
        }
Exemple #43
0
        public Polygon(Vector3 position, IEnumerable<Vector3> points)
        {
            var pointsArray = points.ToArray();
            this.points = pointsArray;

            var rightDirection = pointsArray[0] - pointsArray[1];
            NormalDirection = Vector3.Cross(Util.UpVector, rightDirection);
        }
Exemple #44
0
        public override bool Scatter(ref Ray rIn, ref HitRecord rec, ref Point3 attenuation, ref Ray scattered)
        {
            Vector3 reflected = Program.VecReflect(Vector3.Normalize(rIn.Direction), rec.Normal);

            scattered   = new Ray(rec.P, reflected + Fuzz * Program.RandInUnitSphere());
            attenuation = Albedo;
            return(Vector3.Dot(scattered.Direction, rec.Normal) > 0);
        }
Exemple #45
0
        public static Matrix4x4 Up(this Matrix4x4 matrix, Vector3 value)
        {
            matrix.M21 = value.X;
            matrix.M22 = value.Y;
            matrix.M23 = value.Z;

            return matrix;
        }
 private void InspectVector3()
 {
     Num.Vector3 value = GetValue <Vector3>().ToNumerics();
     if (ImGui.DragFloat3(_name, ref value))
     {
         SetValue(value.ToXNA());
     }
 }
Exemple #47
0
 internal Unit(int unitId, string name, System.Numerics.Vector3 startPosition)
 {
     collider.type        = Collider.Type.Unit;
     this.name            = name;
     this.unitId          = unitId;
     this.startPosition   = startPosition;
     this.startPosition.Y = 3;
 }
    public void WorldToScreen(IGameViewport viewport, Vector3 worldPos, out Vector2 screenPos)
    {
        screenPos = viewport.Camera.WorldToScreen(worldPos);
        var offset2d = viewport.Camera.Get2dTranslation();

        screenPos.X += offset2d.X;
        screenPos.Y += offset2d.Y;
    }
 public Attributes3D(Vector3 pos, Vector3 vel, Vector3 forward, Vector3 up)
     : this()
 {
     Position = pos;
     Velocity = vel;
     Forward = forward;
     Up = up;
 }
// ReSharper restore NotAccessedField.Global
// ReSharper restore MemberCanBePrivate.Global

        public VertexPositionTextureNormalBinormalTangent(Vector3 position, Vector2 textureCoordinate, Vector3 normal, Vector3 binormal, Vector3 tangent)
        {
            Position = position.ToXNA();
            TextureCoordinate = textureCoordinate.ToXNA();
            Normal = normal.ToXNA();
            Binormal = binormal.ToXNA();
            Tangent = tangent.ToXNA();
        }
Exemple #51
0
        /// <summary>
        /// R_RotateForEntity
        /// </summary>
        public override void RotateForEntity(Vector3 origin, Vector3 angles)
        {
            GL.Translate(origin.X, origin.Y, origin.Z);

            GL.Rotate(angles.Y, 0, 0, 1);
            GL.Rotate(-angles.X, 0, 1, 0);
            GL.Rotate(angles.Z, 1, 0, 0);
        }
        /// <summary>
        /// Transforms a point in global space to its equivalent in local space.
        /// </summary>
        /// <param name="basis">The basis which this should operate on</param>
        /// <param name="globalPosition">The global space position to transform.</param>
        /// <returns>The global space position transformed to local space.</returns>
        public static Vector3 LocalizePosition(this ILocalSpaceBasis basis, Vector3 globalPosition)
        {
            // global offset from local origin
            Vector3 globalOffset = globalPosition - basis.Position;

            // dot offset with local basis vectors to obtain local coordiantes
            return LocalizeDirection(basis, globalOffset);
        }
Exemple #53
0
        public SimpleVertex(Vector3 position, Vector3 normal, Color4f color)
        {
            this.Color    = color;
            this.Normal   = Vector3.Normalize(normal);
            this.Position = position;

            this.__packing = 0f;
        }
Exemple #54
0
        public ObjParser(byte[] data)
        {
            char[] splitCharacters = new char[] { ' ' };
            string line;
            using (TextReader reader = new StreamReader((new MemoryStream(data))))
            {
                while ((line = reader.ReadLine()) != null)
                {
                    line = line.Trim(splitCharacters);
                    line = line.Replace("  ", " ");

                    string[] parameters = line.Split(splitCharacters);
                    switch (parameters[0])
                    {
                        case "mtllib": //material lib
                            materialFileName = parameters[1];
                            break;
                        case "p": // Point
                            break;

                        case "v": // Vertex
                            float x = float.Parse(parameters[1], CultureInfo.InvariantCulture);
                            float y = float.Parse(parameters[2], CultureInfo.InvariantCulture);
                            float z = float.Parse(parameters[3], CultureInfo.InvariantCulture);
                            position.Add(new Vector3(x, y, z));
                            break;

                        case "vt": // TexCoord
                            float u = float.Parse(parameters[1], CultureInfo.InvariantCulture);
                            float v = float.Parse(parameters[2], CultureInfo.InvariantCulture);
                            texCoords.Add(new Vector2(u, v));
                            break;

                        case "vn": // Normal
                            float nx = float.Parse(parameters[1], CultureInfo.InvariantCulture);
                            float ny = float.Parse(parameters[2], CultureInfo.InvariantCulture);
                            float nz = float.Parse(parameters[3], CultureInfo.InvariantCulture);
                            Vector3 n = new Vector3(nx, ny, nz);
                            normals.Add(n);
                            break;

                        case "f":
                            //todo: add face
                            var face = new List<Vertex>();
                            faces.Add(face);
                            for (int i = 1; i < parameters.Length; ++i)
                            {
                                face.Add(ParseVertex(parameters[i]));
                            }
                            break;
                        case "g": //new group
                            break;
                        case "usemtl": //set current material
                            break;
                    }
                }
            }
        }
 ///<summary>
 /// Constructs a new affine transform.
 ///</summary>
 ///<param name="scaling">Scaling to apply in the linear transform.</param>
 ///<param name="orientation">Orientation to apply in the linear transform.</param>
 ///<param name="translation">Translation to apply.</param>
 public AffineTransform(ref Vector3 scaling, ref Quaternion orientation, ref Vector3 translation)
 {
     //Create an SRT transform.
     Matrix3x3.CreateScale(ref scaling, out LinearTransform);
     Matrix3x3 rotation;
     Matrix3x3.CreateFromQuaternion(ref orientation, out rotation);
     Matrix3x3.Multiply(ref LinearTransform, ref rotation, out LinearTransform);
     Translation = translation;
 }
 public ImplicitHeart()
 {
     boundingBox = new BoundingBox();
     lowBound = new Vector3(-1.5f);
     highBound = new Vector3(1.5f);
     minimumRaymarchStep = 1.0e-5f;
     maximumRaymarchStep = 4.0f;
     distanceMultiplier = 0.1f;
 }
Exemple #57
0
 public void Operation(Operations operation)
 {
     Random rand = new Random(84329);
     Vector3 v1 = new Vector3(Convert.ToSingle(rand.NextDouble()), Convert.ToSingle(rand.NextDouble()), Convert.ToSingle(rand.NextDouble()));
     Vector3 v2 = new Vector3(Convert.ToSingle(rand.NextDouble()), Convert.ToSingle(rand.NextDouble()), Convert.ToSingle(rand.NextDouble()));
     foreach (var iteration in Benchmark.Iterations)
         using (iteration.StartMeasurement())
             ExecuteTest(operation, 1000000, v1, v2);
 }
Exemple #58
0
 public Camera(Vector3 position, Vector3 direction, Vector3 up, float fieldOfView = 0.65f, float nearPlane = 0.01f, float farPlane = 1000f)
 {
     _position = position;
     _direction = direction;
     _up = up;
     _fieldOfView = fieldOfView;
     _nearPlane = nearPlane;
     _farPlane = farPlane;
 }
 public ImplicitBarthSextic()
 {
     boundingBox = new BoundingBox();
     lowBound = new Vector3(-3.5f);
     highBound = new Vector3(3.5f);
     minimumRaymarchStep = 1.0e-5f;
     maximumRaymarchStep = 10.0f;
     distanceMultiplier = 0.4f;
     triggerDistance = 0.01f;
 }
Exemple #60
0
 public void ExecuteTest(Operations operation, int innerIterations, Vector3 v1, Vector3 v2)
 {
     Vector3 res;
     switch (operation)
     {
         case Operations.Add_Operator:
             for (int i = 0; i < innerIterations; i++)
             { res = v1 + v2; res = v1 + v2; res = v1 + v2; res = v1 + v2; res = v1 + v2; res = v1 + v2; res = v1 + v2; res = v1 + v2; res = v1 + v2; res = v1 + v2; }
             break;
         case Operations.Add_Function:
             for (int i = 0; i < innerIterations; i++)
             { Vector3.Add(v1, v2); Vector3.Add(v1, v2); Vector3.Add(v1, v2); Vector3.Add(v1, v2); Vector3.Add(v1, v2); Vector3.Add(v1, v2); Vector3.Add(v1, v2); Vector3.Add(v1, v2); Vector3.Add(v1, v2); Vector3.Add(v1, v2); }
             break;
         case Operations.Sub_Operator:
             for (int i = 0; i < innerIterations; i++)
             { res = v1 - v2; res = v1 - v2; res = v1 - v2; res = v1 - v2; res = v1 - v2; res = v1 - v2; res = v1 - v2; res = v1 - v2; res = v1 - v2; res = v1 - v2; }
             break;
         case Operations.Sub_Function:
             for (int i = 0; i < innerIterations; i++)
             { Vector3.Subtract(v1, v2); Vector3.Subtract(v1, v2); Vector3.Subtract(v1, v2); Vector3.Subtract(v1, v2); Vector3.Subtract(v1, v2); Vector3.Subtract(v1, v2); Vector3.Subtract(v1, v2); Vector3.Subtract(v1, v2); Vector3.Subtract(v1, v2); Vector3.Subtract(v1, v2); }
             break;
         case Operations.Mul_Operator:
             for (int i = 0; i < innerIterations; i++)
             { res = v1 * v2; res = v1 * v2; res = v1 * v2; res = v1 * v2; res = v1 * v2; res = v1 * v2; res = v1 * v2; res = v1 * v2; res = v1 * v2; res = v1 * v2; }
             break;
         case Operations.Mul_Function:
             for (int i = 0; i < innerIterations; i++)
             { Vector3.Multiply(v1, v2); Vector3.Multiply(v1, v2); Vector3.Multiply(v1, v2); Vector3.Multiply(v1, v2); Vector3.Multiply(v1, v2); Vector3.Multiply(v1, v2); Vector3.Multiply(v1, v2); Vector3.Multiply(v1, v2); Vector3.Multiply(v1, v2); Vector3.Multiply(v1, v2); }
             break;
         case Operations.Dot:
             for (int i = 0; i < innerIterations; i++)
             { Vector3.Dot(v1, v2); Vector3.Dot(v1, v2); Vector3.Dot(v1, v2); Vector3.Dot(v1, v2); Vector3.Dot(v1, v2); Vector3.Dot(v1, v2); Vector3.Dot(v1, v2); Vector3.Dot(v1, v2); Vector3.Dot(v1, v2); Vector3.Dot(v1, v2); }
             break;
         case Operations.SquareRoot:
             for (int i = 0; i < innerIterations; i++)
             { Vector3.SquareRoot(v1); Vector3.SquareRoot(v1); Vector3.SquareRoot(v1); Vector3.SquareRoot(v1); Vector3.SquareRoot(v1); Vector3.SquareRoot(v1); Vector3.SquareRoot(v1); Vector3.SquareRoot(v1); Vector3.SquareRoot(v1); Vector3.SquareRoot(v1); }
             break;
         case Operations.Length_Squared:
             for (int i = 0; i < innerIterations; i++)
             { v1.LengthSquared(); v1.LengthSquared(); v1.LengthSquared(); v1.LengthSquared(); v1.LengthSquared(); v1.LengthSquared(); v1.LengthSquared(); v1.LengthSquared(); v1.LengthSquared(); v1.LengthSquared(); }
             break;
         case Operations.Normalize:
             for (int i = 0; i < innerIterations; i++)
             { Vector3.Normalize(v1); Vector3.Normalize(v1); Vector3.Normalize(v1); Vector3.Normalize(v1); Vector3.Normalize(v1); Vector3.Normalize(v1); Vector3.Normalize(v1); Vector3.Normalize(v1); Vector3.Normalize(v1); Vector3.Normalize(v1); }
             break;
         case Operations.Distance_Squared:
             for (int i = 0; i < innerIterations; i++)
             { Vector3.DistanceSquared(v1, v2); Vector3.DistanceSquared(v1, v2); Vector3.DistanceSquared(v1, v2); Vector3.DistanceSquared(v1, v2); Vector3.DistanceSquared(v1, v2); Vector3.DistanceSquared(v1, v2); Vector3.DistanceSquared(v1, v2); Vector3.DistanceSquared(v1, v2); Vector3.DistanceSquared(v1, v2); Vector3.DistanceSquared(v1, v2); }
             break;
         case Operations.Cross:
             for (int i = 0; i < innerIterations; i++)
             { Vector3.Cross(v1, v2); Vector3.Cross(v1, v2); Vector3.Cross(v1, v2); Vector3.Cross(v1, v2); Vector3.Cross(v1, v2); Vector3.Cross(v1, v2); Vector3.Cross(v1, v2); Vector3.Cross(v1, v2); Vector3.Cross(v1, v2); Vector3.Cross(v1, v2); }
             break;
     }
 }