示例#1
0
        /// <summary>
        /// Gets a <see cref="Rectangle"/> that represents the valid area that items can be picked up at from
        /// the given <paramref name="spatial"/>.
        /// </summary>
        /// <param name="spatial">The <see cref="ISpatial"/> doing the picking-up.</param>
        /// <returns>A <see cref="Rectangle"/> that represents the area region that items can be picked up at from
        /// the given <paramref name="spatial"/>.</returns>
        public static Rectangle GetPickupArea(ISpatial spatial)
        {
            const int padding = 70;
            var       r       = spatial.ToRectangle();

            return(new Rectangle(r.X - padding, r.Y - padding, r.Width + (padding * 2), r.Height + (padding * 2)));
        }
示例#2
0
 public Ray2D(ISpatial character, Vector2 position, Vector2 direction, ISpatialCollection collection)
 {
     Position              = position;
     Direction             = direction;
     _mapSpatialCollection = collection;
     _owner = character;
 }
示例#3
0
        /// <summary>
        /// Handles when a <see cref="ISpatial"/> in this <see cref="ISpatialCollection"/> resizes.
        /// </summary>
        /// <param name="sender">The <see cref="ISpatial"/> that resized.</param>
        /// <param name="e">The <see cref="EventArgs{Vector2}"/> instance containing the event data.</param>
        void Spatial_Resized(ISpatial sender, EventArgs <Vector2> e)
        {
            // Get the grid index for the last and current max positions to see if the segments have changed
            var maxSegment    = WorldPositionToGridSegment(sender.Position + sender.Size);
            var oldMaxSegment = WorldPositionToGridSegment(sender.Position + e.Item1);

            if (maxSegment == oldMaxSegment)
            {
                return;
            }

            // FUTURE: Can improve performance by only removing from and adding to the appropriate changed segments

            // The position did change, so we have to remove the spatial from the old segments and add to the new
            var startIndex = WorldPositionToGridSegment(sender.Position);
            var length     = WorldPositionToGridSegment(sender.Position + e.Item1);

            foreach (var segment in GetSegments(startIndex, length))
            {
                segment.Remove(sender);
            }

            Debug.Assert(!CollectionContains(sender), "spatial was not completely removed from the grid!");

            // Add the spatial back using the new positions
            foreach (var segment in GetSegments(sender))
            {
                segment.Add(sender);
            }
        }
        /// <summary>
        /// Checks if the <see cref="ISpatial"/> contains a point.
        /// </summary>
        /// <param name="spatial">The spatial.</param>
        /// <param name="p">Point to check if the <paramref name="spatial"/> contains.</param>
        /// <returns>True if the <paramref name="spatial"/> contains <paramref name="p"/>; otherwise false.</returns>
        public static bool Contains(this ISpatial spatial, Vector2 p)
        {
            var min = spatial.Position;
            var max = spatial.Max;

            return(min.X <= p.X && max.X >= p.X && min.Y <= p.Y && max.Y >= p.Y);
        }
示例#5
0
        /// <summary>
        /// Plays the sound for an <see cref="ActionDisplay"/> in a very basic way.
        /// This is intended to be called by the scripts for playing sound instead of handling sound manually.
        /// </summary>
        /// <param name="actionDisplay">The <see cref="ActionDisplay"/>.</param>
        /// <param name="source">The source of the sound.</param>
        static void PlaySoundSimple(ActionDisplay actionDisplay, ISpatial source)
        {
            // Check for valid parameters
            if (actionDisplay == null)
            {
                Debug.Fail("actionDisplay must not be null.");
                return;
            }
            if (source == null)
            {
                Debug.Fail("source must not be null.");
                return;
            }

            // Make sure there is a valid sound
            if (!actionDisplay.Sound.HasValue)
            {
                return;
            }

            // When possible, attach the sound to the source. Otherwise, just play it where the source is currently at
            var attackerAsAudioEmitter = source as IAudioEmitter;

            if (attackerAsAudioEmitter != null)
            {
                _audioManager.SoundManager.Play(actionDisplay.Sound.Value, attackerAsAudioEmitter);
            }
            else
            {
                _audioManager.SoundManager.Play(actionDisplay.Sound.Value, source.Center);
            }
        }
示例#6
0
        public override IDictionary <string, object> Write(ISpatial value)
        {
            GeoJsonObjectWriter writer = new GeoJsonObjectWriter();

            value.SendTo(new ForwardingSegment((SpatialPipeline)writer));
            return(writer.JsonObject);
        }
示例#7
0
        /// <summary>
        /// Creates a <see cref="Rectangle"/> describing the area of a <see cref="ISpatial"/>.
        /// </summary>
        /// <param name="spatial">The <see cref="ISpatial"/> to get the <see cref="Rectangle"/> for.</param>
        /// <returns>A <see cref="Rectangle"/> describing the area of a <see cref="ISpatial"/>.</returns>
        public static Rectangle ToRectangle(ISpatial spatial)
        {
            Vector2 pos  = spatial.Position;
            Vector2 size = spatial.Size;

            return(new Rectangle(pos.X, pos.Y, size.X, size.Y));
        }
