protected override void OnUpdate() { // The command buffer to record commands, // which are executed by the command buffer system later in the frame EntityCommandBuffer.ParallelWriter commandBuffer = CommandBufferSystem.CreateCommandBuffer().AsParallelWriter(); //The DataToSpawn component tells us how many entities with buffers to create Entities.ForEach((Entity spawnEntity, int entityInQueryIndex, in DataToSpawn data) => { for (int e = 0; e < data.EntityCount; e++) { //Create a new entity for the command buffer Entity newEntity = commandBuffer.CreateEntity(entityInQueryIndex); //Create the dynamic buffer and add it to the new entity DynamicBuffer <MyBufferElement> buffer = commandBuffer.AddBuffer <MyBufferElement>(entityInQueryIndex, newEntity); //Reinterpret to plain int buffer DynamicBuffer <int> intBuffer = buffer.Reinterpret <int>(); //Optionally, populate the dynamic buffer for (int j = 0; j < data.ElementCount; j++) { intBuffer.Add(j); } } //Destroy the DataToSpawn entity since it has done its job commandBuffer.DestroyEntity(entityInQueryIndex, spawnEntity); }).ScheduleParallel(); CommandBufferSystem.AddJobHandleForProducer(this.Dependency); }
public static NativeArray <ArrayType> AsNativeArrayT <BufferType, ArrayType>( this DynamicBuffer <BufferType> buffer) where BufferType : unmanaged, IBufferElementData where ArrayType : unmanaged { return(buffer.Reinterpret <ArrayType>().AsNativeArray()); }
public unsafe PathQueryState FindPath(float2 from, float2 to, float radius, DynamicBuffer <PathSegmentElement> segments, DynamicBuffer <TriangleElement> triangleIds, Navmesh.Navmesh *navmesh, out int cost) { triangleIds.Clear(); var result = _astar.Search(from, to, navmesh, _channel, radius, triangleIds, out cost); if (result == PathQueryState.PathFound) { _funnel.GetPath(_channel, from, to, radius, _path); triangleIds.Reinterpret <int>().AsNativeArray().Sort(); } for (int i = 0; i < _path.Count; i++) { var w = _path.FromFront(i); Assert.IsTrue(!float.IsNaN(w.To.x) && !float.IsNaN(w.To.y)); segments.Add(new PathSegmentElement { Corner = i > 0 ? _path.FromFront(i - 1).Vertex : w.From, From = w.From, To = w.To }); } _astar.Clear(); _channel.Clear(); _funnel.Clear(); _path.Clear(); return(result); }
void LocalRefinement(DynamicBuffer <DestroyedTriangleElement> destroyed) { var verts = V.GetEnumerator(); while (verts.MoveNext()) { _refinementQueue.PushBack(verts.Current); } InfiniteLoopDetection.Reset(); while (_refinementQueue.Count > 0) { InfiniteLoopDetection.Register(1000, "LocalRefinement"); var v = (Vertex *)_refinementQueue.PopFront(); var e = v->GetEdgeEnumerator(); while (e.MoveNext()) { if (TriDisturbed(e.Current, out var vRef) || TravsDisturbed(e.Current, out vRef)) { // todo are we adding duplicates here? _refinementQueue.PushBack((IntPtr)v); _refinementQueue.PushBack((IntPtr)vRef); break; } } } var tris = DestroyedTriangles.GetEnumerator(); while (tris.MoveNext()) { destroyed.Add(tris.Current); } destroyed.Reinterpret <int>().AsNativeArray().Sort(); }
public void SetMovementValues() { _flowFieldQuery = GetEntityQuery(typeof(FlowFieldData)); _flowFieldEntity = _flowFieldQuery.GetSingletonEntity(); _flowFieldData = EntityManager.GetComponentData <FlowFieldData>(_flowFieldEntity); _destinationCellData = EntityManager.GetComponentData <DestinationCellData>(_flowFieldEntity); _entityBuffer = EntityManager.GetBuffer <EntityBufferElement>(_flowFieldEntity); _gridEntities = _entityBuffer.Reinterpret <Entity>(); if (_cellDataContainer.IsCreated) { _cellDataContainer.Dispose(); } _cellDataContainer = new NativeArray <CellData>(_gridEntities.Length, Allocator.Persistent); for (int i = 0; i < _entityBuffer.Length; i++) { _cellDataContainer[i] = GetComponent <CellData>(_entityBuffer[i]); } Entities.ForEach((ref EntityMovementData entityMovementData) => { entityMovementData.destinationReached = false; }).Run(); }
// Start is called before the first frame update void Start() { EntityManager entityManager = World.DefaultGameObjectInjectionWorld.EntityManager; // get EM reference Entity entity = entityManager.CreateEntity(); //create an entity to play with DynamicBuffer <IntBufferElement> dynamicBuffer = entityManager.AddBuffer <IntBufferElement>(entity); //add a buffer to the entity dynamicBuffer.Add(new IntBufferElement { Value = 1 }); //instantiate buffer elements dynamicBuffer.Add(new IntBufferElement { Value = 2 }); dynamicBuffer.Add(new IntBufferElement { Value = 3 }); DynamicBuffer <int> intDynamicBuffer = dynamicBuffer.Reinterpret <int>(); //reinterpret so we don't have to keep instantiating IntBufferElements intDynamicBuffer[1] = 5; // you can alter something already in the buffer intDynamicBuffer.Add(1); // you can add things to the buffer, and it affects the original buffer for (int i = 0; i < intDynamicBuffer.Length; i++) { intDynamicBuffer[i]++; } DynamicBuffer <IntBufferElement> dynBuff //You put what type the buffer holds in the <> = entityManager.GetBuffer <IntBufferElement>(entity); //you pass the entity that has the buffer attached to it }
JobHandle ProcessViewEntities(bool mapRegenerated, DynamicBuffer <MapTiles> map, MapData mapData, JobHandle inputDeps) { // Process Entities with only a view and no memory return(Entities .WithReadOnly(map) .WithChangeFilter <Position>() .WithNone <TilesInMemory>() .ForEach((ref DynamicBuffer <TilesInView> view, in Position pos, in ViewRange range) => { if (view.Length != map.Length || mapRegenerated) { view.ResizeUninitialized(map.Length); } // Always reset view before rebuilding for (int i = 0; i < view.Length; ++i) { view[i] = false; } var visibility = new VisibilityMap( mapData.width, mapData.height, map.Reinterpret <TileType>().AsNativeArray(), view.Reinterpret <bool>().AsNativeArray() ); FOV.Compute(pos, range, visibility); }).Schedule(inputDeps));
protected override void OnUpdate() { EntityCommandBuffer commandBuffer = _ecbSystem.CreateCommandBuffer(); Entities.ForEach((Entity entity, in NewFlowFieldData newFlowFieldData, in FlowFieldData flowFieldData) => { commandBuffer.RemoveComponent <NewFlowFieldData>(entity); DynamicBuffer <EntityBufferElement> buffer = newFlowFieldData.isExistingFlowField ? GetBuffer <EntityBufferElement>(entity) : commandBuffer.AddBuffer <EntityBufferElement>(entity); DynamicBuffer <Entity> entityBuffer = buffer.Reinterpret <Entity>(); float cellRadius = flowFieldData.cellRadius; float cellDiameter = cellRadius * 2; int2 gridSize = flowFieldData.gridSize; for (int x = 0; x < gridSize.x; x++) { for (int y = 0; y < gridSize.y; y++) { float3 cellWorldPos = new float3(cellDiameter * x + cellRadius, 0, cellDiameter * y + cellRadius); byte cellCost = CostFieldHelper.instance.EvaluateCost(cellWorldPos, cellRadius); CellData newCellData = new CellData { worldPos = cellWorldPos, gridIndex = new int2(x, y), cost = cellCost, bestCost = ushort.MaxValue, bestDirection = int2.zero }; Entity curCell; if (newFlowFieldData.isExistingFlowField) { int flatIndex = FlowFieldHelper.ToFlatIndex(new int2(x, y), gridSize.y); curCell = entityBuffer[flatIndex]; } else { curCell = commandBuffer.CreateEntity(_cellArchetype); entityBuffer.Add(curCell); } commandBuffer.SetComponent(curCell, newCellData); } } int2 destinationIndex = FlowFieldHelper.GetCellIndexFromWorldPos(flowFieldData.clickedPos, gridSize, cellDiameter); DestinationCellData newDestinationCellData = new DestinationCellData { destinationIndex = destinationIndex }; if (!newFlowFieldData.isExistingFlowField) { commandBuffer.AddComponent <DestinationCellData>(entity); } commandBuffer.SetComponent(entity, newDestinationCellData); commandBuffer.AddComponent <CalculateFlowFieldTag>(entity); }).Run();
public void Execute(Entity entity, int index, DynamicBuffer <MyBufferElement> buffer) { foreach (int integer in buffer.Reinterpret <int>()) { sums[index] += integer; } }
public void Execute(Entity entity, int index, DynamicBuffer <TrailBufferElement> buffer, ref Translation _Translation, ref TrailComponent _TrailComponent) { if (buffer.Length > _TrailComponent.MeshCount) { buffer.RemoveAt(0); } DynamicBuffer <float3> rbuffer = buffer.Reinterpret <float3>(); rbuffer.Add(_Translation.Value); }
public FlatMeshDataColors(DynamicBuffer <MeshVerticesBuffer> vs, DynamicBuffer <MeshTrianglesBuffer> ts, DynamicBuffer <MeshNormalsBuffer> ns, DynamicBuffer <MeshColorsBuffer> cs) { m_Vertices = vs.Reinterpret <float3>(); m_Triangles = ts.Reinterpret <int>(); m_Normals = ns.Reinterpret <float3>(); m_Colors = cs.Reinterpret <byte4>(); }
public FlatMeshDataUVs(DynamicBuffer <MeshVerticesBuffer> vs, DynamicBuffer <MeshTrianglesBuffer> ts, DynamicBuffer <MeshNormalsBuffer> ns, DynamicBuffer <MeshUVsBuffer> uvs) { m_Vertices = vs.Reinterpret <float3>(); m_Triangles = ts.Reinterpret <int>(); m_Normals = ns.Reinterpret <float3>(); m_UVs = uvs.Reinterpret <float2>(); }
// NB: vertexColor needs to be as srgb when in gamma space, and in linear otherwise public static unsafe void LayoutString(char *text, int textLength, float fontSize, HorizontalAlignment hAlign, VerticalAlignment vAlign, float4 vertexColor, ref FontData font, DynamicBuffer <DynamicSimpleVertex> dynMesh, DynamicBuffer <DynamicIndex> dynTriangles, out AABB aabb) { LayoutString(text, textLength, fontSize, hAlign, vAlign, vertexColor, ref font, dynMesh.Reinterpret <SimpleVertex>(), dynTriangles.Reinterpret <ushort>(), out aabb); }
public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex) { NativeArray <Entity> entityArray = chunk.GetNativeArray(entityType); BufferAccessor <ReynoldsNearbyFlockPos> nearbyPosBuffers = chunk.GetBufferAccessor <ReynoldsNearbyFlockPos>(nearbyPosBufferType); BufferAccessor <ReynoldsNearbyFlockVel> nearbyVelBuffers = chunk.GetBufferAccessor <ReynoldsNearbyFlockVel>(nearbyVelBufferType); NativeArray <Translation> transArray = chunk.GetNativeArray(translationType); NativeArray <ReynoldsFlockBehaviour> flockArray = chunk.GetNativeArray(flockType); NativeArray <PreviousMovement> preVelArray = chunk.GetNativeArray(preVelType); NativeArray <ReynoldsMovementValues> movementArray = chunk.GetNativeArray(reynoldsMovementValuesType); for (int i = 0; i < chunk.Count; i++) { Entity entity = entityArray[i]; DynamicBuffer <ReynoldsNearbyFlockPos> posBuffer = nearbyPosBuffers[i]; DynamicBuffer <ReynoldsNearbyFlockVel> velBuffer = nearbyVelBuffers[i]; Translation trans = transArray[i]; ReynoldsFlockBehaviour flockBehaviour = flockArray[i]; PreviousMovement preVel = preVelArray[i]; ReynoldsMovementValues movement = movementArray[i]; float3 agentPosition = trans.Value; // the position of the seeker DynamicBuffer <float3> nearCrowdPosList = posBuffer.Reinterpret <float3>(); // reinterpret the buffer so that it is used like a buffer of float3s nearCrowdPosList.Clear(); DynamicBuffer <float3> nearCrowdVelList = velBuffer.Reinterpret <float3>(); // reinterpret the buffer so that it is used like a buffer of float3s nearCrowdVelList.Clear(); float searchRadius = math.max(flockBehaviour.CohesionRadius, flockBehaviour.AvoidanceRadius); // Choose the farther radius int hashMapKey = MovingQuadrantSystem.GetPositionHashMapKey(trans.Value); // Calculate the hash key of the seeker in question FindCrowdAgents(hashMapKey, agentPosition, entity, ref nearCrowdPosList, ref nearCrowdVelList, ref searchRadius); // Seach the quadrant that the seeker is in FindCrowdAgents(hashMapKey + 1, agentPosition, entity, ref nearCrowdPosList, ref nearCrowdVelList, ref searchRadius); // search the quadrant to the right FindCrowdAgents(hashMapKey - 1, agentPosition, entity, ref nearCrowdPosList, ref nearCrowdVelList, ref searchRadius); // search the quadrant to the left FindCrowdAgents(hashMapKey + MovingQuadrantSystem.quadrantYMultiplier, agentPosition, entity, ref nearCrowdPosList, ref nearCrowdVelList, ref searchRadius); // quadrant above FindCrowdAgents(hashMapKey - MovingQuadrantSystem.quadrantYMultiplier, agentPosition, entity, ref nearCrowdPosList, ref nearCrowdVelList, ref searchRadius); // quadrant below FindCrowdAgents(hashMapKey + 1 + MovingQuadrantSystem.quadrantYMultiplier, agentPosition, entity, ref nearCrowdPosList, ref nearCrowdVelList, ref searchRadius); // up right FindCrowdAgents(hashMapKey - 1 + MovingQuadrantSystem.quadrantYMultiplier, agentPosition, entity, ref nearCrowdPosList, ref nearCrowdVelList, ref searchRadius); // up left FindCrowdAgents(hashMapKey + 1 - MovingQuadrantSystem.quadrantYMultiplier, agentPosition, entity, ref nearCrowdPosList, ref nearCrowdVelList, ref searchRadius); // down right FindCrowdAgents(hashMapKey - 1 - MovingQuadrantSystem.quadrantYMultiplier, agentPosition, entity, ref nearCrowdPosList, ref nearCrowdVelList, ref searchRadius); // down left movementArray[i] = GetFlockingBehaviour(ref trans, ref preVel.value, ref nearCrowdPosList, ref nearCrowdVelList, ref flockBehaviour, movement); } }
protected override void OnUpdate() { Entities.ForEach((BoidAuthoring boidAuthoring) => { var entity = GetPrimaryEntity(boidAuthoring); DstEntityManager.AddSharedComponentData(entity, new Boid { CellRadius = boidAuthoring.CellRadius, SeparationWeight = boidAuthoring.SeparationWeight, AlignmentWeight = boidAuthoring.AlignmentWeight, TargetWeight = boidAuthoring.TargetWeight, OuterDetectionRadius = boidAuthoring.OuterDetectionRadius, InnerDetectionRadius = boidAuthoring.InnerDetectionRadius, MoveSpeed = boidAuthoring.MoveSpeed, WanderRadius = boidAuthoring.WanderRadius, WanderWeight = boidAuthoring.WanderWeight, VisionAngle = boidAuthoring.VisionAngle, NavigationRayCount = boidAuthoring.NavigationRayCount, }); DynamicBuffer <Float3BufferElement> buffer = DstEntityManager.AddBuffer <Float3BufferElement>(entity); DynamicBuffer <float3> floatBuffer = buffer.Reinterpret <float3>(); for (int i = 0; i < boidAuthoring.NavigationRayCount; i++) { float turnFraction = 0.6180f; float t = i / (boidAuthoring.NavigationRayCount - 1f); float phi = math.acos(1f - 2f * t); float theta = 2 * math.PI * turnFraction * i; float x = math.sin(phi) * math.cos(theta); float y = math.sin(phi) * math.sin(theta); float z = math.cos(phi); float3 p = new float3(x, y, z); if (math.acos(math.dot(p, new float3(0, 0, 1))) < boidAuthoring.VisionAngle) { floatBuffer.Add(p); } } // Remove default transform system components DstEntityManager.RemoveComponent <Translation>(entity); DstEntityManager.RemoveComponent <Rotation>(entity); }); }
protected override void OnUpdate() { Camera.onPostRender = null; Camera.onPostRender += (Camera camera) => { // Pushes the current matrix onto the stack so that can be restored later GL.PushMatrix(); // Loads a new Projection Matrix, you can also use other methods like LoadOrtho() or GL.LoadPixelMatrix() //GL.LoadProjectionMatrix(Matrix4x4.Perspective(90, camera.aspect, -10f, 10f)); GL.LoadPixelMatrix(0, Screen.width, 0, Screen.height); // You can also multiply the current matrix in order to do things like translation, rotation and scaling // Here I'm rotating and scaling up the current Matrix //GL.MultMatrix(Matrix4x4.TRS(Vector3.zero, Quaternion.Euler(0, 0, 45), new Vector3(2, 2))); }; Entity entity = m_MinimapQuery.GetSingletonEntity(); DynamicBuffer <RenderTexture> buffer = EntityManager.GetBuffer <RenderTexture>(entity); RectComponent pos = EntityManager.GetComponentData <RectComponent>(entity); if (buffer.Capacity > buffer.Length) { buffer.TrimExcess(); } Texture2D tex = new Texture2D(100, 100); tex.SetPixels(buffer.Reinterpret <Color>().AsNativeArray().ToArray()); tex.Apply(); tex.wrapMode = TextureWrapMode.Clamp; Camera.onPostRender += (Camera camera) => { if (tex != null) { Graphics.DrawTexture(new Rect(pos.x, pos.y, pos.width, pos.height), tex); } }; Camera.onPostRender += (Camera camera) => { // Pops the matrix that was just loaded, restoring the old matrix GL.PopMatrix(); }; }
/// <summary> /// Applies percent modifiers on a stat. /// </summary> protected static void ApplyModifiers <T>(ref float stat, DynamicBuffer <T> modifierBuffer) where T : struct, IBufferElementData { DynamicBuffer <float> modifiers = modifierBuffer.Reinterpret <float>(); for (int i = modifiers.Length - 1; i >= 0; i--) { float modifier = modifiers[i]; modifiers.RemoveAt(i); if (stat <= 0) { continue; // Don't multiply negative values } stat *= 1 + modifier; // Multiply stat if (stat < 0) { stat = 0; // Don't reduce stat below 0 } } }
void EntityJobScheduling() { m_EntityCommandBuffer = m_EntityBufferSystem.CreateCommandBuffer(); //Lambda doesnt run in normal C#, Unity converts it in a more performant job system construct and burst for better PC resource usage Entities.ForEach((Entity entity, in UserData userData, in UpdatedFFData updatedFFData) => { m_EntityCommandBuffer.RemoveComponent <UpdatedFFData>(entity); DynamicBuffer <EBufferElement> eBuffer = updatedFFData.exists ? GetBuffer <EntityCommandBufferManagedComponentExtensions>(entity) : m_EntityCommandBuffer.AddBuffer <EBufferElement>(entity); DynamicBuffer <Entity> m_EntityBuffer = eBuffer.Reinterpret <Entity>(); InitGrid(updatedFFData); //From Elite framework IPoint2 idxInWorld = GetNodeIdxFromWorldPos(userData.GetClickedPos(), IPoint2(nrOfCols, nrOfRows), colSize, rowSize); EndNode endNode = new EndNode(idxInWorld); if (!updatedFFData.exists) { m_EntityCommandBuffer.AddComponent <EndNode>(entity); } m_EntityCommandBuffer.SetComponent(entity, endNode); m_EntityCommandBuffer.AddComponent <TagObstacleCalc>(entity); }).Run();
static public void CreateBullet(float3 _StartPosition, float _LifeTime, int _HostID, E_BulletType _Type, int _Damage, float3 _Direction, float _Speed, LayerMask _TargetLayerMask, int _TrailMeshCount = 10) { int meshcount = _TrailMeshCount; Entity entity = m_EntityManger.CreateEntity(m_BulletArchetype); m_EntityManger.SetComponentData(entity, new Translation() { Value = _StartPosition }); m_EntityManger.SetComponentData(entity, new BulletComponent(_HostID, _Type, _Damage, Unity.Mathematics.math.normalize(_Direction), _Speed, _TargetLayerMask)); m_EntityManger.SetComponentData(entity, new TrailComponent() { MeshCount = meshcount }); m_EntityManger.SetComponentData(entity, new LifeTimerComponent(_LifeTime)); DynamicBuffer <TrailBufferElement> buffer = m_EntityManger.GetBuffer <TrailBufferElement>(entity); DynamicBuffer <float3> reinb = buffer.Reinterpret <float3>(); for (int i = 0; i < meshcount; ++i) { reinb.Add(_StartPosition); } }
//The DataToSpawn component tells us how many entities with buffers to create public void Execute(Entity spawnEntity, int index, [ReadOnly] ref DataToSpawn data) { for (int e = 0; e < data.EntityCount; e++) { //Create a new entity for the command buffer Entity newEntity = CommandBuffer.CreateEntity(index); //Create the dynamic buffer and add it to the new entity DynamicBuffer <MyBufferElement> buffer = CommandBuffer.AddBuffer <MyBufferElement>(index, newEntity); //Reinterpret to plain int buffer DynamicBuffer <int> intBuffer = buffer.Reinterpret <int>(); //Optionally, populate the dynamic buffer for (int j = 0; j < data.ElementCount; j++) { intBuffer.Add(j); } } //Destroy the DataToSpawn entity since it has done its job CommandBuffer.DestroyEntity(index, spawnEntity); }
public void Execute(ArchetypeChunk chunk, int chunkIndex, int firstEntityIndex) { NativeArray <NavigationGridData> navigationGrids = chunk.GetNativeArray(this.navigationGridType); BufferAccessor <AStarNodeElement> nodeBufferAccessor = chunk.GetBufferAccessor(this.nodeBufferType); for (int ci = 0, cn = chunk.Count; ci < cn; ci++) { NavigationGridData navigationGrid = outNavigationGrid[0] = navigationGrids[ci]; DynamicBuffer <AStarNodeElement> nodeBuffer = nodeBufferAccessor[ci]; // Solve path if requested if (navigationGrid.pathRequested) { // All nodes NativeArray <AStarNode> nodes = nodeBuffer.Reinterpret <AStarNode>().ToNativeArray(Allocator.Temp); // Create temp grid AStarGrid aStarGrid = new AStarGrid(navigationGrid.lengthX, navigationGrid.lengthY, nodes); // Start/end nodes AStarNode start = navigationGrid.pathStart; AStarNode end = navigationGrid.pathEnd; // Solve path NativeList <AStarNode> pathNodeList = new NativeList <AStarNode>(Allocator.Temp); bool pathFound = AStarSolver.SolvePath(aStarGrid, start, end, ref pathNodeList); int pathLength = pathNodeList.Length; if (pathFound && navigationGrid.pathMustBeStraightLine) { // Check if path is straight line if specfied as a requirement bool xDiverge = false; bool yDiverge = false; for (int i = 1, n = pathNodeList.Length; i < n; i++) { if (!xDiverge) { xDiverge = pathNodeList[i].XCoord != pathNodeList[i - 1].XCoord; } if (!yDiverge) { yDiverge = pathNodeList[i].YCoord != pathNodeList[i - 1].YCoord; } if (xDiverge && yDiverge) { pathFound = false; break; } } } // Copy path node list to output array NativeSlice <AStarNode> pathNodeListSlice = new NativeSlice <AStarNode>(pathNodeList.AsArray()); NativeSlice <AStarNode> pathNodeSlice = new NativeSlice <AStarNode>(this.outPathNodes, 0, pathLength); pathNodeSlice.CopyFrom(pathNodeListSlice); // Dispose native containers pathNodeList.Dispose(); aStarGrid.Dispose(); nodes.Dispose(); this.outPathFound[0] = pathFound ? 1 : 0; this.outPathFound[1] = pathLength; navigationGrid.pathRequested = false; navigationGrid.pathMustBeStraightLine = false; // Apply changes navigationGrids[ci] = navigationGrid; } } }
protected override void OnUpdate( ) { if (group_MMMamager.CalculateChunkCount() == 0) { Debug.LogWarning("There is no active manager."); return; } EntityCommandBuffer ecb = becb.CreateCommandBuffer(); EntityCommandBuffer.ParallelWriter ecbp = ecb.AsParallelWriter(); l_managerSharedData.Clear(); EntityManager.GetAllUniqueSharedComponentData(l_managerSharedData); ComponentDataFromEntity <NNManagerBestFitnessComponent> a_managerBestFitness = GetComponentDataFromEntity <NNManagerBestFitnessComponent> (false); ComponentDataFromEntity <NNManagerComponent> a_manager = GetComponentDataFromEntity <NNManagerComponent> (true); ComponentDataFromEntity <NNScoreComponent> a_managerScore = GetComponentDataFromEntity <NNScoreComponent> (true); ComponentDataFromEntity <NNBrainScoreComponent> a_brainScore = GetComponentDataFromEntity <NNBrainScoreComponent> (true); ComponentDataFromEntity <NNMangerIsSpawningNewGenerationTag> a_mangerIsSpawningNewGeneration = GetComponentDataFromEntity <NNMangerIsSpawningNewGenerationTag> (false); BufferFromEntity <NNInput2HiddenLayersWeightsBuffer> NNInput2HiddenLayersWeightsBuffer = GetBufferFromEntity <NNInput2HiddenLayersWeightsBuffer> (false); BufferFromEntity <NNHidden2OutputLayersWeightsBuffer> NNHidden2OutputLayersWeightsBuffer = GetBufferFromEntity <NNHidden2OutputLayersWeightsBuffer> (false); // BufferFromEntity <NNHiddenLayersNeuronsBiasBuffer> NNHiddenLayersNeuronsBiasBuffer = GetBufferFromEntity <NNHiddenLayersNeuronsBiasBuffer> ( false ) ; // ComponentDataFromEntity <NNScoreComponent> a_managerScore = GetComponentDataFromEntity <NNScoreComponent> ( true ) ; BufferFromEntity <NNINdexProbabilityBuffer> indexProbabilityBuffer = GetBufferFromEntity <NNINdexProbabilityBuffer> (false); // int i_validManagersCount = 0 ; // bool canCalculateCrossovers = false ; for (int i = 0; i < l_managerSharedData.Count; i++) { NNManagerSharedComponent mangerSharedComponent = l_managerSharedData [i]; Entity nnManagerEntity = new Entity() { Index = mangerSharedComponent.i_entityIndex, Version = mangerSharedComponent.i_entityVersion }; if (a_mangerIsSpawningNewGeneration.HasComponent(nnManagerEntity)) { group_parentPopulation.SetSharedComponentFilter(mangerSharedComponent); group_offspringPopulation.SetSharedComponentFilter(mangerSharedComponent); NativeArray <Entity> na_parentPopulationEntities = group_parentPopulation.ToEntityArray(Allocator.TempJob); NativeArray <Entity> na_offspringPopulationEntities = group_offspringPopulation.ToEntityArray(Allocator.TempJob); DynamicBuffer <NNINdexProbabilityBuffer> a_indexProbability = indexProbabilityBuffer [nnManagerEntity]; NNScoreComponent managerScore = a_managerScore [nnManagerEntity]; // int i_eliteScore = managerScore.i ; Debug.Log("Total score: " + managerScore.i + "; elite score: " + managerScore.i_elite); if (managerScore.i_elite <= 1) { Dependency = new CopyLastBestGenerationDNAJob() { na_parentPopulationEntities = na_parentPopulationEntities, na_offspringPopulationEntities = na_offspringPopulationEntities, // na_indexProbability = na_indexProbability, input2HiddenLayersWeightsBuffer = NNInput2HiddenLayersWeightsBuffer, hidden2OutputLayersWeightsBuffer = NNHidden2OutputLayersWeightsBuffer, // hiddenLayersNeuronsBiasBuffer = NNHiddenLayersNeuronsBiasBuffer }.Schedule(na_parentPopulationEntities.Length, 256, Dependency); Dependency.Complete(); } else { // New score is fine. // Calculate index probability, to get best parents. // Each entity indicies will be in the array, as many times, as many score has // e.g. // 0th entity with 0 points won't be in the array // 1st entity with 2 points will be 2 times // nth entity with xth score will be xth times in the array NNManagerComponent manager = a_manager [nnManagerEntity]; NativeMultiHashMap <int, EntityIndex> nmhm_parentEntitiesScore = new NativeMultiHashMap <int, EntityIndex> (na_parentPopulationEntities.Length, Allocator.TempJob); // Debug.Log ( "crossover parent score" ) ; Dependency = new CommonJobs.GetPopulationScoreJob( ) { canGetEachScore = false, na_populationEntities = na_parentPopulationEntities, a_brainScore = a_brainScore, nmhm_populationEntitiesScore = nmhm_parentEntitiesScore.AsParallelWriter() }.Schedule(na_parentPopulationEntities.Length, 256, Dependency); Dependency.Complete(); NativeArray <int> na_parentSortedKeysWithDuplicates = nmhm_parentEntitiesScore.GetKeyArray(Allocator.TempJob); // This stores key keys in order. But keeps first unique keys at the front of an array. // Total array size matches of total elements. na_parentSortedKeysWithDuplicates.Sort(); // Sorted. int i_uniqueKeyCount = na_parentSortedKeysWithDuplicates.Unique(); int i_eltieCountTemp = (int)(na_parentSortedKeysWithDuplicates.Length * manager.f_eliteSize); // Minimum elite size mus be met. int i_eltiesCount = i_eltieCountTemp > 0 ? i_eltieCountTemp : na_parentSortedKeysWithDuplicates.Length; if (na_parentSortedKeysWithDuplicates.Length == 0) { Debug.LogError("Not enough elites for training. Please increase population, or elites %."); na_offspringPopulationEntities.Dispose(); na_parentPopulationEntities.Dispose(); nmhm_parentEntitiesScore.Dispose(); na_parentSortedKeysWithDuplicates.Dispose(); continue; } NativeArray <EntityIndex> na_elities = new NativeArray <EntityIndex> (i_eltiesCount, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); DynamicBuffer <NNINdexProbabilityBuffer> a_eliteIndexProbability = indexProbabilityBuffer [nnManagerEntity]; int i_totalElitesScore = managerScore.i_elite; a_eliteIndexProbability.ResizeUninitialized(i_totalElitesScore); Dependency = new CommonJobs.GetElitesEntitiesJob() { i_eltiesCount = i_eltiesCount, na_elities = na_elities, nmhm_entitiesScore = nmhm_parentEntitiesScore, na_currentSortedKeysWithDuplicates = na_parentSortedKeysWithDuplicates }.Schedule(); Dependency = new CalculateIndexProbabilityOfPopulationJob() { na_populationEntities = na_elities, a_indexProbability = a_eliteIndexProbability, a_brainScore = a_brainScore }.Schedule(Dependency); NativeArray <int> na_randomValues = new NativeArray <int> (na_parentPopulationEntities.Length, Allocator.TempJob, NativeArrayOptions.UninitializedMemory); random.NextInt2(); Dependency = new RandomIntsJob() { na_randomValues = na_randomValues, random = random }.Schedule(Dependency); Dependency.Complete(); // Debug.LogError ( "parent pop: " + na_parentPopulationEntities.Length + "; offspring pop: " + na_offspringPopulationEntities.Length ) ; Dependency = new DNACrossOverJob() { na_parentPopulationEntities = na_parentPopulationEntities, na_offspringPopulationEntities = na_offspringPopulationEntities, na_indexProbability = a_eliteIndexProbability.Reinterpret <int> ().AsNativeArray(), input2HiddenLayersWeightsBuffer = NNInput2HiddenLayersWeightsBuffer, hidden2OutputLayersWeightsBuffer = NNHidden2OutputLayersWeightsBuffer, na_randomValues = na_randomValues, random = random, // i_eliteScore = i_eliteScore }.Schedule(na_parentPopulationEntities.Length, 256, Dependency); Dependency.Complete(); na_randomValues.Dispose(); na_elities.Dispose(); nmhm_parentEntitiesScore.Dispose(); na_parentSortedKeysWithDuplicates.Dispose(); } ecb.RemoveComponent <NNMangerIsSpawningNewGenerationTag> (nnManagerEntity); becb.AddJobHandleForProducer(Dependency); na_offspringPopulationEntities.Dispose(); na_parentPopulationEntities.Dispose(); } } // for Entities .WithName("GenerationSpawningIsCompleteJob") .WithAll <NNBrainTag, IsSpawningTag> () .ForEach((Entity entity, int entityInQueryIndex) => { ecbp.RemoveComponent <IsSpawningTag> (entityInQueryIndex, entity); ecbp.AddComponent <IsSpawningCompleteTag> (entityInQueryIndex, entity); }).ScheduleParallel(); becb.AddJobHandleForProducer(Dependency); }
public void Execute(Entity entity, int index, ref ArmComponent armComponent, [ReadOnly] ref Translation translation, [ReadOnly] ref Rotation rotation) { float armBoneLength = armComponent.armBoneLength; float3 handUp = armComponent.handUp; float armBendStrength = armComponent.armBendStrength; Matrix4x4[] matrices = new Matrix4x4[17]; DynamicBuffer <ArmChainsBuffer> armChainsBuffer = armChainsBufferLookup[entity]; DynamicBuffer <FingerChainsBuffer> fingerChainsBuffer = fingerChainsBufferLookup[entity]; DynamicBuffer <ThumbChainsBuffer> thumbChainsBuffer = thumbChainsBufferLookup[entity]; /////////////////////////// // Resting position for hand float time = worldTime + armComponent.timeOffset; // solve the arm IK chain first float3 anchor = translation.Value; //float3 anchor = new float3(); FABRIK.SolveViaBuffer(armChainsBuffer.Reinterpret <float3>(), armBoneLength, anchor, armComponent.handTarget, handUp * armBendStrength); Quaternion q = rotation.Value; float3 transformRight = math.normalize(math.mul(q, directions.right)); // figure out our current "hand vectors" from our arm orientation float3 handForward = math.normalize(util.Last(armChainsBuffer.Reinterpret <float3>(), 0) - util.Last(armChainsBuffer.Reinterpret <float3>(), 1)); handUp = math.normalize(math.cross(handForward, transformRight)); float3 handRight = math.cross(handUp, handForward); // create handspace-to-worldspace matrix armComponent.handMatrix = Matrix4x4.TRS(util.Last(armChainsBuffer.Reinterpret <float3>(), 0), Quaternion.LookRotation(handForward, handUp), directions.one); // how much are our fingers gripping? // (during a reach, this is based on the reach timer) float fingerGrabT = armComponent.savedGrabT; if (armComponent.heldRock != Entity.Null) { //Translation heldRockTrans = translationsFromEntity[armComponent.heldRock]; fingerGrabT = 1.0f; //When holding the rock, we're fully gripped. var held = new RockHeldComponent(); held.rockInHandPosition = armComponent.handMatrix.MultiplyPoint3x4(armComponent.heldRockOffset); ecb.AddComponent(index, armComponent.heldRock, held); // armComponent.lastIntendedRockPos = } // create rendering matrices for arm bones util.UpdateMatrices(matrices, armChainsBuffer.Reinterpret <float3>(), 0, armComponent.armBoneThickness, handUp); int matrixIndex = armChainsBuffer.Reinterpret <float3>().Length - 1; // next: fingers float3 handPos = util.Last(armChainsBuffer.Reinterpret <float3>(), 0); // fingers spread out during a throw float openPalm = throwCurve.Evaluate(armComponent.throwTimer); //TODO add these to arm component? float fingerXOffset = -0.12f; float fingerSpacing = 0.08f; float[] fingerBoneLengths = { 0.2f, 0.22f, 0.2f, 0.16f }; float[] fingerThicknesses = { 0.05f, 0.05f, 0.05f, 0.05f }; float fingerBendStrength = 0.2f; for (int i = 0; i < 4; i++) { float3 handRightTemp = handRight * (fingerXOffset + i * fingerSpacing); // find knuckle position for this finger float3 fingerPos = handPos + handRightTemp; // find resting position for this fingertip float3 fingerTarget = fingerPos + handForward * (.5f - .1f * fingerGrabT); // spooky finger wiggling while we're idle fingerTarget += handUp * Mathf.Sin((time + i * .2f) * 3f) * .2f * (1f - fingerGrabT); // if we're gripping, move this fingertip onto the surface of our rock float3 rockFingerDelta = fingerTarget - armComponent.lastIntendedRockPos; float3 rockFingerPos = armComponent.lastIntendedRockPos + math.normalize(rockFingerDelta) * (armComponent.lastIntendedRockSize * .5f + fingerThicknesses[i]); fingerTarget = math.lerp(fingerTarget, rockFingerPos, fingerGrabT); // apply finger-spreading during throw animation fingerTarget += (handUp * .3f + handForward * .1f + handRight * (i - 1.5f) * .1f) * openPalm; // solve this finger's IK chain // FABRIK.Solve(fingerChains[i],fingerBoneLengths[i],fingerPos,fingerTarget,handUp*fingerBendStrength); int startIdx = i * 4; int stopIdx = startIdx + 4; FABRIK.SolveViaBufferSliced(fingerChainsBuffer.Reinterpret <float3>(), fingerBoneLengths[i], fingerPos, fingerTarget, handUp * fingerBendStrength, startIdx, stopIdx); // update this finger's rendering matrices util.UpdateMatricesSliced(matrices, fingerChainsBuffer.Reinterpret <float3>(), matrixIndex, fingerThicknesses[i], handUp, startIdx, stopIdx); matrixIndex += 4 - 1; } // the thumb is pretty much the same as the fingers // (but pointing in a strange direction) float thumbXOffset = -0.05f; float thumbThickness = 0.06f; float thumbBendStrength = 0.1f; float thumbBoneLength = 0.13f; float3 thumbPos = handPos + handRight * thumbXOffset; float3 thumbTarget = thumbPos - handRight * .15f + handForward * (.2f + .1f * fingerGrabT) - handUp * .1f; thumbTarget += handRight * Mathf.Sin(time * 3f + .5f) * .1f * (1f - fingerGrabT); // thumb bends away from the palm, instead of "upward" like the fingers float3 thumbBendHint = (-handRight - handForward * .5f); float3 rockThumbDelta = thumbTarget - armComponent.lastIntendedRockPos; float3 rockThumbPos = armComponent.lastIntendedRockPos + math.normalize(rockThumbDelta) * (armComponent.lastIntendedRockSize * .5f); thumbTarget = math.lerp(thumbTarget, rockThumbPos, fingerGrabT); FABRIK.SolveViaBuffer(thumbChainsBuffer.Reinterpret <float3>(), thumbBoneLength, thumbPos, thumbTarget, thumbBendHint * thumbBendStrength); util.UpdateMatrices(matrices, thumbChainsBuffer.Reinterpret <float3>(), matrixIndex, thumbThickness, thumbBendHint); DynamicBuffer <ArmMatrixBuffer> buffer = matrixBufferLookup[entity]; buffer.Clear(); for (int i = 0; i < matrices.Length; i++) { buffer.Add(new ArmMatrixBuffer() { Value = matrices[i] }); } }
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem) { var renderer = GetComponent <Renderer>(); Mesh mesh; if (UseColliderMeshInsteadOfRendererMesh) { mesh = GetComponent <MeshCollider>().sharedMesh; } else { mesh = GetComponent <MeshFilter>().mesh; } GeometryDataModels.Edge[] edges = new GeometryDataModels.Edge[1]; dstManager.AddBuffer <GeometryDataModelsEntities.EdgesBuffer>(entity); dstManager.AddBuffer <GeometryDataModelsEntities.VerticesBuffer>(entity); dstManager.AddBuffer <GeometryDataModelsEntities.TrianglesBuffer>(entity); DynamicBuffer <GeometryDataModelsEntities.EdgesBuffer> eBuffer = dstManager.GetBuffer <GeometryDataModelsEntities.EdgesBuffer>(entity); DynamicBuffer <GeometryDataModelsEntities.VerticesBuffer> vBuffer = dstManager.GetBuffer <GeometryDataModelsEntities.VerticesBuffer>(entity); DynamicBuffer <GeometryDataModelsEntities.TrianglesBuffer> tBuffer = dstManager.GetBuffer <GeometryDataModelsEntities.TrianglesBuffer>(entity); //Reinterpret to plain int buffer DynamicBuffer <GeometryDataModels.Edge> edgesBuffer = eBuffer.Reinterpret <GeometryDataModels.Edge>(); DynamicBuffer <Vector3> vector3Buffer = vBuffer.Reinterpret <Vector3>(); DynamicBuffer <int> triangleBuffer = tBuffer.Reinterpret <int>(); //populate the dynamic buffer for (int j = 0; j < mesh.vertexCount; j++) { vector3Buffer.Add(mesh.vertices[j]); } for (int j = 0; j < mesh.triangles.Length; j++) { triangleBuffer.Add(mesh.triangles[j]); } dstManager.AddComponentData(entity, new GeometryDataModelsEntities.LocalToWorldMatrix { Matrix = renderer.localToWorldMatrix, }); dstManager.AddComponentData(entity, new GeometryDataModelsEntities.Visible { IsVisible = true, }); var geoInfoData = new GeometryDataModelsEntities.GeoInfoEntityComponent { Edges = edgesBuffer, Vertices = vector3Buffer, Triangles = triangleBuffer, Matrix = renderer.localToWorldMatrix, }; dstManager.AddComponentData(entity, geoInfoData); var targetData = new GeometryDataModels.Target { position = transform.position, projectedTargetPosition = Vector3.zero, distanceToRay = 0, distanceToCastOrigin = 0, entity = entity }; dstManager.AddComponentData(entity, targetData); }
internal static void SetEntityTextRendererString(DynamicBuffer <TextRendererString> buffer, string newText) { buffer.Reinterpret <char>().FromString(newText); }
// Start is called before the first frame update void Start() { mapGen = new MapGeneratorComponent(width, height); char[] map = mapGen.GetMap(); entityManager = World.DefaultGameObjectInjectionWorld.EntityManager; MapTranslationComponent mapTranslationComponent = new MapTranslationComponent(map, entityManager, mesh, StoneMaterial, material, width, height); NativeArray <Entity> entityArray = mapTranslationComponent.GetEntityArray(); //Entity e = entityManager.CreateEntity(typeof(MapBuffer)); Entity f = entityManager.CreateEntity(typeof(MapEntityBuffer)); //Setup Neighbour components for (int i = 0; i < width * height; i++) { Entity entity = entityArray[i]; Tile tile = entityManager.GetComponentData <Tile>(entity); ////Bug, need to add it every iteration or it gets deallocated //DynamicBuffer<MapBuffer> bufferFromEntity = entityManager.GetBuffer<MapBuffer>(e); //DynamicBuffer<Tile> tileBuffer = bufferFromEntity.Reinterpret<Tile>(); //tileBuffer.Add(tile); DynamicBuffer <MapEntityBuffer> entityBufferFromEntity = entityManager.GetBuffer <MapEntityBuffer>(f); DynamicBuffer <Entity> entityBuffer = entityBufferFromEntity.Reinterpret <Entity>(); entityBuffer.Add(entity); //NeighbourTiles neighbours = new NeighbourTiles { // eTile = Entity.Null, // neTile = Entity.Null, // seTile = Entity.Null, // nTile = Entity.Null, // nwTile = Entity.Null, // swTile = Entity.Null, // sTile = Entity.Null, // wTile = Entity.Null //}; //if (tile.coordinates.x - 1 >= 0) //{ // neighbours.wTile = entityArray[(int)math.floor((tile.coordinates.y) * width + (tile.coordinates.x - 1))]; // if (tile.coordinates.y - 1 >= 0) // neighbours.swTile = entityArray[(int)math.floor((tile.coordinates.y - 1) * width + tile.coordinates.x - 1)]; // if (tile.coordinates.y + 1 < height) // neighbours.nwTile = entityArray[(int)math.floor((tile.coordinates.y + 1) * width + tile.coordinates.x - 1)]; //} //if (tile.coordinates.x + 1 < width) //{ // neighbours.eTile = entityArray[(int)math.floor((tile.coordinates.y) * width + (tile.coordinates.x + 1))]; // if (tile.coordinates.y - 1 >= 0) // neighbours.seTile = entityArray[(int)math.floor((tile.coordinates.y - 1) * width + tile.coordinates.x + 1)]; // if (tile.coordinates.y + 1 < height) // neighbours.neTile = entityArray[(int)math.floor((tile.coordinates.y + 1) * width + tile.coordinates.x + 1)]; //} ////Down //if (tile.coordinates.y - 1 >= 0) // neighbours.sTile = entityArray[(int)math.floor((tile.coordinates.y - 1) * width + tile.coordinates.x)]; ////Up //if (tile.coordinates.y + 1 < height) // neighbours.nTile = entityArray[(int)math.floor((tile.coordinates.y + 1) * width + tile.coordinates.x)]; //entityManager.SetComponentData(entity, neighbours); } SpawnerComponent spawnerComponent = new SpawnerComponent(entityArray); }
protected override void OnUpdate() { if (!sceneLoaded) { currentScene = SceneManager.GetActiveScene(); Debug.Log("Scene is not loaded"); Debug.Log(currentScene.name); if (currentScene.name == "AnimationScene") { Debug.Log("Can we enter here?"); sceneLoaded = true; } } else { healthText = GameObject.Find("HealthText").GetComponent <Text>(); healthBar = GameObject.Find("Image").GetComponent <Image>(); backPack = GameObject.Find("UIBackPack").GetComponent <Text>(); statText = GameObject.Find("StatText").GetComponent <Text>(); //This Grabs everyone with these components //AKA the player Entities.ForEach((Entity e, ref PlayerComponent playerComponent, ref MovementComponent movementComponent, ref StatsComponent statsComponent, ref VelocityComponent velocityComponent, ref ColliderComponent colliderComponent) => { //StatsComponent updateComponent = statsComponent; //Entities.ForEach((Entity f, // ref HealthBarComponent healthBarComponent) => //{ // healthBarComponent.health = updateComponent.health; // healthBarComponent.attack = updateComponent.attack; // healthBarComponent.attackSpeed = updateComponent.attackSpeed; // healthBarComponent.moveSpeed = updateComponent.moveSpeed; //}); healthText.text = "Current Health: " + statsComponent.health; healthBar.rectTransform.sizeDelta = new Vector2(healthTextSize * statsComponent.health / 100, 20); statText.text = "Attack Damage: " + statsComponent.attack + "\nAttack Speed: " + statsComponent.attackSpeed + "\nMove Speed: " + statsComponent.moveSpeed; DynamicBuffer <IntBufferElement> backpack = entityManager.GetBuffer <IntBufferElement>(e); backPack.text = "Backpack: "; foreach (var spriteValue in backpack.Reinterpret <IntBufferElement>()) { string gameObjectString = "Item" + spriteValue.value; if (GameObject.Find(gameObjectString)) { //Debug.Log("Already Generated"); } else { float myScale = 1.5f; GameObject itemIcon = new GameObject(); Image newImage = itemIcon.AddComponent <Image>(); itemIcon.GetComponent <RectTransform>().SetParent(backPack.transform); itemIcon.transform.position = itemIcon.transform.position + new Vector3(backPackLeftTransform + (numberOfItems * itemWidth), 35, 0); itemIcon.transform.localScale = new Vector3(myScale, myScale, myScale); Debug.Log(itemIcon.transform.localPosition); Item currentItem = GlobalObjects.iTable.lookupItem(spriteValue.value); Sprite currentItemSprite = currentItem.itemSprite; newImage.sprite = currentItemSprite; itemIcon.name = "Item" + spriteValue.value; numberOfItems++; } //backPack.text = backPack.text + " " + spriteValue.value; } }); } }