private static void CalculatePath(NativeHashMap <int, PathNode> pathNodeMap, PathNode endNode, DynamicBuffer <PathCell> pathPointBuffer, ref PathFollow pathFollow) { //Didnt find a path! if (endNode.PreviousNodeIndex == -1) { pathFollow = new PathFollow { PathIndex = -1 }; return; } else { pathPointBuffer.Add(new PathCell { Cell = new int2(endNode.X, endNode.Y) }); PathNode currentNode = endNode; while (currentNode.PreviousNodeIndex != -1) { PathNode previousNode = pathNodeMap[currentNode.PreviousNodeIndex]; pathPointBuffer.Add(new PathCell { Cell = new int2(previousNode.X, previousNode.Y) }); currentNode = previousNode; } pathFollow = new PathFollow { PathIndex = pathPointBuffer.Length - 1 }; } }
private void CalculatePath(int2 startPosition, int2 endPosition, DynamicBuffer <PathPosition> pathPositionBuffer, bool pathFound) { if (pathFound == false) { return; } pathPositionBuffer.Add(new PathPosition { position = new int2(endPosition.x, endPosition.y) }); var current = endPosition; do { var previous = CameFrom[GetIndex(current)]; current = previous.Position; if (previous.NextToObstacle || current.Equals(startPosition)) { pathPositionBuffer.Add(new PathPosition { position = current }); } } while (!current.Equals(startPosition)); }
private static void CalculatePath(NativeArray <PathNode> pathNodeArray, PathNode endNode, DynamicBuffer <PathPosition> positionBuff) { if (endNode.cameFromNodeIndex == -1) { //can't find the path } else { //found a path // var path =new NativeList<int2>(Allocator.Temp); // path.Add(new int2(endNode.x, endNode.y)); positionBuff.Add(new PathPosition { Position = new int2(endNode.x, endNode.y) }); var currentNode = endNode; while (currentNode.cameFromNodeIndex != -1) { var cameFromNode = pathNodeArray[currentNode.cameFromNodeIndex]; positionBuff.Add(new PathPosition { Position = new int2(cameFromNode.x, cameFromNode.y) }); currentNode = cameFromNode; } } }
// 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 }
public void ConsumeResourceWhenAbilityEnabled() { // Arrange Entity caster = _entityManager.CreateEntity(); Ability ability = new Ability(1, 1, new Range()) { HasEnougthRessource = false, State = AbilityState.Active }; DynamicBuffer <AbilityBuffer> abilityBuffer = _entityManager.AddBuffer <AbilityBuffer>(caster); abilityBuffer.Add(new AbilityBuffer() { Ability = ability }); abilityBuffer.Add(new AbilityBuffer() { Ability = ability }); _world.WithSystem <AbilityCostCheckInitializationSystem>(); //Act _world.UpdateSystem <AbilityCostCheckInitializationSystem>(); _world.CompleteAllJobs(); //Assert Assert.IsTrue(_entityManager.GetBuffer <AbilityBuffer>(caster)[0].Ability.HasEnougthRessource); Assert.IsTrue(_entityManager.GetBuffer <AbilityBuffer>(caster)[1].Ability.HasEnougthRessource); }
private void CalculatePath(NativeArray <PathNode> pathNodeArray, PathNode endNode, DynamicBuffer <PathPosition> pathPositionBuffer) { if (endNode.cameFromNodeIndex == -1) { // Couldn't find a path! } else { // Found a path //Debug.Log(endNode.x + ", " + endNode.y + ": " + endNode.isWalkable); pathPositionBuffer.Add(new PathPosition { position = pathfindingGridToTilemapGrid(new int2(endNode.x, endNode.y)) }); PathNode currentNode = endNode; while (currentNode.cameFromNodeIndex != -1) { PathNode cameFromNode = pathNodeArray[currentNode.cameFromNodeIndex]; //Debug.Log(cameFromNode.x + ", " + cameFromNode.y + ": " + cameFromNode.isWalkable); pathPositionBuffer.Add(new PathPosition { position = pathfindingGridToTilemapGrid(new int2(cameFromNode.x, cameFromNode.y)) }); currentNode = cameFromNode; } } }
void CreatePath(DynamicBuffer <PathPositions> path, NativeArray <int> cameFrom, int endIndex, int startIndex, float2 endPos, [ReadOnly] NativeArray <Waypoint> waypoints) { //Clear path path.Clear(); //Build path int currentIndex = endIndex; int maxIteration = 20; path.Add(new PathPositions() { Value = endPos }); while (--maxIteration > 0 && currentIndex != startIndex) { path.Add(new PathPositions() { Value = waypoints[currentIndex].position }); currentIndex = cameFrom[currentIndex]; } path.Add(new PathPositions() { Value = waypoints[startIndex].position }); }
private static void AddQuad(ref WorldSpaceMask rectMask, ref DynamicBuffer <MeshVertex> vertices, ref DynamicBuffer <MeshVertexIndex> triangles, float2 posMin, float2 posMax, float4 color, float2 uvMin, float2 uvMax) { RectMaskCut cut = SpriteUtility.GetRectangleMaskCut(posMin, posMax, ref rectMask); var cutSize = cut.Max + cut.Min; var rectSize = posMax - posMin; if (cutSize.x > rectSize.x || cutSize.y > rectSize.y) { return; } int startIndex = vertices.Length; vertices.Add(new MeshVertex() { Position = new float3(new float2(posMin) + cut.Min, 0.0f), TexCoord0 = new float2(uvMin) + cut.UvMin, Color = color }); vertices.Add(new MeshVertex() { Position = new float3(new float2(posMin.x + cut.Min.x, posMax.y - cut.Max.y), 0.0f), TexCoord0 = new float2(uvMin.x + cut.UvMin.x, uvMax.y - cut.UvMax.y), Color = color }); vertices.Add(new MeshVertex() { Position = new float3(new float2(posMax.x, posMax.y) - cut.Max, 0.0f), TexCoord0 = new float2(uvMax.x, uvMax.y) - cut.UvMax, Color = color }); vertices.Add(new MeshVertex() { Position = new float3(new float2(posMax.x - cut.Max.x, posMin.y + cut.Min.y), 0.0f), TexCoord0 = new float2(uvMax.x - cut.UvMax.x, uvMin.y + cut.UvMin.y), Color = color }); triangles.Add(new MeshVertexIndex { Value = startIndex }); triangles.Add(new MeshVertexIndex { Value = startIndex + 1 }); triangles.Add(new MeshVertexIndex { Value = startIndex + 2 }); triangles.Add(new MeshVertexIndex { Value = startIndex + 2 }); triangles.Add(new MeshVertexIndex { Value = startIndex + 3 }); triangles.Add(new MeshVertexIndex { Value = startIndex }); }
private static void FindAndAddPosibleTargetsToBuffer(FractionalHex position, Fix64 sightRange, ActTargetFilters filters, Team team, Dictionary <Hex, List <EntityOnVision> > unitsForeachHex, List <BuildingOnVision> buildingsOnSight, DynamicBuffer <BEPosibleTarget> buffer) { Hex roundedPosition = position.Round(); //buildings foreach (var building in buildingsOnSight) { var buildingHex = building.building.position; var reversedDirection = (position - (FractionalHex)buildingHex).NormalizedManhathan(); var fullHexTargetPos = FractionalHex.GetBorderPointOfTheHex(buildingHex, reversedDirection); var buildingPos = (FractionalHex)buildingHex; if (ValidPossibleTarget(position, sightRange, team.Number, filters, buildingPos, (Fix64)0.5, building.team)) { buffer.Add(new BEPosibleTarget() { Position = buildingPos, Radius = Fix64.Zero, Entity = building.entity, IsUnit = false, OccupiesFullHex = true, OccupyingHex = buildingHex, GatherTarget = false, ActTypeTarget = filters.actType }); } } //units var pointsOfHex = SpartialSortUtils.GetAllPointsAtRange(roundedPosition, (int)Fix64.Ceiling(sightRange), unitsForeachHex); foreach (var point in pointsOfHex) { int pointTeam = point.team; Entity pointEntity = point.entity; var pointRadius = point.collider.Radius; if (ValidPossibleTarget(position, sightRange, team.Number, filters, point.position, pointRadius, pointTeam)) { buffer.Add(new BEPosibleTarget() { Position = point.position, Radius = pointRadius, Entity = pointEntity, IsUnit = true, OccupiesFullHex = false, OccupyingHex = point.position.Round(), GatherTarget = false, ActTypeTarget = filters.actType }); } } }
//添加三角顶点与颜色 void AddTriangle(Vector3 v1, Color bottomColor, Vector3 v2, Color leftColor, Vector3 v3, Color rightColor, ref DynamicBuffer <ColorBuffer> colorBuffer, ref DynamicBuffer <VertexBuffer> vertexBuffer) { //Color colorTriangle = (bottomColor + leftColor + rightColor) / 3f; colorBuffer.Add(bottomColor); vertexBuffer.Add((v1)); colorBuffer.Add(leftColor); vertexBuffer.Add((v2)); colorBuffer.Add(rightColor); vertexBuffer.Add((v3)); }
public static void AddRange <T>(this DynamicBuffer <T> buffer, IEnumerable <T> values) where T : struct, IBufferElementData { foreach (var value in values) { buffer.Add(value); } }
public void Execute() { DynamicBuffer <CollisionData> collisionsBuffer = CollisionDatasBufferWithEntity.GetDynamicBuffer(); DynamicBuffer <CollisionEnterData> collisionEntersBuffer = CollisionEnterDatasBufferWithEntity.GetDynamicBuffer(); DynamicBuffer <CollisionExitData> collisionExitsBuffer = CollisionExitDatasBufferWithEntity.GetDynamicBuffer(); NativeArray <CollisionData> oldCollisions = collisionsBuffer.ToNativeArray(Allocator.Temp); collisionsBuffer.Clear(); collisionEntersBuffer.Clear(); collisionExitsBuffer.Clear(); // gather new collisions for (int i = 0; i < Colliders.Length; i++) { for (int j = i + 1; j < Colliders.Length; j++) { if (Intersects( Colliders[i], Translations[i], Colliders[j], Translations[j])) { // collision detected! collisionsBuffer.Add(new CollisionData() { EntityA = Entities[i], EntityB = Entities[j] }); } } } // find new and old collision datas (NB: THIS COULD BE OPTIMIZED BY SORTING COLLISIONS) NativeArray <CollisionData> newCollisions = collisionsBuffer.AsNativeArray(); for (int i = 0; i < oldCollisions.Length; i++) { if (!newCollisions.Contains(oldCollisions[i])) { collisionExitsBuffer.Add(new CollisionExitData() { EntityA = oldCollisions[i].EntityA, EntityB = oldCollisions[i].EntityB, }); } } for (int i = 0; i < newCollisions.Length; i++) { if (!oldCollisions.Contains(newCollisions[i])) { collisionEntersBuffer.Add(new CollisionEnterData() { EntityA = newCollisions[i].EntityA, EntityB = newCollisions[i].EntityB, }); } } oldCollisions.Dispose(); }
private void PopulateBuffers(Entity e, EntityManager entityManager) { DynamicBuffer <ArmChainsBuffer> armChains = entityManager.GetBuffer <ArmChainsBuffer>(e); for (int i = 0; i < armChains.Capacity; i++) { armChains.Add(new ArmChainsBuffer() { element = new float3() }); } DynamicBuffer <FingerChainsBuffer> fingerChains = entityManager.GetBuffer <FingerChainsBuffer>(e); for (int i = 0; i < fingerChains.Capacity; i++) { fingerChains.Add(new FingerChainsBuffer() { element = new float3() }); } DynamicBuffer <ThumbChainsBuffer> thumbChains = entityManager.GetBuffer <ThumbChainsBuffer>(e); for (int i = 0; i < thumbChains.Capacity; i++) { thumbChains.Add(new ThumbChainsBuffer() { element = new float3() }); } }
public static void AddCommandData <T>(this DynamicBuffer <T> commandArray, T commandData) where T : struct, ICommandData <T> { uint targetTick = commandData.Tick; int oldestIdx = 0; uint oldestTick = 0; for (int i = 0; i < commandArray.Length; ++i) { uint tick = commandArray[i].Tick; if (tick == targetTick) { // Already exists, replace it commandArray[i] = commandData; return; } if (oldestTick == 0 || SequenceHelpers.IsNewer(oldestTick, tick)) { oldestIdx = i; oldestTick = tick; } } if (commandArray.Length < k_CommandDataMaxSize) { commandArray.Add(commandData); } else { commandArray[oldestIdx] = commandData; } }
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 Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem) { EntityQuery cameraQuery = dstManager.CreateEntityQuery(typeof(CameraMovementData)); EntityQuery mapQuery = dstManager.CreateEntityQuery(typeof(MapRenderInfo)); var mapData = mapQuery.GetSingleton <MapRenderInfo>(); var cameraArray = cameraQuery.ToEntityArray(Allocator.TempJob); //there should only be one... maybe two actually. for right now this is fine. dstManager.AddComponentData(entity, new CursorData { cameraEntity = cameraArray[0], //do this but better somehow maybe idk maybe its fine since theres only one camera rayMagnitude = 10000f, //arbitrary long number so it always collides for now tileSize = mapData.tileSize }); dstManager.AddComponentData(entity, new ControlSchemeData()); DynamicBuffer <HighlightTile> highlights = dstManager.AddBuffer <HighlightTile>(entity); highlights.Add(new HighlightTile { point = new Point(0, 0), state = (ushort)MapLayer.Hover }); #if UNITY_EDITOR dstManager.SetName(entity, "Cursor"); #endif cameraArray.Dispose(); //TODO: fix rhombus }
public static void AddHistoryStateData <T>(this DynamicBuffer <T> self, T data) where T : struct, IHistoryStateData { uint targetTick = data.Tick; int oldestIdx = 0; uint oldestTick = 0; for (int i = 0; i < self.Length; ++i) { uint tick = self[i].Tick; if (tick == targetTick) { self[i] = data; return; } if (oldestTick == 0 || tick < oldestTick) { oldestIdx = i; oldestTick = tick; } } if (self.Length < GlobalConstants.SnapshotHistorySize) { self.Add(data); } else { self[oldestIdx] = data; } }
public static bool InvokeDeserialize <T>(BufferFromEntity <T> snapshotFromEntity, Entity entity, uint snapshot, uint baseline, uint baseline2, uint baseline3, DataStreamReader reader, ref DataStreamReader.Context ctx, NetworkCompressionModel compressionModel) where T : struct, ISnapshotData <T> { DynamicBuffer <T> snapshotArray = snapshotFromEntity[entity]; var baselineData = default(T); if (baseline != snapshot) { for (int i = 0; i < snapshotArray.Length; ++i) { if (snapshotArray[i].Tick == baseline) { baselineData = snapshotArray[i]; break; } } if (baselineData.Tick == 0) { return(false); // Ack desync detected } } if (baseline3 != snapshot) { var baselineData2 = default(T); var baselineData3 = default(T); for (int i = 0; i < snapshotArray.Length; ++i) { if (snapshotArray[i].Tick == baseline2) { baselineData2 = snapshotArray[i]; } if (snapshotArray[i].Tick == baseline3) { baselineData3 = snapshotArray[i]; } } if (baselineData2.Tick == 0 || baselineData3.Tick == 0) { return(false); // Ack desync detected } baselineData.PredictDelta(snapshot, ref baselineData2, ref baselineData3); } var data = default(T); data.Deserialize(snapshot, ref baselineData, reader, ref ctx, compressionModel); // Replace the oldest snapshot and add a new one if (snapshotArray.Length == GhostSystemConstants.SnapshotHistorySize) { snapshotArray.RemoveAt(0); } snapshotArray.Add(data); return(true); }
public void Execute(DynamicBuffer <ObserverSyncVisibleActorBuffer> syncVisibleActorList, [ReadOnly] ref ObserverPosition observerPosition, [ReadOnly] ref ObserverVisibleDistance observerVisibleDistance) { for (int i = 0; i < actorEntitys.Length; ++i) { var actorEntity = actorEntitys[i]; // var actorVisibleDistanceOnSync = actorVisibleDistanceOnSyncs[i]; // if (syncTypeEnables[(int)actorVisibleDistanceOnSync.perFrame] == false) { continue; } if (actorVisibleDistanceOnSync.changed == false) { continue; } // var translation = translations[i]; if (observerVisibleDistance.all || math.distancesq(observerPosition.value, translation.Value) < observerVisibleDistance.valueSq) { syncVisibleActorList.Add(new ObserverSyncVisibleActorBuffer { synActorType = actorVisibleDistanceOnSync.syncType, actorEntity = actorEntity }); } } }
public Entity Build() { if (!EntityManager.Exists(_entity)) { _entity = EntityManager.CreateEntity(); } if (EntityManager.HasComponent <Sequence>(_entity)) { EntityManager.SetComponentData(_entity, new Sequence { Index = 0, Size = _commands.Count }); } else { EntityManager.AddComponentData(_entity, new Sequence { Index = 0, Size = _commands.Count }); } // if(EntityManager.GetBuffer<>()) DynamicBuffer <SequenceCommand> buffer = EntityManager.AddBuffer <SequenceCommand>(_entity); buffer.Clear(); foreach (SequenceCommand cmd in _commands) { buffer.Add(cmd); } return(_entity); }
private void ProcessForEntity(Entity entity, Entity otherEntity) { if (TriggerEventBufferFromEntity.Exists(entity)) { DynamicBuffer <TriggerEventBufferElement> triggerEventBuffer = TriggerEventBufferFromEntity[entity]; bool foundMatch = false; for (int i = 0; i < triggerEventBuffer.Length; i++) { TriggerEventBufferElement triggerEvent = triggerEventBuffer[i]; // If entity is already there, update to Stay if (triggerEvent.Entity == otherEntity) { foundMatch = true; triggerEvent.State = PhysicsEventState.Stay; triggerEvent._isStale = false; triggerEventBuffer[i] = triggerEvent; break; } } // If it's a new entity, add as Enter if (!foundMatch) { triggerEventBuffer.Add(new TriggerEventBufferElement { Entity = otherEntity, State = PhysicsEventState.Enter, _isStale = false, }); } } }
public static void AddCommandData <T>(this DynamicBuffer <T> self, T command) where T : struct, ICommandData { uint targetTick = command.Tick; int oldestIdx = 0; uint oldestTick = 0; for (int i = 0; i < self.Length; ++i) { uint tick = self[i].Tick; if (tick == targetTick) { self[i] = command; return; } if (oldestTick == 0 || tick < oldestTick) { oldestIdx = i; oldestTick = tick; } } if (self.Length < CommandDataMaxSize) { self.Add(command); } else { self[oldestIdx] = command; } }
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem) { Entity holder = dstManager.CreateEntity(); //dstManager.SetName(holder, "Follow WP Holder"); dstManager.AddComponentData <FollowWayPointsStorage>(holder, new FollowWayPointsStorage { // add the followwaypointsstorage component to the holder id = actionID, curPointNum = 0 }); // store the data DynamicBuffer <WayPoint> wp = dstManager.AddBuffer <WayPoint>(holder); // create the list of waypoints on the holder foreach (float3 wayPoint in wayPoints) // fill the list of waypoints on the holder { wp.Add(new WayPoint { value = wayPoint }); } dstManager.AddComponentData <AddFollowWayPointsAction>(entity, new AddFollowWayPointsAction { //add the addfollowwaypointsaction component to the crowd agent id = actionID, priority = priority, timeCreated = 0f, dataHolder = holder }); dstManager.AddBuffer <Action>(entity); dstManager.AddComponentData <CurrentAction>(entity, new CurrentAction { id = -1, type = ActionType.No_Action, dataHolder = holder }); }
/// <summary> /// Setup paths: /// Creating Pure Entity /// Adding Buffer of Curve Entities /// Maping PathEntity with PathGO ir Database /// </summary> private static void SetupPaths() { GameObject[] pathsGO = GetGameObjectsByTag("Path"); foreach (var path in pathsGO) { // Setup Traveler object-entity GameObject travelerGO = path.GetComponent <TravelerSetter>().traveler; Entity travelerEnt = GameObjectEntity.AddToEntityManager(em, travelerGO); em.AddComponentData(travelerEnt, new PathID(path.GetInstanceID())); em.AddSharedComponentData(travelerEnt, new TravelerMarker { }); Database.Travelers.Add(path.GetInstanceID(), travelerEnt); // Setup Path Entity Entity pathEntity = em.CreateEntity(Archetypes.PathSplineArchetype); em.SetComponentData(pathEntity, new Traveler(travelerEnt)); em.SetComponentData(pathEntity, new PathID(path.GetInstanceID())); em.SetComponentData(pathEntity, new UpdateIndicator(1)); List <Entity> tempCurvesEntities = SetupCurves(path); em.SetComponentData(pathEntity, new Traveler()); // Saving curves into path DynamicBuffer <CurveElement> pathCurvesBuffer = em.GetBufferFromEntity <CurveElement>()[pathEntity]; foreach (var ce in tempCurvesEntities) { pathCurvesBuffer.Add(new CurveElement(ce)); } Database.worldPaths.Add(path.GetInstanceID(), pathEntity); Database.ID_GOmap.Add(path.GetInstanceID(), path); } }
public static void AddAmountOf(this DynamicBuffer <InventoryBufferElement> buffer, FixedString32 resourceName, float addedAmount) { var index = -1; for (int i = 0; i < buffer.Length; i++) { if (buffer[i].ResourceName == resourceName) { index = i; break; } } float currentAmount; if (index != -1) { currentAmount = buffer[index].ResourceAmount; buffer.RemoveAt(index); } else { currentAmount = 0f; } if (currentAmount + addedAmount != 0f) { buffer.Add(new InventoryBufferElement { ResourceName = resourceName, ResourceAmount = currentAmount + addedAmount }); } }
public void Add(int index, DynamicBuffer <VertexElement> points) { var s = points.Length; var startEnd = _startEnds[_r.NextInt(_startEnds.Length)]; var scale = 1 - _scaleOffset + _r.NextFloat() * 2 * _scaleOffset; var rot = _r.NextFloat(2 * math.PI); for (int i = startEnd.x; i < startEnd.y; i++) { points.Add(Rotate(scale * _vertices[i], rot)); } var min = new float2(float.MaxValue); var max = new float2(float.MinValue); for (var i = s; i < points.Length; i++) { min = math.min(points[i], min); max = math.max(points[i], max); } var size = max - min; var range = _size - size; var offset = _r.NextFloat2(range); for (var i = s; i < points.Length; i++) { points[i] += offset - min - _size / 2; } }
public void Convert(Entity entity, EntityManager dstManager, GameObjectConversionSystem conversionSystem) { dstManager.AddComponentData(entity, new RoadInfo() { LaneWidth = LaneWidth, MaxLanes = MaxLanes, CarSpawningDistancePercent = CarSpawningDistance, MidRadius = MidRadius, StraightPieceLength = StraightPieceLength, SegmentCount = SegmentCount }); DynamicBuffer <LaneInfoElement> dynamicBuffer = dstManager.AddBuffer <LaneInfoElement>(entity); for (int i = 0; i < MaxLanes; ++i) { LaneInfo info = new LaneInfo { Pivot = LaneWidth * ((MaxLanes - 1) / 2f - i), Radius = MidRadius - LaneWidth * (MaxLanes - 1) / 2f + i * LaneWidth }; info.CurvedPieceLength = info.Radius * math.PI / 2f; dynamicBuffer.Add(new LaneInfoElement { Value = info }); } }
private void PopulateMesh(Entity entity, ref DynamicBuffer <MeshVertex> vertices, ref DynamicBuffer <MeshVertexIndex> triangles, ref DynamicBuffer <SubMeshInfo> subMeshes) { bool materialAssigned = EntityToMaterial.TryGetValue(entity, out MaterialInfo material); if (!materialAssigned) { material.Type = SubMeshType.SpriteImage; material.Id = -1; } if (m_CurrentMaterialId != material.Id) { subMeshes.Add(new SubMeshInfo() { Offset = triangles.Length, MaterialId = material.Id, MaterialType = material.Type }); m_CurrentMaterialId = material.Id; } int startIndex = vertices.Length; if (VertexPointerFromEntity.Exists(entity)) { VertexPointerFromEntity[entity] = new ElementVertexPointerInMesh() { VertexPointer = startIndex } } ; Populate(entity, ref vertices, ref triangles, startIndex); }
private static int GetVertId(ref DynamicBuffer <float3> vertices, ref DynamicBuffer <float3> normals, NativeHashMap <float3, int> oldLayerPosIdDict, NativeHashMap <float3, int> newLayerPosIdDict, VertexNormal vertex, float3 topPoint, ref int len) { int vertId; if (oldLayerPosIdDict.TryGetValue(vertex.position, out vertId)) { //vertId = positionIdDict.TryGetValue; } else { vertices.Add(vertex.position); normals.Add(vertex.normal); vertId = len; if (math.any(vertex.position == topPoint)) { oldLayerPosIdDict.Add(vertex.position, vertId); } if (vertex.position.z == topPoint.z) { newLayerPosIdDict.Add(vertex.position, vertId); } len++; } return(vertId); }
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); }