示例#8
0
        /// <summary>
        /// Gets the world position and rotation for this spatial object.
        /// The result has the same LocalAABB, i.e. it is not inherited.
        /// The result will have no parent.
        /// </summary>
        public static SpatialData GetWorldSpatialData(this ISpatial self)
        {
            Vector2 position = Vector2.Zero;
            float   radians  = 0.0f;

            ISpatial parent = self;

            while (parent != null)
            {
                SpatialData spatial = parent.Spatial;
                position += spatial.Position;
                radians  += spatial.Rotation.Radians;

                Debug.Assert(spatial.Parent != parent);
                parent = spatial.Parent;
            }

            SpatialData result = new SpatialData
            {
                Position = position,
                Rotation = new Angle {
                    Radians = radians
                },
                LocalAABB = self.Spatial.LocalAABB,
            };

            return(result);
        }
示例#9
0
        private ISpatial ReadSpatialValue(IEdmPrimitiveTypeReference expectedValueTypeReference, bool validateNullValue)
        {
            ODataVersionChecker.CheckSpatialValue(base.Version);
            if (this.TryReadNullValue(expectedValueTypeReference, validateNullValue))
            {
                return(null);
            }
            ISpatial spatial = null;

            if (base.JsonReader.NodeType == JsonNodeType.StartObject)
            {
                IDictionary <string, object> source    = this.ReadObjectValue(base.JsonReader);
                GeoJsonObjectFormatter       formatter = SpatialImplementation.CurrentImplementation.CreateGeoJsonObjectFormatter();
                if (expectedValueTypeReference.IsGeographyType())
                {
                    spatial = formatter.Read <Geography>(source);
                }
                else
                {
                    spatial = formatter.Read <Geometry>(source);
                }
            }
            if (spatial == null)
            {
                throw new ODataException(Microsoft.Data.OData.Strings.ODataJsonPropertyAndValueDeserializer_CannotReadSpatialPropertyValue);
            }
            return(spatial);
        }
示例#10
0
        /// <summary>
        /// Find point-normal frame at ray-intersection point on mesh, or return false if no hit.
        /// Returns interpolated vertex-normal frame if available, otherwise tri-normal frame.
        /// </summary>
        public static bool RayHitPointFrame(DMesh3 mesh, ISpatial spatial, Ray3d ray, out Frame3f hitPosFrame, bool bForceFaceNormal = false)
        {
            hitPosFrame = new Frame3f();
            int tid = spatial.FindNearestHitTriangle(ray);

            if (tid == DMesh3.InvalidID)
            {
                return(false);
            }

            var isect = TriangleIntersection(mesh, tid, ray);

            if (isect.Result != IntersectionResult.Intersects)
            {
                return(false);
            }

            Vector3d surfPt = ray.PointAt(isect.RayParameter);

            if (mesh.HasVertexNormals && bForceFaceNormal == false)
            {
                hitPosFrame = SurfaceFrame(mesh, tid, surfPt);                      // TODO isect has bary-coords already!!
            }
            else
            {
                hitPosFrame = new Frame3f(surfPt, mesh.GetTriNormal(tid));
            }

            return(true);
        }
示例#11
0
        /// <summary>
        /// Gets if an <see cref="ISpatial"/> and <see cref="Rectangle"/> occupy any common space.
        /// </summary>
        /// <param name="a">The <see cref="ISpatial"/>.</param>
        /// <param name="b">The <see cref="Rectangle"/>.</param>
        /// <returns>True if the two occupy any common space; otherwise false.</returns>
        public static bool Intersects(this ISpatial a, Rectangle b)
        {
            bool ret;

            a.ToRectangle().Intersects(ref b, out ret);
            return(ret);
        }
示例#12
0
        /// <summary>
        /// Gets the new size to give an <see cref="ISpatial"/>.
        /// </summary>
        /// <param name="spatial">The <see cref="ISpatial"/>.</param>
        /// <param name="forceAlign">When true, aligning to the grid will be forced.</param>
        /// <returns>The new size for the <paramref name="spatial"/>.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="spatial"/> is null.</exception>
        public Vector2 Resize(ISpatial spatial, bool forceAlign = false)
        {
            if (spatial == null)
            {
                throw new ArgumentNullException("spatial");
            }

            if (!WillAlign && !forceAlign)
            {
                return(spatial.Size);
            }

            var s = Align(spatial.Max, forceAlign) - spatial.Position;

            if (s.X < GridSize.X)
            {
                s.X = GridSize.X;
            }
            if (s.Y < GridSize.Y)
            {
                s.Y = GridSize.Y;
            }

            return(s);
        }
示例#13
0
 public static void AttachTo(this ISpatial self, ISpatial newParent)
 {
     if (newParent != self)
     {
         self.Spatial.Parent = newParent;
     }
 }
示例#14
0
 public void CopyFrom(SpatialData other)
 {
     Parent    = other.Parent;
     Position  = other.Position;
     Rotation  = other.Rotation;
     LocalAABB = other.LocalAABB;
 }
示例#15
0
        /// <summary>
        /// Fits an <see cref="ISpatial"/> into the grid so that all sides are snapped to the grid.
        /// The <paramref name="spatial"/> must support both <see cref="ISpatial.SupportsMove"/> and
        /// <see cref="ISpatial.SupportsResize"/>.
        /// </summary>
        /// <param name="forceAlign">When true, aligning to the grid will be forced.</param>
        /// <param name="spatial">The <see cref="ISpatial"/>.</param>
        public void Fit(ISpatial spatial, bool forceAlign = false)
        {
            if (spatial == null)
            {
                return;
            }

            if (!WillAlign && !forceAlign)
            {
                return;
            }

            if (!spatial.SupportsMove || !spatial.SupportsResize)
            {
                return;
            }

            var pos = Align(spatial, forceAlign);

            if (!spatial.TryMove(pos))
            {
                return;
            }

            var size = Resize(spatial, forceAlign);

            spatial.TryResize(size);
        }
