コード例 #1
0
        public void Execute()
        {
            DynamicBuffer <PathPosition> pathPositionBuffer = pathPositionBufferFromEntity[entity];

            pathPositionBuffer.Clear();
            DestinationComponent destination = destinationComponentDataFromEntity[entity];
            int      endNodeIndex            = CalculateIndex(destination.endPosition.x, destination.endPosition.y, gridSize.x);
            PathNode endNode = pathNodeArray[endNodeIndex];

            if (endNode.cameFromNodeIndex == -1)
            {
                //Debug.Log("Didn't find a path!");
                pathFollowComponentDataFromEntity[entity] = new PathFollow {
                    pathIndex = -1
                };
            }
            else
            {
                // Found a path
                CalculatePath(pathNodeArray, endNode, pathPositionBuffer);
                pathFollowComponentDataFromEntity[entity] = new PathFollow {
                    pathIndex = pathPositionBuffer.Length - 1
                };
            }
        }
コード例 #2
0
            public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
            {
                NativeArray <PlayerMovementData>             playerMovements    = chunk.GetNativeArray(this.playerMovementType);
                BufferAccessor <PlayerNavigationNodeElement> nodeBufferAccessor = chunk.GetBufferAccessor(this.pathNodeBufferType);

                for (int ci = 0, cn = chunk.Count; ci < cn; ci++)
                {
                    PlayerMovementData playerMovement = playerMovements[ci];
                    DynamicBuffer <PlayerNavigationNodeElement> pathNodeBuffer = nodeBufferAccessor[ci];

                    // Set path if found
                    if (pathFound[0] != 0)
                    {
                        // Copy path to player's path node buffer

                        pathNodeBuffer.Clear();

                        for (int i = 0, n = pathFound[1]; i < n; i++)
                        {
                            float3 worldPosition = navigationGrid[0].GridToWorldPosition(pathNodes[i].XCoord, pathNodes[i].YCoord);
                            pathNodeBuffer.Add(new PlayerNavigationNode(pathNodes[i].XCoord, pathNodes[i].YCoord, pathNodes[i].Index, worldPosition));
                        }

                        // Start player movement
                        playerMovement.StartMovement(pathNodeBuffer[0]);

                        // Apply changes
                        playerMovements[ci] = playerMovement;
                    }
                }
            }
コード例 #3
0
        //Set path indexes
        public void Execute()
        {
            DynamicBuffer <PathPosition> pathPositionBuffer = pathPositionBufferFromEntity[entity];

            pathPositionBuffer.Clear();

            PathfindingComponentData pathfindingComponentData = pathfindingComponentDataFromEntity[entity];
            int      endNodeIndex = CalculateIndex(pathfindingComponentData.endPosition.x, pathfindingComponentData.endPosition.y, gridSize.x);
            PathNode endNode      = pathNodeArray[endNodeIndex];

            if (endNode.cameFromNodeIndex == -1)
            {
                //Did not find path
                pathFollowComponentDataFromEntity[entity] = new PathFollowComponent {
                    pathIndex = -1
                };
            }
            else
            {
                CalculatePath(pathNodeArray, endNode, pathPositionBuffer);
                pathFollowComponentDataFromEntity[entity] = new PathFollowComponent {
                    pathIndex = pathPositionBuffer.Length - 1
                };
            }
        }
コード例 #4
0
        void CreatePath(DynamicBuffer <PathPositions> path, NativeArray <int> cameFrom, int endIndex, int startIndex, float2 endPos,
                        [ReadOnly] NativeArray <Waypoint> waypoints)
        {
            //Clear path
            path.Clear();

            //Build path
            int currentIndex = endIndex;
            int maxIteration = 20;

            path.Add(new PathPositions()
            {
                Value = endPos
            });

            while (--maxIteration > 0 && currentIndex != startIndex)
            {
                path.Add(new PathPositions()
                {
                    Value = waypoints[currentIndex].position
                });
                currentIndex = cameFrom[currentIndex];
            }

            path.Add(new PathPositions()
            {
                Value = waypoints[startIndex].position
            });
        }
        private void UpdateCollisionEvents(NativeList <StatefulCollisionEvent> collisionEvents,
                                           DynamicBuffer <StatefulCollisionEvent> collisionEventBuffer)
        {
            collisionEvents.Sort();

            var previousFrameCollisionEvents = new NativeList <StatefulCollisionEvent>(collisionEventBuffer.Length, Allocator.Temp);

            for (int i = 0; i < collisionEventBuffer.Length; i++)
            {
                var collisionEvent = collisionEventBuffer[i];
                if (collisionEvent.CollidingState != EventCollidingState.Exit)
                {
                    previousFrameCollisionEvents.Add(collisionEvent);
                }
            }

            var eventsWithState = new NativeList <StatefulCollisionEvent>(collisionEvents.Length, Allocator.Temp);

            CollisionEventConversionSystem.UpdateCollisionEventState(previousFrameCollisionEvents, collisionEvents, eventsWithState);

            collisionEventBuffer.Clear();

            for (int i = 0; i < eventsWithState.Length; i++)
            {
                collisionEventBuffer.Add(eventsWithState[i]);
            }
        }
