コード例 #1
0
            private static void CompletePathSearch(int jobIndex, Entity entityRequest, NavMeshQuery query,
                                                   EntityCommandBuffer.Concurrent commandBuffer, int pathSize, int maximumPoolSize,
                                                   NavMeshPathfindingRequestData request, DynamicBuffer <PathBufferElement> agentPathBuffer)
            {
                var resultPath = new NativeArray <PolygonId>(pathSize, Allocator.Temp);

                query.GetPathResult(resultPath);

                //Extract path from PolygonId list
                var straightPathCount = 0;
                var straightPath      = ExtractPath(query,
                                                    request.Start, request.Destination,
                                                    resultPath, maximumPoolSize, ref straightPathCount);

                //Put the result path into buffer
                for (int i = 0; i < straightPathCount; i++)
                {
                    agentPathBuffer.Add(new PathBufferElement {
                        Value = straightPath[i].position
                    });
                }

                straightPath.Dispose();
                resultPath.Dispose();

                request.Status = PathSearchStatus.Finished;
                commandBuffer.SetComponent(jobIndex, entityRequest, request);
            }
コード例 #2
0
            private void PopulateMesh(WorldSpaceRect rect, ElementScale scale, WorldSpaceMask mask, TextRenderer settings, float4 color, ref DynamicBuffer <TextData> textBuffer, ref DynamicBuffer <ControlVertexData> vertices, ref DynamicBuffer <ControlVertexIndex> triangles)
            {
                _VerticalAlignmentOptions   verticalAlignment   = (_VerticalAlignmentOptions)settings.Alignment;
                _HorizontalAlignmentOptions horizontalAlignment = (_HorizontalAlignmentOptions)settings.Alignment;

                var font      = FontAssetFromEntity[settings.Font];
                var glyphData = FontGlyphDataFromEntity[settings.Font];

                float2 canvasScale = settings.Size * scale.Value / font.PointSize;


                float stylePadding         = 1.25f + (settings.Bold ? font.BoldStyle / 4.0f : font.NormalStyle / 4.0f);
                float styleSpaceMultiplier = 1.0f + (settings.Bold ? font.BoldSpace * 0.01f : font.NormalSpace * 0.01f);

                NativeList <TextUtils.TextLineInfo> lines = new NativeList <TextUtils.TextLineInfo>(Allocator.Temp);

                TextUtils.CalculateLines(ref rect, canvasScale, styleSpaceMultiplier, ref glyphData, ref textBuffer, lines);
                float textBlockHeight = lines.Length * font.LineHeight * canvasScale.y;

                float2 alignedStartPosition = TextUtils.GetAlignedStartPosition(ref rect, ref settings, ref font, textBlockHeight, canvasScale);
                float2 currentCharacter     = alignedStartPosition;

                int lineIdx = 0;

                for (int i = 0; i < textBuffer.Length; i++)
                {
                    if (lineIdx < lines.Length && i == lines[lineIdx].CharacterOffset)
                    {
                        currentCharacter = new float2(TextUtils.GetAlignedLinePosition(ref rect, lines[lineIdx].LineWidth, horizontalAlignment),
                                                      alignedStartPosition.y - font.LineHeight * canvasScale.y * lineIdx);
                        lineIdx++;
                    }

                    var character = textBuffer[i].Value;
                    if (character == (ushort)'\n')
                    {
                        // It's handled in GetLinesOffsets
                        continue;
                    }
                    if (TextUtils.GetGlyph(character, ref glyphData, out FontGlyphData ch))
                    {
                        int startIndex = vertices.Length;

                        float2 uv2 = new float2(ch.Scale, ch.Scale) * math.select(canvasScale, -canvasScale, settings.Bold);

                        float2 vMin = currentCharacter + new float2(ch.Metrics.horizontalBearingX - stylePadding, ch.Metrics.horizontalBearingY - ch.Metrics.height - stylePadding) * canvasScale;
                        float2 vMax = vMin + new float2(ch.Metrics.width + stylePadding * 2.0f, ch.Metrics.height + stylePadding * 2.0f) * canvasScale;

                        float4 uv = new float4(ch.Rect.x - stylePadding, ch.Rect.y - stylePadding, (ch.Rect.x + ch.Rect.width + stylePadding), (ch.Rect.y + ch.Rect.height + stylePadding)) / new float4(font.AtlasSize, font.AtlasSize);

                        RectMaskCut cut     = SpriteUtility.GetRectangleMaskCut(vMin, vMax, uv.xy, uv.zw, ref mask);
                        var         cutSize = cut.Max + cut.Min;
                        if (!(cutSize.x > vMax.x - vMin.x) && !(cutSize.y > vMax.y - vMin.y))
                        {
                            float4 vertexPos = new float4(vMin + cut.Min, vMax - cut.Max);
                            uv.xy = uv.xy + cut.UvMin;
                            uv.zw = uv.zw - cut.UvMax;

                            triangles.Add(new ControlVertexIndex()
                            {
                                Value = startIndex + 2
                            });
                            triangles.Add(new ControlVertexIndex()
                            {
                                Value = startIndex + 1
                            });
                            triangles.Add(new ControlVertexIndex()
                            {
                                Value = startIndex
                            });

                            triangles.Add(new ControlVertexIndex()
                            {
                                Value = startIndex + 3
                            });
                            triangles.Add(new ControlVertexIndex()
                            {
                                Value = startIndex + 2
                            });
                            triangles.Add(new ControlVertexIndex()
                            {
                                Value = startIndex
                            });

                            vertices.Add(new ControlVertexData()
                            {
                                Position  = new float3(vertexPos.xy, 0.0f),
                                Normal    = new float3(0.0f, 0.0f, -1.0f),
                                TexCoord0 = uv.xy,
                                TexCoord1 = uv2,
                                Color     = color
                            });
                            vertices.Add(new ControlVertexData()
                            {
                                Position  = new float3(vertexPos.zy, 0.0f),
                                Normal    = new float3(0.0f, 0.0f, -1.0f),
                                TexCoord0 = uv.zy,
                                TexCoord1 = uv2,
                                Color     = color
                            });
                            vertices.Add(new ControlVertexData()
                            {
                                Position  = new float3(vertexPos.zw, 0.0f),
                                Normal    = new float3(0.0f, 0.0f, -1.0f),
                                TexCoord0 = uv.zw,
                                TexCoord1 = uv2,
                                Color     = color
                            });
                            vertices.Add(new ControlVertexData()
                            {
                                Position  = new float3(vertexPos.xw, 0.0f),
                                Normal    = new float3(0.0f, 0.0f, -1.0f),
                                TexCoord0 = uv.xw,
                                TexCoord1 = uv2,
                                Color     = color
                            });
                        }

                        currentCharacter += (new float2(ch.Metrics.horizontalAdvance * styleSpaceMultiplier, 0.0f) *
                                             canvasScale);
                    }
                }
            }