示例#16
0
        /// <summary>
        /// Aligns an <see cref="ISpatial"/>'s position to the grid.
        /// </summary>
        /// <param name="spatial">The <see cref="ISpatial"/>.</param>
        /// <param name="forceAlign">When true, aligning to the grid will be forced.</param>
        /// <returns>The position for the <paramref name="spatial"/>.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="spatial"/> is null.</exception>
        public Vector2 Align(ISpatial spatial, bool forceAlign = false)
        {
            if (spatial == null)
                throw new ArgumentNullException("spatial");

            return Align(spatial.Position, forceAlign);
        }
示例#17
0
        public virtual void Update()
        {
            base.begin_update();
            int start_timestamp = this.CurrentInputTimestamp;

            if (MeshSource == null)
            {
                throw new Exception("GenerateClosedMeshOp: must set valid MeshSource to compute!");
            }

            try {
                DMesh3   inputmesh    = MeshSource.GetDMeshUnsafe();
                ISpatial inputSpatial = MeshSource.HasSpatial ? MeshSource.GetSpatial() : null;

                DMeshAABBTree3 spatial = (inputSpatial != null && inputSpatial is DMeshAABBTree3) ?
                                         inputSpatial as DMeshAABBTree3 : get_cached_spatial(inputmesh);
                DMesh3 meshIn = new DMesh3(inputmesh);

                MeshRepairOrientation repair = new MeshRepairOrientation(meshIn, spatial);
                repair.OrientComponents();
                repair.SolveGlobalOrientation();

                if (invert_result)
                {
                    meshIn.ReverseOrientation(true);
                }

                ResultMesh = meshIn;
                base.complete_update();
            } catch (Exception e) {
                PostOnOperatorException(e);
                ResultMesh = base.make_failure_output(MeshSource.GetDMeshUnsafe());
                base.complete_update();
            }
        }
        /// <summary>
        /// Handles when a <see cref="ISpatial"/> in this <see cref="ISpatialCollection"/> resizes.
        /// </summary>
        /// <param name="sender">The <see cref="ISpatial"/> that resized.</param>
        /// <param name="e">The <see cref="EventArgs{Vector2}"/> instance containing the event data.</param>
        void Spatial_Resized(ISpatial sender, EventArgs <Vector2> e)
        {
            // Get the grid index for the last and current max positions to see if the segments have changed
            var maxSegment    = WorldPositionToGridSegment(sender.Position + sender.Size);
            var oldMaxSegment = WorldPositionToGridSegment(sender.Position + e.Item1);

            if (maxSegment == oldMaxSegment)
            {
                return;
            }

            // The position did change, so we have to remove the spatial from the old segments and add to the new
            var min    = WorldPositionToGridSegment(sender.Position);
            var max    = WorldPositionToGridSegment(sender.Position + e.Item1);
            var length = new Point(max.X - min.X, max.Y - min.Y);

            foreach (var segment in GetSegments(min, length))
            {
                segment.Remove(sender);
            }

            Debug.Assert(!_gridSegments.Any(x => x.Contains(sender)), "spatial was not completely removed from the grid!");

            // Add the spatial back using the new positions
            foreach (var segment in GetSegments(sender))
            {
                segment.Add(sender);
            }
        }
        /// <summary>
        /// Handles when a <see cref="ISpatial"/> in this <see cref="ISpatialCollection"/> moves.
        /// </summary>
        /// <param name="sender">The <see cref="ISpatial"/> that moved.</param>
        /// <param name="e">The <see cref="EventArgs{Vector2}"/> instance containing the event data.</param>
        void Spatial_Moved(ISpatial sender, EventArgs <Vector2> e)
        {
            // Get the grid index for the last and current positions to see if the segments have changed
            var minSegment    = WorldPositionToGridSegment(sender.Position);
            var maxSegment    = WorldPositionToGridSegment(sender.Max);
            var oldMinSegment = WorldPositionToGridSegment(e.Item1);
            var oldMaxSegment = WorldPositionToGridSegment(e.Item1 + sender.Size);

            if (minSegment == oldMinSegment && maxSegment == oldMaxSegment)
            {
                return;
            }

            // The position did change, so remove the ISpatial from all segments
            foreach (var segment in GetSegments(sender, e.Item1))
            {
                segment.Remove(sender);
            }

            Debug.Assert(!_gridSegments.Any(x => x.Contains(sender)), "spatial was not completely removed from the grid!");

            // Add the spatial back using the new positions
            foreach (var segment in GetSegments(sender))
            {
                segment.Add(sender);
            }
        }
示例#20
0
        /// <summary>
        /// Gets a <see cref="Rectangle"/> that represents the area that represents where this <see cref="ISpatial"/>
        /// is standing.
        /// </summary>
        /// <param name="spatial">The <see cref="ISpatial"/>.</param>
        /// <returns>A <see cref="Rectangle"/> that represents the area that represents where this <see cref="ISpatial"/>
        /// is standing.</returns>
        public static Rectangle GetStandingAreaRect(this ISpatial spatial)
        {
            Vector2   min  = spatial.Position;
            Vector2   size = spatial.Size;
            Rectangle r    = new Rectangle(min.X + 1, min.Y + size.Y - 1, size.X - 2, 2);

            return(r);
        }
