protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        float deltaTime = Time.DeltaTime;

        return(Entities.ForEach((Entity entity, DynamicBuffer <PathPosition> pathPositionBuffer, ref Translation translation, ref Rotation rotation, ref PathFollow pathFollow) =>
        {
            if (pathFollow.pathIndex >= 0)
            {
                // Получаем первую позицию
                PathPosition pathPosition = pathPositionBuffer[pathFollow.pathIndex];
                // Переводим ее координаты в мировые
                float3 targetPosition = PathfindingGridSetup.Instance.pathfindingGrid.GetWorldPosition(pathPosition.position.x, pathPosition.position.y);

                // Расчитываем направление и угол поворота
                float3 moveDir = math.normalizesafe(targetPosition - translation.Value);
                float moveSpeed = 3f;

                float rotationSpeed = 5f;
                var targetRotation = quaternion.LookRotation(targetPosition - translation.Value, new float3(0, 1, 0));

                var newRotation = math.slerp(rotation.Value, math.mul(targetRotation, quaternion.Euler(-90 * Mathf.Deg2Rad, 0, 0)), deltaTime * rotationSpeed);


                rotation.Value = newRotation;
                translation.Value += moveDir * moveSpeed * deltaTime;

                if (math.distance(translation.Value, targetPosition) < .1f)
                {
                    // Next waypoint
                    pathFollow.pathIndex--;
                }
            }
        }).Schedule(inputDeps));
    }
Example #2
0
        public float move(PathPosition currentPosition, float distance, out PathPosition newPosition)
        {
            float distToEnd   = (points.Length - 1 - currentPosition.pointIndex - currentPosition.ratio) * distanceBetweenPoints;
            float distToStart = (currentPosition.pointIndex + currentPosition.ratio) * distanceBetweenPoints;

            if (distance - distToEnd > 0)
            {
                newPosition = getEndPoint();
                return(distance - distToEnd);
            }
            else if (distance + distToStart < 0)
            {
                newPosition = getStartPoint();
                return(distance + distToStart);
            }

            distance += currentPosition.ratio * distanceBetweenPoints;

            int   tam   = (int)(distance / distanceBetweenPoints);
            float artan = distance / distanceBetweenPoints - tam;

            if (artan < 0)
            {
                artan += 1f;
                tam--;
            }

            newPosition = new PathPosition(currentPosition.pointIndex + tam, artan);
            return(0);
        }
Example #3
0
            public override PathPosition GetClosestPoint(Vector3 position, out float distanceSqr)
            {
                PathPosition pathPos = GetPoint(0.0f);

                distanceSqr = (position - pathPos._pathPosition).sqrMagnitude;
                return(pathPos);
            }
Example #4
0
            public override PathPosition GetClosestPoint(Vector3 position, out float distanceSqr)
            {
                PathPosition closestPosition = null;

                int   numLines  = _isLooping ? _nodes.Length : _nodes.Length - 1;
                float linePathT = 1.0f / (float)(numLines);

                distanceSqr = 0.0f;

                for (int i = 0; i < numLines; i++)
                {
                    //Get closest point on line
                    int   toNode   = (i < _nodes.Length - 1) ? i + 1 : 0;
                    float lineLerp = 0.0f;
                    float dist     = 0.0f;
                    float width;

                    Vector3 up, forward;
                    Vector3 closestPoint = GetClosestPointToLine(i, toNode, position, out dist, out lineLerp, out forward, out up, out width);

                    if (closestPosition == null || dist < distanceSqr)
                    {
                        closestPosition = new PathPosition(this, ((float)i + lineLerp) * linePathT, closestPoint, forward, up, width);
                        distanceSqr     = dist;
                    }
                }

                if (closestPosition == null)
                {
                    closestPosition = null;
                }

                return(closestPosition);
            }
 public void AddPickupSerie(float startDistance, int amount, float absoluteStep, PathPosition pathPos)
 {
     for (int i = 0; i < amount; i++)
     {
         AddPickup(startDistance + i * (absoluteStep / totalDistance), pathPos);
     }
 }
Example #6
0
        /// <summary>
        /// Verilen minionu boarda ekler. 2.Parametrede verilen noktaya goturur.
        /// </summary>
        /// <param name="minion">boarda yerlestirilecek minion</param>
        /// <returns>Bu islem her zaman basarili oldugu icin bir return degeri yoktur.</returns>
        public void AddMinionSpecificPosition(Minion minion, PathPosition position, bool notifyPlayers = true)
        {
            if (boardState != BoardState.COLLAPSING)
            {
                try
                {
                    toBeAddedMinions.Add(minion);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.StackTrace + " : " + e.Message);
                }

                if (minion.position == null)
                {
                    minion.position = new MinionPosition();
                }

                minion.position.board        = this;
                minion.position.pathPosition = new PathPosition(position.pointIndex, position.ratio);

                if (notifyPlayers)
                {
                    Messages.OutgoingMessages.Game.GMinionPositionInfo.sendMessage(player.game.players, minion);
                }
            }
            else
            {
                minion.destroyable = true;
                Messages.OutgoingMessages.Game.GDestroyMinionInfo.sendMessage(player.game.players, minion);
            }
        }
