Beispiel #1
0
        public void Execute(Entity entity, int index, [ReadOnly] ref Thickness thickness, [ReadOnly] ref Line line)
        {
            float3 dist = line.P2 - line.P1;
            float3 perp = new float3(-dist.z, dist.y, dist.x);

            perp = math.normalizesafe(perp) * 0.5f * thickness.Value;

            float3 p0 = line.P1 - perp;
            float3 p1 = line.P1 + perp;
            float3 p2 = line.P2 - perp;
            float3 p3 = line.P2 + perp;

            index *= 4;
            if (index + 4 > _vertexBuffer.Length)
            {
                return;
            }

            void *verticesPtr = _vertexBuffer.GetUnsafePtr();

            UnsafeUtility.WriteArrayElement(verticesPtr, index + 0, p0);
            UnsafeUtility.WriteArrayElement(verticesPtr, index + 1, p1);
            UnsafeUtility.WriteArrayElement(verticesPtr, index + 2, p2);
            UnsafeUtility.WriteArrayElement(verticesPtr, index + 3, p3);
        }
Beispiel #2
0
        /// <summary>
        /// 把输入写入发送buffer中
        /// </summary>
        /// <param name="buffer"></param>
        /// <param name="data"></param>
        /// <exception cref="InvalidOperationException"></exception>
        public unsafe void Schedule(DynamicBuffer <OutgoingRpcDataStreamBufferComponent> buffer, TActionRequest data)
        {
            TActionSerializer serializer = default;

            // 1字节:Rpc协议头 2字节:rpcIndex
            DataStreamWriter writer =
                new DataStreamWriter(UnsafeUtility.SizeOf <TActionRequest>() + 1 + 2, Allocator.Temp);

            if (buffer.Length == 0)
            {
                writer.WriteByte((byte)NetworkStreamProtocol.Rpc);
            }
            if (!rpcTypeHashToIndex.TryGetValue(rpcType, out var rpcIndex))
            {
                throw new InvalidOperationException("Could not find RPC index for type");
            }
            writer.WriteUShort((ushort)rpcIndex);
            serializer.Serialize(ref writer, data);

            // 把DataStreamWriter内存数据Copy到Buffer中
            var prevLen = buffer.Length;

            buffer.ResizeUninitialized(buffer.Length + writer.Length);
            byte *ptr = (byte *)buffer.GetUnsafePtr();

            ptr += prevLen;
            UnsafeUtility.MemCpy(ptr, writer.AsNativeArray().GetUnsafeReadOnlyPtr(), writer.Length);
        }
 public static unsafe void NativeInject <T, U>(this List <T> list, DynamicBuffer <U> buffer)
     where T : struct
     where U : struct
 {
     CheckSameDataType <T, U>();
     NativeInject(list, 0, buffer.GetUnsafePtr(), 0, buffer.Length);
 }
Beispiel #4
0
 public static unsafe void Set(DynamicBuffer <TextData> textBuffer, string value)
 {
     textBuffer.ResizeUninitialized(value.Length);
     fixed(char *str = value)
     {
         UnsafeUtility.MemCpy(textBuffer.GetUnsafePtr(), str, value.Length * 2);
     }
 }
Beispiel #5
0
        public unsafe void LoadSoundClipFromDisk(EntityManager mgr, Entity e, string filePath)
        {
            DynamicBuffer <AudioClipCompressed> audioClipCompressed = mgr.GetBuffer <AudioClipCompressed>(e);

            if (audioClipCompressed.Length > 0)
            {
                return;
            }

#if UNITY_ANDROID
            var op = IOService.RequestAsyncRead(filePath);
            while (op.GetStatus() <= AsyncOp.Status.InProgress)
            {
                ;
            }

            op.GetData(out byte *data, out int sizeInBytes);
            audioClipCompressed.ResizeUninitialized(sizeInBytes);
            byte *audioClipCompressedBytes = (byte *)audioClipCompressed.GetUnsafePtr();
            for (int i = 0; i < sizeInBytes; i++)
            {
                audioClipCompressedBytes[i] = data[i];
            }

            op.Dispose();
#else
            FixedString512          filePathFixedString = new FixedString512(filePath);
            Baselib_ErrorState      errorState          = new Baselib_ErrorState();
            Baselib_FileIO_SyncFile fileHandle          = Baselib_FileIO_SyncOpen(filePathFixedString.GetUnsafePtr(), Baselib_FileIO_OpenFlags.Read, &errorState);
            if (errorState.code != Baselib_ErrorCode.Success)
            {
                return;
            }

            UInt64 fileSize = Baselib_FileIO_SyncGetFileSize(fileHandle, &errorState);
            if (fileSize > Int32.MaxValue)
            {
                Baselib_FileIO_SyncClose(fileHandle, &errorState);
                return;
            }

            audioClipCompressed.ResizeUninitialized((int)fileSize);
            UInt64 bytesRead = Baselib_FileIO_SyncRead(fileHandle, 0, (IntPtr)audioClipCompressed.GetUnsafePtr(), (ulong)audioClipCompressed.Length, &errorState);
            Baselib_FileIO_SyncClose(fileHandle, &errorState);
#endif
        }