コード例 #6
0
        public unsafe PathQueryState FindPath(float2 from, float2 to, float radius, DynamicBuffer <PathSegmentElement> segments, DynamicBuffer <TriangleElement> triangleIds, Navmesh.Navmesh *navmesh, out int cost)
        {
            triangleIds.Clear();
            var result = _astar.Search(from, to, navmesh, _channel, radius, triangleIds, out cost);

            if (result == PathQueryState.PathFound)
            {
                _funnel.GetPath(_channel, from, to, radius, _path);
                triangleIds.Reinterpret <int>().AsNativeArray().Sort();
            }

            for (int i = 0; i < _path.Count; i++)
            {
                var w = _path.FromFront(i);
                Assert.IsTrue(!float.IsNaN(w.To.x) && !float.IsNaN(w.To.y));

                segments.Add(new PathSegmentElement
                {
                    Corner = i > 0 ? _path.FromFront(i - 1).Vertex : w.From,
                    From   = w.From,
                    To     = w.To
                });
            }

            _astar.Clear();
            _channel.Clear();
            _funnel.Clear();
            _path.Clear();
            return(result);
        }
コード例 #7
0
        /// <summary>
        /// set the buffer elements of the given aBuffer
        /// </summary>
        /// <param name="entityManager"></param>
        /// <param name="entity"></param>
        /// <param name="bBuffer"></param>
        public static void SetBuffer(EntityManager entityManager, Entity entity, DynamicBuffer <ProceduralGenerationSpawnDataBufferElement> bBuffer)
        {
            DynamicBuffer <ProceduralGenerationSpawnDataBufferElement> aBuffer = GetBuffer(entityManager, entity);

            aBuffer.Clear();
            aBuffer.CopyFrom(bBuffer);
        }
コード例 #8
0
        public void Execute()
        {
            DynamicBuffer <PathPosition> pathPositionBuffer = pathPositionBufferFromEntity[entity];

            pathPositionBuffer.Clear();

            PathfindingParams pathfindingParams = pathfindingParamsComponentDataFromEntity[entity];
            int endNodeIndex = CalculateIndex(pathfindingParams.endPosition.x, pathfindingParams.endPosition.y, gridSize.x);

            // Выход за пределы карты
            if (endNodeIndex >= gridSize.x * gridSize.y && endNodeIndex >= 0)
            {
                pathFollowComponentDataFromEntity[entity] = new PathFollow {
                    pathIndex = -1
                };
                return;
            }
            PathNode endNode = pathNodeArray[endNodeIndex];

            if (endNode.cameFromNodeIndex == -1)
            {
                // Didn't find a path!
                pathFollowComponentDataFromEntity[entity] = new PathFollow {
                    pathIndex = -1
                };
            }
            else
            {
                // Found a path
                CalculatePath(pathNodeArray, endNode, pathPositionBuffer);
                pathFollowComponentDataFromEntity[entity] = new PathFollow {
                    pathIndex = pathPositionBuffer.Length - 1
                };
            }
        }