Example #7
0
    protected override void OnUpdate()
    {
        float deltaTime = Time.DeltaTime;

        float cellSize = Testing.Instance.grid.GetCellSize();

        Entities.ForEach((Entity entity, DynamicBuffer <PathPosition> pathPositionBuffer, ref Translation translation, ref PathFollow pathFollow) => {
            if (pathFollow.pathIndex >= 0)
            {
                // Has path to follow
                PathPosition pathPosition = pathPositionBuffer[pathFollow.pathIndex];

                float3 targetPosition = new float3(pathPosition.position.x * cellSize + cellSize * 0.5f, pathPosition.position.y * cellSize + cellSize * 0.5f, 0);
                float3 moveDir        = math.normalizesafe(targetPosition - translation.Value);
                float moveSpeed       = 1f;

                translation.Value += moveDir * moveSpeed * deltaTime;

                if (math.distance(translation.Value, targetPosition) < cellSize * .25f)
                {
                    // Next waypoint
                    pathFollow.pathIndex--;
                }
            }
        }).ScheduleParallel();
    }
Example #8
0
            public override float GetDistanceBetween(float fromT, float toT)
            {
                ClampPathT(ref fromT, ref toT);

                float        distance     = 0.0f;
                int          numSamples   = (int)Mathf.Ceil(Mathf.Abs(toT - fromT) * kNumSamples);
                float        sampleT      = (toT > fromT ? 1.0f : -1.0f) / (float)kNumSamples;
                float        pathT        = fromT;
                PathPosition pathPosition = GetPoint(fromT);

                for (int i = 0; i < numSamples; i++)
                {
                    if (i == numSamples - 1)
                    {
                        pathT = toT;
                    }
                    else
                    {
                        pathT += sampleT;
                    }

                    PathPosition samplePos   = GetPoint(pathT);
                    Vector3      toSamplePos = samplePos._pathPosition - pathPosition._pathPosition;
                    distance    += toSamplePos.magnitude;
                    pathPosition = samplePos;
                }

                return(distance);
            }
            public static PathRoute FindRoute(PathPosition startPos, PathPosition endPos)
            {
                if (startPos == null || endPos == null || startPos._path == null || endPos._path == null)
                {
                    return(null);
                }

                PathRoute bestRoute = null;

                List <PathNode> linkedNodes = new List <PathNode>();
                PathNode        nodeA       = GetNextNode(startPos, Direction1D.Forwards);

                if (nodeA != null && nodeA.isActiveAndEnabled)
                {
                    linkedNodes.Add(nodeA);
                }

                PathNode nodeB = GetNextNode(startPos, Direction1D.Backwards);

                if (nodeB != null && nodeA != nodeB && nodeB.isActiveAndEnabled)
                {
                    linkedNodes.Add(nodeB);
                }

                List <PathNode> traversedNodes = new List <PathNode>();

                FindRoute(startPos, endPos, startPos._path, startPos._pathT, linkedNodes, 0.0f, new List <PathRouteWaypoint>(), ref bestRoute, ref traversedNodes);

                return(bestRoute);
            }
            public static PathPosition GetClosestPoint(Path startPath, Ray ray)
            {
                PathPosition closestPoint = null;

                if (startPath != null)
                {
                    //Traverse path network and work out nearest point
                    List <Path> paths = new List <Path>();
                    paths.Add(startPath);
                    FindPaths(startPath, ref paths);

                    float bestDist = 0.0f;

                    //for each path find closest point and get connected paths
                    foreach (Path path in paths)
                    {
                        float        distanceSqr;
                        PathPosition pathClosestPoint = path.GetClosestPoint(ray, out distanceSqr);

                        if (closestPoint == null || distanceSqr < bestDist)
                        {
                            closestPoint = pathClosestPoint;
                            bestDist     = distanceSqr;
                        }
                    }
                }

                return(closestPoint);
            }
Example #11
0
            public override PathPosition GetClosestPoint(Vector3 position, out float sqrMagnitude)
            {
                PathPosition closestPosition = null;

                float sampleT = 1.0f / (float)kNumSamples;
                float pathT   = 0.0f;

                sqrMagnitude = 0.0f;

                for (int i = 0; i < kNumSamples; i++)
                {
                    PathPosition samplePos   = GetPoint(pathT);
                    Vector3      toSamplePos = samplePos._pathPosition - position;
                    float        posDistance = toSamplePos.sqrMagnitude;

                    if (closestPosition == null || posDistance < sqrMagnitude)
                    {
                        closestPosition = samplePos;
                        sqrMagnitude    = posDistance;
                    }

                    pathT += sampleT;
                }

                return(closestPosition);
            }
                public PathPosition GetPointAtDistance(float distance)
                {
                    PathPosition pathPosition = new PathPosition(_startPosition);
                    float        targetT      = _endPosition._pathT;

                    //If the path has waypoints, travel along them
                    for (int i = 0; i < _waypoints.Length; i++)
                    {
                        float waypointPathT  = pathPosition._path.GetPathT(_waypoints[i]._pathNode);
                        float distToWaypoint = pathPosition._path.GetDistanceBetween(pathPosition._pathT, waypointPathT);

                        pathPosition._path  = _waypoints[i]._path;
                        pathPosition._pathT = _waypoints[i]._path.GetPathT(_waypoints[i]._pathNode);

                        //if next waypoint is less than distance away, move towards this waypoint instead of path end
                        if (distance < distToWaypoint)
                        {
                            targetT = waypointPathT;
                            break;
                        }
                        else
                        {
                            distance -= distToWaypoint;
                            i++;
                        }
                    }

                    //Find new position
                    pathPosition = pathPosition._path.TravelPath(pathPosition._pathT, targetT, distance);

                    return(pathPosition);
                }