Beispiel #6
0
        public static unsafe void CopyToBuffer(NativeArray <float3> path, int pathLength, DynamicBuffer <AgentPathBuffer> buffer)
        {
            if (buffer.Length < pathLength)
            {
                buffer.ResizeUninitialized(pathLength);
            }

            UnsafeUtility.MemCpy(buffer.GetUnsafePtr(), path.GetUnsafePtr(), pathLength * UnsafeUtility.SizeOf <float3>());
        }
 public static void MemClear <T>(this DynamicBuffer <T> buffer)
     where T : unmanaged, IBufferElementData
 {
     unsafe
     {
         UnsafeUtility.MemClear(buffer.GetUnsafePtr(),
                                UnsafeUtility.SizeOf <T>() * buffer.Length);
     }
 }
Beispiel #8
0
        public CommandRingQueue(DynamicBuffer <B> dynamicBuffer)
        {
            int headSize = UnsafeUtility.SizeOf <CommandRingQueueHead>();

            if (headSize > dynamicBuffer.Length)
            {
                throw new InvalidOperationException("无法创建队列,Buffer长度不对: err -1");
            }

            _head = (CommandRingQueueHead *)dynamicBuffer.GetUnsafePtr();

            if (UnsafeUtility.SizeOf <T>() * _head->Capacity != dynamicBuffer.Length - headSize)
            {
                throw new InvalidOperationException("无法创建队列,Buffer长度不对.err -2");
            }

            _data = (T *)((byte *)dynamicBuffer.GetUnsafePtr() + headSize);
        }
        public static unsafe void SetBufferAsString <T>(DynamicBuffer <T> buf, string s) where T : struct
        {
            Assert.AreEqual(sizeof(char), TypeManager.GetTypeInfo <T>().ElementSize);

            buf.ResizeUninitialized(s.Length);
            fixed(char *ptr = s)
            {
                UnsafeUtility.MemCpy(buf.GetUnsafePtr(), ptr, s.Length * sizeof(char));
            }
        }
Beispiel #10
0
        /// <summary>
        /// Extension for <see cref="DynamicBuffer{T}"/> to copy to <see cref="NativeArray{T}"/>.
        /// </summary>
        /// <typeparam name="T">The type.</typeparam>
        /// <param name="buffer">The <see cref="DynamicBuffer{T}"/> to copy from.</param>
        /// <param name="nativeArray">The <see cref="NativeArray{T}"/> to copy to.</param>
        public static unsafe void CopyTo <T>(this DynamicBuffer <T> buffer, NativeArray <T> nativeArray)
            where T : struct
        {
            if (buffer.Length != nativeArray.Length)
            {
                throw new ArgumentException("array.Length does not match the length of this instance");
            }

            UnsafeUtility.MemCpy(nativeArray.GetUnsafePtr(), buffer.GetUnsafePtr(), buffer.Length * (long)UnsafeUtility.SizeOf <T>());
        }