示例#21
0
        /// <summary>
        /// Gets if an <see cref="ISpatial"/> and another <see cref="ISpatial"/> occupy any common space.
        /// </summary>
        /// <param name="a">The first <see cref="ISpatial"/>.</param>
        /// <param name="b">The other <see cref="ISpatial"/>.</param>
        /// <returns>True if the two occupy any common space; otherwise false.</returns>
        public static bool Intersects(this ISpatial a, ISpatial b)
        {
            var  bRect = b.ToRectangle();
            bool ret;

            a.ToRectangle().Intersects(ref bRect, out ret);
            return(ret);
        }
        /// <summary>
        /// Gets the grid segments that the <paramref name="spatial"/> occupies.
        /// </summary>
        /// <param name="spatial">The <see cref="ISpatial"/> to get the segments for.</param>
        /// <param name="position">The position to treat the <see cref="spatial"/> as being at.</param>
        /// <returns>The grid segments that the <paramref name="spatial"/> occupies.</returns>
        protected IEnumerable <IGridSpatialCollectionSegment> GetSegments(ISpatial spatial, Vector2 position)
        {
            var min    = WorldPositionToGridSegment(position);
            var max    = WorldPositionToGridSegment(position + spatial.Size);
            var length = new Point(max.X - min.X, max.Y - min.Y);

            return(GetSegments(min, length));
        }
示例#23
0
        /// <summary>
        /// Gets a <see cref="Rectangle"/> that represents the area that represents where this <see cref="ISpatial"/>
        /// is standing.
        /// </summary>
        /// <param name="spatial">The <see cref="ISpatial"/>.</param>
        /// <returns>A <see cref="Rectangle"/> that represents the area that represents where this <see cref="ISpatial"/>
        /// is standing.</returns>
        public static Rectangle GetStandingAreaRect(this ISpatial spatial)
        {
            var min  = spatial.Position;
            var size = spatial.Size;
            var r    = new Rectangle((int)min.X + 1, (int)(min.Y + size.Y - 1), (int)size.X - 2, 2);

            return(r);
        }
示例#24
0
        public bool Intersects <T>(out ISpatial spatial) where T : ISpatial
        {
            Vector2 nullVector;

            spatial = Cast <T>((int)Position.X, (int)Position.Y, (int)Direction.X, (int)Direction.Y, out nullVector);

            return(spatial != null);
        }
示例#25
0
        /// <summary>
        /// Finds the Minimal Translational Distance between two <see cref="ISpatial"/>s.
        /// </summary>
        /// <param name="source">Source (dynamic) <see cref="ISpatial"/> that will be the one moving.</param>
        /// <param name="target">Target (static) <see cref="ISpatial"/> that will not move.</param>
        /// <returns>The MTD for the <paramref name="source"/> to no longer intersect the <paramref name="target"/>.</returns>
        public static Vector2 MTD(ISpatial source, ISpatial target)
        {
            Vector2 srcMin = source.Position;
            Vector2 srcMax = source.Max;
            Vector2 tarMin = target.Position;
            Vector2 tarMax = target.Max;

            return(MTD(srcMin, srcMax, tarMin, tarMax));
        }
示例#26
0
 public MeshProjectionTarget(DMesh3 mesh, ISpatial spatial)
 {
     Mesh    = mesh;
     Spatial = spatial;
     if (Spatial == null)
     {
         Spatial = new DMeshAABBTree3(mesh, true);
     }
 }
        private void DoService(ref BehaviorTreeContext context)
        {
            ISpatial p = spatial.Get(context, this);

            if (p != null)
            {
                positionSetter.Set(context, this, p.Position);
            }
        }
示例#28
0
        /// <summary>
        /// Finds the Minimal Translational Distance between two <see cref="ISpatial"/>s.
        /// </summary>
        /// <param name="source">Source (dynamic) <see cref="ISpatial"/> that will be the one moving.</param>
        /// <param name="target">Target (static) <see cref="ISpatial"/> that will not move.</param>
        /// <returns>The MTD for the <paramref name="source"/> to no longer intersect the <paramref name="target"/>.</returns>
        public static Vector2 MTD(ISpatial source, ISpatial target)
        {
            Vector2 srcMin = source.Position;
            Vector2 srcMax = source.Max;
            Vector2 tarMin = target.Position;
            Vector2 tarMax = target.Max;

            return MTD(srcMin, srcMax, tarMin, tarMax);
        }
示例#29
0
        /// <summary>
        /// Aligns an <see cref="ISpatial"/>'s position to the grid.
        /// </summary>
        /// <param name="spatial">The <see cref="ISpatial"/>.</param>
        /// <param name="forceAlign">When true, aligning to the grid will be forced.</param>
        /// <returns>The position for the <paramref name="spatial"/>.</returns>
        /// <exception cref="ArgumentNullException"><paramref name="spatial"/> is null.</exception>
        public Vector2 Align(ISpatial spatial, bool forceAlign = false)
        {
            if (spatial == null)
            {
                throw new ArgumentNullException("spatial");
            }

            return(Align(spatial.Position, forceAlign));
        }
            /// <summary>
            /// Initializes a new instance of the <see cref="TransBox"/> class.
            /// </summary>
            /// <param name="owner">The <see cref="TransBoxManager"/>.</param>
            /// <param name="type">The <see cref="TransBoxType"/>.</param>
            /// <param name="spatial">The <see cref="ISpatial"/>.</param>
            TransBox(TransBoxManager owner, TransBoxType type, ISpatial spatial)
            {
                _owner = owner;

                _type    = type;
                _spatial = spatial;

                _size     = GetTransBoxSize(type);
                _position = GetPosition();
            }