Example #13
0
    protected override JobHandle OnUpdate(JobHandle inputDeps)
    {
        float deltaTime = Time.DeltaTime;

        return(Entities.ForEach((Entity entity, DynamicBuffer <PathPosition> pathPositionBuffer, ref DeathComponent _dead, ref Translation translation, ref Rotation rot, ref PathFollow pathFollow, ref MovementComponent _move, ref IDComponent _id) =>
        {
            rot.Value = new quaternion(0, 0, 0, 1);
            if (pathFollow.pathIndex >= 0 && _move.isMoving && _dead.isDead == false)
            {
                // Has path to follow
                PathPosition pathPosition = pathPositionBuffer[pathFollow.pathIndex];
                float3 targetPosition = new float3((pathPosition.position.x + .5f) * 0.32f, (pathPosition.position.y + .5f) * 0.32f, 0);
                float3 moveDir = math.normalizesafe(targetPosition - translation.Value);
                translation.Value += moveDir * _move.speed * deltaTime;
                float3 myXy = translation.Value;
                //Debug.Log(_id.id);
                //GameController.Instance.SetPosition(_id.id, myXy.x, myXy.y);
                if (math.distance(translation.Value, targetPosition) < .1f)
                {
                    // Next waypoint
                    pathFollow.pathIndex--;
                }
            }
            else
            {
                _move.isMoving = false;
            }
        }).Schedule(inputDeps));
    }
Example #14
0
            public override PathPosition GetClosestPoint(Ray ray, out float distanceSqr)
            {
                PathPosition pathPos = GetPoint(0.0f);

                //TO DO! Should return distance between closest point on ray and position
                distanceSqr = (ray.origin - pathPos._pathPosition).sqrMagnitude;
                return(pathPos);
            }
Example #15
0
 public PathPosition(PathPosition other)
 {
     _path         = other._path;
     _pathT        = other._pathT;
     _pathNode     = other._pathNode;
     _pathPosition = other._pathPosition;
     _pathForward  = other._pathForward;
     _pathUp       = other._pathUp;
     _pathWidth    = other._pathWidth;
 }
Example #16
0
 public static void DrawPathPosGizmo(PathPosition position, Color color)
 {
     if (position != null)
     {
         Color origColor = UnityEditor.Handles.color;
         UnityEditor.Handles.color = color;
         UnityEditor.Handles.SphereHandleCap(2, position._pathPosition, Quaternion.identity, 0.1f, EventType.Repaint);
         UnityEditor.Handles.color = origColor;
     }
 }
Example #17
0
            public override void ProcessFrame(Playable playable, FrameData info, object playerData)
            {
                _trackBinding = playerData as Transform;

                if (_trackBinding == null)
                    return;

                if (_firstFrame)
                {
                    _defaultPosition = _trackBinding.position;
                    _defaultRotation = _trackBinding.rotation;
                    _firstFrame = false;
                }

                Vector3 position = _defaultPosition;
                Quaternion rotation  = _defaultRotation;

                int numInputs = playable.GetInputCount();

                for (int i = 0; i < numInputs; i++)
                {
                    ScriptPlayable<PathPlayableBehaviour> scriptPlayable = (ScriptPlayable<PathPlayableBehaviour>)playable.GetInput(i);
                    PathPlayableBehaviour inputBehaviour = scriptPlayable.GetBehaviour();

                    if (inputBehaviour != null && inputBehaviour._path != null)
                    {
                        float inputWeight = playable.GetInputWeight(i);

                        if (inputWeight > 0.0f)
                        {
                            TimelineClip clip = TimelineUtils.GetClip(_trackAsset, inputBehaviour._clipAsset);

                            if (clip != null)
                            {
                                double clipStart = clip.hasPreExtrapolation ? clip.extrapolatedStart : clip.start;
                                double clipDuration = clip.hasPreExtrapolation || clip.hasPostExtrapolation ? clip.extrapolatedDuration : clip.duration;

                                if (_director.time >= clipStart && _director.time <= clipStart + clipDuration)
                                {
                                    //To do handle loops etc

                                    double t = Mathf.Clamp01((float)(_director.time - clip.start) / (float)clip.duration);
                                    PathPosition pos = inputBehaviour._path.GetPoint((float)t);

                                    position = Vector3.Lerp(position, pos._pathPosition, inputWeight);
                                    rotation = Quaternion.Slerp(rotation, Quaternion.LookRotation(pos._pathForward, pos._pathUp), inputWeight);
                                }
                            }
                        }
                    }
                }

                _trackBinding.position = position;
                _trackBinding.rotation = rotation;
            }
Example #18
0
        /// <summary>
        /// Calculates a point on the BezierPath
        /// </summary>
        /// <param name="curveIndex">On which bezier curve, your point is ? (Starts from 0)</param>
        /// <param name="t">between 0 and 1 , specifies the point on the curve</param>
        /// <returns>A Vector3 of the specified point</returns>
        public Vector3 getLocalPosition(PathPosition position)
        {
            int nodeIndex = position.pointIndex;

            Vector3 p0 = controlPoints[nodeIndex];
            Vector3 p1 = controlPoints[nodeIndex + 1];
            Vector3 p2 = controlPoints[nodeIndex + 2];
            Vector3 p3 = controlPoints[nodeIndex + 3];

            return(CalculateBezierPoint(position.ratio, p0, p1, p2, p3));
        }
Example #19
0
        private Vector3 findDiffOnPath(PathPosition position)
        {
            int     index = position.pointIndex;
            Vector3 x     = controlPoints[index];
            Vector3 y     = controlPoints[index + 1];
            Vector3 z     = controlPoints[index + 2];
            Vector3 w     = controlPoints[index + 3];

            float t = position.ratio;

            return(t * t * (-3 * x + 9 * y - 9 * z + 3 * w) + t * (6 * x - 12 * y + 6 * z) + (-3 * x + 3 * y));
        }