コード例 #9
0
        public void Execute()
        {
            DynamicBuffer <CollisionData>      collisionsBuffer      = CollisionDatasBufferWithEntity.GetDynamicBuffer();
            DynamicBuffer <CollisionEnterData> collisionEntersBuffer = CollisionEnterDatasBufferWithEntity.GetDynamicBuffer();
            DynamicBuffer <CollisionExitData>  collisionExitsBuffer  = CollisionExitDatasBufferWithEntity.GetDynamicBuffer();
            NativeArray <CollisionData>        oldCollisions         = collisionsBuffer.ToNativeArray(Allocator.Temp);

            collisionsBuffer.Clear();
            collisionEntersBuffer.Clear();
            collisionExitsBuffer.Clear();

            // gather new collisions
            for (int i = 0; i < Colliders.Length; i++)
            {
                for (int j = i + 1; j < Colliders.Length; j++)
                {
                    if (Intersects(
                            Colliders[i], Translations[i],
                            Colliders[j], Translations[j]))
                    {
                        // collision detected!
                        collisionsBuffer.Add(new CollisionData()
                        {
                            EntityA = Entities[i],
                            EntityB = Entities[j]
                        });
                    }
                }
            }

            // find new and old collision datas (NB: THIS COULD BE OPTIMIZED BY SORTING COLLISIONS)
            NativeArray <CollisionData> newCollisions = collisionsBuffer.AsNativeArray();

            for (int i = 0; i < oldCollisions.Length; i++)
            {
                if (!newCollisions.Contains(oldCollisions[i]))
                {
                    collisionExitsBuffer.Add(new CollisionExitData()
                    {
                        EntityA = oldCollisions[i].EntityA,
                        EntityB = oldCollisions[i].EntityB,
                    });
                }
            }

            for (int i = 0; i < newCollisions.Length; i++)
            {
                if (!oldCollisions.Contains(newCollisions[i]))
                {
                    collisionEntersBuffer.Add(new CollisionEnterData()
                    {
                        EntityA = newCollisions[i].EntityA,
                        EntityB = newCollisions[i].EntityB,
                    });
                }
            }


            oldCollisions.Dispose();
        }
コード例 #10
0
        public Entity Build()
        {
            if (!EntityManager.Exists(_entity))
            {
                _entity = EntityManager.CreateEntity();
            }

            if (EntityManager.HasComponent <Sequence>(_entity))
            {
                EntityManager.SetComponentData(_entity, new Sequence
                {
                    Index = 0,
                    Size  = _commands.Count
                });
            }
            else
            {
                EntityManager.AddComponentData(_entity, new Sequence
                {
                    Index = 0,
                    Size  = _commands.Count
                });
            }

//            if(EntityManager.GetBuffer<>())
            DynamicBuffer <SequenceCommand> buffer = EntityManager.AddBuffer <SequenceCommand>(_entity);

            buffer.Clear();
            foreach (SequenceCommand cmd in _commands)
            {
                buffer.Add(cmd);
            }
            return(_entity);
        }
コード例 #11
0
 public void Clear()
 {
     m_Vertices.Clear();
     m_Triangles.Clear();
     m_Normals.Clear();
     m_UVs.Clear();
 }
コード例 #12
0
        /// <summary>
        /// set the buffer elements of the given aBuffer
        /// </summary>
        /// <param name="entityManager"></param>
        /// <param name="entity"></param>
        /// <param name="bBuffer"></param>
        public static void SetBuffer(EntityManager entityManager, Entity entity, DynamicBuffer <EntityPrefabBufferElement> bBuffer)
        {
            DynamicBuffer <EntityPrefabBufferElement> aBuffer = GetBuffer(entityManager, entity);

            aBuffer.Clear();
            aBuffer.CopyFrom(bBuffer);
        }
コード例 #13
0
        private void Initialize(ref DungeonComponent dungeon, ref DynamicBuffer <EntityBufferElement> cellsBuffer)
        {
            cellsBuffer.Clear();
            cellsBuffer.ResizeUninitialized(dungeon.SizeInCell.x * dungeon.SizeInCell.y);

            float cellWidth = GameManager.Instance().CellScale;

            for (int y = 0; y < dungeon.SizeInCell.y; y++)
            {
                for (int x = 0; x < dungeon.SizeInCell.x; x++)
                {
                    float3 pos = float3.zero;
                    pos.x = cellWidth * (0.5f + x);
                    pos.y = cellWidth * (0.5f + y);

                    Entity entity = PostUpdateCommands.CreateEntity(GameManager.Instance().CellArchetype);
                    PostUpdateCommands.SetComponent(entity, new CellComponent
                    {
                        Coordinate = new int2(x, y),
                        IsWall     = true,
                    });
                    PostUpdateCommands.SetComponent(entity, new Translation
                    {
                        Value = pos,
                    });
                    PostUpdateCommands.SetComponent(entity, new Scale()
                    {
                        Value = cellWidth,
                    });
                }
            }
        }
        private void UpdateTriggerEvents(NativeList <StatefulTriggerEvent> triggerEvents,
                                         DynamicBuffer <StatefulTriggerEvent> triggerEventBuffer)
        {
            triggerEvents.Sort();

            var previousFrameTriggerEvents = new NativeList <StatefulTriggerEvent>(triggerEventBuffer.Length, Allocator.Temp);

            for (int i = 0; i < triggerEventBuffer.Length; i++)
            {
                var triggerEvent = triggerEventBuffer[i];
                if (triggerEvent.State != EventOverlapState.Exit)
                {
                    previousFrameTriggerEvents.Add(triggerEvent);
                }
            }

            var eventsWithState = new NativeList <StatefulTriggerEvent>(triggerEvents.Length, Allocator.Temp);

            TriggerEventConversionSystem.UpdateTriggerEventState(previousFrameTriggerEvents, triggerEvents, eventsWithState);

            triggerEventBuffer.Clear();

            for (int i = 0; i < eventsWithState.Length; i++)
            {
                triggerEventBuffer.Add(eventsWithState[i]);
            }
        }