示例#31
0
            /// <summary>
            /// Initializes a new instance of the <see cref="TransBox"/> class.
            /// </summary>
            /// <param name="owner">The <see cref="TransBoxManager"/>.</param>
            /// <param name="type">The <see cref="TransBoxType"/>.</param>
            /// <param name="spatial">The <see cref="ISpatial"/>.</param>
            TransBox(TransBoxManager owner, TransBoxType type, ISpatial spatial)
            {
                _owner = owner;

                _type = type;
                _spatial = spatial;

                _size = GetTransBoxSize(type);
                _position = GetPosition();
            }
示例#32
0
        /// <summary>
        /// Find distance from point to mesh
        /// Returns interpolated vertex-normal frame if available, otherwise tri-normal frame.
        /// </summary>
        public static double NearestPointDistance(DMesh3 mesh, ISpatial spatial, Vector3d queryPoint, double maxDist = double.MaxValue)
        {
            int tid = spatial.FindNearestTriangle(queryPoint, maxDist);

            if (tid == DMesh3.InvalidID)
            {
                return(double.MaxValue);
            }
            return(Math.Sqrt(TriangleDistance(mesh, tid, queryPoint).DistanceSquared));
        }
示例#33
0
        private void AddEntityGrh(ISpatial entity, Grh grh)
        {
            // Find the scaling value so we can position the entities correctly
            var scaleX    = GamePlayScreen.Map.Size.X / ScaledMapGrh.Size.X;
            var scaleY    = GamePlayScreen.Map.Size.Y / ScaledMapGrh.Size.Y;
            var scaledPos = new Vector2((entity.Position.X / scaleX) - grh.Size.X / 2, (entity.Position.Y / scaleY) - grh.Size.Y / 2);

            // Add the grh as well as the position
            _grhEntities.Add(new Tuple <Grh, Vector2>(new Grh(grh.GrhData), scaledPos));
        }
示例#34
0
 public static string Write(this SpatialFormatter<TextReader, TextWriter> formatter, ISpatial spatial)
 {
     Util.CheckArgumentNull(formatter, "formatter");
     StringBuilder sb = new StringBuilder();
     using (TextWriter writer = new StringWriter(sb, CultureInfo.InvariantCulture))
     {
         formatter.Write(spatial, writer);
     }
     return sb.ToString();
 }
示例#35
0
        /// <summary>
        /// Initializes a new instance of the <see cref="MapGrhEffectLoopOnce"/> class.
        /// </summary>
        /// <param name="grh">Grh to draw.</param>
        /// <param name="position">Position to draw on the map.</param>
        /// <param name="target">The <see cref="ISpatial"/> to seek out.</param>
        /// <param name="speed">How fast this object moves towards the target in pixels per second.</param>
        /// <exception cref="ArgumentNullException"><paramref name="target"/> is null.</exception>
        public MapGrhEffectSeekSpatial(Grh grh, Vector2 position, ISpatial target, float speed)
            : base(grh, position)
        {
            if (target == null)
                throw new ArgumentNullException("target");

            _lastUpdate = TickCount.Now;

            _target = target;
            _speed = speed / 1000f;
        }
示例#36
0
 public static string Write(this SpatialFormatter<XmlReader, XmlWriter> formatter, ISpatial spatial)
 {
     Util.CheckArgumentNull(formatter, "formatter");
     StringBuilder output = new StringBuilder();
     XmlWriterSettings settings = new XmlWriterSettings {
         OmitXmlDeclaration = true
     };
     using (XmlWriter writer = XmlWriter.Create(output, settings))
     {
         formatter.Write(spatial, writer);
     }
     return output.ToString();
 }
示例#37
0
        /// <summary>
        /// Finds the Minimal Translational Distance between two <see cref="ISpatial"/>s.
        /// </summary>
        /// <param name="source">Source (dynamic) <see cref="ISpatial"/> that will be the one moving.</param>
        /// <param name="target">Target (static) <see cref="ISpatial"/> that will not move.</param>
        /// <returns>The MTD for the <paramref name="source"/> to no longer intersect the <paramref name="target"/>.</returns>
        public static Vector2 MTD(ISpatial source, ISpatial target)
        {
            var srcMin = source.Position;
            var srcMax = source.Max;
            var tarMin = target.Position;
            var tarMax = target.Max;

            // Down
            var mtd = source.Max.Y - tarMin.Y;
            var side = BoxSide.Bottom;

            // Left
            var diff = srcMax.X - tarMin.X;
            if (diff < mtd)
            {
                mtd = diff;
                side = BoxSide.Left;
            }

            // Right
            diff = tarMax.X - srcMin.X;
            if (diff < mtd)
            {
                mtd = diff;
                side = BoxSide.Right;
            }

            // Up
            diff = tarMax.Y - srcMin.Y;
            if (diff < mtd)
            {
                mtd = diff;
                side = BoxSide.Top;
            }

            if (mtd < 0.0f)
                return Vector2.Zero;

            return CreateMTDVector(side, mtd + 1);
        }
