private void DrawPartialGrid() { var channelData = m_Target.ChannelData; var buffer = m_Target.Buffer; int n = buffer.NumChannels; int w = buffer.Width; m_Pixels.CopyFrom(m_Black); for (int c = 0; c < n; c++) { if (m_DrawChannel[c]) { Color color = channelData.GetColor(c); var positions = channelData.GetGridPositions(c); foreach (var pos in positions) { int i = pos.y * w + pos.x; Color32 a = m_Pixels[i]; Color32 b = buffer.Read(c, pos) * color; // Add colors. b.r = (byte)Math.Min(a.r + b.r, 255); b.g = (byte)Math.Min(a.g + b.g, 255); b.b = (byte)Math.Min(a.b + b.b, 255); b.a = 255; m_Pixels[i] = b; } } } m_Texture.Apply(); }
public void DeepCopyFrom(AnimalBrain source) { // inputSynapsesWeights = source.inputSynapsesWeights.Clone() as float[,]; // outputSynapsesWeights = source.outputSynapsesWeights.Clone() as float[,]; // hiddenLayerSynapsesWeights = source.hiddenLayerSynapsesWeights.Clone() as float[,]; // secondHiddenLayerBias = source.secondHiddenLayerBias.Clone() as float[]; // hiddenLayerBias = source.hiddenLayerBias.Clone() as float[]; inputSynapsesWeights.CopyFrom(source.inputSynapsesWeights); outputSynapsesWeights.CopyFrom(source.outputSynapsesWeights); secondHiddenLayerBias.CopyFrom(source.secondHiddenLayerBias); hiddenLayerSynapsesWeights.CopyFrom(source.hiddenLayerSynapsesWeights); hiddenLayerBias.CopyFrom(source.hiddenLayerBias); }
private IEnumerator raiseMap(float duration) { float endTime = Time.time + duration; Color[] colors = tileDamageMap.GetPixels(); // Ensure pixels array is destroyed to prevent memory leaks if (pixels != null && pixels.IsCreated) { pixels.Dispose(); } pixels = new NativeArray <Color>(colors.Length, Allocator.Persistent); VelocityJob job; JobHandle jobHandle; while (endTime > Time.time) { colors = tileDamageMap.GetPixels(); pixels.CopyFrom(colors); // Initialize the job data job = new VelocityJob() { deltaTime = Time.deltaTime / duration, pixels = pixels }; jobHandle = job.Schedule(pixels.Length, 64); jobHandle.Complete(); job.pixels.CopyTo(colors); tileDamageMap.SetPixels(colors); yield return(null); } colors = tileDamageMap.GetPixels(); pixels.CopyFrom(colors); // Initialize the job data job = new VelocityJob() { deltaTime = 1, pixels = pixels }; jobHandle = job.Schedule(pixels.Length, 64); jobHandle.Complete(); job.pixels.CopyTo(colors); tileDamageMap.SetPixels(colors); pixels.Dispose(); }
/// <summary>Sort an array of unsigned integers.</summary> public void Sort(int maxShiftWidth = 32) { Profiler.BeginSample("RadixSort"); uint mask = 1; int valueCount = na_values.Length; JobHandle jobHandle; for (int m = 0; m < maxShiftWidth; m++) { radixBitCheckJob.mask = mask; jobHandle = radixBitCheckJob.Schedule(valueCount, Jobx.XL_BATCH_SIZE); jobHandle.Complete(); trueSumScanJob.InclusiveSumScan(); falseSumScanJob.InclusiveSumScan(); radixSortShuffleJob.lastFalseIdx = na_falsePrefixSum[valueCount - 1]; jobHandle = radixSortShuffleJob.Schedule(valueCount, Jobx.XL_BATCH_SIZE); jobHandle.Complete(); na_values.CopyFrom(na_sortedValues); na_indices.CopyFrom(na_sortedIndices); mask <<= 1; } Profiler.EndSample(); }
public static Mesh GetMesh() { vertices = new List <Vertex>(); triangles = new List <int>(); Mesh mesh = new Mesh(); AddCube(new Vector3Int(0, 0, 0), 1); AddCube(new Vector3Int(1, 0, 0), 2); AddCube(new Vector3Int(2, 0, 0), 3); AddCube(new Vector3Int(3, 0, 0), 7); AddCube(new Vector3Int(4, 0, 0), 12); AddCube(new Vector3Int(5, 0, 0), 13); AddCube(new Vector3Int(6, 0, 0), 14); AddCube(new Vector3Int(7, 0, 0), 15); AddCube(new Vector3Int(8, 0, 0), 16); AddCube(new Vector3Int(9, 0, 0), 17); var vertexCount = vertices.Count; mesh.SetVertexBufferParams(vertexCount, new[] { new VertexAttributeDescriptor(VertexAttribute.Position, VertexAttributeFormat.Float32, 4), new VertexAttributeDescriptor(VertexAttribute.TexCoord0, VertexAttributeFormat.Float32, 2), }); var verts = new NativeArray <Vertex>(vertexCount, Allocator.Temp); verts.CopyFrom(vertices.ToArray()); mesh.SetVertexBufferData(verts, 0, 0, vertexCount); mesh.SetTriangles(triangles.ToArray(), 0); mesh.RecalculateBounds(); return(mesh); }
public void SortNativeSlice_DoesNotChangeArrayBeyondLimits() { var random = new System.Random(); NativeArray <int> array = new NativeArray <int>(1000, Allocator.Persistent); Assert.IsTrue(array.IsCreated); for (int i = 0; i < array.Length; ++i) { array[i] = random.Next(int.MinValue, int.MaxValue); } var backupArray = new NativeArray <int>(array.Length, Allocator.Persistent); backupArray.CopyFrom(array); var slice = new NativeSlice <int>(array, 200, 600); slice.Sort(); for (var i = 0; i < 200; ++i) { Assert.AreEqual(backupArray[i], array[i]); } for (var i = 800; i < 1000; ++i) { Assert.AreEqual(backupArray[i], array[i]); } array.Dispose(); backupArray.Dispose(); }
//public void SetTextureInverseCurve(float[] curveArray) //{ // TextureInverseCurveArray = new NativeArray<float>(curveArray.Length, Allocator.Persistent); // TextureInverseCurveArray.CopyFrom(curveArray); //} void CreateSegments() { _segments = new LineSegment2D[_points2D.Length]; for (int i = 0; i <= _points2D.Length - 2; i++) { LineSegment2D lineSegment2D = new LineSegment2D(_points2D[i], _points2D[i + 1]); _segments[i] = lineSegment2D; if (_disableEdges[i] && _disableEdges[i + 1]) { _segments[i].DisableEdge = 1; } } if (_points2D.Length > 0) { LineSegment2D lineSegment2D = new LineSegment2D(_points2D[0], _points2D[_points2D.Length - 1]); _segments[_points2D.Length - 1] = lineSegment2D; if (_disableEdges[0] && _disableEdges[_points2D.Length - 1]) { _segments[_points2D.Length - 1].DisableEdge = 1; } } SegmentArray = new NativeArray <LineSegment2D>(_segments.Length, Allocator.Persistent); SegmentArray.CopyFrom(_segments); }
public void Execute() { var _path = StringToBytes.FromBytes(path.ToArray()); if (string.IsNullOrEmpty(_path)) { return; } StreamReader reader = null; try { rLOD0.CopyFrom(ReadGeomDataFromFile(FilePathForBuffer(_path, 0))); rLOD1.CopyFrom(ReadGeomDataFromFile(FilePathForBuffer(_path, 1))); rLOD2.CopyFrom(ReadGeomDataFromFile(FilePathForBuffer(_path, 2))); } catch (Exception) { } finally { if (reader != null) { reader.Close(); } } }
private void Update() { var randomizer = -Time.time / 2; if (Resolution <= 0) { Resolution = 0; } verticesNativeArray.CopyFrom(modifiedVertices); var job = new CalculateWavesJob(); job.Vertices = verticesNativeArray; job.BasePosition = transform.position; job.Randomizer = randomizer; job.Resolution = Resolution; job.Speed = Speed; job.YScale = YScale; var handle = job.Schedule(modifiedVertices.Length, 64); handle.Complete(); job.Vertices.CopyTo(modifiedVertices); }
public void InsertTriggerDivideNonBurstBulk() { var values = GetValues(); var positions = new NativeArray <float2>(values.Length, Allocator.TempJob); var quadTree = new NativeQuadTree <int>(Bounds); positions.CopyFrom(values); NativeArray <QuadElement <int> > elements = new NativeArray <QuadElement <int> >(positions.Length, Allocator.Temp); for (int i = 0; i < positions.Length; i++) { elements[i] = new QuadElement <int> { pos = positions[i], element = i }; } var s = Stopwatch.StartNew(); quadTree.ClearAndBulkInsert(elements); s.Stop(); Debug.Log(s.Elapsed.TotalMilliseconds); QuadTreeDrawer.Draw(quadTree); quadTree.Dispose(); positions.Dispose(); }
private void Update() { if (Input.GetKeyDown(KeyCode.Y)) { float startTime = Time.realtimeSinceStartup; for (int i = 0; i < myNumbers.Length; i++) { myNumbers[i] = Sigmoid(myNumbers[i]); } Debug.Log("Without jobs: " + (Time.realtimeSinceStartup - startTime)); } if (Input.GetKeyDown(KeyCode.U)) { float startTime = Time.realtimeSinceStartup; NativeArray <float> numbersToCompute = new NativeArray <float>(myNumbers.Length, Allocator.TempJob); numbersToCompute.CopyFrom(myNumbers); MyJob myJob = new MyJob() { numbers = numbersToCompute }; JobHandle jobHandle = myJob.Schedule(numbersToCompute.Length, 64); jobHandle.Complete(); Debug.Log("With jobs: " + (Time.realtimeSinceStartup - startTime)); numbersToCompute.Dispose(); } }
protected override JobHandle OnUpdate(JobHandle inputDeps) { if (audioSource == null) { audioSource = MusicManager.Instance.Source; return(inputDeps); } audioSource.GetSpectrumData(samples, 0, FFTWindow.Blackman); sampleArr.CopyFrom(samples); totalAmplitude[0] = 0f; var samplerJob = new AudioAmplitudeCalcJob { SampleGroupArr = sampleGroupArr, SampleArr = sampleArr, AmplitudeArr = amplitudeArr, TotalAmplitude = totalAmplitude }.Schedule(sampleGroupArr.Length, 1024, inputDeps); var ampJob = new AudioAmplitudeJob { Amplitudes = amplitudeArr, TotalAmplitude = totalAmplitude }.Schedule(audioEntities, samplerJob); return(ampJob); }
public void Refresh() { mesh.Clear(); var vertexCount = vertexList.Count; mesh.SetVertexBufferParams(vertexCount, new[] { new VertexAttributeDescriptor(VertexAttribute.Position, VertexAttributeFormat.Float32, 4), new VertexAttributeDescriptor(VertexAttribute.Color, VertexAttributeFormat.Float32, 4), new VertexAttributeDescriptor(VertexAttribute.TexCoord0, VertexAttributeFormat.Float32, 2), }); var verts = new NativeArray <Vertex>(vertexCount, Allocator.Temp); verts.CopyFrom(vertexList.ToArray()); mesh.SetVertexBufferData(verts, 0, 0, vertexCount); mesh.SetTriangles(triangles.ToArray(), 0); mesh.RecalculateBounds(); GetComponent <MeshRenderer>().sharedMaterial.SetTexture("_Array", TextureArrayManager.GetArray()); GetComponent <MeshFilter>().sharedMesh = mesh; if (isCollidable) { GetComponent <MeshCollider>().sharedMesh = mesh; } }
/// <summary> /// Animates the vertices of the procedural mesh analyzing the spectrum data, and updates the /// mesh vertices. /// </summary> private void AnimateVertices() { getSpectrumSampler.Begin(); audioSrc.GetSpectrumData(spectrumManaged, 0, FFTWindow.BlackmanHarris); getSpectrumSampler.End(); copySpectrumSampler.Begin(); spectrum.CopyFrom(spectrumManaged); copySpectrumSampler.End(); JobHandle meansHandle = spectrumAnalyzer.ScheduleSpectrumBandMeans(audioSrc.clip.frequency, spectrum); new AnimateVerticesJob { vertices = vertices, means = spectrumAnalyzer.SmoothedMeans, resolution = resolution, scale = scale, middleCorridorWidth = middleCorridorWidth, mountainNoiseWeight = mountainNoiseWeight, mountainNoiseFreq = mountainNoiseFrequency, mountainEdgeSmoothness = mountainEdgeSmoothness, time = Time.time * noiseTimeSpeed, } .ScheduleParallel(vertices.Length, 64, meansHandle) .Complete(); mesh.SetVertexBufferData(vertices, 0, 0, vertices.Length, 0, ~MeshUpdateFlags.Default); }
JobHandle ScheduleMeshPreview(PhysicsShapeAuthoring shape, NativeArray <BlobAssetReference <Collider> > output) { var points = new NativeList <float3>(65535, Allocator.Temp); var indices = new NativeList <int>(65535, Allocator.Temp); shape.GetBakedMeshProperties(points, indices); // copy to NativeArray because NativeList not yet compatible with DeallocateOnJobCompletion var pointsArray = new NativeArray <float3>( points.Length, Allocator.Persistent, NativeArrayOptions.UninitializedMemory ); pointsArray.CopyFrom(points); var indicesArray = new NativeArray <int>( indices.Length, Allocator.Persistent, NativeArrayOptions.UninitializedMemory ); indicesArray.CopyFrom(indices); // TODO: if there is still an active job with the same input data hash, then just set it to be most recently scheduled job return(new CreateTempMeshJob { Points = pointsArray, Indices = indicesArray, Output = output }.Schedule()); }
public static NativeArray <RigidTransform> RemoveOverlappingPoints( NativeList <RigidTransform> spline, Allocator allocator, float minDist = 0.1f) { var culledPoints = new NativeList <RigidTransform>(spline.Length, allocator); if (spline.Length != 0) { var minDistSqr = minDist * minDist; culledPoints.Add(spline[0]); for (int i = 1, j = 0; i < spline.Length; i++) { var dist = math.distancesq(culledPoints[j].pos, spline[i].pos); if (dist > minDistSqr) { culledPoints.Add(spline[i]); j++; } } } var culledSpline = new NativeArray <RigidTransform>( culledPoints.Length, allocator, NativeArrayOptions.UninitializedMemory); culledSpline.CopyFrom(culledPoints); culledPoints.Dispose(); return(culledSpline); }
/// <summary> /// Get the face classifications for the given mesh ID. /// </summary> /// <param name="subsystem">The meshing subsystem.</param> /// <param name="meshId">The trackable ID representing the mesh.</param> /// <param name="allocator">The memory allocator type to use in allocating the native array memory.</param> /// <returns> /// An array of mesh classifications, one for each face in the mesh. /// </returns> public static unsafe NativeArray <ARMeshClassification> GetFaceClassifications(this XRMeshSubsystem subsystem, TrackableId meshId, Allocator allocator) { void *classifications = NativeApi.UnityARKit_MeshProvider_AcquireClassifications(meshId, out int numClassifications); try { if (classifications == null) { numClassifications = 0; } var meshClassifications = new NativeArray <ARMeshClassification>(numClassifications, allocator); if (classifications != null) { NativeArray <ARMeshClassification> tmp = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray <ARMeshClassification>(classifications, numClassifications, Allocator.None); meshClassifications.CopyFrom(tmp); } return(meshClassifications); } finally { NativeApi.UnityARKit_MeshProvider_ReleaseClassifications(classifications); } }
void RemoveShipsFromList() { foreach (Boid ship in shipsToDestroy) { // Get ship no int shipNo = ships.IndexOf(ship); // Remove ship from list ships.RemoveAt(shipNo); shipComp.RemoveAt(shipNo); // Recreate the velocities array List <Vector3> tempVelocities = new List <Vector3>(velocities.ToArray()); tempVelocities.RemoveAt(shipNo); velocities.Dispose(); velocities = new NativeArray <Vector3>(ships.Count, Allocator.Persistent); velocities.CopyFrom(tempVelocities.ToArray()); // Remove from transfrom access array transformAccessArray.Dispose(); Transform[] tempTransforms = new Transform[ships.Count]; for (int i = 0; i < ships.Count; i++) { tempTransforms[i] = ships[i].transform; } transformAccessArray = new TransformAccessArray(tempTransforms); } shipsToDestroy.Clear(); }
// this takes in the compGroup and entityType, and gives us out all entities from all chunks within the group. public NativeArray <Entity> GetEntities(ComponentGroup compGroup, ArchetypeChunkEntityType entityType) { NativeArray <ArchetypeChunk> dataChunks = compGroup.CreateArchetypeChunkArray(Allocator.TempJob); NativeList <ArchetypeChunk> chunkList = new NativeList <ArchetypeChunk> (Allocator.Temp); NativeList <Entity> entityList = new NativeList <Entity> (Allocator.Temp); for (int d = 0; d < dataChunks.Length; d++) { chunkList.Add(dataChunks [d]); } dataChunks.Dispose(); for (int c = 0; c < chunkList.Length; c++) { ArchetypeChunk dataChunk = chunkList [c]; NativeArray <Entity> entityHolder = dataChunk.GetNativeArray(entityType); for (int i = 0; i < entityHolder.Length; i++) { entityList.Add(entityHolder [i]); } } chunkList.Dispose(); NativeArray <Entity> chunkEntities = new NativeArray <Entity> (entityList.Length, Allocator.Persistent); chunkEntities.CopyFrom(entityList); entityList.Dispose(); return(chunkEntities); }
// public bool HasVotesToAdd; public void Execute() { //Convert back to useable objects string validURL = Encoding.UTF8.GetString(ValidURLBytes.ToArray()); List <Player> players = PlayersBytes.ObjectFromNativeArrayBytes <List <Player> > (); List <Replacement> replacements = ReplacementBytes.ObjectFromNativeArrayBytes <List <Replacement> >(); List <String> moderatorNames = ModeratorNamesBytes.ObjectFromNativeArrayBytes <List <String> >(); HtmlDocument doc = URLReadLogic.GetHTMLDocumentFromURL(validURL); List <Post> postsFromPage = RunScrubLogic.RunScrubLogic.RunScrubOnADoc(doc, players, replacements, moderatorNames); byte[] postBytes = postsFromPage.ObjectToBytes <List <Post> >(); if (postBytes.Length > MAX_BYTE_ARRAY_LENGTH) { throw new System.ArgumentOutOfRangeException("Too long a list post object allocate more space."); } else if (postBytes.Length <= MAX_BYTE_ARRAY_LENGTH) { byte[] byteArrayProperLength = new byte[MAX_BYTE_ARRAY_LENGTH]; for (int i = 0; i < postBytes.Length; i++) { byteArrayProperLength[i] = postBytes[i]; } PostBytes.CopyFrom(byteArrayProperLength); } }
/// <summary> /// Get the blend shape coefficients for the face. Blend shapes describe a number of facial /// features on a scale of 0..1. For example, how closed is the left eye, how open is the mouth. /// See <see cref="ARKitBlendShapeCoefficient"/> for more details. /// </summary> /// <param name="faceId">The <c>TrackableId</c> associated with the face to query.</param> /// <param name="allocator">The allocator to use for the returned <c>NativeArray</c>.</param> /// <returns>A new <c>NativeArray</c> allocated with <paramref name="allocator"/> describing /// the blend shapes for the face with id <paramref name="faceId"/>. The caller owns the /// <c>NativeArray</c> and is responsible for calling <c>Dispose</c> on it.</returns> public unsafe NativeArray <ARKitBlendShapeCoefficient> GetBlendShapeCoefficients( TrackableId faceId, Allocator allocator) { IntPtr ptrNativeCoefficientsArray; int coefficientsCount; if (!UnityARKit_FaceProvider_TryAcquireFaceBlendCoefficients(faceId, out ptrNativeCoefficientsArray, out coefficientsCount) || coefficientsCount <= 0) { return(new NativeArray <ARKitBlendShapeCoefficient>(0, allocator)); } try { // Points directly to the native memory var nativeCoefficientsArray = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray <ARKitBlendShapeCoefficient>( (void *)ptrNativeCoefficientsArray, coefficientsCount, Allocator.None); var coefficients = new NativeArray <ARKitBlendShapeCoefficient>(coefficientsCount, allocator); coefficients.CopyFrom(nativeCoefficientsArray); return(coefficients); } finally { UnityARKit_FaceProvider_DeallocateTempMemory(ptrNativeCoefficientsArray); } }
public static byte[] EndianSwap(byte[] inputBytes) { NativeArray <byte> a = new NativeArray <byte>(inputBytes.Length, Allocator.TempJob); NativeArray <byte> result = new NativeArray <byte>(inputBytes.Length, Allocator.TempJob); a.CopyFrom(inputBytes); MyParallelJob jobData = new MyParallelJob(); jobData.a = a; jobData.result = result; // Schedule the job with one Execute per index in the results array and only 1 item per processing batch JobHandle handle = jobData.Schedule(result.Length, 1); // Wait for the job to complete handle.Complete(); result.CopyTo(inputBytes); a.Dispose(); result.Dispose(); return(inputBytes); }
public void Update(ref ScopeNode audioKernel) { _BufferX.CopyFrom(audioKernel.BufferX); InputChannelsX = audioKernel.InputChannelsX; BufferIdx = audioKernel.BufferIdx; TriggerThreshold = audioKernel.TriggerThreshold; }
public override unsafe XRPointCloudData GetPointCloudData( TrackableId trackableId, Allocator allocator) { void *positionsPtr, identifiersPtr; int numPoints; var pointCloud = UnityARKit_depth_acquirePointCloud( trackableId, out positionsPtr, out identifiersPtr, out numPoints); try { var positions = new NativeArray <Vector3>(numPoints, allocator); var positionsHandle = new TransformPositionsJob { positionsIn = NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray <Quaternion>(positionsPtr, numPoints, Allocator.None), positionsOut = positions }.Schedule(numPoints, 32); var identifiers = new NativeArray <ulong>(numPoints, allocator); identifiers.CopyFrom(NativeArrayUnsafeUtility.ConvertExistingDataToNativeArray <ulong>(identifiersPtr, numPoints, Allocator.None)); positionsHandle.Complete(); return(new XRPointCloudData { positions = positions, identifiers = identifiers }); } finally { UnityARKit_depth_releasePointCloud(pointCloud); } }
/// <summary> /// A copy of this list as a [NativeArray](https://docs.unity3d.com/ScriptReference/Unity.Collections.NativeArray_1.html) /// allocated with the specified type of memory. /// </summary> /// <param name="allocator">A member of the /// [Unity.Collections.Allocator](https://docs.unity3d.com/ScriptReference/Unity.Collections.Allocator.html) enumeration.</param> /// <returns>A NativeArray containing copies of all the items in the list.</returns> public NativeArray <T> ToArray(Allocator allocator) { NativeArray <T> result = new NativeArray <T>(Length, allocator, NativeArrayOptions.UninitializedMemory); result.CopyFrom(this); return(result); }
static public NativeArray <ECS.Blocks.Pattern.CompositeInPatternPrefabComponent> a_patternPrefabs; // default protected override void OnCreateManager(int capacity) { //commandBuffer = compositeBarrier.CreateCommandBuffer () ; // new EntityCommandBuffer () ; entityManager = World.Active.GetOrCreateManager <EntityManager>(); archetype = entityManager.CreateArchetype( //typeof ( Blocks.CompositeComponent ), //typeof ( Common.Components.IsNotAssignedTag ), //typeof ( Common.Components.Lod01Tag ) // typeof ( Position ), // typeof ( Common.Components.Lod01Tag ) // typeof ( Common.BufferElements.EntityBuffer ), // typeof ( Blocks.RequestPatternSetupTag ), // typeof ( Blocks.MovePattern ) typeof(Blocks.Pattern.RequestAddPrefabTag) // typeof ( BufferArray <Blocks.PatternPrefab.RequestAddPrefabBufferElement> ) ); // a_requestAddComposites2PatternPrefab = new BufferDataFromEntity <RequestAddPrefabBufferElement> () ; // int i_componentsPatternPrefabIndex = 0 ; //number of prefab types int i_prefabs2AddCount = 5; int i_initialIndex = a_requestAddComposites2PatternPrefab.Length; if (i_initialIndex == 0) { a_requestAddComposites2PatternPrefab.Dispose(); // dispose old array a_requestAddComposites2PatternPrefab = new NativeArray <CompositeInPatternPrefabComponent> (i_prefabs2AddCount * i_compositesCountPerPatternGroup, Allocator.Persistent); } // Copy and extend an array NativeArray <CompositeInPatternPrefabComponent> a_requestAddComposites2PatternPrefabTemp = new NativeArray <CompositeInPatternPrefabComponent> (i_initialIndex + i_prefabs2AddCount * i_compositesCountPerPatternGroup, Allocator.Temp); // Coppy array elements, from smaller to bigger array for (int i = 0; i < i_prefabs2AddCount; i++) { // int i_componentsPatternPrefabIndex = _GenerateNewPatternPrefab () ; a_requestAddComposites2PatternPrefabTemp [i] = a_requestAddComposites2PatternPrefab [i]; } // arrays are equal now a_requestAddComposites2PatternPrefab.CopyFrom(a_requestAddComposites2PatternPrefabTemp); // add some new pattern prefabs for (int i = 0; i < i_prefabs2AddCount; i++) { _GenerateNewPatternPrefab(i); } Entity requestAddNewPrefabEntity = entityManager.CreateEntity(archetype); a_requestAddComposites2PatternPrefabTemp.Dispose(); base.OnCreateManager(capacity); }
private void CPUComputePointCloudData() { if (vertexTexture == null) { vertexTexture = new Texture2D(StructureCore.Instance.DepthWidth, StructureCore.Instance.DepthHeight, TextureFormat.RGBAFloat, false); colorTexture = new Texture2D(StructureCore.Instance.ImageWidth, StructureCore.Instance.ImageHeight, TextureFormat.RGB24, false); } NativeArray <float> data = ((Texture2D)vertexTexture).GetRawTextureData <float>(); data.CopyFrom(StructureCore.Instance.PointCloudData); ((Texture2D)vertexTexture).Apply(); ((Texture2D)colorTexture).LoadRawTextureData(StructureCore.Instance.ImageData); ((Texture2D)colorTexture).Apply(); //if (!File.Exists("depth.png")) //{ // var tex = new Texture2D(StructureCore.Instance.DepthWidth, StructureCore.Instance.DepthHeight, TextureFormat.RFloat, false); // NativeArray<float> td = tex.GetRawTextureData<float>(); // td.CopyFrom(StructureCore.Instance.DepthData); // tex.Apply(); // File.WriteAllBytes("depth.png", tex.EncodeToPNG()); //} }
public unsafe void UnsafeAppendBuffer_AddAndPop() { var buffer = new UnsafeAppendBuffer(0, 8, Allocator.Temp); buffer.Add <int>(123); buffer.Add <int>(234); buffer.Add <int>(345); { var array = new NativeArray <int>(3, Allocator.Temp); buffer.Pop(array.GetUnsafePtr(), 3 * UnsafeUtility.SizeOf <int>()); CollectionAssert.AreEqual(new[] { 123, 234, 345 }, array); } { var array = new NativeArray <int>(4, Allocator.Temp); array.CopyFrom(new[] { 987, 876, 765, 654 }); buffer.Add(array.GetUnsafePtr(), 4 * UnsafeUtility.SizeOf <int>()); } Assert.AreEqual(654, buffer.Pop <int>()); Assert.AreEqual(765, buffer.Pop <int>()); Assert.AreEqual(876, buffer.Pop <int>()); Assert.AreEqual(987, buffer.Pop <int>()); buffer.Dispose(); }
protected override void OnCreateManager() { _capacity = TrafficConfig.Instance.MaxPedestrian; PedestrianFactory.Init(EntityManager); for (var j = 0; j < _capacity; j++) { PedestrianFactory.AddPedestrian(EntityManager); } _walkableArea = new NativeArray <ulong>(PedestrianArea.Instance.WalkableArea.Count, Allocator.Persistent); _walkableArea.CopyFrom(PedestrianArea.Instance.WalkableArea.ToArray()); var seeds = Utils.GetRandomSeed(_capacity); _randSeed = new NativeArray <uint>(seeds, Allocator.Persistent); _randSeed.CopyFrom(seeds); Vector3 texel = PedestrianArea.Instance.Size / (PedestrianArea.Instance.PatchResolution * 8); texelSize = new float2(texel.x, texel.z); patchResolution = PedestrianArea.Instance.PatchResolution; _pedestrianAnimStateConfig = TrafficConfig.Instance.PedestrianConfig.State; }
private void UpdateAudioVisualizer() { audioProcessor.SampleSpectrum(); // copy audio samples to native array samples samples.CopyFrom(audioProcessor.samples); AudioMeshVisualizer audioMeshVisualizer = new AudioMeshVisualizer { normals = normals, triangles = triangles, samples = samples, bandDistribution = bandDistribution, power = audioProfile.power, scale = audioProfile.scale, bandAverage = audioProcessor.bandAverage, vertices = vertices, prevBands = prevBands, bandVelocities = bandVelocities, velocityMultiplier = velocityMultiplier, deltaTime = Time.deltaTime }; JobHandle jobHandle = audioMeshVisualizer.Schedule <AudioMeshVisualizer>(totalTriangles, batchSize); jobHandle.Complete(); modifiedSampleMesh.SetVertices <float3>(vertices); }