コード例 #15
0
        public void Execute(Entity e, int index, DynamicBuffer <CollisionInfoComp> cb, ref BoubleComp b, ref CollisionInfoSettingComp setting)
        {
            // var b = bubs[e];
            if (cb.Length > 0)
            {
                for (int i = 0; i < cb.Length; i++)
                {
                    ci = cb[i];
                    if (bubs.ContainsKey(ci.Opponent) == false || ci.Opponent == prefabEntity)
                    {
                        continue;
                    }

                    if (ci.OpponentType == OpponentType.Bouble)
                    {
                        op = bubs[ci.Opponent];

                        if (b.gravRadius == op.gravRadius)
                        {
                            // the tie breaker is Entity index
                            b.gravRadius += (b.entity.Index > op.entity.Index) ? 0.0001f: -0.0001f;
                        }

                        if (b.gravRadius > op.gravRadius)
                        {
                            b.gravRadius += op.gravRadius * scaleInc;
                            b.velc       += (double3)op.vel * (op.gravRadius / b.gravRadius) * scaleInc;
                        }
                        else
                        {
                            if (explode)
                            {
                                exp = new ExplosionComp {
                                    timeToLive = explosionLifeTime,
                                    endScale   = explosionEndScale,
                                    init       = true,
                                };
                                ecb.AddComponent <ExplosionComp>(i, e, exp);
                                ecb.RemoveComponent <CollisionInfoSettingComp>(i, e);
                                ecb.RemoveComponent <CollisionInfoComp>(i, e);
                                ecb.RemoveComponent <PhysicsVelocity>(i, e);
                                ecb.RemoveComponent <PhysicsCollider>(i, e);
                                ecb.RemoveComponent <PhysicsDamping>(i, e);
                                ecb.RemoveComponent <PhysicsGravityFactor>(i, e);
                                ecb.RemoveComponent <PhysicsMass>(i, e);
                                ecb.RemoveComponent <BoubleComp>(i, e);
                            }
                            else
                            {
                                ecb.DestroyEntity(i, e);
                            }
                            break;
                        }
                    }
                }
                cb.Clear();
            }
        }
コード例 #16
0
 public void Execute(DynamicBuffer <Cell> buffer)
 {
     buffer.Clear();
     while (queue.TryDequeue(out int2 position))
     {
         buffer.Add(new Cell {
             value = position
         });
     }
 }
コード例 #17
0
        protected override void OnUpdate()
        {
            var detectors  = _entityQuery.ToComponentDataArray <DetectorComponent>(Allocator.TempJob);
            var colliders  = _entityQuery.ToComponentArray <BoxCollider2D>();
            var transforms = _entityQuery.ToComponentArray <Transform>();

            var entities = _entityQuery.ToEntityArray(Allocator.TempJob);

            for (var i = 0; i < detectors.Length; i++)
            {
                var detector  = detectors[i];
                var transform = transforms[i];
                var collider  = colliders[i];

                var count = Physics2D.OverlapBoxNonAlloc(transform.position, collider.size, transform.rotation.eulerAngles.z, _colliders,
                                                         _triggerMask);

                detector.TriggersCount = count;

                var triggerIds = new NativeArray <int>(count, Allocator.Temp);

                for (int j = 0; j < count; j++)
                {
                    triggerIds[j] = _colliders[j].GetInstanceID();
                }

                int triggersHash = Utils.CombineHashCodes(triggerIds);

                if (detector.TriggersHash != triggersHash)
                {
                    detector.TriggersHash = triggersHash;

                    DynamicBuffer <ColliderId> buffer = EntityManager.GetBuffer <ColliderId>(entities[i]);

                    buffer.Clear();

                    for (var index = 0; index < triggerIds.Length; index++)
                    {
                        int id = triggerIds[index];
                        buffer.Add(new ColliderId {
                            Value = id
                        });
                    }
                }

                detectors[i] = detector;

                triggerIds.Dispose();
            }

            _entityQuery.CopyFromComponentDataArray(detectors);

            entities.Dispose();
            detectors.Dispose();
        }