示例#38
0
        /// <summary>
        /// Converts a spatial value into a string representation suitable for the specified format. If specified, injects a type name into the JSON format(s).
        /// </summary>
        /// <param name="format">The format to create the spatial value string representation for.</param>
        /// <param name="spatial">The spatial value.</param>
        /// <param name="typeName">The (optional) type name to inject into a JSON string representation.</param>
        /// <returns>The string representation of the spatial value in the specified format.</returns>
        /// <remarks>When using a type name with the JSON Light format, the resulting string representation will be invalid 
        /// (since the odata.type annotation is not supported inside of spatial values); only used for error tests.</remarks>
        public static string GetSpatialStringValue(ODataFormat format, ISpatial spatial, string typeName = null)
        {
            if (format == ODataFormat.Atom)
            {
                return GmlFormatter.Create().Write(spatial);
            }

            IDictionary<string, object> dictionary = GeoJsonObjectFormatter.Create().Write(spatial);

            var converter = new DictionaryToJsonObjectConverter();
            ExceptionUtilities.CheckAllRequiredDependencies(converter);

            var jsonObject = converter.Convert(dictionary);
            if (typeName != null)
            {
                // NOTE: using a type name with the JSON Light format will produce invalid payloads and is only used
                //       for error tests.
                jsonObject.Insert(0, new JsonProperty(JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName, new JsonPrimitiveValue(typeName)));
            }

            return jsonObject.ToText(format == ODataFormat.Json, indent:false);
        }
示例#39
0
        /// <summary>
        /// Handles when the <see cref="IRefractionEffect.PositionProvider"/> moves.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The event args.</param>
        void PositionProvider_Moved(ISpatial sender, EventArgs<Vector2> e)
        {
            // Avoid needless calculations on finding the position when there are no listeners for Moved
            if (Moved != null)
            {
                // Moved has listener(s)
                var oldValue = Position;
                _position = sender.Position;

                Moved.Raise(this, EventArgsHelper.Create(oldValue));
            }
            else
            {
                // No Moved listeners
                _position = sender.Position;
            }
        }
示例#40
0
文件: Map.cs 项目: wtfcolt/game
 /// <summary>
 /// Send a packet to every user in the map within a reasonable range from the origin. Use this for packets
 /// that only affect those who are already in view from the origin such as brief visual effects.
 /// </summary>
 /// <param name="origin">The <see cref="ISpatial"/> that the event comes from.</param>
 /// <param name="data">BitStream containing the data to send.</param>
 /// <param name="messageType">The <see cref="ServerMessageType"/> to use for sending the <paramref name="data"/>.</param>
 public void SendToArea(ISpatial origin, BitStream data, ServerMessageType messageType)
 {
     SendToArea(origin.Position + (origin.Size / 2f), data, messageType);
 }
示例#41
0
 /// <summary>
 /// Initializes a new instance of the <see cref="WaterRefractionEffect"/> class.
 /// </summary>
 /// <param name="waveNoise">The sprite to use for the wave noise.</param>
 /// <param name="positionProvider">The <see cref="ISpatial"/> that will provide the positioning.</param>
 /// <param name="size">The size of the effect in pixels.</param>
 /// <param name="shader">The <see cref="Shader"/> to use to draw the water's refraction map. If null, the
 /// <see cref="WaterRefractionEffect.DefaultShader"/> will be used. If you provide your own shader, you must
 /// make sure that you either use the same effect parameters the default shader uses, or override this class
 /// so you can override the <see cref="WaterRefractionEffect.SetShaderParameters"/> method and set the parameters
 /// you require.</param>
 /// <exception cref="ArgumentNullException"><paramref name="waveNoise"/> is null.</exception>
 /// <exception cref="NullReferenceException"><paramref name="positionProvider"/> is null.</exception>
 public WaterRefractionEffect(Grh waveNoise, ISpatial positionProvider, Vector2 size, Shader shader = null)
     : this(waveNoise, positionProvider.Position, size, shader)
 {
     PositionProvider = positionProvider;
 }
示例#42
0
文件: Camera2D.cs 项目: wtfcolt/game
        /// <summary>
        /// Checks if a specified object is in view of the camera.
        /// </summary>
        /// <param name="spatial">The <see cref="ISpatial"/> to check if in view.</param>
        /// <returns>
        /// True if in the view area; otherwise false.
        /// </returns>
        public bool InView(ISpatial spatial)
        {
            if (spatial == null)
            {
                const string errmsg = "spatial is null.";
                Debug.Fail(errmsg);
                if (log.IsErrorEnabled)
                    log.Error(errmsg);
                return false;
            }

            return InView(spatial.Position, spatial.Size);
        }
示例#43
0
文件: Map.cs 项目: wtfcolt/game
        /// <summary>
        /// Finds the Users close enough to the <paramref name="toSynchronize"/> to synchronize their
        /// Position and Velocity to.
        /// </summary>
        /// <param name="toSynchronize">The <see cref="ISpatial"/> to synchronize.</param>
        /// <returns>An IEnumerable of Users close enough to the <paramref name="toSynchronize"/> that they
        /// need to have the <paramref name="toSynchronize"/>'s Position and Velocity synchronized.</returns>
        IEnumerable<User> GetUsersToSyncPandVTo(ISpatial toSynchronize)
        {
            int xPad = (int)(GameData.ScreenSize.X * 1.5);
            int yPad = (int)(GameData.ScreenSize.Y * 1.5);

            var syncRegion = toSynchronize.ToRectangle().Inflate(xPad, yPad);

            foreach (var user in Users)
            {
                Rectangle userRegion = user.ToRectangle();
                if (syncRegion.Intersects(userRegion))
                    yield return user;
            }
        }
