Пример #1
0
        public void PathRandomObstacles()
        {
            using (var grid = new TestGrid(31))
            {
                int obstacleCount = 32;
                var rand          = new Unity.Mathematics.Random(0xF545AA3F);
                for (int i = 0; i < obstacleCount; i++)
                {
                    var faceIndex      = rand.NextInt(0, 6);
                    var xy             = rand.NextInt2(new int2(grid.RowCount, grid.RowCount));
                    var sourcePosition = new CartesianGridCoordinates {
                        x = (short)xy.x, y = (short)xy.y
                    };
                    var cubeFace = new CartesianGridOnCubeFace {
                        Value = (byte)faceIndex
                    };
                    var cellIndex = CartesianGridOnCubeUtility.CellIndex(sourcePosition, cubeFace, grid.RowCount);
                    if (rand.NextBool())
                    {
                        grid.AddWallWest(cellIndex);
                    }
                    else
                    {
                        grid.AddWallSouth(cellIndex);
                    }
                }

                int testCount = 64;
                for (int i = 0; i < testCount; i++)
                {
                    var sourceXY        = rand.NextInt2(new int2(grid.RowCount, grid.RowCount));
                    var sourceFaceIndex = rand.NextInt(0, 6);
                    var sourceCubeFace  = new CartesianGridOnCubeFace {
                        Value = (byte)sourceFaceIndex
                    };
                    var sourcePosition = new CartesianGridCoordinates {
                        x = (short)sourceXY.x, y = (short)sourceXY.y
                    };

                    var targetXY        = rand.NextInt2(new int2(grid.RowCount, grid.RowCount));
                    var targetFaceIndex = rand.NextInt(0, 6);
                    var targetCubeFace  = new CartesianGridOnCubeFace {
                        Value = (byte)targetFaceIndex
                    };
                    var targetPosition = new CartesianGridCoordinates {
                        x = (short)targetXY.x, y = (short)targetXY.y
                    };

                    grid.WalkPathDistance(sourcePosition, sourceCubeFace, targetPosition, targetCubeFace);
                }
            }
        }
Пример #2
0
    IEnumerator SpawnZombieBatch()
    {
        while (spawnedCount < 5000)
        {
            yield return(new WaitForSeconds(4));

            spawnedCount += 80;
            Unity.Mathematics.Random rand = new Unity.Mathematics.Random(42);
            var  prefab        = GameObjectConversionUtility.ConvertGameObjectHierarchy(zombiePrefab, World.DefaultGameObjectInjectionWorld);
            var  entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
            uint count         = 0;
            while (count++ < 100)
            {
                var instance = entityManager.Instantiate(prefab);
                var space    = rand.NextInt2(minPos, maxPos);
                space.x += rand.NextInt(-2, 2);
                space.y += rand.NextInt(-2, 2);
                var position = transform.TransformPoint(new float3(space.x, 1, space.y));
                entityManager.SetComponentData(instance, new Translation {
                    Value = position
                });
                var movementData = entityManager.GetComponentData <MovementComponent>(instance);
                movementData.speed += rand.NextFloat(-4f, 0f);
                entityManager.SetComponentData(instance, movementData);
            }
        }
    }
        protected override void OnCreate( )
        {
            eecb = World.GetOrCreateSystem <EndSimulationEntityCommandBufferSystem> ();

            random = new Unity.Mathematics.Random((uint)System.DateTime.UtcNow.Millisecond + 5000);
            random.NextInt2();
        }
Пример #4
0
        private void Next(int2 xy)
        {
            var room = new Room
            {
                x = xy.x,
                y = xy.y,
                w = minWidth + rand.NextInt(cellWidth),
                h = minWidth + rand.NextInt(cellWidth)
            };

            rooms.Add(room);
            roomsCount--;
            rand.NextInt2(-1, 1);
            if (roomsCount >= 0)
            {
                Next(xy + rand.NextInt2(new int2(-1, 1), new int2(-1, 1)) * new int2(room.w, room.h));
            }
        }