コード例 #3
0
 private static DynamicBuffer <VoxelBufferElement> GenerateTerrain(
     DynamicBuffer <VoxelBufferElement> voxelBuffer,
     in Translation translation
コード例 #4
0
 /// <summary>
 /// set the buffer elements of the given aBuffer
 /// </summary>
 /// <param name="ecb"></param>
 /// <param name="aBuffer"></param>
 /// <param name="bBuffer"></param>
 public static void SetBuffer(EntityCommandBuffer.ParallelWriter ecb, ref DynamicBuffer <FloatBufferElement> aBuffer, DynamicBuffer <FloatBufferElement> bBuffer)
 {
     aBuffer.Clear();
     aBuffer.CopyFrom(bBuffer);
 }
コード例 #5
0
        public void DynamicBuffer_Default_IsCreated_IsFalse()
        {
            DynamicBuffer <EcsIntElement> buffer = default;

            Assert.False(buffer.IsCreated);
        }
コード例 #6
0
ファイル: TextUtils.cs プロジェクト: wuyin1985/DotsUI
        public static void CalculateLines(ref WorldSpaceRect rect, float2 canvasScale, float styleSpaceMultiplier, ref DynamicBuffer <FontGlyphData> glyphData,
                                          ref DynamicBuffer <TextData> textBuffer, NativeList <TextLineInfo> ret)
        {
            float maxLineWidth = rect.Max.x - rect.Min.x;

            CurrentLineData currentLine = default;

            for (int i = 0; i < textBuffer.Length; i++)
            {
                var character = textBuffer[i].Value;
                if (character == '\n')
                {
                    ret.Add(new TextLineInfo()
                    {
                        CharacterOffset = currentLine.CharacterOffset,
                        LineWidth       = currentLine.LineWidth,
                    });
                    currentLine.CharacterOffset    = i + 1;
                    currentLine.LineWidth          = 0.0f;
                    currentLine.LineWordIndex      = 0;
                    currentLine.WordCharacterCount = 0;
                    currentLine.WordWidth          = 0.0f;
                    continue;
                }
                if (character == ' ')
                {
                    currentLine.LineWordIndex++;
                    currentLine.WordCharacterCount = -1;
                    currentLine.WordWidth          = 0.0f;
                }
                if (GetGlyph(character, ref glyphData, out var ch))
                {
                    if (((ch.Metrics.width * styleSpaceMultiplier *
                          canvasScale.x) < rect.Width))
                    {
                        currentLine.WordCharacterCount++;
                        float characterWidth = ch.Metrics.horizontalAdvance * styleSpaceMultiplier *
                                               canvasScale.x;
                        currentLine.LineWidth += characterWidth;
                        currentLine.WordWidth += characterWidth;

                        if (currentLine.LineWidth > maxLineWidth)
                        {
                            if (currentLine.LineWordIndex != 0)
                            {
                                ret.Add(new TextLineInfo()
                                {
                                    CharacterOffset = currentLine.CharacterOffset,
                                    LineWidth       = currentLine.LineWidth - currentLine.WordWidth,
                                });
                                currentLine.CharacterOffset = i - currentLine.WordCharacterCount + 1;
                                currentLine.LineWidth       = 0.0f;
                                currentLine.WordWidth       = 0.0f;
                                i = i - currentLine.WordCharacterCount + 1;
                                currentLine.LineWordIndex      = 0;
                                currentLine.WordCharacterCount = 0;
                            }
                            else
                            {
                                ret.Add(new TextLineInfo()
                                {
                                    CharacterOffset = currentLine.CharacterOffset,
                                    LineWidth       = currentLine.LineWidth,
                                });
                                currentLine.CharacterOffset    = i;
                                currentLine.LineWidth          = 0.0f;
                                currentLine.WordWidth          = 0.0f;
                                currentLine.LineWordIndex      = 0;
                                currentLine.WordCharacterCount = 0;
                            }
                        }
                        continue;
                    }
                    ret.Add(new TextLineInfo()
                    {
                        CharacterOffset = currentLine.CharacterOffset,
                        LineWidth       = currentLine.LineWidth,
                    });
                    currentLine.CharacterOffset    = i;
                    currentLine.LineWidth          = 0.0f;
                    currentLine.WordWidth          = 0.0f;
                    currentLine.LineWordIndex      = 0;
                    currentLine.WordCharacterCount = 0;
                }
            }
            ret.Add(new TextLineInfo()
            {
                CharacterOffset = currentLine.CharacterOffset, LineWidth = currentLine.LineWidth
            });
        }
コード例 #7
0
 public void Serialization(DynamicBuffer oBuffer)
 {
     oBuffer.WriteUTF8(Content);
 }
コード例 #8
0
 public static ref TSnapshot GetLastBaseline <TSnapshot>(this DynamicBuffer <TSnapshot> snapshotBuffer)
     where TSnapshot : struct, ISnapshotData <TSnapshot>
 {
     if (snapshotBuffer.Length == 0)
     {
         snapshotBuffer.Add(default);                 // needed or else we will read out of range on first execution
コード例 #9
0
ファイル: MapMeshGenSystem.cs プロジェクト: trazd66/PJddd
    protected override void OnUpdate()
    {
        // Acquire an ECB and convert it to a concurrent one to be able
        // to use it from a parallel job.
        var ecb = ecbSystem.CreateCommandBuffer();
        BufferFromEntity <TileMapBufferElement> lookup = GetBufferFromEntity <TileMapBufferElement>();


        Entities.WithAny <TileMapGeneration.T_MeshGen>().ForEach(
            (Entity entity, int entityInQueryIndex, in MapGenRequirement mapGenReq) =>
        {
            DynamicBuffer <TileMapBufferElement> tileMapBuffers = lookup[entity];
            if (tileMapBuffers.Length > 0)
            {
                MapMeshGenerator mapMeshGenerator = GetMapMeshGenerator(in mapGenReq, in tileMapBuffers, TileType.wall);

                RenderMesh tileMapRenderMesh = mapMeshGenerator.generateRenderMesh(
                    Resources.Load("testMaterial", typeof(UnityEngine.Material)) as UnityEngine.Material,
                    mapMeshGenerator.createTileMesh());
                //TODO: Make it read the materail from a material registry instead

                var meshCoillider = MapGenPhysics.createMeshCollider(mapMeshGenerator.vertices.ToArray(), mapMeshGenerator.triangles.ToArray());

                var tileMeshEntity = ecb.CreateEntity();
                ecb.AddComponent(tileMeshEntity, new PhysicsCollider {
                    Value = meshCoillider
                });

/*                    ecb.AddComponent(tileMeshEntity, new Parent {Value=entity});
 */
                ecb.AddComponent(tileMeshEntity, new LocalToWorld {
                });
                ecb.AddSharedComponent(tileMeshEntity, tileMapRenderMesh);
                ecb.AddComponent(tileMeshEntity, new RenderBounds
                {
                    Value =
                        new AABB
                    {
                        Center  = 0,
                        Extents = 10000000    //for testing purpose
                    }
                });
                ecb.AddComponent(tileMeshEntity, new Translation {
                });



                RenderMesh wallRenderMesh = mapMeshGenerator.generateRenderMesh(
                    Resources.Load("testMaterial", typeof(UnityEngine.Material)) as UnityEngine.Material,
                    mapMeshGenerator.CreateWallMesh(5));
                //TODO: Make it read the materail from a material registry instead

                var wallMeshCoillider = MapGenPhysics.createMeshCollider(mapMeshGenerator.wallVertices.ToArray(), mapMeshGenerator.wallTriangles.ToArray());

                var wallMeshEntity = ecb.CreateEntity();
                ecb.AddComponent(wallMeshEntity, new PhysicsCollider {
                    Value = wallMeshCoillider
                });

                /*                    ecb.AddComponent(tileMeshEntity, new Parent {Value=entity});
                 */
                ecb.AddComponent(wallMeshEntity, new LocalToWorld {
                });
                ecb.AddSharedComponent(wallMeshEntity, wallRenderMesh);
                ecb.AddComponent(wallMeshEntity, new RenderBounds
                {
                    Value =
                        new AABB
                    {
                        Center  = 0,
                        Extents = 10000000    //for testing purpose
                    }
                });
                ecb.AddComponent(wallMeshEntity, new Translation {
                });
                //-----------------------------------------------------------------

/*                    MapMeshGenerator floorMeshGenerator = GetMapMeshGenerator(in mapGenReq, in tileMapBuffers, TileType.floor);
 *                  RenderMesh floorRenderMesh = floorMeshGenerator.generateRenderMesh(
 *  Resources.Load("testMaterial", typeof(UnityEngine.Material)) as UnityEngine.Material,
 *  floorMeshGenerator.createTileMesh());
 *                  //TODO: Make it read the materail from a material registry instead
 *
 *                  var floorMeshCoillider = MapGenPhysics.createMeshCollider(floorMeshGenerator.vertices.ToArray(), floorMeshGenerator.triangles.ToArray());
 *
 *                  var floorMeshEntity = ecb.CreateEntity();
 *                  ecb.AddComponent(floorMeshEntity, new PhysicsCollider { Value = floorMeshCoillider });
 *//*                    ecb.AddComponent(tileMeshEntity, new Parent {Value=entity});
 *//*
 *                  ecb.AddComponent(floorMeshEntity, new LocalToWorld { });
 *                  ecb.AddSharedComponent(floorMeshEntity, floorRenderMesh);
 *                  ecb.AddComponent(floorMeshEntity, new RenderBounds
 *                  {
 *                      Value =
 *                      new AABB
 *                      {
 *                          Center = 0,
 *                          Extents = 10000000//for testing purpose
 *                      }
 *                  });
 *                  ecb.AddComponent(floorMeshEntity, new Translation { });
 *
 */
                ecb.RemoveComponent <TileMapGeneration.T_MeshGen>(entity);   //mesh Generation finished
                ecb.AddComponent <TileMapGeneration.T_SpawnFlagGen>(entity); //Request starting spawn flag generation
            }
        }
            ).WithoutBurst().Run();//TODO : make it parrallel one day

        ecbSystem.AddJobHandleForProducer(this.Dependency);
    }
コード例 #10
0
 /// <summary>
 /// Adds a native version of <see cref="List{T}.AddRange(IEnumerable{T})"/>.
 /// </summary>
 /// <typeparam name="T">The type.</typeparam>
 /// <param name="list">The <see cref="List{T}"/> to add to.</param>
 /// <param name="dynamicBuffer">The dynamic buffer to add to the list.</param>
 public static unsafe void AddRange <T>(this List <T> list, DynamicBuffer <T> dynamicBuffer)
     where T : struct
 {
     list.AddRange(dynamicBuffer.GetUnsafePtr(), dynamicBuffer.Length);
 }
コード例 #11
0
        public void RetrieveSkinnedMeshData(Mesh uMesh, Entity meshEntity, EntityManager entityManager, bool isLit)
        {
            //There's no need to generate special vertex data for gpu skinning
            if (uMesh.bindposes.Length <= MeshSkinningConfig.GPU_SKINNING_MAX_BONES)
            {
                if (isLit)
                {
                    RetrieveLitMeshData(uMesh);
                }
                else
                {
                    RetrieveSimpleMeshData(uMesh);
                }
                return;
            }

            List <int>                duplicateVertexIndex        = new List <int>();
            List <Vector4>            duplicateBoneIndex          = new List <Vector4>();
            Dictionary <int, Vector4> existingVertex2NewBoneIndex = new Dictionary <int, Vector4>();
            Dictionary <int, int>     boneIndexCounter            = new Dictionary <int, int>();
            List <Vector2>            gpuDrawRange = new List <Vector2>();

            BoneWeight[] boneWeights = uMesh.boneWeights;
            int[]        triangles   = uMesh.triangles;

            //Separate mesh into different draw range for gpu skinning use
            for (int subMeshIndex = 0; subMeshIndex < uMesh.subMeshCount; subMeshIndex++)
            {
                UnityEngine.Rendering.SubMeshDescriptor uSubMeshDescriptor = uMesh.GetSubMesh(subMeshIndex);
                int curIndex  = uSubMeshDescriptor.indexStart;
                int lastIndex = uSubMeshDescriptor.indexStart;
                int endIndex  = curIndex + uSubMeshDescriptor.indexCount;
                while (curIndex < endIndex)
                {
                    int curBoneCount = boneIndexCounter.Count;
                    for (int offset = 0; offset < 3; offset++)
                    {
                        int        vertexIndex = triangles[curIndex + offset];
                        BoneWeight boneWeight  = boneWeights[vertexIndex];
                        curBoneCount += CalcToBeAddBoneIndexCount(boneIndexCounter, boneWeight);
                    }

                    if (curBoneCount > MeshSkinningConfig.GPU_SKINNING_MAX_BONES)
                    {
                        gpuDrawRange.Add(new Vector2(curIndex, subMeshIndex));
                        Debug.Log("GPU SkinnedMesh Draw Range[" + lastIndex + ":" + curIndex + "] BoneCount:" + boneIndexCounter.Count);
                        lastIndex = curIndex;
                        boneIndexCounter.Clear();
                    }
                    else
                    {
                        for (int offset = 0; offset < 3; offset++)
                        {
                            int        vertexIndex   = triangles[curIndex + offset];
                            BoneWeight curBoneWeight = boneWeights[vertexIndex];

                            //restore the new bone index and set it to the mesh later
                            Vector4 newBoneIndex = new Vector4();
                            newBoneIndex.x = GetNewBoneIndex(boneIndexCounter, curBoneWeight.weight0, curBoneWeight.boneIndex0);
                            newBoneIndex.y = GetNewBoneIndex(boneIndexCounter, curBoneWeight.weight1, curBoneWeight.boneIndex1);
                            newBoneIndex.z = GetNewBoneIndex(boneIndexCounter, curBoneWeight.weight2, curBoneWeight.boneIndex2);
                            newBoneIndex.w = GetNewBoneIndex(boneIndexCounter, curBoneWeight.weight3, curBoneWeight.boneIndex3);

                            Vector4 existingNewBoneIndex = new Vector4();
                            bool    isExist = existingVertex2NewBoneIndex.TryGetValue(vertexIndex, out existingNewBoneIndex);
                            if (isExist && newBoneIndex != existingNewBoneIndex)
                            {
                                bool needAdd        = true;
                                int  newVertexIndex = 0;
                                for (int j = 0; j < duplicateVertexIndex.Count; j++)
                                {
                                    if (duplicateVertexIndex[j] == vertexIndex && duplicateBoneIndex[j] == newBoneIndex)
                                    {
                                        newVertexIndex = uMesh.vertexCount + j;
                                        triangles[curIndex + offset] = newVertexIndex;
                                        needAdd = false;
                                        break;
                                    }
                                }

                                if (needAdd)
                                {
                                    duplicateVertexIndex.Add(vertexIndex);
                                    duplicateBoneIndex.Add(newBoneIndex);
                                    newVertexIndex = uMesh.vertexCount + duplicateVertexIndex.Count - 1;
                                    triangles[curIndex + offset] = newVertexIndex;
                                    existingVertex2NewBoneIndex[newVertexIndex] = newBoneIndex;
                                }
                            }
                            else
                            {
                                existingVertex2NewBoneIndex[vertexIndex] = newBoneIndex;
                            }
                        }

                        curIndex += 3;
                    }
                }

                if (lastIndex != curIndex)
                {
                    gpuDrawRange.Add(new Vector2(curIndex, subMeshIndex));
                    Debug.Log("GPU SkinnedMesh Draw Range[" + lastIndex + ":" + curIndex + "] BoneCount:" + boneIndexCounter.Count);
                }
            }
            Debug.Log("GPU SkinnedMesh Duplicate VertexCount:" + duplicateVertexIndex.Count);
            Debug.Log("GPU SkinnedMesh DrawCalls: " + gpuDrawRange.Count);

            //generate UMeshDataCache and adding duplicate vertices into UMeshDataCache
            int newVertexCount = uMesh.vertexCount + duplicateVertexIndex.Count;

            if (isLit)
            {
                RetrieveLitMeshData(uMesh, newVertexCount);
            }
            else
            {
                RetrieveSimpleMeshData(uMesh, newVertexCount);
            }
            for (int i = 0; i < duplicateVertexIndex.Count; i++)
            {
                int curVertexIndex      = uMesh.vertexCount + i;
                int originalVertexIndex = duplicateVertexIndex[i];
                uPositions[curVertexIndex]   = uPositions[originalVertexIndex];
                uUVs[curVertexIndex]         = uUVs[originalVertexIndex];
                uBoneWeights[curVertexIndex] = uBoneWeights[originalVertexIndex];
                uBoneIndices[curVertexIndex] = uBoneIndices[originalVertexIndex];

                if (!isLit)
                {
                    continue;
                }
                uNormals[curVertexIndex]    = uNormals[originalVertexIndex];
                uTangents[curVertexIndex]   = uTangents[originalVertexIndex];
                uBiTangents[curVertexIndex] = uBiTangents[originalVertexIndex];
                uColors[curVertexIndex]     = uColors[originalVertexIndex];
            }
            //Update the indices, some of the triangles reference to the duplicate vertex
            for (int i = 0; i < triangles.Length; i++)
            {
                uIndices[i] = Convert.ToUInt16(triangles[i]);
            }
            //Restore the original vertex bone index for switching GPU skinning to CPU skinning in the runtime
            DynamicBuffer <OriginalVertexBoneIndex> obiBuffer = entityManager.AddBuffer <OriginalVertexBoneIndex>(meshEntity);

            for (int i = 0; i < newVertexCount; i++)
            {
                Vector4 uBoneIndex = uBoneIndices[i];
                obiBuffer.Add(new OriginalVertexBoneIndex {
                    BoneIndex = new float4(uBoneIndex.x, uBoneIndex.y, uBoneIndex.z, uBoneIndex.w)
                });
                Vector4 newBoneIndex = existingVertex2NewBoneIndex[i];
                uBoneIndices[i] = newBoneIndex;
            }
            //Add GPUSkinnedMeshDrawRange for SkinnedMeshRendererConversion use.
            DynamicBuffer <GPUSkinnedMeshDrawRange> gsmdrBuffer = entityManager.AddBuffer <GPUSkinnedMeshDrawRange>(meshEntity);

            for (int i = 0; i < gpuDrawRange.Count; i++)
            {
                gsmdrBuffer.Add(new GPUSkinnedMeshDrawRange
                {
                    TriangleIndex = (int)gpuDrawRange[i].x,
                    SubMeshIndex  = (int)gpuDrawRange[i].y,
                });
            }
        }
コード例 #12
0
        public void OnlyTriggerEffectOfActiveSkill([Values(AbilityState.CooledDown, AbilityState.CoolingDown, AbilityState.Casting)] AbilityState state)
        {
            // Arrange
            Entity caster = _entityManager.CreateEntity();

            _entityManager.AddComponentData(caster, new Target()
            {
                Value = Entity.Null
            });

            _entityManager.AddComponentData(caster, new TestResource()
            {
                Value = 20
            });

            Ability ability = new Ability(1, 1, new Range())
            {
                State = AbilityState.Active
            };

            DynamicBuffer <AbilityBuffer> abilityBuffer = _entityManager.AddBuffer <AbilityBuffer>(caster);

            abilityBuffer.Add(new AbilityBuffer()
            {
                Ability = ability
            });
            abilityBuffer.Add(new AbilityBuffer()
            {
                Ability = new Ability(1, 1, new Range())
                {
                    State = state
                }
            });

            DynamicBuffer <TestEffectBuffer> testEffectBuffer = _entityManager.AddBuffer <TestEffectBuffer>(caster);

            testEffectBuffer.Add(new TestEffectBuffer()
            {
                AbilityIndex = 0,
                Effect       = new TestEffect()
                {
                    Affects = EffectAffectType.Target,
                    Value   = 1
                }
            });
            testEffectBuffer.Add(new TestEffectBuffer()
            {
                AbilityIndex = 1,
                Effect       = new TestEffect()
                {
                    Affects = EffectAffectType.Target,
                    Value   = 1
                }
            });

            _world.WithSystem <TestEffectTriggerSystem>();

            //Act
            _world.UpdateSystem <TestEffectTriggerSystem>();
            _world.CompleteAllJobs();

            //Assert
            TestEffectConsumerSystem conusmerSystem = _world.GetReference().GetExistingSystem <TestEffectConsumerSystem>();

            NativeStream.Reader reader = conusmerSystem.GetEffectReader();
            Assert.AreEqual(1, conusmerSystem.GetEffectReader().ComputeItemCount());
            reader.BeginForEachIndex(0);
            TestEffectContext ctx = reader.Read <TestEffectContext>();

            Assert.AreEqual(Entity.Null, ctx.Target);
            Assert.AreEqual(EffectAffectType.Target, ctx.Effect.Affects);
            Assert.AreEqual(1, ctx.Effect.Value);
            Assert.AreEqual(20, ctx.testResourceValue);
            reader.EndForEachIndex();
        }
コード例 #13
0
        protected int UpdateOneDisplayListCamera(Entity e, ref Camera2D cam, ref DisplayListCamera dlcCam, ref LocalToWorld tx, float primaryAspect)
        {
            var mgr = EntityManager;

            // get list and sorted list buffers
            DynamicBuffer <DisplayListEntry> dest       = mgr.GetBuffer <DisplayListEntry>(e);
            DynamicBuffer <SortedEntity>     destSorted = mgr.GetBuffer <SortedEntity>(e);

            dest.Clear();
            destSorted.Clear();
#if DEBUG
            if (!(cam.rect.x >= 0.0f && cam.rect.y >= 0.0f && cam.rect.x + cam.rect.width <= 1.0f &&
                  cam.rect.y + cam.rect.height <= 1.0f))
            {
                Debug.LogFormat("The camera {0} has an invalid rect field ({1},{2},{3},{4}). Fixing by clamping it to the unit rectangle (0,0,1,1) in DEVELOPMENT build only.",
                                e, cam.rect.x, cam.rect.y, cam.rect.width, cam.rect.height);
                cam.rect.Clamp(new Rect(0, 0, 1, 1));
            }
            if (cam.rect.IsEmpty())
            {
                Debug.LogFormat("The camera {0} has an empty rect field. Fixing by setting it to identity in DEVELOPMENT build only.", e);
                cam.rect = new Rect(0, 0, 1, 1);
            }
            if (cam.halfVerticalSize <= 0)
            {
                Debug.LogFormat("The camera {0} has an invalid halfVerticalSize size of {1}. Nothing will render for it.", e, cam.halfVerticalSize);
                return(0);
            }
            float mas = MaxAbsScale(tx.Value);
            if (!(mas > .99f && mas < 1.01f))
            {
                Debug.LogFormat("The entity {0} with a Camera2D has a maximum absolute scaling factor of {1}. Cameras can not be scaled for rendering. Rendering and picking with this camera will likely be wrong.",
                                e, mas);
            }
#endif
            // get camera sorting axis
            if (mgr.HasComponent <Camera2DAxisSort>(e))
            {
                var axissort = mgr.GetComponentData <Camera2DAxisSort>(e);
                dlcCam.sortingDot.xyz = -axissort.axis;
                dlcCam.sortingDot.w   = 0;
            }
            else
            {
                dlcCam.sortingDot.x = 0.0f;
                dlcCam.sortingDot.y = 0.0f;
                dlcCam.sortingDot.z = -1.0f;
                dlcCam.sortingDot.w = 0.0f;
            }
            // copy transform matrix
            dlcCam.world        = tx.Value;
            dlcCam.inverseWorld = math.inverse(dlcCam.world);

            // initialize 2d clipping
            if (mgr.HasComponent <Camera2DRenderToTexture>(e))
            {
                var   rtt         = mgr.GetComponentData <Camera2DRenderToTexture>(e);
                float localAspect = (float)rtt.width / (float)rtt.height;
                dlcCam.clip2D.x = cam.halfVerticalSize * localAspect;
                dlcCam.clip2D.y = cam.halfVerticalSize;
            }
            else
            {
                dlcCam.clip2D.x = cam.halfVerticalSize * primaryAspect;
                dlcCam.clip2D.y = cam.halfVerticalSize;
            }

            // initialize near/far clipping
            if (mgr.HasComponent <Camera2DClippingPlanes>(e))
            {
                var clipz = mgr.GetComponentData <Camera2DClippingPlanes>(e);
                dlcCam.clipZNear = clipz.near;
                dlcCam.clipZFar  = clipz.far;
            }
            else
            {
                dlcCam.clipZNear = float.MinValue;
                dlcCam.clipZFar  = float.MaxValue;
            }

#if DEBUG
            if (dlcCam.clipZNear >= dlcCam.clipZFar)
            {
                Debug.LogFormat("The camera {0} has an invalid z clip range [{1}...{2}]. Nothing will render for it.", e, dlcCam.clipZNear, dlcCam.clipZFar);
                return(0);
            }
#endif

            // add all items
            for (int i = 0; i < dlMakerReg.Count; i++)
            {
                AddItemsToListByType(dlMakerReg[i], dlcCam, cam, dest, destSorted);
            }

            // sort in c++
            unsafe {
                SortExternal(dest.GetUnsafePtr(), destSorted.GetUnsafePtr(), dest.Length);
            }

            return(dest.Length);
        }
コード例 #14
0
        protected override void OnUpdate()
        {
            var detectors = _entityQuery.ToComponentDataArray <DetectorComponent>(Allocator.TempJob);
            var entities  = _entityQuery.ToEntityArray(Allocator.TempJob);

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

                var triggersSet = new NativeHashMap <int, bool>(MaxColliders, Allocator.Temp);

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

                for (var index = 0; index < buffer.Length; index++)
                {
                    ColliderId colliderId = buffer[index];
                    _triggersCache[index] = colliderId.Value;
                    triggersSet.Add(colliderId.Value, false);
                }

                if (_detectorTriggers.TryGetValue(entities[i], out HashSet <int> triggerIds))
                {
                    int removeOldTriggersCount = 0;
                    var removeOldTriggers      = new NativeArray <int>(MaxColliders, Allocator.Temp);

                    foreach (var id in triggerIds)
                    {
                        // in new triggers there is no old
                        if (!triggersSet.ContainsKey(id))
                        {
                            removeOldTriggers[removeOldTriggersCount++] = id;
#if UNITY_EDITOR
                            Debug.Log("Trigger exit::" + id);
#endif
                            TryRemoveComponentsFromTriggers(EntityManager, entities[i], id);
                        }
                    }

                    for (var k = 0; k < removeOldTriggersCount; k++)
                    {
                        triggerIds.Remove(removeOldTriggers[k]);
                    }

                    for (int j = 0; j < detector.TriggersCount; j++)
                    {
                        var triggerId = _triggersCache[j];

                        if (!triggerIds.Contains(triggerId))
                        {
                            triggerIds.Add(triggerId);
#if UNITY_EDITOR
                            Debug.Log("Trigger enter::" + triggerId);
#endif
                            TryAddComponentsFromTriggers(EntityManager, entities[i]);
                        }
                    }

                    removeOldTriggers.Dispose();
                }
                else
                {
                    for (int j = 0; j < detector.TriggersCount; j++)
                    {
                        var triggerId = _triggersCache[j];

                        _detectorTriggers.Add(entities[i], new HashSet <int> {
                            triggerId
                        });
#if UNITY_EDITOR
                        Debug.Log("Trigger enter::" + triggerId);
#endif
                        TryAddComponentsFromTriggers(EntityManager, entities[i]);
                    }
                }

                triggersSet.Dispose();

                detectors[i] = detector;
            }

            _entityQuery.CopyFromComponentDataArray(detectors);

            detectors.Dispose();
            entities.Dispose();
        }
コード例 #15
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="a_collisionChecksEntities"></param>
        /// <param name="a_rayData"></param>
        /// <param name="a_rayMaxDistanceData"></param>
        /// <param name="a_isCollidingData"></param>
        /// <param name="collisionInstancesBufferElement"></param>
        /// <param name="canDebugAllChecks">Debug Log all checks, or only one (first one)</param>
        /// <param name="canDebugAllrays">Draw all, or only single ray (first one).</param>
        static public void _DebugRays(EntityCommandBuffer ecb, EntityArray a_collisionChecksEntities, ComponentDataFromEntity <RayData> a_rayData, ComponentDataFromEntity <RayMaxDistanceData> a_rayMaxDistanceData, ComponentDataFromEntity <IsCollidingData> a_isCollidingData, BufferFromEntity <CollisionInstancesBufferElement> collisionInstancesBufferElement, ComponentDataFromEntity <RayEntityPair4CollisionData> a_rayEntityPair4CollisionData, bool canDebugAllChecks, bool canDebugAllrays)
        {
            // Debug
            // ! Ensure test this only with single, or at most few ray entiities.


            // if ( !canDebugAllrays )

            // Debug all, or only one check
            int i_debugCollisionChecksCount = canDebugAllChecks ? a_collisionChecksEntities.Length : 1;

            for (int i_collisionChecksIndex = 0; i_collisionChecksIndex < i_debugCollisionChecksCount; i_collisionChecksIndex++)
            {
                Entity octreeRayEntity = a_collisionChecksEntities [i_collisionChecksIndex];
                Entity octreeRayEntity2;

                if (!a_rayData.Exists(octreeRayEntity))
                {
                    RayEntityPair4CollisionData rayEntityPair4CollisionData = a_rayEntityPair4CollisionData [octreeRayEntity];
                    octreeRayEntity2 = rayEntityPair4CollisionData.ray2CheckEntity;
                }
                else
                {
                    octreeRayEntity2 = octreeRayEntity;
                }

                // Draw all available rays, or signle ray
                if (canDebugAllrays)
                {
                    RayData            rayData            = a_rayData [octreeRayEntity2];
                    RayMaxDistanceData rayMaxDistanceData = a_rayMaxDistanceData [octreeRayEntity2];

                    Debug.DrawLine(rayData.ray.origin, rayData.ray.origin + rayData.ray.direction * rayMaxDistanceData.f, Color.red);
                }
                else if (i_collisionChecksIndex == 0)
                {
                    RayData            rayData            = a_rayData [octreeRayEntity2];
                    RayMaxDistanceData rayMaxDistanceData = a_rayMaxDistanceData [octreeRayEntity2];

                    Debug.DrawLine(rayData.ray.origin, rayData.ray.origin + rayData.ray.direction * rayMaxDistanceData.f, Color.red);
                }
                //}


                // Last known instances collisions count.
                IsCollidingData isCollidingData = a_isCollidingData [octreeRayEntity];

                if (isCollidingData.i_collisionsCount > 0)
                {
                    // Debug.Log ( "Octree: Last known instances collisions count #" + isCollidingData.i_collisionsCount ) ;

                    // Stores reference to detected colliding instance.
                    DynamicBuffer <CollisionInstancesBufferElement> a_collisionInstancesBuffer = collisionInstancesBufferElement [octreeRayEntity];


                    string s_collidingIDs = "";

                    CollisionInstancesBufferElement collisionInstancesBuffer;

                    for (int i = 0; i < isCollidingData.i_collisionsCount; i++)
                    {
                        collisionInstancesBuffer = a_collisionInstancesBuffer [i];
                        s_collidingIDs          += collisionInstancesBuffer.i_ID + ", ";
                    }

                    CollisionInstancesBufferElement closestCollisionInstance = a_collisionInstancesBuffer [isCollidingData.i_nearestInstanceCollisionIndex];
                    Entity closestInstanceEntity = new Entity()
                    {
                        Index   = closestCollisionInstance.i_ID,
                        Version = closestCollisionInstance.i_version
                    };

                    // Test highlight
                    Highlight.SwitchMethods._Switch(ecb, closestInstanceEntity);

                    Debug.Log("Is colliding with #" + isCollidingData.i_collisionsCount + " instances of IDs: " + s_collidingIDs + "; Nearest collided instance is at " + isCollidingData.f_nearestDistance + "m, with ID #" + a_collisionInstancesBuffer [isCollidingData.i_nearestInstanceCollisionIndex].i_ID);
                }
            } // for
        }
コード例 #16
0
        internal static void InitEmitterConeSource(EntityManager mgr, Entity emitter, DynamicBuffer <Particle> particles, int offset, Range speed, float randomizePos, float randomizeDir, float4x4 matrix, ref Random rand)
        {
            var source = mgr.GetComponentData <EmitterConeSource>(emitter);

            source.Angle = math.clamp(source.Angle, 0.0f, 90.0f);
            float coneAngle = math.radians(source.Angle);

            for (var i = offset; i < particles.Length; i++)
            {
                var    particle         = particles[i];
                float  angle            = rand.Random01() * 2.0f * math.PI;
                float  radiusNormalized = math.sqrt(rand.Random01());
                float3 localPositionOnConeBase;
                localPositionOnConeBase.x = math.cos(angle);
                localPositionOnConeBase.y = math.sin(angle);
                localPositionOnConeBase.z = 0.0f;
                localPositionOnConeBase  *= radiusNormalized;
                particle.position         = GetParticlePosition(localPositionOnConeBase * source.Radius, randomizePos, matrix, ref rand);
                float  directionRadius = math.sin(coneAngle);
                float  directionHeight = math.cos(coneAngle);
                float3 direction       = new float3(localPositionOnConeBase.x * directionRadius, localPositionOnConeBase.y * directionRadius, directionHeight);
                particle.velocity = GetParticleVelocity(ref direction, speed, randomizeDir, matrix, ref rand);
                particle.rotation = GetParticleRotation(mgr, emitter, direction, ref rand);
                particles[i]      = particle;
            }
        }
コード例 #17
0
 public static void Collide(ref BallData ball, ref NativeQueue <EventData> .ParallelWriter events,
                            ref CollisionEventData collEvent, ref DynamicBuffer <BallInsideOfBufferElement> insideOfs,
                            ref TriggerAnimationData animationData, in Collider coll)
コード例 #18
0
        internal static void InitEmitterSphereSource(EntityManager mgr, Entity emitter, DynamicBuffer <Particle> particles, int offset, float radius, bool hemisphere, Range speed, float randomizePos, float randomizeDir, float4x4 matrix, ref Random rand)
        {
            for (var i = offset; i < particles.Length; i++)
            {
                var    particle             = particles[i];
                float3 positionOnUnitSphere = rand.NextFloat3Direction();

                // For sphere, z ranges from [-1, 1]. For hemisphere, z ranges from [0, 1].
                if (hemisphere)
                {
                    positionOnUnitSphere.z = math.abs(positionOnUnitSphere.z);
                }

                // Create more points toward the outer part of the sphere
                float3 position = positionOnUnitSphere * math.pow(rand.Random01(), 1.0f / 3.0f) * radius;

                particle.position = GetParticlePosition(position, randomizePos, matrix, ref rand);
                particle.velocity = GetParticleVelocity(ref positionOnUnitSphere, speed, randomizeDir, matrix, ref rand);
                particle.rotation = GetParticleRotation(mgr, emitter, positionOnUnitSphere, ref rand);
                particles[i]      = particle;
            }
        }
コード例 #19
0
 public void Deserialization(DynamicBuffer oBuffer)
 {
     Content = oBuffer.ReadUTF8();
 }
コード例 #20
0
        internal static void InitEmitterRectangleSource(EntityManager mgr, Entity emitter, DynamicBuffer <Particle> particles, int offset, Range speed, float randomizePos, float randomizeDir, float4x4 matrix, ref Random rand)
        {
            // Unit rectangle centered at the origin
            float2 bottomLeft = new float2(-0.5f, -0.5f);
            float2 topRight   = new float2(0.5f, 0.5f);
            float3 direction  = new float3(0, 0, 1);

            for (var i = offset; i < particles.Length; i++)
            {
                var particle = particles[i];
                var position = new float3(rand.NextFloat2(bottomLeft, topRight), 0.0f);
                particle.position = GetParticlePosition(position, randomizePos, matrix, ref rand);
                particle.velocity = GetParticleVelocity(ref direction, speed, randomizeDir, matrix, ref rand);
                particle.rotation = GetParticleRotation(mgr, emitter, direction, ref rand);
                particles[i]      = particle;
            }
        }
コード例 #21
0
    Mesh MakeMesh(DynamicBuffer <MeshVert> vertices, DynamicBuffer <MeshTri> triangles, DynamicBuffer <MeshUv> uvs)
    {
        //	Convert vertices and uvs
        Vector3[] verticesArray  = new Vector3[vertices.Length];
        int[]     trianglesArray = new int[triangles.Length];
        Vector2[] uvsArray       = new Vector2[uvs.Length];

        for (int i = 0; i < vertices.Length; i++)
        {
            verticesArray[i] = vertices[i].vertex;
            uvsArray[i]      = uvs[i].uv;
        }

        for (int i = 0; i < triangles.Length; i++)
        {
            trianglesArray[i] = triangles[i].triangle;
        }

        Mesh mesh = new Mesh();

        mesh.vertices = verticesArray;
        mesh.uv       = uvsArray;
        mesh.SetTriangles(trianglesArray, 0);

        mesh.RecalculateNormals();
        return(mesh);
    }
コード例 #22
0
        internal static void InitEmitterCircleSource(EntityManager mgr, Entity emitter, DynamicBuffer <Particle> particles, int offset, Range speed, float randomizePos, float randomizeDir, float4x4 matrix, ref Random rand)
        {
            var radius = mgr.GetComponentData <EmitterCircleSource>(emitter).Radius;

            for (var i = offset; i < particles.Length; i++)
            {
                var   particle         = particles[i];
                float randomAngle      = rand.NextFloat((float)-math.PI, (float)math.PI);
                float radiusNormalized = math.sqrt(rand.Random01());
                radius *= radiusNormalized;
                var positionNormalized = new float3(math.sin(randomAngle), math.cos(randomAngle), 0.0f);
                particle.position = GetParticlePosition(positionNormalized * radius, randomizePos, matrix, ref rand);
                particle.velocity = GetParticleVelocity(ref positionNormalized, speed, randomizeDir, matrix, ref rand);
                particle.rotation = GetParticleRotation(mgr, emitter, positionNormalized, ref rand);
                particles[i]      = particle;
            }
        }
コード例 #23
0
        public void CreateAllPasses(int w, int h, Entity eCam, Entity eNode)
        {
            Camera     cam        = EntityManager.GetComponentData <Camera>(eCam);
            CameraMask cameraMask = new CameraMask {
                mask = ulong.MaxValue
            };

            if (EntityManager.HasComponent <CameraMask>(eCam))
            {
                cameraMask = EntityManager.GetComponentData <CameraMask>(eCam);
            }

            Entity ePassOpaque = EntityManager.CreateEntity();

            EntityManager.AddComponentData(ePassOpaque, new RenderPass
            {
                inNode              = eNode,
                sorting             = RenderPassSort.Unsorted,
                projectionTransform = float4x4.identity,
                viewTransform       = float4x4.identity,
                passType            = RenderPassType.Opaque,
                viewId              = 0xffff,
                scissor             = new RenderPassRect(),
                viewport            = new RenderPassRect {
                    x = 0, y = 0, w = (ushort)w, h = (ushort)h
                },
                clearFlags   = RenderPassClear.Depth | (cam.clearFlags == CameraClearFlags.SolidColor ? RenderPassClear.Color : 0),
                clearRGBA    = RendererBGFXSystem.PackColorBGFX(cam.backgroundColor),
                clearDepth   = 1.0f,
                clearStencil = 0
            });
            SetPassComponents(ePassOpaque, cameraMask, eCam);

            Entity ePassTransparent = EntityManager.CreateEntity();

            EntityManager.AddComponentData(ePassTransparent, new RenderPass
            {
                inNode              = eNode,
                sorting             = RenderPassSort.SortZLess,
                projectionTransform = float4x4.identity,
                viewTransform       = float4x4.identity,
                passType            = RenderPassType.Transparent,
                viewId              = 0xffff,
                scissor             = new RenderPassRect(),
                viewport            = new RenderPassRect {
                    x = 0, y = 0, w = (ushort)w, h = (ushort)h
                },
                clearFlags   = 0,
                clearRGBA    = 0,
                clearDepth   = 1.0f,
                clearStencil = 0
            });
            SetPassComponents(ePassTransparent, cameraMask, eCam);

            Entity ePassSprites = EntityManager.CreateEntity();

            EntityManager.AddComponentData(ePassSprites, new RenderPass
            {
                inNode              = eNode,
                sorting             = RenderPassSort.Sorted,
                projectionTransform = float4x4.identity,
                viewTransform       = float4x4.identity,
                passType            = RenderPassType.Sprites,
                viewId              = 0xffff,
                scissor             = new RenderPassRect(),
                viewport            = new RenderPassRect {
                    x = 0, y = 0, w = (ushort)w, h = (ushort)h
                },
                clearFlags   = 0,
                clearRGBA    = 0,
                clearDepth   = 1.0f,
                clearStencil = 0
            });
            SetPassComponents(ePassSprites, cameraMask, eCam);
            EntityManager.AddBuffer <SortSpritesEntry>(ePassSprites);

            Entity ePassUI = EntityManager.CreateEntity();

            EntityManager.AddComponentData(ePassUI, new RenderPass
            {
                inNode              = eNode,
                sorting             = RenderPassSort.Sorted,
                projectionTransform = float4x4.identity,
                viewTransform       = float4x4.identity,
                passType            = RenderPassType.UI,
                viewId              = 0xffff,
                scissor             = new RenderPassRect(),
                viewport            = new RenderPassRect {
                    x = 0, y = 0, w = (ushort)w, h = (ushort)h
                },
                clearFlags   = 0,
                clearRGBA    = 0,
                clearDepth   = 1.0f,
                clearStencil = 0
            });
            SetPassComponents(ePassUI, cameraMask, eCam);

            // add passes to node, in order
            DynamicBuffer <RenderPassRef> passRefs = EntityManager.GetBuffer <RenderPassRef>(eNode);

            passRefs.Add(new RenderPassRef {
                e = ePassOpaque
            });
            passRefs.Add(new RenderPassRef {
                e = ePassTransparent
            });
            passRefs.Add(new RenderPassRef {
                e = ePassSprites
            });
            passRefs.Add(new RenderPassRef {
                e = ePassUI
            });
        }
コード例 #24
0
ファイル: Init.cs プロジェクト: glapoint22/SpaceShooter
    private void Start()
    {
        Vector3 topLeftScreen = Camera.main.ScreenToWorldPoint(new Vector3(0, Screen.height, Camera.main.transform.position.y));
        Vector3 gridExtents   = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, 0, Camera.main.transform.position.y));
        Vector2 cellSize      = new Vector2((gridExtents.x - topLeftScreen.x) / (cellsMultiplier - 2), (topLeftScreen.z - gridExtents.z) / (cellsMultiplier - 2));
        float2  gridPosition  = new float2
        {
            x = topLeftScreen.x - cellSize.x,
            y = topLeftScreen.z + cellSize.y
        };


        // Cursor.lockState = CursorLockMode.Locked;

        EntityManager entityManager = World.Active.EntityManager;


        // Cell
        EntityArchetype entityArcheType = entityManager.CreateArchetype(
            typeof(CellBounds),
            typeof(Units),
            typeof(NeighboringCells)
            );

        int totalCells = cellsMultiplier * cellsMultiplier;

        // Array of all the cells in the grid
        NativeArray <Entity> cells = new NativeArray <Entity>(totalCells, Allocator.Temp);

        entityManager.CreateEntity(entityArcheType, cells);


        for (int i = 0; i < cells.Length; i++)
        {
            Entity cell = cells[i];

            // Calculate the bounds of the current cell
            CellBounds cellBounds = new CellBounds
            {
                minX = gridPosition.x + (cellSize.x * (i % cellsMultiplier)),
                maxX = gridPosition.x + (cellSize.x * (i % cellsMultiplier)) + cellSize.x,
                minZ = gridPosition.y - (cellSize.y * (math.floor(i / cellsMultiplier))),
                maxZ = gridPosition.y - (cellSize.y * (math.floor(i / cellsMultiplier))) - cellSize.y
            };


            entityManager.SetComponentData(cell, cellBounds);
            entityManager.AddBuffer <Units>(cell);
            entityManager.AddBuffer <NeighboringCells>(cell);


            Debug.DrawLine(new Vector3(cellBounds.minX, 0, cellBounds.minZ), new Vector3(cellBounds.maxX, 0, cellBounds.minZ), Color.red, Mathf.Infinity);
            Debug.DrawLine(new Vector3(cellBounds.maxX, 0, cellBounds.minZ), new Vector3(cellBounds.maxX, 0, cellBounds.maxZ), Color.red, Mathf.Infinity);
            Debug.DrawLine(new Vector3(cellBounds.minX, 0, cellBounds.maxZ), new Vector3(cellBounds.maxX, 0, cellBounds.maxZ), Color.red, Mathf.Infinity);
            Debug.DrawLine(new Vector3(cellBounds.minX, 0, cellBounds.minZ), new Vector3(cellBounds.minX, 0, cellBounds.maxZ), Color.red, Mathf.Infinity);
        }



        // Create an array of the cell bounds. This is so we can calculate the neighboring cells to each cell
        EntityQuery entityQuery = entityManager.CreateEntityQuery(ComponentType.ReadOnly <CellBounds>());
        NativeArray <CellBounds> cellBoundsArray = entityQuery.ToComponentDataArray <CellBounds>(Allocator.TempJob);


        // Loop through all the cells to assign their neighboring cells
        for (int i = 0; i < cells.Length; i++)
        {
            // Extract the neighboring cells buffer from the current cell
            Entity cell = cells[i];
            DynamicBuffer <NeighboringCells> neighboringCellsBuffer = entityManager.GetBuffer <NeighboringCells>(cell);


            int cellIndex = i - (cellsMultiplier + 1);
            // Upper left neighbor
            if (cellIndex > -1 && cellBoundsArray[cellIndex].maxX == cellBoundsArray[i].minX)
            {
                neighboringCellsBuffer.Add(new NeighboringCells
                {
                    value = cellIndex
                });
            }

            // Upper neighbor
            cellIndex = i - cellsMultiplier;
            if (cellIndex > -1)
            {
                neighboringCellsBuffer.Add(new NeighboringCells
                {
                    value = cellIndex
                });
            }

            // Upper right neighbor
            cellIndex = i - (cellsMultiplier - 1);
            if (cellIndex > -1 && cellBoundsArray[cellIndex].minX == cellBoundsArray[i].maxX)
            {
                neighboringCellsBuffer.Add(new NeighboringCells
                {
                    value = cellIndex
                });
            }

            // Left neighbor
            cellIndex = i - 1;
            if (cellIndex > -1 && cellBoundsArray[cellIndex].maxX == cellBoundsArray[i].minX)
            {
                neighboringCellsBuffer.Add(new NeighboringCells
                {
                    value = cellIndex
                });
            }

            // Right neighbor
            cellIndex = i + 1;
            if (cellIndex <= totalCells - 1 && cellBoundsArray[i].maxX == cellBoundsArray[cellIndex].minX)
            {
                neighboringCellsBuffer.Add(new NeighboringCells
                {
                    value = cellIndex
                });
            }

            // Lower left neighbor
            cellIndex = i + (cellsMultiplier - 1);
            if (cellIndex <= totalCells - 1 && cellBoundsArray[i].minX == cellBoundsArray[cellIndex].maxX)
            {
                neighboringCellsBuffer.Add(new NeighboringCells
                {
                    value = cellIndex
                });
            }

            // Lower neighbor
            cellIndex = i + cellsMultiplier;
            if (cellIndex <= totalCells - 1)
            {
                neighboringCellsBuffer.Add(new NeighboringCells
                {
                    value = cellIndex
                });
            }

            // Lower right neighbor
            cellIndex = i + (cellsMultiplier + 1);
            if (cellIndex <= totalCells - 1 && cellBoundsArray[i].maxX == cellBoundsArray[cellIndex].minX)
            {
                neighboringCellsBuffer.Add(new NeighboringCells
                {
                    value = cellIndex
                });
            }
        }

        cellBoundsArray.Dispose();
        cells.Dispose();


        // Player
        entityArcheType = entityManager.CreateArchetype(
            typeof(Player),
            typeof(Translation),
            typeof(RenderMesh),
            typeof(LocalToWorld),
            typeof(Rotation),
            typeof(Velocity),
            typeof(Rotate),
            typeof(RotateSpeed),
            typeof(Size),
            typeof(CellIndex)
            );


        Entity player = entityManager.CreateEntity(entityArcheType);

        entityManager.SetSharedComponentData(player, new RenderMesh
        {
            mesh     = playerMesh,
            material = material
        });


        entityManager.SetComponentData(player, new Translation
        {
            Value = new float3
            {
                x = 0,
                y = 0,
                z = 0
            }
        });

        entityManager.SetComponentData(player, new Size
        {
            value = new float3 {
                x = 1, y = 1, z = 1
            }
        });

        entityManager.SetComponentData(player, new RotateSpeed
        {
            value = 0.05f
        });


        entityManager.SetComponentData(player, new CellIndex
        {
            value = -1
        });

        // Bullet
        entityArcheType = entityManager.CreateArchetype(
            typeof(Bullet),
            typeof(Translation),
            typeof(RenderMesh),
            typeof(LocalToWorld),
            typeof(Velocity),
            typeof(Scale),
            typeof(Size),
            typeof(Disabled),
            typeof(CellIndex)
            );

        NativeArray <Entity> bulletsArray = new NativeArray <Entity>(22, Allocator.Temp);

        entityManager.CreateEntity(entityArcheType, bulletsArray);

        for (int i = 0; i < bulletsArray.Length; i++)
        {
            Entity bullet = bulletsArray[i];

            entityManager.SetSharedComponentData(bullet, new RenderMesh
            {
                mesh     = bulletMesh,
                material = material
            });

            entityManager.SetComponentData(bullet, new Scale
            {
                Value = 0.1f
            });
            entityManager.SetComponentData(bullet, new Size
            {
                value = new float3 {
                    x = 0.1f, y = 0.1f, z = 0.1f
                }
            });

            entityManager.SetComponentData(bullet, new CellIndex
            {
                value = -1
            });
        }

        bulletsArray.Dispose();

        // Enemy
        entityArcheType = entityManager.CreateArchetype(
            typeof(Enemy),
            typeof(Translation),
            typeof(RenderMesh),
            typeof(LocalToWorld),
            typeof(Rotation),
            typeof(Velocity),
            typeof(Size),
            typeof(Disabled),
            typeof(CellIndex)
            );

        NativeArray <Entity> enemiesArray = new NativeArray <Entity>(1000, Allocator.Temp);

        entityManager.CreateEntity(entityArcheType, enemiesArray);

        float2 extents = new float2
        {
            x = gridExtents.x + (cellSize.x * 0.5f),
            y = math.abs(gridExtents.z) + (cellSize.y * 0.5f)
        };

        for (int i = 0; i < enemiesArray.Length; i++)
        {
            Entity enemy = enemiesArray[i];

            entityManager.SetSharedComponentData(enemy, new RenderMesh
            {
                mesh     = enemyMesh,
                material = material
            });

            entityManager.SetComponentData(enemy, new Size
            {
                value = new float3 {
                    x = 1, y = 1, z = 1
                }
            });

            entityManager.SetComponentData(enemy, new CellIndex
            {
                value = -1
            });

            entityManager.SetComponentData(enemy, new Translation
            {
                Value = GetEnemyPosition(extents)
            });
        }


        enemiesArray.Dispose();
    }