示例#44
0
 private void AddEntityGrh(ISpatial entity, Grh grh)
 {
     // Find the scaling value so we can position the entities correctly
     var scaleX = GamePlayScreen.Map.Size.X / ScaledMapGrh.Size.X;
     var scaleY = GamePlayScreen.Map.Size.Y / ScaledMapGrh.Size.Y;
     var scaledPos = new Vector2((entity.Position.X / scaleX) - grh.Size.X / 2, (entity.Position.Y / scaleY) - grh.Size.Y / 2);
     // Add the grh as well as the position
     _grhEntities.Add(new Tuple<Grh, Vector2>(new Grh(grh.GrhData), scaledPos));
 }
示例#45
0
        /// <summary>
        /// Handles when an ItemEntity is resized.
        /// </summary>
        /// <param name="sender">The <see cref="ItemEntity"/> that was resized.</param>
        /// <param name="e">The <see cref="NetGore.EventArgs{Vector2}"/> instance containing the event data.</param>
        void ItemEntity_Resized(ISpatial sender, EventArgs<Vector2> e)
        {
            Debug.Assert(sender == this, "Why did we receive an ItemEntity_OnResize for another Entity?");

            // Get the sizes as a byte
            var oldWidth = (byte)e.Item1.X;
            var oldHeight = (byte)e.Item1.Y;
            var width = (byte)sender.Size.X;
            var height = (byte)sender.Size.Y;

            // Update the changed sizes
            if (oldWidth != width)
                SynchronizeField("width", width);

            if (oldHeight != height)
                SynchronizeField("height", height);
        }
示例#46
0
 /// <summary>
 /// Gets if the <paramref name="shopper"/> is close enough to the <paramref name="shopOwner"/> to shop.
 /// </summary>
 /// <param name="shopper">The <see cref="Entity"/> doing the shopping.</param>
 /// <param name="shopOwner">The <see cref="Entity"/> that owns the shop.</param>
 /// <returns>True if the <paramref name="shopper"/> is close enough to the <paramref name="shopOwner"/> to
 /// shop; otherwise false.</returns>
 public static bool IsValidDistanceToShop(ISpatial shopper, ISpatial shopOwner)
 {
     var area = GetValidShopArea(shopper);
     return shopOwner.Intersects(area);
 }
示例#47
0
 /// <summary>
 /// Checks if an <see cref="ISpatial"/> is close enough to another <see cref="ISpatial"/> to pick it up.
 /// </summary>
 /// <param name="grabber">The <see cref="ISpatial"/> doing the picking up.</param>
 /// <param name="toGrab">The <see cref="ISpatial"/> being picked up.</param>
 /// <returns>True if the <paramref name="grabber"/> is close enough to the <paramref name="toGrab"/>
 /// to pick it up; otherwise false.</returns>
 public static bool IsValidPickupDistance(ISpatial grabber, ISpatial toGrab)
 {
     var region = GetPickupArea(grabber);
     return toGrab.Intersects(region);
 }
示例#48
0
 /// <summary>
 /// Gets a <see cref="Rectangle"/> that represents the valid area that items can be picked up at from
 /// the given <paramref name="spatial"/>.
 /// </summary>
 /// <param name="spatial">The <see cref="ISpatial"/> doing the picking-up.</param>
 /// <returns>A <see cref="Rectangle"/> that represents the area region that items can be picked up at from
 /// the given <paramref name="spatial"/>.</returns>
 public static Rectangle GetPickupArea(ISpatial spatial)
 {
     const int padding = 70;
     return spatial.ToRectangle().Inflate(padding);
 }
示例#49
0
 /// <summary>
 /// Gets a <see cref="Rectangle"/> containing the area that the <paramref name="shopper"/> may use to
 /// shop. Any <see cref="Entity"/> that owns a shop and intersects with this area is considered in a valid
 /// distance to shop with.
 /// </summary>
 /// <param name="shopper">The <see cref="Entity"/> doing the shopping.</param>
 /// <returns>A <see cref="Rectangle"/> containing the area that the <paramref name="shopper"/> may use to
 /// shop.</returns>
 public static Rectangle GetValidShopArea(ISpatial shopper)
 {
     return shopper.ToRectangle();
 }
示例#50
0
 /// <summary>
 /// Gets the top-left corner to use for drawing for the given <paramref name="target"/>.
 /// </summary>
 /// <param name="target">The <see cref="ISpatial"/> to attach the bubble to.</param>
 /// <returns>The coordinate of the top-left corner of the <paramref name="target"/> to use for drawing.</returns>
 static Vector2 GetTopLeftCorner(ISpatial target)
 {
     return target.Position;
 }
示例#51
0
 /// <summary>
 /// Handles when the <see cref="ILight.PositionProvider"/> moves.
 /// </summary>
 /// <param name="sender">The source of the event.</param>
 /// <param name="e">The <see cref="EventArgs{Vector2}"/> instance containing the event data.</param>
 void PositionProvider_Moved(ISpatial sender, EventArgs<Vector2> e)
 {
     _position = sender.Position;
 }
示例#52
0
 /// <summary>
 /// Draws a <see cref="Rectangle"/>.
 /// </summary>
 /// <param name="sb"><see cref="ISpriteBatch"/> to draw to.</param>
 /// <param name="color">Color to draw the CollisionBox.</param>
 static void Draw(ISpriteBatch sb, ISpatial spatial, Color color, bool border = true)
 {
     Draw(sb, spatial.Position, spatial.Size, color, border);
 }