Beispiel #11
0
        public void Execute(DynamicBuffer <ClothProjectedPosition> projected, DynamicBuffer <ClothCurrentPosition> current, DynamicBuffer <ClothPreviousPosition> previous)
        {
            var copySize = sizeof(float3) * previous.Length;

            // Copy current to previous
            {
                var srcPtr = current.GetUnsafePtr();
                var dstPtr = previous.GetUnsafePtr();

                UnsafeUtility.MemCpy(dstPtr, srcPtr, copySize);
            }

            // Copy projected to current
            {
                var srcPtr = projected.GetUnsafePtr();
                var dstPtr = current.GetUnsafePtr();

                UnsafeUtility.MemCpy(dstPtr, srcPtr, copySize);
            }
        }
            public void Execute(Entity entity, int index, DynamicBuffer <SkinMatrix> skinMatrices, ref BoneIndexOffset boneIndexOffset, ref ComputeBufferIndex computeBufferIndex)
            {
                UnsafeUtility.MemCpy(
                    (float3x4 *)SkinMatricesBuffer.GetUnsafePtr() + computeBufferIndex.Value,
                    skinMatrices.GetUnsafePtr(),
                    skinMatrices.Length * UnsafeUtility.SizeOf <float3x4>()
                    );

                boneIndexOffset = new BoneIndexOffset {
                    Value = computeBufferIndex.Value
                };
            }
Beispiel #13
0
        public unsafe void Schedule(DynamicBuffer <OutgoingRpcDataStreamBufferComponent> buffer,
                                    ComponentDataFromEntity <GhostComponent> ghostFromEntity, TActionRequest data)
        {
            var serializer      = default(TActionSerializer);
            var serializerState = new RpcSerializerState {
                GhostFromEntity = ghostFromEntity
            };
            var msgHeaderLen = dynamicAssemblyList ? 10 : 4;
            int maxSize      = UnsafeUtility.SizeOf <TActionRequest>() + msgHeaderLen + 1;
            int rpcIndex     = 0;

            if (!dynamicAssemblyList && !rpcTypeHashToIndex.TryGetValue(rpcType, out rpcIndex))
            {
                throw new InvalidOperationException("Could not find RPC index for type");
            }
            while (true)
            {
                DataStreamWriter writer = new DataStreamWriter(maxSize, Allocator.Temp);
                int packetHeaderLen     = 0;
                if (buffer.Length == 0)
                {
                    packetHeaderLen = 1;
                    writer.WriteByte((byte)NetworkStreamProtocol.Rpc);
                }
                if (dynamicAssemblyList)
                {
                    writer.WriteULong(rpcType);
                }
                else
                {
                    writer.WriteUShort((ushort)rpcIndex);
                }
                var lenWriter = writer;
                writer.WriteUShort((ushort)0);
                serializer.Serialize(ref writer, serializerState, data);
                if (!writer.HasFailedWrites)
                {
                    if (writer.Length - packetHeaderLen > ushort.MaxValue)
                    {
                        throw new InvalidOperationException("RPC is too large to serialize");
                    }
                    lenWriter.WriteUShort((ushort)(writer.Length - msgHeaderLen - packetHeaderLen));
                    var prevLen = buffer.Length;
                    buffer.ResizeUninitialized(buffer.Length + writer.Length);
                    byte *ptr = (byte *)buffer.GetUnsafePtr();
                    ptr += prevLen;
                    UnsafeUtility.MemCpy(ptr, writer.AsNativeArray().GetUnsafeReadOnlyPtr(), writer.Length);
                    break;
                }
                maxSize *= 2;
            }
        }
            public unsafe void Execute(Entity entity, int index, DynamicBuffer <NetworkInBuffer> inBuffer, ref NetworkConnection connection)
            {
                //if (!connection.value.IsCreated) return;


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


                DataStreamReader reader;

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

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

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

                    default:
#if ENABLE_UNITY_COLLECTIONS_CHECKS
                        throw new InvalidOperationException("Received unknown network event " + networkEvent);
#else
                        break;
#endif
                    }
                }
            }
