示例#1
0
    public void NativeMultiHashMap_ForEach_Throws_When_Modified()
    {
        using (var container = new NativeMultiHashMap <int, int>(32, Allocator.TempJob))
        {
            for (int i = 0; i < 30; ++i)
            {
                container.Add(i, 30 + i);
                container.Add(i, 60 + i);
            }

            Assert.Throws <ObjectDisposedException>(() =>
            {
                foreach (var kv in container)
                {
                    container.Add(10, 10);
                }
            });

            Assert.Throws <ObjectDisposedException>(() =>
            {
                foreach (var kv in container)
                {
                    container.Remove(1);
                }
            });
        }
    }
示例#2
0
        public void Execute(Entity e, int jobIndex, [ReadOnly] ref Translation translation, [ReadOnly] ref MeleeStrengthComponent strength, ref AttackStateComponent state, ref TargetComponent target)
        {
            state.value = (ushort)AttackState.None;
            if (target.entity == Entity.Null)
            {
                return;
            }

            float distance = distancesq(target.location, translation.Value);

            if (distance > MinDistance)
            {
                return;
            }

            state.value = (ushort)AttackState.Attacking;

            if (!DamageTakerData.Exists(target.entity))
            {
                if (!HealthData.Exists(target.entity))
                {
                    // entity is dead
                    target.entity = Entity.Null;
                    return;
                }
                CommandBuffer.AddComponent <DamageTakerTag>(jobIndex, target.entity);
                // add entry in the map
                EntityDamageMap.Add(target.entity, strength.value);
            }
            // add a new entry in the map
            EntityDamageMap.Add(target.entity, strength.value);
        }
示例#3
0
        public void Execute(int index)
        {
            RangeQueryResult blobNearestNeighbour = BlobNearestNeighbours[index];

            for (int j = 0; j < blobNearestNeighbour.Length; j++)
            {
                int indexOfOther = blobNearestNeighbour[j];
                if (index == indexOfOther)
                {
                    continue;                       //ignore self finds.
                }
                SpringEdge edge = new SpringEdge(index, indexOfOther);

                long hash = edge.CustomHashCode();
                if (UniqueEdges.Add(hash))//only allow unique EDGES.
                {
                    //  Debug.Log($"Adding unique edge: {edge.A}, { edge.B} " );
                    Edges.Add(edge.A, edge.B);

                    //  Debug.Log($"Adding unique edge: {edge.B}, { edge.A} " );
                    Edges.Add(edge.B, edge.A);
                }
                else
                {
                    //  Debug.Log($"Hash Clash: {edge.A}, { edge.B} " );
                }
            }
        }