Example #20
0
            public override PathPosition GetClosestPoint(Ray ray, out float distanceSqr)
            {
                PathPosition closestPosition = null;

                int   numLines  = _isLooping ? _nodes.Length : _nodes.Length - 1;
                float linePathT = 1.0f / (float)(numLines);

                distanceSqr = 0.0f;

                for (int i = 0; i < numLines; i++)
                {
                    //THIS is wrong - path line should be of fixed length!


                    //Get closest point on line
                    int   toNode   = (i < _nodes.Length - 1) ? i + 1 : 0;
                    float lineLerp = 0.0f;
                    float dist;

                    Vector3 fromNodePos = GetNodePosition(i);
                    Vector3 toNodePos   = GetNodePosition(toNode);

                    Vector3 closestPoint;
                    Vector3 pathLineDir = (toNodePos - fromNodePos).normalized;
                    if (MathUtils.ClosestPointsOnTwoLines(ray.origin, ray.direction, fromNodePos, pathLineDir, out _, out float closestPointPathLineT))
                    {
                        closestPoint = fromNodePos + pathLineDir * closestPointPathLineT;
                        Vector3 closestPointOnRay = ray.origin + ray.direction * closestPointPathLineT;
                        dist = (closestPointOnRay - closestPoint).sqrMagnitude;
                    }
                    //Lines are parallel - use start points of both lines
                    else
                    {
                        closestPoint = fromNodePos;
                        dist         = (closestPoint - ray.origin).sqrMagnitude;
                    }

                    if (closestPosition == null || dist < distanceSqr)
                    {
                        Vector3 startNodeUp = GetNodeUp(i, pathLineDir);
                        Vector3 endNodeUp   = GetNodeUp(toNode, pathLineDir);

                        closestPosition = new PathPosition(this, ((float)i + lineLerp) * linePathT, closestPoint,
                                                           pathLineDir,
                                                           Vector3.Lerp(startNodeUp, endNodeUp, lineLerp),
                                                           Mathf.Lerp(_nodes[i]._width, _nodes[toNode]._width, lineLerp));

                        distanceSqr = dist;
                    }
                }

                return(closestPosition);
            }
Example #21
0
    //Function for moving
    protected void Move()
    {
        //Entity data getting
        Entity        entity        = convertedEntityHolder.GetEntity();
        EntityManager entityManager = convertedEntityHolder.GetEntityManager();

        if (entityManager == null)
        {
            return;
        }
        PathFollowComponent          pathFollow         = entityManager.GetComponentData <PathFollowComponent>(entity);
        DynamicBuffer <PathPosition> pathPositionBuffer = entityManager.GetBuffer <PathPosition>(entity);

        //If still following path
        if (pathFollow.pathIndex >= 0)
        {
            //Get path position
            PathPosition pathPosition = pathPositionBuffer[pathFollow.pathIndex];

            //Get world position for each node
            float3 targetPosition = new float3(pathPosition.position.x, 0, pathPosition.position.y) + Vector3.one * new float3(gridCellSize, 0, gridCellSize) * 0.5f;
            //Calculate move direction
            float3 moveDir = math.normalizesafe(targetPosition - (float3)transform.position);

            //Move the ai to the next node
            transform.position += (Vector3)(moveDir * (3f + unitSpeed) * Time.deltaTime);
            //Check if within radius of next node
            if (math.distance(transform.position, targetPosition) < movementStopDist)
            {
                //If reached destination
                if (pathFollow.pathIndex == 0)
                {
                    hasCompletedCurrentTask = true;
                }
                //Next node
                pathFollow.pathIndex--;
                //Update pathfollow array
                entityManager.SetComponentData(entity, pathFollow);
            }
        }

        //If current task completed
        if (hasCompletedCurrentTask == true)
        {
            //Null pointer check for next task
            if (nextTask != null)
            {
                //Invoke next task
                nextTask.Invoke();
                nextTask = null;
            }
        }
    }
Example #22
0
            void OnEnable()
            {
                //lock transform
                PathPosition pathPosition = target as PathPosition;

                if (pathPosition.Path)
                {
                    SetHideFlags();
                }

                Undo.undoRedoPerformed += UpdatePosition;
            }
Example #23
0
            public void DebugDraw()
            {
                Color origColor = Handles.color;

                Handles.color = _pathColor;

                if (_nodes != null && _nodes.Length > 0)
                {
                    float sampleT = 1.0f / (float)(_debugDrawPointCount - 1);
                    float pathT   = 0.0f;

                    Vector3 prevPointA = Vector3.zero;
                    Vector3 prevPointB = Vector3.zero;

                    for (int i = 0; i < _debugDrawPointCount; i++)
                    {
                        PathPosition pos = GetPoint(pathT);

                        Vector3 pathRight = Vector3.Cross(pos._pathUp, pos._pathForward).normalized;
                        Vector3 pathHoriz = pathRight * (pos._pathWidth * 0.5f);

                        Vector3 pointA = pos._pathPosition - pathHoriz;
                        Vector3 pointB = pos._pathPosition + pathHoriz;

                        Handles.DrawLine(pointA, pointB);

                        if (i > 0)
                        {
                            Handles.DrawLine(prevPointA, pointA);
                            Handles.DrawLine(prevPointB, pointB);
                        }

                        prevPointA = pointA;
                        prevPointB = pointB;

                        pathT += sampleT;
                    }

                    //Draw node up directions
                    for (int i = 0; i < _nodes.Length; i++)
                    {
                        Quaternion nodeUpRotation = Quaternion.FromToRotation(Vector3.up, _nodes[i]._up);
                        Vector3    nodePos        = GetNodePosition(i);
                        Vector3    controlPos     = nodePos + nodeUpRotation * (Vector3.up * _nodes[i]._width);

                        Handles.DrawLine(nodePos, controlPos);
                        Handles.SphereHandleCap(0, controlPos, Quaternion.identity, _nodes[i]._width * 0.166f, EventType.Repaint);
                    }

                    Handles.color = origColor;
                }
            }