Beispiel #15
0
        public static unsafe void Add <T>(this DynamicBuffer <T> self, ref DataStreamReader reader)
            where T : struct, IBufferElementData
        {
#if ENABLE_UNITY_COLLECTIONS_CHECKS
            if (UnsafeUtility.SizeOf <T>() != 1)
            {
                throw new System.InvalidOperationException("Can only Add to DynamicBuffers of size 1 from DataStreamReaders");
            }
#endif
            var oldLen = self.Length;
            var length = reader.Length - reader.GetBytesRead();
            self.ResizeUninitialized(oldLen + length);
            reader.ReadBytes((byte *)self.GetUnsafePtr() + oldLen, length);
        }
            public unsafe void Execute(Entity entity, int index, DynamicBuffer <TBufferElementData> buffer, ref NetworkConnection connection)
            {
                //if (!connection.value.IsCreated)
                //    return;

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

                    /*DataStreamWriter tmp = new DataStreamWriter(buffer.Length, Allocator.Temp);
                     * tmp.WriteBytes((byte*)buffer.GetUnsafePtr(), buffer.Length);
                     * driver.Send(unreliablePipeline, connection.Value, tmp);
                     * buffer.Clear();*/
                }
            }
Beispiel #17
0
        protected void ConvertMeshRenderDataToDynamicMeshData(EntityCommandBuffer ecb, Entity smrEntity, SkinnedMeshRenderer smr,
                                                              bool needSkinningData)
        {
            if (smr.dynamicMesh != Entity.Null)
            {
                return;
            }

            Entity meshEntity        = smr.sharedMesh;
            Entity dynamicMeshEntity = ecb.CreateEntity();

            smr.dynamicMesh = dynamicMeshEntity;
            ecb.SetComponent(smrEntity, smr);

            if (EntityManager.HasComponent <LitMeshRenderData>(meshEntity))
            {
                LitMeshRenderData litMeshRenderData = EntityManager.GetComponentData <LitMeshRenderData>(meshEntity);
                ref LitMeshData   litMeshData       = ref litMeshRenderData.Mesh.Value;
                int indicesCount  = litMeshData.Indices.Length;
                int verticesCount = litMeshData.Vertices.Length;

                DynamicMeshData dmd = new DynamicMeshData
                {
                    Dirty               = true,
                    IndexCapacity       = indicesCount,
                    VertexCapacity      = verticesCount,
                    NumIndices          = indicesCount,
                    NumVertices         = verticesCount,
                    UseDynamicGPUBuffer = true,
                    CopyFrom            = needSkinningData ? meshEntity : Entity.Null
                };
                ecb.AddComponent(dynamicMeshEntity, dmd);

                DynamicBuffer <DynamicLitVertex> dlvBuffer = ecb.AddBuffer <DynamicLitVertex>(dynamicMeshEntity);
                dlvBuffer.ResizeUninitialized(verticesCount);
                void *verticesPtr  = litMeshData.Vertices.GetUnsafePtr();
                byte *dlvBufferPtr = (byte *)dlvBuffer.GetUnsafePtr();
                int   vertexSize   = UnsafeUtility.SizeOf <LitVertex>();
                UnsafeUtility.MemCpy(dlvBufferPtr, verticesPtr, verticesCount * vertexSize);

                DynamicBuffer <DynamicIndex> diBuffer = ecb.AddBuffer <DynamicIndex>(dynamicMeshEntity);
                diBuffer.ResizeUninitialized(indicesCount);
                void *indicesPtr  = litMeshData.Indices.GetUnsafePtr();
                void *dlBufferPtr = diBuffer.GetUnsafePtr();
                int   indexSize   = UnsafeUtility.SizeOf <DynamicIndex>();
                UnsafeUtility.MemCpy(dlBufferPtr, indicesPtr, indicesCount * indexSize);
            }
Beispiel #18
0
        /// <summary>
        /// 初始化队列
        /// </summary>
        /// <param name="dynamicBuffer"></param>
        /// <param name="capacity"></param>
        public static void Init(DynamicBuffer <B> dynamicBuffer, int capacity = 64)
        {
            if (UnsafeUtility.SizeOf <B>() != 1)
            {
                throw new InvalidOperationException("BufferElementData Size 只能是1字节");
            }

            // 分配大小
            int size = UnsafeUtility.SizeOf <CommandRingQueueHead>() + UnsafeUtility.SizeOf <T>() * capacity;

            dynamicBuffer.ResizeUninitialized(size);
            CommandRingQueueHead *head = (CommandRingQueueHead *)dynamicBuffer.GetUnsafePtr();

            head->Capacity = capacity;
            head->Count    = 0;
            head->Read     = 0;
            head->Write    = 0;
        }
Beispiel #19
0
        public unsafe void Schedule(DynamicBuffer <OutgoingRpcDataStreamBufferComponent> buffer, T data)
        {
            DataStreamWriter writer = new DataStreamWriter(128, Allocator.Temp);

            if (buffer.Length == 0)
            {
                writer.Write((byte)NetworkStreamProtocol.Rpc);
            }
            writer.Write(rpcType);
            data.Serialize(writer);
            var prevLen = buffer.Length;

            buffer.ResizeUninitialized(buffer.Length + writer.Length);
            byte *ptr = (byte *)buffer.GetUnsafePtr();

            ptr += prevLen;
            UnsafeUtility.MemCpy(ptr, writer.GetUnsafeReadOnlyPtr(), writer.Length);
        }
        public static unsafe void SendProtocolVersion(DynamicBuffer <OutgoingRpcDataStreamBufferComponent> buffer, NetworkProtocolVersion version)
        {
            bool             dynamicAssemblyList = (version.RpcCollectionVersion == 0);
            int              msgHeaderLen        = dynamicAssemblyList ? 10 : 4;
            DataStreamWriter writer = new DataStreamWriter(UnsafeUtility.SizeOf <NetworkProtocolVersion>() + msgHeaderLen + 1, Allocator.Temp);

#if ENABLE_UNITY_COLLECTIONS_CHECKS
            if (buffer.Length != 0)
            {
                throw new InvalidOperationException("Protocol version must be the very first RPC sent");
            }
#endif
            writer.WriteByte((byte)NetworkStreamProtocol.Rpc);
            if (dynamicAssemblyList)
            {
                writer.WriteULong(0);
            }
            else
            {
                writer.WriteUShort(ushort.MaxValue);
            }
            var lenWriter = writer;
            writer.WriteUShort((ushort)0);
            writer.WriteInt(version.NetCodeVersion);
            writer.WriteInt(version.GameVersion);
            if (dynamicAssemblyList)
            {
                writer.WriteULong(0);
                writer.WriteULong(0);
            }
            else
            {
                writer.WriteULong(version.RpcCollectionVersion);
                writer.WriteULong(version.ComponentCollectionVersion);
            }
            lenWriter.WriteUShort((ushort)(writer.Length - msgHeaderLen - 1));
            var prevLen = buffer.Length;
            buffer.ResizeUninitialized(buffer.Length + writer.Length);
            byte *ptr = (byte *)buffer.GetUnsafePtr();
            ptr += prevLen;
            UnsafeUtility.MemCpy(ptr, writer.AsNativeArray().GetUnsafeReadOnlyPtr(), writer.Length);
        }
Beispiel #21
0
        public unsafe void Convert(
            Entity entity,
            EntityManager destinationManager,
            GameObjectConversionSystem _)
        {
            DynamicBuffer <TBufferElementData> dynamicBuffer = destinationManager.AddBuffer <TBufferElementData>(entity);

            dynamicBuffer.ResizeUninitialized(Values.Length);

            if (Values.Length == 0)
            {
            }

            fixed(void *sourcePtr = &Values[0])
            {
                UnsafeUtility.MemCpy(
                    destination: dynamicBuffer.GetUnsafePtr(),
                    sourcePtr,
                    size: Values.Length * UnsafeUtility.SizeOf <TBufferElementData>());
            }
        }
        public static unsafe void SendProtocolVersion(DynamicBuffer <OutgoingRpcDataStreamBufferComponent> buffer, NetworkProtocolVersion version)
        {
            DataStreamWriter writer = new DataStreamWriter(UnsafeUtility.SizeOf <NetworkProtocolVersion>() + 2 + 1, Allocator.Temp);

#if ENABLE_UNITY_COLLECTIONS_CHECKS
            if (buffer.Length != 0)
            {
                throw new InvalidOperationException("Protocol version must be the very first RPC sent");
            }
#endif
            writer.Write((byte)NetworkStreamProtocol.Rpc);
            writer.Write(ushort.MaxValue);
            writer.Write(version.NetCodeVersion);
            writer.Write(version.GameVersion);
            writer.Write(version.RpcCollectionVersion);
            var prevLen = buffer.Length;
            buffer.ResizeUninitialized(buffer.Length + writer.Length);
            byte *ptr = (byte *)buffer.GetUnsafePtr();
            ptr += prevLen;
            UnsafeUtility.MemCpy(ptr, writer.GetUnsafeReadOnlyPtr(), writer.Length);
        }
Beispiel #23
0
        public unsafe void Schedule(DynamicBuffer <OutgoingRpcDataStreamBufferComponent> buffer, T data)
        {
            DataStreamWriter writer = new DataStreamWriter(UnsafeUtility.SizeOf <T>() + 2 + 1, Allocator.Temp);

            if (buffer.Length == 0)
            {
                writer.Write((byte)NetworkStreamProtocol.Rpc);
            }
            if (!rpcTypeHashToIndex.TryGetValue(rpcType, out var rpcIndex))
            {
                throw new InvalidOperationException("Could not find RPC index for type");
            }
            writer.Write((ushort)rpcIndex);
            data.Serialize(writer);
            var prevLen = buffer.Length;

            buffer.ResizeUninitialized(buffer.Length + writer.Length);
            byte *ptr = (byte *)buffer.GetUnsafePtr();

            ptr += prevLen;
            UnsafeUtility.MemCpy(ptr, writer.GetUnsafeReadOnlyPtr(), writer.Length);
        }
    protected override unsafe void OnUpdate()
    {
        EntityQuery          query   = GetEntityQuery(ComponentType.ReadWrite <TrailBufferElement>());
        NativeArray <Entity> entitis = query.ToEntityArray(Allocator.Persistent);
        int segmentCount             = entitis.Length;
        int trailElementCount        = 0;
        BufferFromEntity <TrailBufferElement> buffers = GetBufferFromEntity <TrailBufferElement>();

        for (int i = 0; i < entitis.Length; ++i)
        {
            trailElementCount += buffers[entitis[i]].Length;
        }

        if (!m_TrailElements.IsCreated || m_TrailElements.Length < trailElementCount)
        {
            if (m_TrailElements.IsCreated)
            {
                m_TrailElements.Dispose();
            }
            m_TrailElements = new NativeArray <float3>(CalcWrappingArraySize(trailElementCount), Allocator.Persistent);

            m_TrailElementBufferInShader?.Dispose();
            m_TrailElementBufferInShader = new ComputeBuffer(m_TrailElements.Length, sizeof(TrailBufferElement));
        }

        if (!m_Segments.IsCreated || m_Segments.Length < segmentCount)
        {
            if (m_Segments.IsCreated)
            {
                m_Segments.Dispose();
            }
            m_Segments = new NativeArray <int3>(CalcWrappingArraySize(segmentCount), Allocator.Persistent);

            m_SegmentBufferInShader?.Dispose();
            m_SegmentBufferInShader = new ComputeBuffer(m_Segments.Length, sizeof(TrailBufferElement));
        }

        int     offset           = 0;
        float3 *trailElementsPtr = (float3 *)m_TrailElements.GetUnsafePtr();
        int3 *  segmentsPtr      = (int3 *)m_Segments.GetUnsafePtr();

        for (int i = 0; i < segmentCount; ++i)
        {
            DynamicBuffer <float3> trailbuffer = buffers[entitis[i]].Reinterpret <float3>();
            Entity entity = entitis[i];

            int bufferlength = trailbuffer.Length;

            UnsafeUtility.MemCpy(trailElementsPtr, trailbuffer.GetUnsafePtr(), sizeof(float3) * bufferlength);
            *segmentsPtr = new int3(offset, bufferlength, entity.Index);

            offset += bufferlength;

            segmentsPtr++;
            trailElementsPtr += bufferlength;

            for (int j = 0; j < trailbuffer.Length; ++j)
            {
                if (trailbuffer[j].x == 0.0f && trailbuffer[j].y == 0.0f && trailbuffer[j].z == 0.0f)
                {
                    Debug.Log(entity.Index);
                }
            }
        }

        m_TrailElementBufferInShader.SetData(m_TrailElements);
        m_SegmentBufferInShader.SetData(m_Segments);

        m_MaterialPropertyBlock.SetBuffer("_Positions", m_TrailElementBufferInShader);
        m_MaterialPropertyBlock.SetBuffer("_Segments", m_SegmentBufferInShader);

        m_MeshInstancedArgs.SetData(m_TrailMesh, (uint)segmentCount);

        Graphics.DrawMeshInstancedIndirect(
            m_TrailMesh, 0, m_Material,
            new Bounds(Vector3.zero, Vector3.one * 1000),
            m_MeshInstancedArgs.m_Buffer, 0, m_MaterialPropertyBlock
            );

        entitis.Dispose();
    }
 /// <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);
 }