コード例 #18
0
    protected override void OnUpdate()
    {
        DynamicBuffer <HealthChangeRequestData> damageRequests = GetDamageRequestBuffer();

        _processingHealthChanges.CopyFrom(damageRequests.AsNativeArray());
        damageRequests.Clear();

        foreach (HealthChangeRequestData healthChangeData in _processingHealthChanges)
        {
            ProcessHealthChange(healthChangeData.Target, healthChangeData.Amount, healthChangeData.EffectGroupID);
        }
    }
コード例 #19
0
ファイル: SessionClient.cs プロジェクト: xiazx/UnityChatRoom
        /// <summary>
        /// 关闭套接字
        /// </summary>
        public void Close()
        {
            if (!isUse)
            {
                return;
            }

            State = SessionState.Close;
            socket.Close();
            dynamicBuffer.Clear();
            isUse = false;
        }
コード例 #20
0
            public unsafe void Execute(Entity entity, int index, DynamicBuffer <NetworkInBuffer> inBuffer, ref NetworkConnection connection)
            {
                //if (!connection.value.IsCreated) return;


                if (inBuffer.Length > 0)
                {
                    inBuffer.Clear();
                    endCommandBuffer.AddComponent(entity, new NetworkDisconnectedMessage {
                        error = (short)DisconnectedErrors.Receive_InBufferLength
                    });
                    return;
                }


                DataStreamReader reader;

                NetworkEvent.Type networkEvent;
                while ((networkEvent = driver.PopEventForConnection(connection.value, out reader)) != NetworkEvent.Type.Empty)
                {
                    //Debug.LogWarning($"networkEvent={networkEvent}");
                    switch (networkEvent)
                    {
                    case NetworkEvent.Type.Connect:
                        commandBuffer.AddComponent(index, entity, NetworkConnectedMessage);
                        break;

                    case NetworkEvent.Type.Disconnect:
                        //Debug.Log($"Disconnect  entity={entity}");
                        // Flag the connection as lost, it will be deleted in a separate system, giving user code one frame to detect and respond to lost connection
                        endCommandBuffer.AddComponent(entity, new NetworkDisconnectedMessage {
                            error = (short)DisconnectedErrors.Disconnect
                        });
                        return;

                    case NetworkEvent.Type.Data:
                        var oldLen = inBuffer.Length;
                        inBuffer.ResizeUninitialized(oldLen + reader.Length);
                        UnsafeUtility.MemCpy(((byte *)inBuffer.GetUnsafePtr()) + oldLen,
                                             reader.GetUnsafeReadOnlyPtr(),
                                             reader.Length);
                        break;

                    default:
#if ENABLE_UNITY_COLLECTIONS_CHECKS
                        throw new InvalidOperationException("Received unknown network event " + networkEvent);
#else
                        break;
#endif
                    }
                }
            }
コード例 #21
0
        /// <summary>
        /// 关闭套接字
        /// </summary>
        public void Close()
        {
            if (!isUse)
            {
                return;
            }

            string address = GetRemoteAddress();

            socket.Close();
            dynamicBuffer.Clear();
            isUse = false;
        }
コード例 #22
0
    public IEnumerator Triangulate(Entity[] cells)
    {
        yield return(new WaitForSeconds(0.01f));

        int                  totalCount      = cells.Length;
        EntityManager        m_EntityManager = MainWorld.Instance.GetEntityManager();
        NativeList <Vector3> Vertices        = new NativeList <Vector3>(totalCount, Allocator.Temp);
        NativeList <int>     Triangles       = new NativeList <int>(totalCount, Allocator.Temp);
        NativeList <Vector2> uvs             = new NativeList <Vector2>(totalCount, Allocator.Temp);

        for (int i = 0; i < totalCount; i++)
        {
            //0.取出实体,如果实体的索引为m_Builder则跳过
            Entity entity = cells[i];
            Cell   cell   = m_EntityManager.GetComponentData <Cell>(entity);
            if (cell.HasRiver)
            {
                DynamicBuffer <RiverBuffer> riverBuffers = m_EntityManager.GetBuffer <RiverBuffer>(entity);
                if (riverBuffers.Length > 0)
                {
                    DynamicBuffer <UvBuffer> uvBuffers = m_EntityManager.GetBuffer <UvBuffer>(entity);
                    for (int j = 0; j < riverBuffers.Length; j++)
                    {
                        Triangles.Add(Vertices.Length);
                        Vertices.Add(riverBuffers[j]);
                        uvs.Add(uvBuffers[j]);
                    }
                    uvBuffers.Clear();
                    riverBuffers.Clear();
                }
            }
        }

        Debug.Log("-----------------------------------------------------------------------------------------");
        Debug.Log("Vertices=" + Vertices.Length + "----Triangles=" + Triangles.Length + "----UV=" + uvs.Length);

        if (Vertices.Length > 1)
        {
            m_Mesh.Clear();
            m_Mesh.vertices  = Vertices.ToArray();
            m_Mesh.triangles = Triangles.ToArray();
            m_Mesh.uv        = uvs.ToArray();
            m_Mesh.RecalculateNormals();
            m_Mesh.Optimize();
        }
        Vertices.Dispose();
        Triangles.Dispose();
        uvs.Dispose();
    }