Example #24
0
        /// <summary>
        /// Parses the root node of an XMP Path, checks if namespace and prefix fit together
        /// and resolve the property to the base property if it is an alias.
        /// </summary>
        /// <param name="schemaNs">the root namespace</param>
        /// <param name="pos">the parsing position helper</param>
        /// <param name="expandedXPath">the path to contribute to</param>
        /// <exception cref="XmpException">If the path is not valid.</exception>
        private static void ParseRootNode(string schemaNs, PathPosition pos, XmpPath expandedXPath)
        {
            while (pos.StepEnd < pos.Path.Length && "/[*".IndexOf(pos.Path[pos.StepEnd]) < 0)
            {
                pos.StepEnd++;
            }

            if (pos.StepEnd == pos.StepBegin)
            {
                throw new XmpException("Empty initial XMPPath step", XmpErrorCode.BadXPath);
            }

            var rootProp  = VerifyXPathRoot(schemaNs, pos.Path.Substring(pos.StepBegin, pos.StepEnd - pos.StepBegin));
            var aliasInfo = XmpMetaFactory.SchemaRegistry.FindAlias(rootProp);

            if (aliasInfo == null)
            {
                // add schema xpath step
                expandedXPath.Add(new XmpPathSegment(schemaNs, XmpPathStepType.SchemaNode));
                var rootStep = new XmpPathSegment(rootProp, XmpPathStepType.StructFieldStep);
                expandedXPath.Add(rootStep);
                return;
            }

            // add schema xpath step and base step of alias
            expandedXPath.Add(new XmpPathSegment(aliasInfo.Namespace, XmpPathStepType.SchemaNode));
            expandedXPath.Add(new XmpPathSegment(VerifyXPathRoot(aliasInfo.Namespace, aliasInfo.PropName), XmpPathStepType.StructFieldStep)
            {
                IsAlias   = true,
                AliasForm = aliasInfo.AliasForm.GetOptions()
            });

            if (aliasInfo.AliasForm.IsArrayAltText)
            {
                expandedXPath.Add(new XmpPathSegment("[?xml:lang='x-default']", XmpPathStepType.QualSelectorStep)
                {
                    IsAlias   = true,
                    AliasForm = aliasInfo.AliasForm.GetOptions()
                });
            }
            else if (aliasInfo.AliasForm.IsArray)
            {
                expandedXPath.Add(new XmpPathSegment("[1]", XmpPathStepType.ArrayIndexStep)
                {
                    IsAlias   = true,
                    AliasForm = aliasInfo.AliasForm.GetOptions()
                });
            }
        }
Example #25
0
            public override PathPosition TravelPath(float fromT, float toT, float distance)
            {
                ClampPathT(ref fromT);
                ClampPathT(ref toT);

                Direction1D direction = toT >= fromT ? Direction1D.Forwards : Direction1D.Backwards;

                float sampleT = (direction == Direction1D.Forwards ? 1.0f : -1.0f) / (float)kNumSamples;

                PathPosition pathPosition = GetPoint(fromT);
                PathPosition samplePos    = GetPoint(pathPosition._pathT + sampleT);

                while (true)
                {
                    Vector3 toSamplePos = samplePos._pathPosition - pathPosition._pathPosition;
                    float   sampleDist  = toSamplePos.magnitude;

                    if (distance <= sampleDist || sampleDist == 0.0f)
                    {
                        float distLerp = sampleDist <= 0f ? 0.0f : (distance / sampleDist);
                        pathPosition._pathPosition = pathPosition._pathPosition + (toSamplePos * distLerp);
                        pathPosition._pathForward  = Vector3.Lerp(pathPosition._pathForward, samplePos._pathForward, distLerp);
                        pathPosition._pathUp       = Vector3.Lerp(pathPosition._pathUp, samplePos._pathUp, distLerp);
                        pathPosition._pathT        = pathPosition._pathT + (sampleT * distLerp);
                        pathPosition._pathWidth    = Mathf.Lerp(pathPosition._pathWidth, samplePos._pathWidth, distLerp);
                        break;
                    }
                    else
                    {
                        distance                  -= sampleDist;
                        pathPosition._pathT       += sampleT;
                        pathPosition._pathPosition = samplePos._pathPosition;
                        pathPosition._pathForward  = samplePos._pathForward;
                        pathPosition._pathUp       = samplePos._pathUp;
                        pathPosition._pathWidth    = samplePos._pathWidth;
                        samplePos                  = GetPoint(pathPosition._pathT + sampleT);
                    }
                }

                //Face opposite direction if traveling backwards
                if (direction == Direction1D.Backwards)
                {
                    pathPosition._pathForward = Quaternion.AngleAxis(180f, pathPosition._pathUp) * pathPosition._pathForward;
                }

                return(pathPosition);
            }