コード例 #25
0
        private void ShowAdd()
        {
            DynamicBuffer <int> buffer       = new DynamicBuffer <int>();
            DynamicBuffer <int> secondBuffer = new DynamicBuffer <int>();

            #region dynamicbuffer.add

            buffer.Add(5);

            #endregion

            #region dynamicbuffer.addrange

            int[]             source      = { 1, 2, 3, 4, 5 };
            NativeArray <int> newElements = new NativeArray <int>(source, Allocator.Persistent);
            buffer.AddRange(newElements);

            #endregion

            #region dynamicbuffer.asnativearray

            int[] intArray = { 1, 2, 3, 4, 5 };
            NativeArray <int> .Copy(intArray, buffer.AsNativeArray());

            #endregion

            #region dynamicbuffer.capacity

            #endregion

            #region dynamicbuffer.clear

            buffer.Clear();

            #endregion

            #region dynamicbuffer.copyfrom.dynamicbuffer

            buffer.CopyFrom(secondBuffer);

            #endregion

            #region dynamicbuffer.copyfrom.nativearray

            int[]             sourceArray = { 1, 2, 3, 4, 5 };
            NativeArray <int> nativeArray = new NativeArray <int>(source, Allocator.Persistent);
            buffer.CopyFrom(nativeArray);

            #endregion

            #region dynamicbuffer.copyfrom.array

            int[] integerArray = { 1, 2, 3, 4, 5 };
            buffer.CopyFrom(integerArray);

            #endregion

            #region dynamicbuffer.getenumerator

            foreach (var element in buffer)
            {
                //Use element...
            }

            #endregion

            #region dynamicbuffer.getunsafeptr

            #endregion

            int insertionIndex = 2;

            #region dynamicbuffer.insert

            if (insertionIndex < buffer.Length)
            {
                buffer.Insert(insertionIndex, 6);
            }

            #endregion

            #region dynamicbuffer.iscreated

            #endregion

            #region dynamicbuffer.length

            for (int i = 0; i < buffer.Length; i++)
            {
                buffer[i] = i * i;
            }

            #endregion

            #region dynamicbuffer.removeat

            if (insertionIndex < buffer.Length)
            {
                buffer.RemoveAt(insertionIndex);
            }

            #endregion

            int start = 1;

            #region dynamicbuffer.removerange

            buffer.RemoveRange(start, 5);

            #endregion

            #region dynamicbuffer.reserve

            buffer.EnsureCapacity(buffer.Capacity + 10);

            #endregion

            #region dynamicbuffer.resizeuninitialized

            buffer.ResizeUninitialized(buffer.Length + 10);

            #endregion

            #region dynamicbuffer.indexoperator

            for (int i = 0; i < buffer.Length; i++)
            {
                buffer[i] = i * i;
            }

            #endregion

            #region dynamicbuffer.tonativearray

            NativeArray <int> copy = buffer.ToNativeArray(Allocator.Persistent);

            #endregion

            #region dynamicbuffer.trimexcess

            if (buffer.Capacity > buffer.Length)
            {
                buffer.TrimExcess();
            }

            #endregion
        }