コード例 #23
0
        public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
        {
            var entities = chunk.GetNativeArray(EntityType);
            var pathfindingParamsArray = chunk.GetNativeArray(PathfindingParamsType);
            var pathIndexArray         = chunk.GetNativeArray(PathIndexType);
            var pathPositionBuffers    = chunk.GetBufferAccessor(PathPositionType);

            for (int i = 0; i < chunk.Count; i++)
            {
                var pathfindingParams = pathfindingParamsArray[i];
                var endNodeIndex      = CalculateIndex(pathfindingParams.EndPosition.x, pathfindingParams.EndPosition.y, GridSize.x);
                var startNode         = PathNodeArray[CalculateIndex(pathfindingParams.StartPosition.x, pathfindingParams.StartPosition.y, GridSize.x)];
                startNode.GCost = 0;
                startNode.HCost = CalculateDistanceCost(new int2(startNode.X, startNode.Y),
                                                        pathfindingParams.EndPosition);
                startNode.CalculateFCost();
                startNode.CameFromNodeIndex    = -1;
                PathNodeArray[startNode.Index] = startNode;

                NativeList <int> openList   = new NativeList <int>(128, Allocator.Temp);
                NativeList <int> closedList = new NativeList <int>(128, Allocator.Temp);

                openList.Add(startNode.Index);
                int currentNodeIndex = GetLowestCostFNodeIndex(openList, PathNodeArray);
                var recursionCounter = 0;
                var flags            = RecursivePathFinding(currentNodeIndex, endNodeIndex, openList, closedList, recursionCounter);

                DynamicBuffer <PathPosition> pathPositionBuffer = pathPositionBuffers[i];
                pathPositionBuffer.Clear();
                if (flags == 0)//Found Path
                {
                    PathNode endNode = PathNodeArray[endNodeIndex];
                    CalculatePath(PathNodeArray, endNode, pathPositionBuffer);
                    pathIndexArray[i] = new PathIndex {
                        Value = pathPositionBuffer.Length - 1
                    };
                }
                else
                {
                    pathIndexArray[i] = new PathIndex {
                        Value = -1
                    };
                }

                openList.Dispose();
                closedList.Dispose();
                CommandBuffer.RemoveComponent <PathfindingParams>(chunkIndex, entities[i]); //removing the components removes the entity from our entity query
            }
        }
コード例 #24
0
            public void Execute(Entity entity, int index, DynamicBuffer <DamageStack> stacks, ref Health health)
            {
                var damagetotal = new DamageEvent();
                int damage      = 0;

                // Apply damage
                for (int de = 0; de < stacks.Length; de++)
                {
                    damage += stacks[de].Value.Amount;
                }
                stacks.Clear();
                damagetotal.Amount = damage;

                health.ApplyDamage(damagetotal);
            }
コード例 #25
0
            public unsafe void Execute(Entity entity, int index, DynamicBuffer <TBufferElementData> buffer, ref NetworkConnection connection)
            {
                //if (!connection.value.IsCreated)
                //    return;

                if (buffer.Length > 0)
                {
                    driver.Send(pipeline, connection.value, (System.IntPtr)buffer.GetUnsafePtr(), buffer.Length);
                    buffer.Clear();

                    /*DataStreamWriter tmp = new DataStreamWriter(buffer.Length, Allocator.Temp);
                     * tmp.WriteBytes((byte*)buffer.GetUnsafePtr(), buffer.Length);
                     * driver.Send(unreliablePipeline, connection.Value, tmp);
                     * buffer.Clear();*/
                }
            }