Example #26
0
            void SetHideFlags()
            {
                PathPosition pathPosition = target as PathPosition;

                //don't hide transform if there is no path yet
                if (!pathPosition.Path)
                {
                    return;
                }

                if (SHF != null)
                {
                    SHF.Undo();
                }
                SHF = new UnityCommands.SetHideFlags(pathPosition.transform, HideFlags.NotEditable);
                SHF.Execute();
            }
    public void AddPickup(float relativeDistance, PathPosition pathPos)
    {
        GameObject pickup = Instantiate <GameObject>(pickupPrefab, transform);

        pickup.GetComponent <BelongToPath>().position = pathPos;
        pickup.transform.localPosition = DistanceToPosition(relativeDistance) + Vector3.up * 0.5f;
        Vector3 dir = DistanceToDirection(relativeDistance);

        if (pathPos == PathPosition.LEFT)
        {
            pickup.transform.localPosition += Quaternion.Euler(0, -90, 0) * dir * rowOffset;
        }
        else if (pathPos == PathPosition.RIGHT)
        {
            pickup.transform.localPosition += Quaternion.Euler(0, 90, 0) * dir * rowOffset;
        }
    }
Example #28
0
        /// <summary>Parses a struct segment</summary>
        /// <param name="pos">the current position in the path</param>
        /// <returns>Retusn the segment or an errror</returns>
        /// <exception cref="XmpException">If the sement is empty</exception>
        private static XmpPathSegment ParseStructSegment(PathPosition pos)
        {
            pos.NameStart = pos.StepBegin;
            while (pos.StepEnd < pos.Path.Length && "/[*".IndexOf(pos.Path[pos.StepEnd]) < 0)
            {
                pos.StepEnd++;
            }

            pos.NameEnd = pos.StepEnd;

            if (pos.StepEnd == pos.StepBegin)
            {
                throw new XmpException("Empty XMPPath segment", XmpErrorCode.BadXPath);
            }

            // ! Touch up later, also changing '@' to '?'.
            return(new XmpPathSegment(pos.Path.Substring(pos.StepBegin, pos.StepEnd - pos.StepBegin), XmpPath.StructFieldStep));
        }
Example #29
0
    public void CreateEntities(int count)
    {
        var settings = GameObjectConversionSettings.FromWorld(World.DefaultGameObjectInjectionWorld, blobAssetStore);
        var myPrefab = GameObjectConversionUtility.ConvertGameObjectHierarchy(koboltPrefab, settings);

        for (int i = 0; i < count; i++)
        {
            var   instance = entityManager.Instantiate(myPrefab);
            float xValueF  = UnityEngine.Random.Range(0, 10f);
            float yValueF  = UnityEngine.Random.Range(0f, 10f);
            int   xValueI  = (int)Mathf.Round(xValueF) * (int)Mathf.Round(PathfindingGridSetup.Instance.pathfindingGrid.GetCellSize());
            int   yValueI  = (int)Mathf.Round(yValueF) * (int)Mathf.Round(PathfindingGridSetup.Instance.pathfindingGrid.GetCellSize());
            entityManager.SetComponentData(instance, new Translation()
            {
                Value = new float3(new float3(xValueF, yValueF, -0.1f))
            });
            entityManager.AddComponentData(instance, new IDComponent()
            {
                id = 1
            });
            entityManager.AddComponentData(instance, new HealthComponent()
            {
                maxHealth = 100, health = 100
            });
            entityManager.AddComponentData(instance, new MovementComponent()
            {
                isMoving = false, speed = 1.2f
            });
            entityManager.AddComponentData(instance, new PathFollow()
            {
            });
            entityManager.AddComponentData(instance, new Selected()
            {
                isSelected = false
            });
            entityManager.AddBuffer <PathPosition>(instance);
            PathPosition someBufferElement          = new PathPosition();
            DynamicBuffer <PathPosition> someBuffer = entityManager.GetBuffer <PathPosition>(instance);
            someBufferElement.position = new int2(xValueI, yValueI);
            someBuffer.Add(someBufferElement);
            someBufferElement.position = new int2(xValueI, yValueI);
            someBuffer.Add(someBufferElement);
        }
    }
Example #30
0
        public void AddMinionSpecificPosition(Minion minion, PathPosition position)
        {
            try
            {
                toBeAddedMinions.Add(minion);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.StackTrace + " : " + e.Message);
            }

            if (minion.position == null)
            {
                minion.position = new MinionPosition();
            }

            minion.position.board        = this;
            minion.position.pathPosition = new PathPosition(position.pointIndex, position.ratio);
        }
Example #31
0
        /// <param name="path"/>
        /// <param name="pos"/>
        /// <exception cref="XmpException"/>
        private static void SkipPathDelimiter(string path, PathPosition pos)
        {
            if (path[pos.StepBegin] == '/')
            {
                // skip slash
                pos.StepBegin++;

                if (pos.StepBegin >= path.Length)
                    throw new XmpException("Empty XMPPath segment", XmpErrorCode.BadXPath);
            }

            if (path[pos.StepBegin] == '*')
            {
                // skip asterisk
                pos.StepBegin++;
                if (pos.StepBegin >= path.Length || path[pos.StepBegin] != '[')
                    throw new XmpException("Missing '[' after '*'", XmpErrorCode.BadXPath);
            }
        }
Example #32
0
        /// <summary>Parses a struct segment</summary>
        /// <param name="pos">the current position in the path</param>
        /// <returns>Retusn the segment or an errror</returns>
        /// <exception cref="XmpException">If the sement is empty</exception>
        private static XmpPathSegment ParseStructSegment(PathPosition pos)
        {
            pos.NameStart = pos.StepBegin;
            while (pos.StepEnd < pos.Path.Length && "/[*".IndexOf(pos.Path[pos.StepEnd]) < 0)
                pos.StepEnd++;

            pos.NameEnd = pos.StepEnd;

            if (pos.StepEnd == pos.StepBegin)
                throw new XmpException("Empty XMPPath segment", XmpErrorCode.BadXPath);

            // ! Touch up later, also changing '@' to '?'.
            return new XmpPathSegment(pos.Path.Substring (pos.StepBegin, pos.StepEnd - pos.StepBegin), XmpPath.StructFieldStep);
        }