Пример #5
0
    // Start is called before the first frame update
    void Start()
    {
        spawnedCount = initialZombieSpawnCount;
        Unity.Mathematics.Random rand = new Unity.Mathematics.Random(42);
        var  prefab        = GameObjectConversionUtility.ConvertGameObjectHierarchy(zombiePrefab, World.Active);
        var  entityManager = World.DefaultGameObjectInjectionWorld.EntityManager;
        uint count         = 0;

        while (count++ < initialZombieSpawnCount)
        {
            var instance = entityManager.Instantiate(prefab);
            var space    = rand.NextInt2(minPos, maxPos);
            space.x += rand.NextInt(-2, 2);
            space.y += rand.NextInt(-2, 2);

            while (usedPositions.Contains(space))
            {
                space = rand.NextInt2(minPos, maxPos);
            }

            usedPositions.Add(space);

            var position = transform.TransformPoint(new float3(space.x, 1, space.y));
            entityManager.SetComponentData(instance, new Translation {
                Value = position
            });

            var movementData = entityManager.GetComponentData <MovementComponent>(instance);
            // todo: the ones that can maneuver should be faster
            // todo: leaders -> force outer zombies to stick around them
            movementData.speed += rand.NextFloat(-6f, 1f);
            entityManager.SetComponentData(instance, movementData);
        }

        EntityArchetype arch = entityManager.CreateArchetype(typeof(ZombieSpawnerComponent));
        Entity          e    = entityManager.CreateEntity(arch);

        entityManager.SetComponentData(e, new ZombieSpawnerComponent {
            prefab = prefab
        });
        entityManager.Instantiate(e);

        // StartCoroutine(SpawnZombieBatch());
    }
            // public int i_eliteScore ;


            public void Execute(int i)
            {
                int i_eliteProbablityCount = na_indexProbability.Length;

                random.InitState((uint)(random.NextInt(i_eliteProbablityCount) + na_randomValues [i]));
                random.NextInt2();

                int i_firstPorbabilityIndex  = random.NextInt(0, i_eliteProbablityCount);
                int i_secondPorbabilityIndex = random.NextInt(0, i_eliteProbablityCount);

                int i_firstParentEntityIndex  = na_indexProbability [i_firstPorbabilityIndex];
                int i_secondParentEntityIndex = na_indexProbability [i_secondPorbabilityIndex];



                Entity firstParentEntity  = na_parentPopulationEntities [i_firstParentEntityIndex];
                Entity secondParentEntity = na_parentPopulationEntities [i_secondParentEntityIndex];

                DynamicBuffer <NNInput2HiddenLayersWeightsBuffer>  a_firstParentInput2HiddenLayersWeights  = input2HiddenLayersWeightsBuffer [firstParentEntity];
                DynamicBuffer <NNHidden2OutputLayersWeightsBuffer> a_firstParentHidden2OutputLayersWeights = hidden2OutputLayersWeightsBuffer [firstParentEntity];

                DynamicBuffer <NNInput2HiddenLayersWeightsBuffer>  a_secondParentInput2HiddenLayersWeights  = input2HiddenLayersWeightsBuffer [secondParentEntity];
                DynamicBuffer <NNHidden2OutputLayersWeightsBuffer> a_secondParentHidden2OutputLayersWeights = hidden2OutputLayersWeightsBuffer [secondParentEntity];

                Entity offspringEntity = na_offspringPopulationEntities [i];

                DynamicBuffer <NNInput2HiddenLayersWeightsBuffer>  a_offspringInput2HiddenLayersWeights   = input2HiddenLayersWeightsBuffer [offspringEntity];
                DynamicBuffer <NNHidden2OutputLayersWeightsBuffer> a_offspringtHidden2OutputLayersWeights = hidden2OutputLayersWeightsBuffer [offspringEntity];


                int i_input2HiddenLayersWeightsCount  = a_firstParentInput2HiddenLayersWeights.Length;
                int i_hidden2OutputLayersWeightsCount = a_firstParentHidden2OutputLayersWeights.Length;

                a_offspringInput2HiddenLayersWeights.ResizeUninitialized(i_input2HiddenLayersWeightsCount);
                a_offspringtHidden2OutputLayersWeights.ResizeUninitialized(i_hidden2OutputLayersWeightsCount);

                // 50 / 50 chance to get trait (NN weights) from parent A or B.
                for (int j = 0; j < a_offspringInput2HiddenLayersWeights.Length; j++)
                {
                    float f = random.NextFloat() < 0.5f ? a_firstParentInput2HiddenLayersWeights [j].f : a_secondParentInput2HiddenLayersWeights [j].f;
                    a_offspringInput2HiddenLayersWeights [j] = new NNInput2HiddenLayersWeightsBuffer()
                    {
                        f = f
                    };
                }

                for (int j = 0; j < a_offspringtHidden2OutputLayersWeights.Length; j++)
                {
                    float f = random.NextFloat() < 0.5f ? a_firstParentHidden2OutputLayersWeights [j].f : a_secondParentHidden2OutputLayersWeights [j].f;
                    a_offspringtHidden2OutputLayersWeights [j] = new NNHidden2OutputLayersWeightsBuffer()
                    {
                        f = f
                    };
                }
            }
        public void PathRandomObstacles()
        {
            using (var grid = new TestGrid(32, 15))
            {
                int obstacleCount = 32;
                var rand          = new Unity.Mathematics.Random(0xF545AA3F);
                for (int i = 0; i < obstacleCount; i++)
                {
                    var xy = rand.NextInt2(new int2(grid.ColCount, grid.RowCount));
                    if (rand.NextBool())
                    {
                        grid.AddWallWest(new CartesianGridCoordinates {
                            x = (short)xy.x, y = (short)xy.y
                        });
                    }
                    else
                    {
                        grid.AddWallSouth(new CartesianGridCoordinates {
                            x = (short)xy.x, y = (short)xy.y
                        });
                    }
                }

                int testCount = 64;
                for (int i = 0; i < testCount; i++)
                {
                    var sourceXY       = rand.NextInt2(new int2(grid.ColCount, grid.RowCount));
                    var targetXY       = rand.NextInt2(new int2(grid.ColCount, grid.RowCount));
                    var sourcePosition = new CartesianGridCoordinates {
                        x = (short)sourceXY.x, y = (short)sourceXY.y
                    };
                    var targetPosition = new CartesianGridCoordinates {
                        x = (short)targetXY.x, y = (short)targetXY.y
                    };
                    grid.WalkPathDistance(sourcePosition, targetPosition);
                }
            }
        }