示例#4
0
    public void NativeMultiHashMap_ValueIterator()
    {
        var hashMap = new NativeMultiHashMap <int, int> (1, Allocator.Temp);

        hashMap.Add(5, 0);
        hashMap.Add(5, 1);
        hashMap.Add(5, 2);

        var list = new NativeList <int>(Allocator.TempJob);

        GCAllocRecorder.ValidateNoGCAllocs(() =>
        {
            list.Clear();
            foreach (var value in hashMap.GetValuesForKey(5))
            {
                list.Add(value);
            }
        });

        list.Sort();
        Assert.AreEqual(list.ToArray(), new int[] { 0, 1, 2 });

        foreach (var value in hashMap.GetValuesForKey(6))
        {
            Assert.Fail();
        }

        list.Dispose();
        hashMap.Dispose();
    }
        private int Add(int typeIndex, int hashCode, object newData)
        {
            int index;

            if (m_FreeListIndex != -1)
            {
                index           = m_FreeListIndex;
                m_FreeListIndex = m_SharedComponentVersion[index];

                Assert.IsTrue(m_SharedComponentData[index] == null);

                m_HashLookup.Add(hashCode, index);
                m_SharedComponentData[index]     = newData;
                m_SharedComponentRefCount[index] = 1;
                m_SharedComponentVersion[index]  = 1;
                m_SharedComponentType[index]     = typeIndex;
            }
            else
            {
                index = m_SharedComponentData.Count;
                m_HashLookup.Add(hashCode, index);
                m_SharedComponentData.Add(newData);
                m_SharedComponentRefCount.Add(1);
                m_SharedComponentVersion.Add(1);
                m_SharedComponentType.Add(typeIndex);
            }

            return(index);
        }
    public void NativeMultiHashMap_ForEach_Throws_When_Modified()
    {
        using (var container = new NativeMultiHashMap <int, int>(32, Allocator.TempJob))
        {
            for (int i = 0; i < 30; ++i)
            {
                container.Add(i, 30 + i);
                container.Add(i, 60 + i);
            }

#if UNITY_2020_2_OR_NEWER
            Assert.Throws <ObjectDisposedException>(() =>
#else
            Assert.Throws <InvalidOperationException>(() =>
#endif
            {
                foreach (var kv in container)
                {
                    container.Add(10, 10);
                }
            });

#if UNITY_2020_2_OR_NEWER
            Assert.Throws <ObjectDisposedException>(() =>
#else
            Assert.Throws <InvalidOperationException>(() =>
#endif
            {
                foreach (var kv in container)
                {
                    container.Remove(1);
                }
            });
        }
    }
示例#7
0
            public void Execute(int index)
            {
                //Get the 8 neighbors cells to the agent's cell + it's cell
                int  agent = AgentData[index].ID;
                int3 cell  = new int3((int)math.floor(Position[index].Value.x / 2.0f) * 2 + 1, 0,
                                      (int)math.floor(Position[index].Value.z / 2.0f) * 2 + 1);

                CellToAgent.Add(cell, agent);
                int startX = cell.x - 2;
                int startZ = cell.z - 2;
                int endX   = cell.x + 2;
                int endZ   = cell.z + 2;

                float3 agentPos = Position[index].Value;

                AgentIDToPos.TryAdd(agent, agentPos);
                float distCell = math.distance((float3)cell, agentPos);

                for (int i = startX; i <= endX; i = i + 2)
                {
                    for (int j = startZ; j <= endZ; j = j + 2)
                    {
                        int3 key = new int3(i, 0, j);

                        CellToAgent.Add(key, agent);
                    }
                }
            }
示例#8
0
    public void NativeMultiHashMap_GetKeys()
    {
        var container = new NativeMultiHashMap <int, int>(1, Allocator.Temp);

        for (int i = 0; i < 30; ++i)
        {
            container.Add(i, 2 * i);
            container.Add(i, 3 * i);
        }
        var keys = container.GetKeyArray(Allocator.Temp);

#if !NET_DOTS // Tuple is not supported by TinyBCL
        var(unique, uniqueLength) = container.GetUniqueKeyArray(Allocator.Temp);
        Assert.AreEqual(30, uniqueLength);
#endif

        Assert.AreEqual(60, keys.Length);
        keys.Sort();
        for (int i = 0; i < 30; ++i)
        {
            Assert.AreEqual(i, keys[i * 2 + 0]);
            Assert.AreEqual(i, keys[i * 2 + 1]);
#if !NET_DOTS // Tuple is not supported by TinyBCL
            Assert.AreEqual(i, unique[i]);
#endif
        }
    }
示例#9
0
        protected unsafe override void OnUpdate()
        {
            //TODO: Convert to switch table generation method
            this.meshes.Clear();
            var entities         = new NativeList <Entity>(8, Allocator.TempJob);
            var contexts         = new NativeList <UIContextData>(8, Allocator.TempJob);
            var referencedGraphs = new NativeList <UIGraphData>(8, Allocator.TempJob);
            var entityUpdate     = new NativeMultiHashMap <int, ValueTuple <Entity, int> >(8, Allocator.Temp);
            var schema           = GetSingleton <UICompiledSchemaData>();

            Entities.WithSharedComponentFilter <UIDirtyState>(true).ForEach((Entity entity, DynamicBuffer <UINode> nodes, in UIGraphData graphData, in UIContextData context, in RenderMesh renderMesh) =>
            {
                int index = meshes.IndexOf(renderMesh.mesh);
                if (index < 0)
                {
                    index = meshes.Count;
                    meshes.Add(renderMesh.mesh);
                    entities.Add(entity);
                    referencedGraphs.Add(graphData);
                    contexts.Add(context);
                }
                entityUpdate.Add(index, ValueTuple.Create(entity, 0));
                foreach (var node in nodes)
                {
                    entityUpdate.Add(index, ValueTuple.Create(node.value, GetComponent <UINodeInfo>(node.value).submesh));
                }
            }).WithoutBurst().Run();
示例#10
0
            void Process(Entity ea, Entity eb)
            {
                Entity self, other;

                if (ea.Index > eb.Index)
                {
                    var tmp = ea;
                    ea = eb;
                    eb = tmp;
                }

                if (ThisMask.Matches(ea) && OtherMask.Matches(eb))
                {
                    self  = ea;
                    other = eb;
                }
                else if (ThisMask.Matches(eb) && OtherMask.Matches(ea))
                {
                    self  = eb;
                    other = ea;
                }
                else
                {
                    return;
                }

                bool found = false;

                if (CollInfos.TryGetFirstValue(self, out var collInfo, out var it))
                {
                    do
                    {
                        if (collInfo.Other != other)// || (collInfo.EventType & EventType) == 0)
                        {
                            continue;
                        }

                        found = true;
                        if (collInfo.Frame == Frame - 1) // had a collision during the prev frame
                        {
                            collInfo.State = CollisionState.Stay;
                            collInfo.Frame = Frame;
                            CollInfos.SetValue(collInfo, it);
                        }

                        break;
                    }while (CollInfos.TryGetNextValue(out collInfo, ref it));
                }

                if (!found) // new collision
                {
                    CollInfos.Add(self, new CollisionTriggerData {
                        Other = other, Frame = Frame, State = CollisionState.Enter, EventType = EventType
                    });
                    CollInfos.Add(other, new CollisionTriggerData {
                        Other = self, Frame = Frame, State = CollisionState.Enter, EventType = EventType
                    });
                }
            }
示例#11
0
        /// <summary>
        /// Smooth mesh.
        /// </summary>
        /// <param name="vert">Vertex array</param>
        /// <param name="tris">Triangle array</param>
        /// <param name="normals">Array that normals would be stored in</param>
        /// <param name="angle">Smoothing angle</param>
        public static void RecalculateNormals(NativeArray <Vertex> vert, NativeArray <Triangle> tris, ref NativeArray <float3> normals, float angle = 60)
        {
            var cosineThreshold = Mathf.Cos(angle * Mathf.Deg2Rad);
            var triNormals      = new NativeArray <float3>(tris.Length, Allocator.Temp);
            var dictionary      = new NativeMultiHashMap <VertexKey, VertexEntry>(vert.Length * 2, Allocator.Temp);

            for (var i = 0; i < tris.Length; i++)
            {
                var i1 = tris[i].indices[0];
                var i2 = tris[i].indices[1];
                var i3 = tris[i].indices[2];

                // Calculate the normal of the triangle
                var p1     = vert[i2].pos - vert[i1].pos;
                var p2     = vert[i3].pos - vert[i1].pos;
                var normal = math.normalize(math.cross(p1, p2));

                triNormals[i] = normal;

                dictionary.Add(new VertexKey(vert[i1].pos), new VertexEntry(0, i, i1));
                dictionary.Add(new VertexKey(vert[i2].pos), new VertexEntry(0, i, i2));
                dictionary.Add(new VertexKey(vert[i3].pos), new VertexEntry(0, i, i3));
            }

            var keys = dictionary.GetKeyArray(Allocator.Temp);

            for (var i = 0; i < keys.Length; i++)
            {
                var enumerator1 = dictionary.GetValuesForKey(keys[i]);
                do
                {
                    var sum         = new float3();
                    var lhs         = enumerator1.Current;
                    var enumerator2 = dictionary.GetValuesForKey(keys[i]);
                    do
                    {
                        var rhs = enumerator2.Current;

                        if (lhs.VertexIndex == rhs.VertexIndex)
                        {
                            sum += triNormals[rhs.TriangleIndex];
                        }
                        else
                        {
                            // The dot product is the cosine of the angle between the two triangles.
                            // A larger cosine means a smaller angle.
                            var dot = math.dot(triNormals[lhs.TriangleIndex], triNormals[rhs.TriangleIndex]);

                            if (dot >= cosineThreshold)
                            {
                                sum += triNormals[rhs.TriangleIndex];
                            }
                        }
                    } while(enumerator2.MoveNext());

                    normals[lhs.VertexIndex] = math.normalize(sum);
                } while(enumerator1.MoveNext());
            }
        }
示例#12
0
        public void Execute()
        {
            var container = new NativeMultiHashMap <int, int>(10, Allocator.Temp);

            container.Add(0, 17);
            container.Dispose();
            container.Add(1, 42);
        }
示例#13
0
    void FinishLine()
    {
        // skip first point on purpose
        for (int i = 1; i < lineRenderer.positionCount - 1; i++)
        {
            var p1 = lineRenderer.GetPosition(i);
            var p2 = lineRenderer.GetPosition(i + 1);

            var mid = (p1 + p2) * .5f;

            var hash = LifeTimeSystem.GetPositionHash(mid);

            var pp1 = 2 * p1 - mid;
            var pp2 = 2 * p2 - mid;

            //var value = new float4(p1.x, p1.z, p2.x, p2.z);
            // use wider lines to prevent floating point errors
            var value = new float4(pp1.x, pp1.z, pp2.x, pp2.z);

            hashmap.Add(hash, value);

            hashmap.Add(LifeTimeSystem.GetPositionHash(mid, 0, 1), value);
            hashmap.Add(LifeTimeSystem.GetPositionHash(mid, 0, -1), value);
            hashmap.Add(LifeTimeSystem.GetPositionHash(mid, 1, 0), value);
            hashmap.Add(LifeTimeSystem.GetPositionHash(mid, 1, 1), value);
            hashmap.Add(LifeTimeSystem.GetPositionHash(mid, 1, -1), value);
            hashmap.Add(LifeTimeSystem.GetPositionHash(mid, -1, 0), value);
            hashmap.Add(LifeTimeSystem.GetPositionHash(mid, -1, 1), value);
            hashmap.Add(LifeTimeSystem.GetPositionHash(mid, -1, -1), value);
        }
    }
示例#14
0
        public void Execute([ReadOnly] ref EntityPair entityPair, [ReadOnly] ref Elasticity elasticity, [ReadOnly] ref Line line)
        {
            float3 dist    = (line.P2 - line.P1);
            float  distMag = math.length(dist);
            float  refDist = elasticity.ReferenceLength;

            if (distMag > refDist)
            {
                float3 force = dist * (1 - refDist / distMag) * elasticity.YoungModulus;
                _hashMap.Add(entityPair.E1, force);
                _hashMap.Add(entityPair.E2, -force);
            }
        }
示例#15
0
    public void NativeMultiHashMap_RemoveKeyAndValue()
    {
        var hashMap = new NativeMultiHashMap <int, long> (1, Allocator.Temp);

        hashMap.Add(10, 0);
        hashMap.Add(10, 1);
        hashMap.Add(10, 2);

        hashMap.Add(20, 2);
        hashMap.Add(20, 2);
        hashMap.Add(20, 1);
        hashMap.Add(20, 2);
        hashMap.Add(20, 1);

        hashMap.Remove(10, 1L);
        ExpectValues(hashMap, 10, new [] { 0L, 2L });
        ExpectValues(hashMap, 20, new [] { 1L, 1L, 2L, 2L, 2L });

        hashMap.Remove(20, 2L);
        ExpectValues(hashMap, 10, new [] { 0L, 2L });
        ExpectValues(hashMap, 20, new [] { 1L, 1L });

        hashMap.Remove(20, 1L);
        ExpectValues(hashMap, 10, new [] { 0L, 2L });
        ExpectValues(hashMap, 20, new long [0]);

        hashMap.Dispose();
    }
示例#16
0
    public void NativeMultiHashMap_CountValuesForKey()
    {
        var hashMap = new NativeMultiHashMap <int, int> (1, Allocator.Temp);

        hashMap.Add(5, 7);
        hashMap.Add(6, 9);
        hashMap.Add(6, 10);

        Assert.AreEqual(1, hashMap.CountValuesForKey(5));
        Assert.AreEqual(2, hashMap.CountValuesForKey(6));
        Assert.AreEqual(0, hashMap.CountValuesForKey(7));

        hashMap.Dispose();
    }
    public void NativeMultiHashMap_GetKeysAndValues()
    {
        var hashMap = new NativeMultiHashMap <int, int> (1, Allocator.Temp);

        for (int i = 0; i < 30; ++i)
        {
            hashMap.Add(i, 30 + i);
            hashMap.Add(i, 60 + i);
        }
        var keysValues = hashMap.GetKeyValueArrays(Allocator.Temp);

        hashMap.Dispose();

        Assert.AreEqual(60, keysValues.Keys.Length);
        Assert.AreEqual(60, keysValues.Values.Length);

        // ensure keys and matching values are aligned (though unordered)
        for (int i = 0; i < 30; ++i)
        {
            var k0 = keysValues.Keys[i * 2 + 0];
            var k1 = keysValues.Keys[i * 2 + 1];
            var v0 = keysValues.Values[i * 2 + 0];
            var v1 = keysValues.Values[i * 2 + 1];

            if (v0 > v1)
            {
                (v0, v1) = (v1, v0);
            }

            Assert.AreEqual(k0, k1);
            Assert.AreEqual(30 + k0, v0);
            Assert.AreEqual(60 + k0, v1);
        }

        keysValues.Keys.Sort();
        for (int i = 0; i < 30; ++i)
        {
            Assert.AreEqual(i, keysValues.Keys[i * 2 + 0]);
            Assert.AreEqual(i, keysValues.Keys[i * 2 + 1]);
        }

        keysValues.Values.Sort();
        for (int i = 0; i < 60; ++i)
        {
            Assert.AreEqual(30 + i, keysValues.Values[i]);
        }

        keysValues.Dispose();
    }
    public void NativeHashMap_RemoveFromMultiHashMap()
    {
        var hashMap = new NativeMultiHashMap <int, int> (16, Allocator.Temp);
        int iSquared;

        // Make sure inserting values work
        for (int i = 0; i < 8; ++i)
        {
            hashMap.Add(i, i * i);
        }
        for (int i = 0; i < 8; ++i)
        {
            hashMap.Add(i, i);
        }
        Assert.AreEqual(16, hashMap.Capacity, "HashMap grew larger than expected");
        // Make sure reading the inserted values work
        for (int i = 0; i < 8; ++i)
        {
            NativeMultiHashMapIterator <int> it;
            Assert.IsTrue(hashMap.TryGetFirstValue(i, out iSquared, out it), "Failed get value from hash table");
            Assert.AreEqual(iSquared, i, "Got the wrong value from the hash table");
            Assert.IsTrue(hashMap.TryGetNextValue(out iSquared, ref it), "Failed get value from hash table");
            Assert.AreEqual(iSquared, i * i, "Got the wrong value from the hash table");
        }
        for (int rm = 0; rm < 8; ++rm)
        {
            Assert.AreEqual(2, hashMap.Remove(rm));
            NativeMultiHashMapIterator <int> it;
            Assert.IsFalse(hashMap.TryGetFirstValue(rm, out iSquared, out it), "Failed to remove value from hash table");
            for (int i = rm + 1; i < 8; ++i)
            {
                Assert.IsTrue(hashMap.TryGetFirstValue(i, out iSquared, out it), "Failed get value from hash table");
                Assert.AreEqual(iSquared, i, "Got the wrong value from the hash table");
                Assert.IsTrue(hashMap.TryGetNextValue(out iSquared, ref it), "Failed get value from hash table");
                Assert.AreEqual(iSquared, i * i, "Got the wrong value from the hash table");
            }
        }
        // Make sure entries were freed
        for (int i = 0; i < 8; ++i)
        {
            hashMap.Add(i, i * i);
        }
        for (int i = 0; i < 8; ++i)
        {
            hashMap.Add(i, i);
        }
        Assert.AreEqual(16, hashMap.Capacity, "HashMap grew larger than expected");
        hashMap.Dispose();
    }
示例#19
0
            public void Execute(int cell)
            {
                int      i;
                Position p_i;

                NativeMultiHashMapIterator <int> pos_it;
                NativeMultiHashMapIterator <int> hash_it;

                int cell_index_x = cell % cells_per_side.x;
                int cell_index_y = cell % (cells_per_side.x * cells_per_side.y);

                cell_index_y /= cells_per_side.x;
                int cell_index_z = cell / (cells_per_side.x * cells_per_side.y);

                int3 cell_index = new int3(
                    cell_index_x,
                    cell_index_y,
                    cell_index_z);

                if (cell_positions.TryGetFirstValue(cell, out p_i, out pos_it) &&
                    hash_map.TryGetFirstValue(cell, out i, out hash_it))
                {
                    float4 result = SumForcesAndEnergies(i, p_i, cell_index);

                    Force force = new Force
                    {
                        Value = new float3(result.x, result.y, result.z)
                    };

                    cell_forces.Add(cell, force);
                    cell_energies.Add(cell, result.w);
                    force_hash_map.Add(cell, i);

                    while (cell_positions.TryGetNextValue(out p_i, ref pos_it) &&
                           hash_map.TryGetNextValue(out i, ref hash_it))
                    {
                        result = SumForcesAndEnergies(i, p_i, cell_index);

                        force = new Force
                        {
                            Value = new float3(result.x, result.y, result.z)
                        };

                        cell_forces.Add(cell, force);
                        cell_energies.Add(cell, result.w);
                        force_hash_map.Add(cell, i);
                    }
                }
            }
示例#20
0
    public void NativeHashMap_ContainsKeyMultiHashMap()
    {
        var hashMap = new NativeMultiHashMap <int, int> (1, Allocator.Temp);

        hashMap.Add(5, 7);

        hashMap.Add(6, 9);
        hashMap.Add(6, 10);

        Assert.IsTrue(hashMap.ContainsKey(5));
        Assert.IsTrue(hashMap.ContainsKey(6));
        Assert.IsFalse(hashMap.ContainsKey(4));

        hashMap.Dispose();
    }
            private void OccupyLane(ref VehiclePathing vehicle, ref RoadSection rs, int laneIndex)
            {
                int i0 = CurvePositionToOccupancyIndex(vehicle.RoadIndex, laneIndex, vehicle.curvePos - rs.vehicleHalfLen);
                int i1 = CurvePositionToOccupancyIndex(vehicle.RoadIndex, laneIndex, vehicle.curvePos + rs.vehicleHalfLen);

                var d = new VehicleSlotData {
                    Speed = vehicle.speed, Id = vehicle.vehicleId
                };

                OccupancyToVehicleMap.Add(i0, d);
                if (i0 != i1)
                {
                    OccupancyToVehicleMap.Add(i1, d);
                }
            }
示例#22
0
    public void NativeHashMap_MergeCountShared()
    {
        var count            = 1024;
        var sharedKeyCount   = 16;
        var sharedCount      = new NativeArray <int>(count, Allocator.TempJob);
        var sharedIndices    = new NativeArray <int>(count, Allocator.TempJob);
        var totalSharedCount = new NativeArray <int>(1, Allocator.TempJob);
        var hashMap          = new NativeMultiHashMap <int, int>(count, Allocator.TempJob);

        for (int i = 0; i < count; i++)
        {
            hashMap.Add(i & (sharedKeyCount - 1), i);
            sharedCount[i] = 1;
        }

        var mergeSharedValuesJob = new MergeSharedValues
        {
            sharedCount   = sharedCount,
            sharedIndices = sharedIndices,
        };

        var mergetedSharedValuesJobHandle = mergeSharedValuesJob.Schedule(hashMap, 64);

        mergetedSharedValuesJobHandle.Complete();

        for (int i = 0; i < count; i++)
        {
            Assert.AreEqual(count / sharedKeyCount, sharedCount[sharedIndices[i]]);
        }

        sharedCount.Dispose();
        sharedIndices.Dispose();
        totalSharedCount.Dispose();
        hashMap.Dispose();
    }
示例#23
0
        public void Execute(Entity entity, int index, [ReadOnly] ref Bullet bullet, ref Translation translation, [ReadOnly] ref Rotation rotation)
        {
            var nextPosition = new Translation {
                Value = translation.Value + dt * bullet.moveSpeed * math.forward(rotation.Value)
            };

            CollisionFilter collisionFilter = new CollisionFilter()
            {
                BelongsTo    = ~0u,
                CollidesWith = ~0u,
                GroupIndex   = 0
            };
            RaycastInput raycastInput = new RaycastInput {
                Start  = translation.Value,
                End    = nextPosition.Value,
                Filter = collisionFilter
            };

            if (physicsWorld.CastRay(raycastInput, out RaycastHit hit))
            {
                Entity targetEntity = physicsWorld.CollisionWorld.Bodies[hit.RigidBodyIndex].Entity;
                var    hash         = (int)math.hash(new int2(targetEntity.Index, targetEntity.Version));
                damageDict.Add(hash, bullet.damage);

                commandBuffer.DestroyEntity(index, entity);
            }

            translation = nextPosition;
        }
        public unsafe void HandleClientConnect(Room room, Client client)
        {
            room.ValidityCheck();

            // Inform server of new connection
            DataStreamWriter client_writer, server_writer;

            client_writer = driver.BeginSend(pipeline, connections[client.ConnectionId]);
            server_writer = driver.BeginSend(pipeline, connections[room.ServerConnectionId]);

            // Write the messageType
            client_writer.WriteByte((byte)MessageType.ConnectToServer);  // Event type to send to both server and client

            // Write the connectionId
            client_writer.WriteInt(client.ConnectionId);

            // Send event to client
            driver.EndSend(client_writer);

            // Write the messageType
            server_writer.WriteByte((byte)MessageType.ConnectToServer);

            // Write the connectionId
            server_writer.WriteInt(client.ConnectionId);

            // Send connect to client
            driver.EndSend(server_writer);

            // Add client to active clients list
            connectedClients.Add(room.RoomId, client);
        }
示例#25
0
        public void Execute(int i, TransformAccess transform)
        {
            AgentBehaviors mask = AgentBehaviors.Active;

            if ((behaviors[i] & mask) == 0)
            {
                return;
            }

            float mass   = movementConfigs[movement[i]].mass;
            int3  grid   = GridPosition(transform.position);
            int3  bucket = new int3(
                grid.x / size.x,
                grid.y / size.y,
                grid.z / size.z
                );

            Agents.AgentKinematics agent = agents[i];
            agent.position = transform.position;
            agents[i]      = agent;

            SpatialMapData data = new SpatialMapData();

            data.position = transform.position;
            data.height   = collision.height;
            data.radius   = collision.radius;
            data.mass     = mass;

            spatialMap.Add(bucket, data);
        }
示例#26
0
    public void NativeMultiHashMap_ForEach_FixedStringInHashMap()
    {
        using (var stringList = new NativeList <FixedString32>(10, Allocator.Persistent)
        {
            "Hello", ",", "World", "!"
        })
        {
            var container = new NativeMultiHashMap <FixedString128, float>(50, Allocator.Temp);
            var seen      = new NativeArray <int>(stringList.Length, Allocator.Temp);
            foreach (var str in stringList)
            {
                container.Add(str, 0);
            }

            foreach (var pair in container)
            {
                int index = stringList.IndexOf(pair.Key);
                Assert.AreEqual(stringList[index], pair.Key.ToString());
                seen[index] = seen[index] + 1;
            }

            for (int i = 0; i < stringList.Length; i++)
            {
                Assert.AreEqual(1, seen[i], $"Incorrect value count {stringList[i]}");
            }
        }
    }
示例#27
0
        // Start is called before the first frame update
        void Start()
        {
            nativeResult = new NativeArray <int>(1, Allocator.Persistent);
            blobResult   = new NativeArray <int>(1, Allocator.Persistent);
            random       = new Unity.Mathematics.Random((uint)System.DateTime.Now.Ticks);

            // generate all keys
            allKeys    = new NativeArray <int>(itemCount, Allocator.Persistent);
            allQueries = new NativeArray <int>(itemCount * 2, Allocator.Persistent);
            for (int i = 0; i < itemCount; i++)
            {
                allKeys[i] = random.NextInt(0, 50); // generate duplicate keys

                // 50/50 random queries and certainly existing keys
                allQueries[i * 2]     = allKeys[i];
                allQueries[i * 2 + 1] = random.NextInt(-1000, 1000);
            }

            // construct source
            source = new NativeMultiHashMap <int, int>(allKeys.Length, Allocator.Persistent);
            for (int i = 0; i < itemCount; i++)
            {
                source.Add(allKeys[i], 1);
            }


            BlobBuilder builder = new BlobBuilder(Allocator.Temp);
            ref var     root    = ref builder.ConstructRoot <BlobMultiHashMap <int, int> >();
示例#28
0
            public void Execute(int index)
            {
                var chunk = Chunks[index];
                var rendererSharedComponentIndex = chunk.GetSharedComponentIndex(MeshInstanceRendererType);

                ChunkRendererMap.Add(rendererSharedComponentIndex, index);
            }
            public void Execute(ArchetypeChunk batchInChunk, int batchIndex)
            {
                if (batchInChunk.DidChange(ParentTypeHandle, LastSystemVersion))
                {
                    var chunkPreviousParents = batchInChunk.GetNativeArray(PreviousParentTypeHandle);
                    var chunkParents         = batchInChunk.GetNativeArray(ParentTypeHandle);
                    var chunkEntities        = batchInChunk.GetNativeArray(EntityTypeHandle);

                    for (int j = 0; j < batchInChunk.Count; j++)
                    {
                        if (chunkParents[j].Value != chunkPreviousParents[j].Value)
                        {
                            var childEntity          = chunkEntities[j];
                            var parentEntity         = chunkParents[j].Value;
                            var previousParentEntity = chunkPreviousParents[j].Value;

                            ParentChildrenToAdd.Add(parentEntity, childEntity);
                            UniqueParents.TryAdd(parentEntity, 0);

                            if (previousParentEntity != Entity.Null)
                            {
                                ParentChildrenToRemove.Add(previousParentEntity, childEntity);
                                UniqueParents.TryAdd(previousParentEntity, 0);
                            }

                            chunkPreviousParents[j] = new PreviousParent
                            {
                                Value = parentEntity
                            };
                        }
                    }
                }
            }
示例#30
0
        protected override void OnUpdate()
        {
            if (m_UpdateMeshAndCommandBufferGroup.CalculateEntityCount() < 1 && m_UpdateVerticesOnlyGroup.CalculateEntityCount() < 1)
            {
                return;
            }

            if (m_UpdateMeshAndCommandBufferGroup.CalculateEntityCount() > 0)
            {
                RebuildMeshAndCommandBuffers();

                // Now sort layers:
                NativeArray <CanvasLayer> layerEntity;
                var canvasLayerIdFromEntity = GetComponentDataFromEntity <CanvasSortLayer>(true);
                using (var roots = m_AnyTarget.ToEntityArray(Allocator.TempJob))
                {
                    layerEntity = new NativeArray <CanvasLayer>(roots.Length, Allocator.TempJob);
                    for (int i = 0; i < layerEntity.Length; i++)
                    {
                        layerEntity[i] = new CanvasLayer()
                        {
                            CanvasEntity = roots[i],
                            SortId       = canvasLayerIdFromEntity[roots[i]].Value
                        }
                    }
                    ;
                    layerEntity.Sort();
                }
                NativeMultiHashMap <int, int> cameraIdToLayerIdx = new NativeMultiHashMap <int, int>(layerEntity.Length, Allocator.Temp);
                for (int i = 0; i < layerEntity.Length; i++)
                {
                    if (EntityManager.HasComponent(layerEntity[i].CanvasEntity,
                                                   typeof(CanvasTargetCamera)))
                    {
                        var camera = EntityManager.GetSharedComponentData <CanvasTargetCamera>(layerEntity[i].CanvasEntity);
                        camera.Target.InjectedCommandBuffers.Clear();
                        cameraIdToLayerIdx.Add(camera.Target.GetInstanceID(), i);
                    }
                }

                for (int i = 0; i < layerEntity.Length; i++)
                {
                    var entity = layerEntity[i].CanvasEntity;
                    if (EntityManager.HasComponent(entity, typeof(CanvasTargetCamera)))
                    {
                        var camera = EntityManager.GetSharedComponentData <CanvasTargetCamera>(entity);
                        camera.Target.InjectedCommandBuffers.Add(EntityManager.GetSharedComponentData <CanvasCommandBufferContainer>(entity).Value);
                    }
                    else if (EntityManager.HasComponent(entity, typeof(CanvasTargetRenderTexture)))
                    {
                    }
                }
                layerEntity.Dispose();
            }

            if (m_UpdateVerticesOnlyGroup.CalculateEntityCount() > 0)
            {
                UpdateVerticesOnly();
            }
        }