コード例 #26
0
    public void CalculatePath(Entity entity)
    {
        //reading of the start and end positions and generation of the path to provide it to the
        //entity that is related later
        Translation ballposEnemy = manager.GetComponentData <Translation>(entity);

        startPosition = ballposEnemy.Value;
        NavMeshPath path = new NavMeshPath();

        targetPosition = AppManager.instance.playerPosition;
        NavMesh.CalculatePath(startPosition, targetPosition, NavMesh.AllAreas, path);

        // set nodeindex to 0 so the Job does not run during update
        ActiveNodeIndexData nodeIndex = manager.GetComponentData <ActiveNodeIndexData>(entity);
        ActiveNodeIndexData tempNode  = nodeIndex;

        tempNode.nodeInPath = 0;
        manager.SetComponentData(entity, tempNode);

        //when you do not reload the buffer directly from the entity but rather try to cach it then
        //you get spammed by errors telling you the native array has been deallocated and cant be accessed
        DynamicBuffer <Float3BufferElement> float3Buffer = manager.GetBuffer <Float3BufferElement>(entity);

        float3Buffer.Clear();

        for (int i = 0; i < path.corners.Length; i++)
        {
            convertPlaceholder = path.corners[i];
            float3Buffer.Add(new Float3BufferElement {
                Value = convertPlaceholder
            });
        }

        //reset the variables since they could have bneen changed by other operations in the mean time
        //by another script
        nodeIndex           = manager.GetComponentData <ActiveNodeIndexData>(entity);
        tempNode            = nodeIndex;
        tempNode.nodeInPath = 1;
        manager.SetComponentData(entity, tempNode);

        OJO_RequestRecalculationData recalc = manager.GetComponentData <OJO_RequestRecalculationData>(entity);

        recalc.requestState = MyCode.RequestState.NoRequest;
        manager.SetComponentData(entity, recalc);

        return;
    }
コード例 #27
0
        public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex)
        {
            NativeArray <Entity> entityArray = chunk.GetNativeArray(entityType);
            BufferAccessor <ReynoldsNearbyFlockPos> nearbyPosBuffers = chunk.GetBufferAccessor <ReynoldsNearbyFlockPos>(nearbyPosBufferType);
            BufferAccessor <ReynoldsNearbyFlockVel> nearbyVelBuffers = chunk.GetBufferAccessor <ReynoldsNearbyFlockVel>(nearbyVelBufferType);
            NativeArray <Translation>            transArray          = chunk.GetNativeArray(translationType);
            NativeArray <ReynoldsFlockBehaviour> flockArray          = chunk.GetNativeArray(flockType);
            NativeArray <PreviousMovement>       preVelArray         = chunk.GetNativeArray(preVelType);
            NativeArray <ReynoldsMovementValues> movementArray       = chunk.GetNativeArray(reynoldsMovementValuesType);

            for (int i = 0; i < chunk.Count; i++)
            {
                Entity entity = entityArray[i];
                DynamicBuffer <ReynoldsNearbyFlockPos> posBuffer = nearbyPosBuffers[i];
                DynamicBuffer <ReynoldsNearbyFlockVel> velBuffer = nearbyVelBuffers[i];
                Translation            trans          = transArray[i];
                ReynoldsFlockBehaviour flockBehaviour = flockArray[i];
                PreviousMovement       preVel         = preVelArray[i];
                ReynoldsMovementValues movement       = movementArray[i];

                float3 agentPosition = trans.Value;                                         // the position of the seeker

                DynamicBuffer <float3> nearCrowdPosList = posBuffer.Reinterpret <float3>(); // reinterpret the buffer so that it is used like a buffer of float3s
                nearCrowdPosList.Clear();

                DynamicBuffer <float3> nearCrowdVelList = velBuffer.Reinterpret <float3>(); // reinterpret the buffer so that it is used like a buffer of float3s
                nearCrowdVelList.Clear();


                float searchRadius = math.max(flockBehaviour.CohesionRadius, flockBehaviour.AvoidanceRadius);                                                                    // Choose the farther radius

                int hashMapKey = MovingQuadrantSystem.GetPositionHashMapKey(trans.Value);                                                                                        // Calculate the hash key of the seeker in question

                FindCrowdAgents(hashMapKey, agentPosition, entity, ref nearCrowdPosList, ref nearCrowdVelList, ref searchRadius);                                                // Seach the quadrant that the seeker is in
                FindCrowdAgents(hashMapKey + 1, agentPosition, entity, ref nearCrowdPosList, ref nearCrowdVelList, ref searchRadius);                                            // search the quadrant to the right
                FindCrowdAgents(hashMapKey - 1, agentPosition, entity, ref nearCrowdPosList, ref nearCrowdVelList, ref searchRadius);                                            // search the quadrant to the left
                FindCrowdAgents(hashMapKey + MovingQuadrantSystem.quadrantYMultiplier, agentPosition, entity, ref nearCrowdPosList, ref nearCrowdVelList, ref searchRadius);     // quadrant above
                FindCrowdAgents(hashMapKey - MovingQuadrantSystem.quadrantYMultiplier, agentPosition, entity, ref nearCrowdPosList, ref nearCrowdVelList, ref searchRadius);     // quadrant below
                FindCrowdAgents(hashMapKey + 1 + MovingQuadrantSystem.quadrantYMultiplier, agentPosition, entity, ref nearCrowdPosList, ref nearCrowdVelList, ref searchRadius); // up right
                FindCrowdAgents(hashMapKey - 1 + MovingQuadrantSystem.quadrantYMultiplier, agentPosition, entity, ref nearCrowdPosList, ref nearCrowdVelList, ref searchRadius); // up left
                FindCrowdAgents(hashMapKey + 1 - MovingQuadrantSystem.quadrantYMultiplier, agentPosition, entity, ref nearCrowdPosList, ref nearCrowdVelList, ref searchRadius); // down right
                FindCrowdAgents(hashMapKey - 1 - MovingQuadrantSystem.quadrantYMultiplier, agentPosition, entity, ref nearCrowdPosList, ref nearCrowdVelList, ref searchRadius); // down left

                movementArray[i] = GetFlockingBehaviour(ref trans, ref preVel.value, ref nearCrowdPosList, ref nearCrowdVelList, ref flockBehaviour, movement);
            }
        }