コード例 #26
0
 private void BuildCommandBuffer(DynamicBuffer <MeshVertex> vertexArray, DynamicBuffer <MeshVertexIndex> indexArray, DynamicBuffer <SubMeshInfo> subMeshArray, Mesh unityMesh, CommandBuffer canvasCommandBuffer)
 {
     using (new ProfilerSample("RenderSystem.SetVertexBuffer"))
     {
         //unityMesh.Clear(true);
         unityMesh.SetVertexBufferParams(vertexArray.Length, m_MeshDescriptors[0], m_MeshDescriptors[1], m_MeshDescriptors[2], m_MeshDescriptors[3], m_MeshDescriptors[4]);
     }
     using (new ProfilerSample("UploadMesh"))
     {
         unityMesh.SetVertexBufferData(vertexArray.AsNativeArray(), 0, 0, vertexArray.Length, 0);
         unityMesh.SetIndexBufferParams(indexArray.Length, IndexFormat.UInt32);
         unityMesh.SetIndexBufferData(indexArray.AsNativeArray(), 0, 0, indexArray.Length);
         unityMesh.subMeshCount = subMeshArray.Length;
         for (int i = 0; i < subMeshArray.Length; i++)
         {
             var subMesh = subMeshArray[i];
             var descr   = new SubMeshDescriptor()
             {
                 baseVertex  = 0,
                 bounds      = default,
コード例 #27
0
            public void Execute(DynamicBuffer <ObserverDestroyVisibleActorBuffer> observerDestroyVisibleActorBuffer, DynamicBuffer <NetworkReliableOutBuffer> outBuffer)
            {
                for (int i = 0; i < observerDestroyVisibleActorBuffer.Length; ++i)
                {
                    var actorEntity = observerDestroyVisibleActorBuffer[i].actorEntity;

                    var s = new ActorDestroySerialize {
                        actorId = actorEntity.Index
                    };
                    s._DoSerialize(outBuffer);
                    //actorServerSystem.actorSpawner.OnDestroySerializeInServer(actorEntity, broadcastBuffer);
                }
            }
コード例 #28
0
        /// <summary>
        /// Returns an array of objects that intersect with the specified ray, if any. Otherwise returns an empty array. See also: IsColliding.
        /// </summary>
        /// <param name="i_nodeIndex">Internal octree node index.</param>
        /// <param name="checkRay">Ray to check. Passing by ref as it improves performance with structs.</param>
        /// <param name="l_resultInstanceIDs">List result.</param>
        /// <param name="i_nearestIndex">Nerest collision index from the lits.</param>
        /// <param name="f_nearestDistance">Nerest collision distance.</param>
        /// <param name="maxDistance">Distance to check.</param>
        /// <returns>Instances index, that intersect with the specified ray.</returns>
        static public bool _GetNodeColliding(RootNodeData rootNodeData, int i_nodeIndex, Ray checkRay, ref DynamicBuffer <CollisionInstancesBufferElement> a_collisionInstancesBuffer, ref IsCollidingData isCollidingData, DynamicBuffer <NodeBufferElement> a_nodesBuffer, DynamicBuffer <NodeChildrenBufferElement> a_nodeChildrenBuffer, DynamicBuffer <NodeInstancesIndexBufferElement> a_nodeInstancesIndexBuffer, DynamicBuffer <InstanceBufferElement> a_instanceBuffer, float f_maxDistance = float.PositiveInfinity)
        {
            float f_distance;

            NodeBufferElement nodeBuffer = a_nodesBuffer [i_nodeIndex];

            if (!nodeBuffer.bounds.IntersectRay(checkRay, out f_distance) || f_distance > f_maxDistance)
            {
                return(isCollidingData.i_collisionsCount > 0 ? true : false);
            }

            if (nodeBuffer.i_instancesCount > 0)
            {
                int i_nodeInstancesIndexOffset = i_nodeIndex * rootNodeData.i_instancesAllowedCount;

                CollisionInstancesBufferElement collisionInstancesBuffer = new CollisionInstancesBufferElement();

                // Check against any objects in this node
                for (int i = 0; i < rootNodeData.i_instancesAllowedCount; i++)
                {
                    NodeInstancesIndexBufferElement nodeInstancesIndexBuffer = a_nodeInstancesIndexBuffer [i_nodeInstancesIndexOffset + i];

                    // Get index of instance
                    int i_instanceIndex = nodeInstancesIndexBuffer.i;

                    // Check if instance exists, and if has intersecting bounds.
                    if (i_instanceIndex >= 0)
                    {
                        InstanceBufferElement instanceBuffer = a_instanceBuffer [i_instanceIndex];


                        if (instanceBuffer.bounds.IntersectRay(checkRay, out f_distance) && f_distance <= f_maxDistance)
                        {
                            if (f_distance < isCollidingData.f_nearestDistance)
                            {
                                isCollidingData.f_nearestDistance = f_distance;
                                isCollidingData.i_nearestInstanceCollisionIndex = isCollidingData.i_collisionsCount;
                            }


                            // Is expected, that the required length is no greater than current length + 1
                            // And is not negative.
                            int i_collisionsCount = isCollidingData.i_collisionsCount;
                            collisionInstancesBuffer.i_ID      = instanceBuffer.i_ID;
                            collisionInstancesBuffer.i_version = instanceBuffer.i_entityVersion;  // Optional, used when Id is used as entity index

                            // Assign colliding instance ID to buffer.
                            if (a_collisionInstancesBuffer.Length <= i_collisionsCount)
                            {
                                // Expand buffer if needed
                                a_collisionInstancesBuffer.Add(collisionInstancesBuffer);
                            }
                            else
                            {
                                a_collisionInstancesBuffer [i_collisionsCount] = collisionInstancesBuffer;
                            }

                            isCollidingData.i_collisionsCount++;
                        }
                    }
                }
            }


            // Check children for collisions
            // Check if having children
            if (nodeBuffer.i_childrenCount > 0)
            {
                int i_nodeChildrenIndexOffset = i_nodeIndex * 8;

                // We checked that is having children.
                for (int i = 0; i < 8; i++)
                {
                    NodeChildrenBufferElement nodeChildrenBuffer = a_nodeChildrenBuffer [i_nodeChildrenIndexOffset + i];
                    int i_nodeChildIndex = nodeChildrenBuffer.i_nodesIndex;

                    // Check if node exists
                    if (i_nodeChildIndex >= 0)
                    {
                        _GetNodeColliding(rootNodeData, i_nodeChildIndex, checkRay, ref a_collisionInstancesBuffer, ref isCollidingData, a_nodesBuffer, a_nodeChildrenBuffer, a_nodeInstancesIndexBuffer, a_instanceBuffer, f_maxDistance);
                    }
                }
            }

            return(isCollidingData.i_collisionsCount > 0 ? true : false);
        }
        public static void Add(ref DynamicBuffer <PublicEntityRef> buffer, PublicEntityRef entityref)
        {
            int i = FindInsertionPoint(ref buffer, entityref);

            buffer.Insert(i, entityref);
        }
コード例 #30
0
        Entity CreateFrontBufferRenderNode(int w, int h)
        {
            Entity eNode = EntityManager.CreateEntity();

            EntityManager.AddComponentData(eNode, new RenderNode {
            });
            EntityManager.AddComponentData(eNode, new RenderNodePrimarySurface {
            });

            var passRect = new RenderPassRect {
                x = 0, y = 0, w = (ushort)w, h = (ushort)h
            };
            Entity ePassBlit = EntityManager.CreateEntity();

            EntityManager.AddComponentData(ePassBlit, new RenderPass {
                inNode              = eNode,
                sorting             = RenderPassSort.Unsorted,
                projectionTransform = float4x4.identity,
                viewTransform       = float4x4.identity,
                passType            = RenderPassType.FullscreenQuad,
                viewId              = 0xffff,
                scissor             = new RenderPassRect(),
                viewport            = passRect,
                targetRect          = passRect,
                clearFlags          = RenderPassClear.Color,
                clearDepth          = 1.0f,
                clearStencil        = 0,
                clearRGBA           = 0xff,
                shadowMask          = ulong.MaxValue,
                cameraMask          = ulong.MaxValue
            });
            EntityManager.AddComponent <RenderPassAutoSizeToNode>(ePassBlit);
            EntityManager.AddComponent <RenderPassClearColorFromBorder>(ePassBlit);

            Entity ePassDebug = EntityManager.CreateEntity();

            EntityManager.AddComponentData(ePassDebug, new RenderPass {
                inNode              = eNode,
                sorting             = RenderPassSort.Sorted,
                projectionTransform = float4x4.identity,
                viewTransform       = float4x4.identity,
                passType            = RenderPassType.DebugOverlay,
                viewId              = 0xffff,
                scissor             = new RenderPassRect(),
                viewport            = passRect,
                targetRect          = passRect,
                clearFlags          = 0,
                clearDepth          = 1.0f,
                clearStencil        = 0,
                shadowMask          = ulong.MaxValue,
                cameraMask          = ulong.MaxValue
            });
            EntityManager.AddComponent <RenderPassAutoSizeToNode>(ePassDebug);

            DynamicBuffer <RenderNodeRef> nodeRefs = EntityManager.AddBuffer <RenderNodeRef>(eNode);
            DynamicBuffer <RenderPassRef> passRefs = EntityManager.AddBuffer <RenderPassRef>(eNode);

            passRefs.Add(new RenderPassRef {
                e = ePassBlit
            });
            passRefs.Add(new RenderPassRef {
                e = ePassDebug
            });

            return(eNode);
        }