Пример #8
0
        public static BlobAssetReference <Collider> GenerateRandomTerrain(ref Random rnd)
        {
            int2   size  = rnd.NextInt2(2, 50);
            float3 scale = rnd.NextFloat3(0.1f, new float3(1, 10, 1));

            int numSamples = size.x * size.y;
            var heights    = new NativeArray <float>(numSamples, Allocator.Temp, NativeArrayOptions.UninitializedMemory);

            for (int i = 0; i < numSamples; i++)
            {
                heights[i] = rnd.NextFloat(0, 1);
            }

            // CollisionMethod.Vertices will fail the unit tests, because it is a low-quality mode
            // that produces inaccurate manifolds. For now we just test CollisionMethod.Triangles
            return(TerrainCollider.Create(heights, size, scale, TerrainCollider.CollisionMethod.Triangles));
        }
Пример #9
0
    private StartPatternStamp[] GeneratePatternStamps(int numberOfStamps, int2 gridSize, int2[][] stampPatterns)
    {
        StartPatternStamp[] stamps = new StartPatternStamp[numberOfStamps];
        var rng = new Unity.Mathematics.Random(WorldSeed);

        for (int idx = 0; idx < numberOfStamps; ++idx)
        {
            var randomStamp    = rng.NextInt(stampPatterns.Length);
            var randomLocation = rng.NextInt2(gridSize);
            stamps[idx] = new StartPatternStamp
            {
                pattern  = stampPatterns[randomStamp],
                location = randomLocation
            };
        }

        return(stamps);
    }