Example #33
0
        /// <summary>Parses an array index segment.</summary>
        /// <param name="pos">the xmp path</param>
        /// <returns>Returns the segment or an error</returns>
        /// <exception cref="XmpException">thrown on xmp path errors</exception>
        private static XmpPathSegment ParseIndexSegment(PathPosition pos)
        {
            XmpPathSegment segment;
            pos.StepEnd++;

            // Look at the character after the leading '['.
            if ('0' <= pos.Path[pos.StepEnd] && pos.Path[pos.StepEnd] <= '9')
            {
                // A numeric (decimal integer) array index.
                while (pos.StepEnd < pos.Path.Length && '0' <= pos.Path[pos.StepEnd] && pos.Path[pos.StepEnd] <= '9')
                    pos.StepEnd++;

                segment = new XmpPathSegment(null, XmpPath.ArrayIndexStep);
            }
            else
            {
                // Could be "[last()]" or one of the selector forms. Find the ']' or '='.
                while (pos.StepEnd < pos.Path.Length && pos.Path[pos.StepEnd] != ']' && pos.Path[pos.StepEnd] != '=')
                    pos.StepEnd++;

                if (pos.StepEnd >= pos.Path.Length)
                    throw new XmpException("Missing ']' or '=' for array index", XmpErrorCode.BadXPath);

                if (pos.Path[pos.StepEnd] == ']')
                {
                    if (!"[last()".Equals(pos.Path.Substring(pos.StepBegin, pos.StepEnd - pos.StepBegin)))
                        throw new XmpException("Invalid non-numeric array index", XmpErrorCode.BadXPath);

                    segment = new XmpPathSegment(null, XmpPath.ArrayLastStep);
                }
                else
                {
                    pos.NameStart = pos.StepBegin + 1;
                    pos.NameEnd = pos.StepEnd;
                    pos.StepEnd++;

                    // Absorb the '=', remember the quote.
                    var quote = pos.Path[pos.StepEnd];
                    if (quote != '\'' && quote != '"')
                        throw new XmpException("Invalid quote in array selector", XmpErrorCode.BadXPath);

                    pos.StepEnd++;

                    // Absorb the leading quote.
                    while (pos.StepEnd < pos.Path.Length)
                    {
                        if (pos.Path[pos.StepEnd] == quote)
                        {
                            // check for escaped quote
                            if (pos.StepEnd + 1 >= pos.Path.Length || pos.Path[pos.StepEnd + 1] != quote)
                                break;

                            pos.StepEnd++;
                        }
                        pos.StepEnd++;
                    }

                    if (pos.StepEnd >= pos.Path.Length)
                        throw new XmpException("No terminating quote for array selector", XmpErrorCode.BadXPath);

                    pos.StepEnd++;

                    // Absorb the trailing quote.
                    // ! Touch up later, also changing '@' to '?'.
                    segment = new XmpPathSegment(null, XmpPath.FieldSelectorStep);
                }
            }

            if (pos.StepEnd >= pos.Path.Length || pos.Path[pos.StepEnd] != ']')
                throw new XmpException("Missing ']' for array index", XmpErrorCode.BadXPath);

            pos.StepEnd++;
            segment.Name = pos.Path.Substring (pos.StepBegin, pos.StepEnd - pos.StepBegin);

            return segment;
        }
Example #34
0
        /// <summary>
        /// Parses the root node of an XMP Path, checks if namespace and prefix fit together
        /// and resolve the property to the base property if it is an alias.
        /// </summary>
        /// <param name="schemaNs">the root namespace</param>
        /// <param name="pos">the parsing position helper</param>
        /// <param name="expandedXPath">the path to contribute to</param>
        /// <exception cref="XmpException">If the path is not valid.</exception>
        private static void ParseRootNode(string schemaNs, PathPosition pos, XmpPath expandedXPath)
        {
            while (pos.StepEnd < pos.Path.Length && "/[*".IndexOf(pos.Path[pos.StepEnd]) < 0)
                pos.StepEnd++;

            if (pos.StepEnd == pos.StepBegin)
                throw new XmpException("Empty initial XMPPath step", XmpErrorCode.BadXPath);

            var rootProp = VerifyXPathRoot(schemaNs, pos.Path.Substring (pos.StepBegin, pos.StepEnd - pos.StepBegin));
            var aliasInfo = XmpMetaFactory.SchemaRegistry.FindAlias(rootProp);

            if (aliasInfo == null)
            {
                // add schema xpath step
                expandedXPath.Add(new XmpPathSegment(schemaNs, XmpPath.SchemaNode));
                var rootStep = new XmpPathSegment(rootProp, XmpPath.StructFieldStep);
                expandedXPath.Add(rootStep);
            }
            else
            {
                // add schema xpath step and base step of alias
                expandedXPath.Add(new XmpPathSegment(aliasInfo.Namespace, XmpPath.SchemaNode));
                var rootStep = new XmpPathSegment(VerifyXPathRoot(aliasInfo.Namespace, aliasInfo.PropName), XmpPath.StructFieldStep);
                rootStep.IsAlias = true;
                rootStep.AliasForm = aliasInfo.AliasForm.GetOptions();
                expandedXPath.Add(rootStep);

                if (aliasInfo.AliasForm.IsArrayAltText)
                {
                    var qualSelectorStep = new XmpPathSegment("[?xml:lang='x-default']", XmpPath.QualSelectorStep);
                    qualSelectorStep.IsAlias = true;
                    qualSelectorStep.AliasForm = aliasInfo.AliasForm.GetOptions();
                    expandedXPath.Add(qualSelectorStep);
                }
                else if (aliasInfo.AliasForm.IsArray)
                {
                    var indexStep = new XmpPathSegment("[1]", XmpPath.ArrayIndexStep);
                    indexStep.IsAlias = true;
                    indexStep.AliasForm = aliasInfo.AliasForm.GetOptions();
                    expandedXPath.Add(indexStep);
                }
            }
        }