示例#53
0
        /// <summary>
        /// Gets the top-left corner to use for drawing for the given <paramref name="target"/>.
        /// </summary>
        /// <param name="target">The <see cref="ISpatial"/> to attach the bubble to.</param>
        /// <returns>The coordinate of the top-left corner of the <paramref name="target"/> to use for drawing.</returns>
        Vector2 GetTopLeftDrawCorner(ISpatial target)
        {
            Character asCharacter;

            // Make use of the Character's DrawPosition, otherwise it will look like the bubble is moving all over
            // the place since Characters like to interpolate all over the place
            if ((asCharacter = target as Character) != null)
                return asCharacter.LastScreenPosition;
            else
                return target.Position - World.Camera.Min;
        }
示例#54
0
文件: Map.cs 项目: Vizzini/netgore
        /// <summary>
        /// Finds the Users close enough to the <paramref name="toSynchronize"/> to synchronize their
        /// Position and Velocity to.
        /// </summary>
        /// <param name="toSynchronize">The <see cref="ISpatial"/> to synchronize.</param>
        /// <returns>An IEnumerable of Users close enough to the <paramref name="toSynchronize"/> that they
        /// need to have the <paramref name="toSynchronize"/>'s Position and Velocity synchronized.</returns>
        IEnumerable<User> GetUsersToSyncPandVTo(ISpatial toSynchronize)
        {
            var xPad = (int)(GameData.ScreenSize.X * 1.5);
            var yPad = (int)(GameData.ScreenSize.Y * 1.5);

            var r = toSynchronize.ToRectangle();
            var syncRegion = new Rectangle(r.X - xPad, r.Y - yPad, r.Width + xPad * 2, r.Height + xPad * 2);

            foreach (var user in Users)
            {
                var userRegion = user.ToRectangle();
                if (syncRegion.Intersects(userRegion))
                    yield return user;
            }
        }
示例#55
0
 /// <summary>
 /// Gets if an <see cref="ISpatial"/> and another <see cref="ISpatial"/> occupy any common space.
 /// </summary>
 /// <param name="a">The first <see cref="ISpatial"/>.</param>
 /// <param name="b">The other <see cref="ISpatial"/>.</param>
 /// <returns>True if the two occupy any common space; otherwise false.</returns>
 public static bool Intersects(this ISpatial a, ISpatial b)
 {
     var bRect = b.ToRectangle();
     bool ret;
     a.ToRectangle().Intersects(ref bRect, out ret);
     return ret;
 }
示例#56
0
 /// <summary>
 /// Creates a <see cref="Rectangle"/> describing the area of a <see cref="ISpatial"/>.
 /// </summary>
 /// <param name="spatial">The <see cref="ISpatial"/> to get the <see cref="Rectangle"/> for.</param>
 /// <returns>A <see cref="Rectangle"/> describing the area of a <see cref="ISpatial"/>.</returns>
 public static Rectangle ToRectangle(ISpatial spatial)
 {
     return new Rectangle((int)spatial.Position.X, (int)spatial.Position.Y, (int)spatial.Size.X, (int)spatial.Size.Y);
 }
示例#57
0
 public static string GetUriLiteral(Type type, ISpatial spatial)
 {
     string typePrefix = typeof(Geometry).IsAssignableFrom(type) ? "geometry" : "geography";
     return string.Format("{0}'{1}'", typePrefix, WellKnownTextSqlFormatter.Create().Write(spatial));
 }
示例#58
0
        /// <summary>
        /// Handles when one of the bound walls have changed.
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="NetGore.EventArgs{Vector2}"/> instance containing the event data.</param>
        void BoundWallChanged(ISpatial sender, EventArgs<Vector2> e)
        {
            var index = lstWalls.Items.IndexOf(sender);
            if (index < 0)
                return;

            lstWalls.RefreshItemAt(index);
        }
示例#59
0
 /// <summary>
 /// Gets if an <see cref="ISpatial"/> is fully contained inside of another <see cref="ISpatial"/>. That is, if
 /// the <see cref="contained"/> resides completely inside of the <see cref="container"/>.
 /// </summary>
 /// <param name="container">The <see cref="ISpatial"/> to check if it contains the <see cref="contained"/>.</param>
 /// <param name="contained">The <see cref="ISpatial"/> to check if is contained.</param>
 /// <returns>If the <paramref name="contained"/> is fully contained inside of the
 /// <paramref name="container"/>.</returns>
 public static bool Contains(this ISpatial container, ISpatial contained)
 {
     return container.ToRectangle().Contains(contained.ToRectangle());
 }
示例#60
0
 /// <summary>
 /// Gets the distance between this <see cref="ISpatial"/> and another.
 /// </summary>
 /// <param name="spatial">The first <see cref="ISpatial"/>.</param>
 /// <param name="other">The other <see cref="ISpatial"/>.</param>
 /// <returns>The distance between this <see cref="ISpatial"/> and another <see cref="ISpatial"/> as an
 /// absolute value greater than or equal to zero. If this intersects <paramref name="other"/>, the
 /// value will be 0. Otherwise, the value will be the length of the shortest path between the two
 /// <see cref="ISpatial"/>s.</returns>
 public static int GetDistance(this ISpatial spatial, ISpatial other)
 {
     return spatial.ToRectangle().GetDistance(other.ToRectangle());
 }