Пример #10
0
        private static void _SpawnPlayer(EntityManager entityManager)
        {
            var playerEntity  = entityManager.CreateEntity(GameManager.PlayerArchetype);
            var spawnPosition = _rng.NextInt2(new int2(0, 0), new int2(GameManager.GameConfig.TerrainSize - 1, GameManager.GameConfig.TerrainSize - 1));
            var materialIndex = _rng.NextInt(0, GameManager.GameConfig.PlayerMaterials.Length);
            var material      = GameManager.GameConfig.PlayerMaterials[materialIndex];

            entityManager.SetSharedComponentData(playerEntity, new RenderMesh {
                mesh = GameManager.GameConfig.PlayerMesh, material = material, receiveShadows = false, castShadows = ShadowCastingMode.On
            });
            entityManager.SetComponentData(playerEntity, new PlayerComponent {
                MaterialIndex = materialIndex
            });
            entityManager.SetComponentData(playerEntity, new Translation()
            {
                Value = new float3(spawnPosition.x, 3.5f, spawnPosition.y)
            });
            entityManager.SetComponentData(playerEntity, new MoveSpeedComponent {
                Value = _rng.NextFloat(GameManager.GameConfig.PlayerSpeedMin, GameManager.GameConfig.PlayerSpeedMax)
            });
            entityManager.SetComponentData(playerEntity, new InitComponent {
                X = spawnPosition.x, Y = spawnPosition.y
            });
        }
        protected override void OnUpdate( )
        {
            EntityCommandBuffer.ParallelWriter ecbp = eecb.CreateCommandBuffer().AsParallelWriter();

            this.random.NextInt2();
            Unity.Mathematics.Random random = this.random;


            ComponentDataFromEntity <NNManagerComponent> a_manager = GetComponentDataFromEntity <NNManagerComponent> (true);

            Entities
            .WithName("NNCreateFirstGenerationWeightsJob")
            .WithAll <NNBrainTag, IsSpawningCompleteTag, NNIsFirstGenerationTag> ()
            .WithNone <IsInitializedTag> ()
            .WithReadOnly(a_manager)
            .ForEach((Entity entity, ref DynamicBuffer <NNInput2HiddenLayersWeightsBuffer> a_input2hiddenLayerWeights, ref DynamicBuffer <NNHidden2OutputLayersWeightsBuffer> a_hidden2OutputLayerWeights, in NNAssignedToManagerComponent assignedManager) =>
            {
                random.InitState((uint)(random.NextInt() + entity.Index));
                random.NextInt2();

                NNManagerComponent managerComponent = a_manager [assignedManager.entity];

                float f_muatationRange = managerComponent.f_muatationRange;

                // Initialize random weights.
                for (int i = 0; i < a_input2hiddenLayerWeights.Length; i++)
                {
                    a_input2hiddenLayerWeights [i] = new NNInput2HiddenLayersWeightsBuffer()
                    {
                        f = random.NextFloat(-f_muatationRange, f_muatationRange)
                    };
                }

                // Initialize random weights.
                for (int i = 0; i < a_hidden2OutputLayerWeights.Length; i++)
                {
                    a_hidden2OutputLayerWeights [i] = new NNHidden2OutputLayersWeightsBuffer()
                    {
                        f = random.NextFloat(-f_muatationRange, f_muatationRange)
                    };
                }
            }).ScheduleParallel();


            this.random.NextInt2();
            random = this.random;

            // DNA mutation.
            Entities
            .WithName("NNDNAMutationJob")
            .WithAll <NNBrainTag, IsSpawningCompleteTag> ()
            .WithNone <IsInitializedTag, NNIsFirstGenerationTag> ()
            .WithReadOnly(a_manager)
            .ForEach((Entity entity, ref DynamicBuffer <NNInput2HiddenLayersWeightsBuffer> a_offspringInput2HiddenLayersWeights, ref DynamicBuffer <NNHidden2OutputLayersWeightsBuffer> a_offspringtHidden2OutputLayersWeights, in NNAssignedToManagerComponent assignedManager) =>
            {
                random.InitState((uint)(random.NextInt() + entity.Index));
                random.NextInt2();

                NNManagerComponent managerComponent = a_manager [assignedManager.entity];

                float f_range = managerComponent.f_muatationRange;

                float f_groupSelection = random.NextFloat();

                if (f_groupSelection <= managerComponent.f_firstGroupSizeInPercentage)
                {
                    float f_majorMutationChance     = managerComponent.f_majorMutationChance0;
                    float f_minorMutationChance     = managerComponent.f_minorMutationChance0;
                    float f_minorMutationRangeScale = managerComponent.f_minorMutationRangeScale0;

                    _MutationChances(ref a_offspringInput2HiddenLayersWeights, ref a_offspringtHidden2OutputLayersWeights, ref random, f_range, f_majorMutationChance, f_minorMutationChance, f_minorMutationRangeScale);
                }
                else if (f_groupSelection <= managerComponent.f_secondGroupSizeInPercentage)
                {
                    float f_majorMutationChance     = managerComponent.f_majorMutationChance1;
                    float f_minorMutationChance     = managerComponent.f_minorMutationChance1;
                    float f_minorMutationRangeScale = managerComponent.f_minorMutationRangeScale1;

                    _MutationChances(ref a_offspringInput2HiddenLayersWeights, ref a_offspringtHidden2OutputLayersWeights, ref random, f_range, f_majorMutationChance, f_minorMutationChance, f_minorMutationRangeScale);
                }
                else if (f_groupSelection <= managerComponent.f_thirdGroupSizeInPercentage)
                {
                    float f_majorMutationChance     = managerComponent.f_majorMutationChance2;
                    float f_minorMutationChance     = managerComponent.f_minorMutationChance2;
                    float f_minorMutationRangeScale = managerComponent.f_minorMutationRangeScale2;

                    _MutationChances(ref a_offspringInput2HiddenLayersWeights, ref a_offspringtHidden2OutputLayersWeights, ref random, f_range, f_majorMutationChance, f_minorMutationChance, f_minorMutationRangeScale);
                }
                else
                {
                    float f_majorMutationChance     = managerComponent.f_majorMutationChance2;
                    float f_minorMutationChance     = managerComponent.f_minorMutationChance2;
                    float f_minorMutationRangeScale = managerComponent.f_minorMutationRangeScale2;

                    _MutationChances(ref a_offspringInput2HiddenLayersWeights, ref a_offspringtHidden2OutputLayersWeights, ref random, f_range, f_majorMutationChance, f_minorMutationChance, f_minorMutationRangeScale);
                }
            }).ScheduleParallel();

            random.NextUInt2();

            // DNA mutation.
            Entities
            .WithName("NNDNAMutationOfFirstGenerationJob")
            .WithAll <NNBrainTag, IsSpawningCompleteTag, NNIsFirstGenerationTag> ()
            .WithNone <IsInitializedTag> ()
            .WithReadOnly(a_manager)
            .ForEach((Entity entity, ref DynamicBuffer <NNInput2HiddenLayersWeightsBuffer> a_offspringInput2HiddenLayersWeights, ref DynamicBuffer <NNHidden2OutputLayersWeightsBuffer> a_offspringtHidden2OutputLayersWeights, in NNAssignedToManagerComponent assignedManager) =>
            {
                random.InitState((uint)(random.NextInt() + entity.Index));
                random.NextInt2();

                NNManagerComponent managerComponent = a_manager [assignedManager.entity];

                float f_range = managerComponent.f_muatationRange;

                for (int i = 0; i < a_offspringInput2HiddenLayersWeights.Length; i++)
                {
                    float f = random.NextFloat(-f_range, f_range);
                    a_offspringInput2HiddenLayersWeights [i] = new NNInput2HiddenLayersWeightsBuffer()
                    {
                        f = f
                    };
                }

                for (int i = 0; i < a_offspringtHidden2OutputLayersWeights.Length; i++)
                {
                    float f = random.NextFloat(-f_range, f_range);
                    a_offspringtHidden2OutputLayersWeights [i] = new NNHidden2OutputLayersWeightsBuffer()
                    {
                        f = f
                    };
                }
            }).ScheduleParallel();

            Entities
            .WithName("NNActivateNewPopulationJob")
            .WithAll <NNBrainTag, IsSpawningCompleteTag> ()
            .WithNone <IsInitializedTag> ()
            .ForEach((Entity entity, int entityInQueryIndex) =>
            {
                ecbp.AddComponent <IsInitializedTag> (entityInQueryIndex, entity);
                ecbp.AddComponent <IsAliveTag> (entityInQueryIndex, entity);
            }).ScheduleParallel();

            eecb.AddJobHandleForProducer(Dependency);
        }