コード例 #28
0
        public static unsafe void FromString(this DynamicBuffer <char> buffer, string name)
        {
            if (string.IsNullOrEmpty(name))
            {
                buffer.Clear();
                return;
            }

            fixed(char *ptr = name)
            {
                var array = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray <char>(ptr, name.Length, Allocator.None);

#if ENABLE_UNITY_COLLECTIONS_CHECKS
                NativeArrayUnsafeUtility.SetAtomicSafetyHandle(ref array, AtomicSafetyHandle.Create());
#endif
                buffer.CopyFrom(array);
            }
        }
コード例 #29
0
    private void HandleRadialImpulseRequests()
    {
        DynamicBuffer <RadialImpulseRequestData> radialImpulses = GetBuffer <RadialImpulseRequestData>(GetRequestSingleton());

        if (radialImpulses.Length > 0)
        {
            DynamicBuffer <DirectImpulseRequestData> directImpulseRequests = GetBuffer <DirectImpulseRequestData>(GetRequestSingleton());

            foreach (RadialImpulseRequestData request in radialImpulses)
            {
                if (!HasComponent <PhysicsColliderBlob>(request.Target))
                {
                    continue;
                }

                var colliderRef = GetComponent <PhysicsColliderBlob>(request.Target).Collider;
                if (!colliderRef.IsCreated)
                {
                    continue;
                }

                ref Collider collider = ref colliderRef.Value;

                fix2 pos             = GetComponent <FixTranslation>(request.Target);
                fix2 centerOfMass    = pos + (fix2)collider.MassProperties.MassDistribution.LocalCenterOfMass;
                fix2 v               = centerOfMass - request.Position;
                fix  distance        = length(v);
                fix  impulseStrength = remap(
                    0, request.Radius,
                    request.StrengthMax, request.StrengthMin,
                    distance);

                fix2 direction = distance < fix.Epsilon ? new fix2(0, 1) : v / distance;

                directImpulseRequests.Add(new DirectImpulseRequestData()
                {
                    IgnoreMass = request.IgnoreMass,
                    Strength   = impulseStrength * direction,
                    Target     = request.Target
                });
            }

            radialImpulses.Clear();
        }
コード例 #30
0
            public void Execute(Entity entity, int index, DynamicBuffer <VelocityCurveBuffer> velocityCurveBuffer, ref PhysicsVelocity physicsVelocity)
            {
                float3 newVelocity = new float3(0, 0, 0);

                for (int i = 0; i < velocityCurveBuffer.Length; i++)
                {
                    VelocityCurveBuffer velocityCurveBufferElement = velocityCurveBuffer[i];
                    VelocityCurve       velocityCurve = VelocityCurveGroup[velocityCurveBufferElement.VelocityCurveEntity];

                    newVelocity.x += velocityCurve.X.CurrentVelocity;
                    newVelocity.y += velocityCurve.Y.CurrentVelocity;
                    newVelocity.z += velocityCurve.Z.CurrentVelocity;
                }

                physicsVelocity.Linear = newVelocity;

                //Clear the buffer
                velocityCurveBuffer.Clear();
            }