Example #35
0
        /// <summary>
        /// Split an XMPPath expression apart at the conceptual steps, adding the
        /// root namespace prefix to the first property component.
        /// </summary>
        /// <remarks>
        /// The schema URI is put in the first (0th) slot in the expanded XMPPath.
        /// Check if the top level component is an alias, but don't resolve it.
        /// <para />
        /// In the most verbose case steps are separated by '/', and each step can be
        /// of these forms:
        /// <list>
        ///   <item>
        ///     <term>prefix:name</term>
        ///     <description>A top level property or struct field.</description>
        ///   </item>
        ///   <item>
        ///     <term>[index]</term>
        ///     <description>An element of an array.</description>
        ///   </item>
        ///   <item>
        ///     <term>[last()]</term>
        ///     <description>The last element of an array.</description>
        ///   </item>
        ///   <item>
        ///     <term>[fieldName=&quot;value&quot;]</term>
        ///     <description>An element in an array of structs, chosen by a field value.</description>
        ///   </item>
        ///   <item>
        ///     <term>[@xml:lang=&quot;value&quot;]</term>
        ///     <description>An element in an alt-text array, chosen by the xml:lang qualifier.</description>
        ///   </item>
        ///   <item>
        ///     <term>[?qualName=&quot;value&quot;]</term>
        ///     <description>An element in an array, chosen by a qualifier value.</description>
        ///   </item>
        ///   <item>
        ///     <term>@xml:lang</term>
        ///     <description>An xml:lang qualifier.</description>
        ///   </item>
        ///   <item>
        ///     <term>?qualName</term>
        ///     <description>A general qualifier.</description>
        ///   </item>
        /// </list>
        /// <para />
        /// The logic is complicated though by shorthand for arrays, the separating
        /// '/' and leading '*' are optional. These are all equivalent: array/*[2]
        /// array/[2] array*[2] array[2] All of these are broken into the 2 steps
        /// "array" and "[2]".
        /// <para />
        /// The value portion in the array selector forms is a string quoted by '''
        /// or '"'. The value may contain any character including a doubled quoting
        /// character. The value may be empty.
        /// <para />
        /// The syntax isn't checked, but an XML name begins with a letter or '_',
        /// and contains letters, digits, '.', '-', '_', and a bunch of special
        /// non-ASCII Unicode characters. An XML qualified name is a pair of names
        /// separated by a colon.
        /// </remarks>
        /// <param name="schemaNs">schema namespace</param>
        /// <param name="path">property name</param>
        /// <returns>Returns the expandet XMPPath.</returns>
        /// <exception cref="XmpException">Thrown if the format is not correct somehow.</exception>
        public static XmpPath ExpandXPath(string schemaNs, string path)
        {
            if (schemaNs == null || path == null)
                throw new XmpException("Parameter must not be null", XmpErrorCode.BadParam);

            var expandedXPath = new XmpPath();
            var pos = new PathPosition { Path = path };

            // Pull out the first component and do some special processing on it: add the schema
            // namespace prefix and and see if it is an alias. The start must be a "qualName".
            ParseRootNode(schemaNs, pos, expandedXPath);

            // Now continue to process the rest of the XMPPath string.
            while (pos.StepEnd < path.Length)
            {
                pos.StepBegin = pos.StepEnd;

                SkipPathDelimiter(path, pos);

                pos.StepEnd = pos.StepBegin;
                var segment = path[pos.StepBegin] != '['
                    ? ParseStructSegment(pos)
                    : ParseIndexSegment(pos);

                if (segment.Kind == XmpPath.StructFieldStep)
                {
                    if (segment.Name[0] == '@')
                    {
                        segment.Name = "?" + segment.Name.Substring (1);
                        if (!"?xml:lang".Equals(segment.Name))
                            throw new XmpException("Only xml:lang allowed with '@'", XmpErrorCode.BadXPath);
                    }

                    if (segment.Name[0] == '?')
                    {
                        pos.NameStart++;
                        segment.Kind = XmpPath.QualifierStep;
                    }

                    VerifyQualName(pos.Path.Substring (pos.NameStart, pos.NameEnd - pos.NameStart));
                }
                else if (segment.Kind == XmpPath.FieldSelectorStep)
                {
                    if (segment.Name[1] == '@')
                    {
                        segment.Name = "[?" + segment.Name.Substring (2);

                        if (!segment.Name.StartsWith("[?xml:lang="))
                            throw new XmpException("Only xml:lang allowed with '@'", XmpErrorCode.BadXPath);
                    }

                    if (segment.Name[1] == '?')
                    {
                        pos.NameStart++;
                        segment.Kind = XmpPath.QualSelectorStep;
                        VerifyQualName(pos.Path.Substring (pos.NameStart, pos.NameEnd - pos.NameStart));
                    }
                }

                expandedXPath.Add(segment);
            }

            return expandedXPath;
        }