Пример #12
0
        protected override void OnUpdate()
        {
            var mapSettings  = GetSingleton <MapSettings>();
            var resourceOres = GetComponentDataFromEntity <ResourceOre>(true);

            var seed = (uint)DateTime.Now.GetHashCode();
            // Init random
            Random random = new Random();

            random.InitState(seed);

            Entities
            .WithReadOnly(resourceOres)
            .WithStructuralChanges()
            .ForEach((Entity e, in UnitsRequest unitsRequest) =>
            {
                // Search for positions
                NativeHashMap <MapIndex, byte> freePositionsSet = new NativeHashMap <MapIndex, byte>(unitsRequest.UnitsCount, Allocator.Temp);
                for (int i = 0; i < unitsRequest.UnitsCount; i++)
                {
                    var mapIndex = MapIndex.From(random.NextInt2(0, mapSettings.MapEdgeSize), mapSettings.MapEdgeSize);

                    while (resourceOres[mapSettings.Tiles[mapIndex.Index1D]].IsValid || freePositionsSet.ContainsKey(mapIndex))
                    {
                        mapIndex = MapIndex.From(random.NextInt2(0, mapSettings.MapEdgeSize), mapSettings.MapEdgeSize);
                    }

                    freePositionsSet.Add(mapIndex, 1);
                }
                var freePositions = freePositionsSet.GetKeyArray(Allocator.Temp);

                // Spawn units
                var unitMaterial = EntityManager.GetComponentObject <Material>(e);
                NativeArray <Entity> entities = new NativeArray <Entity>(unitsRequest.UnitsCount, Allocator.Temp);
                EntityManager.CreateEntity(_unitArchetype, entities);

                for (int i = 0; i < unitsRequest.UnitsCount; i++)
                {
                    // Unit specific
                    EntityManager.SetComponentData(entities[i], new MovementSpeed()
                    {
                        Speed = (float)unitsRequest.UnitSpeed
                    });
                    EntityManager.SetComponentData(entities[i], new MiningSpeed()
                    {
                        Speed = (float)unitsRequest.UnitMiningSpeed
                    });

                    // Position
                    var mapIndex = freePositions[i];
                    EntityManager.SetComponentData(entities[i], mapIndex);

                    var position = new float3(mapIndex.Index2D.x, 3, mapIndex.Index2D.y);
                    EntityManager.SetComponentData(entities[i], new Translation()
                    {
                        Value = position
                    });

                    // Rendering
                    EntityManager.SetSharedComponentData(entities[i], new RenderMesh {
                        material = unitMaterial, mesh = _unitMesh
                    });
                    EntityManager.SetComponentData(entities[i], new RenderBounds
                    {
                        Value = new AABB()
                        {
                            Center  = float3.zero,
                            Extents = new float3(EXTENDS, 0, EXTENDS)
                        }
                    });
                    var materialTile = new float4(random.NextInt(0, unitsRequest.TextureTiles.x), random.NextInt(0, unitsRequest.TextureTiles.y), 0, 0);
                    EntityManager.SetComponentData(entities[i], new TileMaterialProperty {
                        Tile = materialTile
                    });
                    EntityManager.SetComponentData(entities[i], new AnimationSpeedMaterialProperty {
                        Speed = 0.5f
                    });
                    EntityManager.SetComponentData(entities[i], new RowsColumns_Tex_AnimMaterialProperty {
                        Value = new float4(8, 12, 0, 3)
                    });
                }

                entities.Dispose();
                freePositionsSet.Dispose();
                freePositions.Dispose();
                EntityManager.DestroyEntity(e);
            }).Run();
        }