Beispiel #26
0
 public void Execute(DynamicBuffer <EcsIntElement> b0, [ReadOnly] ref EcsTestData c1, [ReadOnly] ref EcsTestData2 c2)
 {
     b0.GetUnsafePtr();
 }
Beispiel #27
0
        public LoadResult CheckLoading(IntPtr cppwrapper, EntityManager man, Entity e, ref Image2D image, ref Image2DSTB imgSTB, ref Image2DLoadFromFile unused, ref Image2DSTBLoading loading)
        {
            int newHandle = 0;
            int r         = ImageIOSTBNativeCalls.CheckLoading(loading.internalId, ref newHandle);

            if (r == 0)
            {
                return(LoadResult.stillWorking);
            }
            FreeNative(man, e, ref imgSTB);
            Assert.IsTrue(newHandle > 0);
            imgSTB.imageHandle = newHandle;

            var fnLog = string.Empty;

            fnLog += man.GetBufferAsString <Image2DLoadFromFileImageFile>(e);
            if (man.HasComponent <Image2DLoadFromFileMaskFile>(e))
            {
                fnLog += " alpha=";
                fnLog += man.GetBufferAsString <Image2DLoadFromFileMaskFile>(e);
            }

            if (r == 2)
            {
                image.status            = ImageStatus.LoadError;
                image.imagePixelSize.xy = 0;
                Debug.LogFormat("Failed to load {0}", fnLog);
                return(LoadResult.failed);
            }

            int hasAlpha = 0;
            int w = 0, h = 0;

            unsafe
            {
                ImageIOSTBNativeCalls.GetImageFromHandle(imgSTB.imageHandle, ref hasAlpha, ref w, ref h);
                Assert.IsTrue(w > 0 && h > 0);
                image.hasAlpha         = hasAlpha != 0;
                image.imagePixelSize.x = (float)w;
                image.imagePixelSize.y = (float)h;
            }
            Debug.LogFormatAlways("Loaded image: {0} Handle {4} Size: {1},{2} Alpha: {3}", fnLog, w, h, image.hasAlpha?"yes":"no", imgSTB.imageHandle);

            // We finished loading the image and retrieve its pixel size, lets init the mask data also
            if (man.HasComponent <Image2DAlphaMask>(e))
            {
                DynamicBuffer <Image2DAlphaMaskData> maskData = man.GetBuffer <Image2DAlphaMaskData>(e);
                maskData.ResizeUninitialized(w * h);
                unsafe
                {
                    ImageIOSTBNativeCalls.InitImage2DMask(imgSTB.imageHandle, (byte *)(maskData.GetUnsafePtr()));
                    Debug.LogAlways("  Created alpha mask for image.");
                }
            }
            image.status = ImageStatus.Loaded;
            return(LoadResult.success);
        }
Beispiel #28
0
 static void CopyArrayToBuffer <T>(DynamicBuffer <T> buffer, void *source, int length, int sizeOfT) where T : struct
 {
     buffer.ResizeUninitialized(length);
     UnsafeUtility.MemCpy(buffer.GetUnsafePtr(), source, length * sizeOfT);
 }
 public static unsafe string AsString(this DynamicBuffer <char> buffer)
 {
     return(new string((char *)buffer.GetUnsafePtr(), 0, buffer.Length));
 }
Beispiel #30
0
 /// <summary>
 /// Resizes a <see cref="DynamicBuffer{T}"/> and then clears the memory.
 /// </summary>
 /// <typeparam name="T">The type.</typeparam>
 /// <param name="buffer">The <see cref="DynamicBuffer{T}"/> to resize.</param>
 /// <param name="length">Size to resize to.</param>
 public static unsafe void ResizeInitialized <T>(this DynamicBuffer <T> buffer, int length)
     where T : struct
 {
     buffer.ResizeUninitialized(length);
     UnsafeUtility.MemClear(buffer.GetUnsafePtr(), length * UnsafeUtility.SizeOf <T>());
 }