コード例 #1
0
 public PlatformersGenerator(IMapDescription <TNode> mapDescription, DungeonGeneratorConfiguration <TNode> configuration = null)
 {
     this.mapDescription         = new MapDescriptionMapping <TNode>(mapDescription);
     this.configuration          = configuration ?? new DungeonGeneratorConfiguration <TNode>();
     this.mapDescriptionOriginal = mapDescription;
     SetupGenerator();
 }
コード例 #2
0
        public void EvolveParameters()
        {
            //var mapDescription = new MapDescription<int>()
            //    .SetupWithGraph(GraphsDatabase.GetExample3())
            //    .AddClassicRoomShapes(new IntVector2(1, 1));
            //    // .AddCorridorRoomShapes(new List<int>() { 2 }, true);

            // var input = CorridorConfigurationSpaces.GetMapDescriptionsSet(new IntVector2(1, 1), true, new List<int>() { 2, 4, 6, 8 }, false)[2];

            var settings = new JsonSerializerSettings()
            {
                PreserveReferencesHandling = PreserveReferencesHandling.All,
                TypeNameHandling           = TypeNameHandling.All,
            };

            var input = new GeneratorInput <MapDescription <int> >(
                "DeadCells",
                JsonConvert.DeserializeObject <MapDescription <int> >(File.ReadAllText("Resources/MapDescriptions/deadCells.json"), settings)
                );
            //var input = new GeneratorInput<MapDescription<int>>(
            //    "example1_corridors",
            //    JsonConvert.DeserializeObject<MapDescription<int>>(File.ReadAllText("Resources/MapDescriptions/example1_corridors.json"), settings)
            //);

            // input.MapDescription.SetDefaultTransformations(new List<Transformation>() { Transformation.Identity }); // TODO: fix later, wrong deserialization

            var analyzers = new List <IPerformanceAnalyzer <DungeonGeneratorConfiguration <int>, Individual <int> > >()
            {
                //new MaxStageTwoFailuresAnalyzer<DungeonGeneratorConfiguration, GeneratorData>(),
                //new ChainMergeAnalyzer<DungeonGeneratorConfiguration, int, GeneratorData>(),
                //new ChainOrderAnalyzer<DungeonGeneratorConfiguration, int, GeneratorData>(),
                new MaxIterationsAnalyzer <DungeonGeneratorConfiguration <int>, GeneratorData>(),
                new MaxBranchingAnalyzer <DungeonGeneratorConfiguration <int>, GeneratorData>(),
                //new ChainDecompositionAnalyzer<DungeonGeneratorConfiguration, int, GeneratorData>(input.MapDescription),
            };

            var evolution = new DungeonGeneratorEvolution <int>(input.MapDescription, analyzers, new EvolutionOptions()
            {
                MaxMutationsPerIndividual = 20,
                EvaluationIterations      = 75,
            }, Path.Combine("DungeonGeneratorEvolutions", FileNamesHelper.PrefixWithTimestamp(input.Name)));

            var initialConfiguration = new DungeonGeneratorConfiguration <int>();

            evolution.Evolve(initialConfiguration);
        }
        public override IEnumerator Process()
        {
            var config           = Config.Config;
            var levelDescription = Payload.LevelDescription;

            if (config.Timeout <= 0)
            {
                throw new ArgumentException($"{nameof(config.Timeout)} must be greater than 0", nameof(config.Timeout));
            }

            var rootGameObject = config.RootGameObject;

            if (rootGameObject == null)
            {
                rootGameObject = GameObject.Find("Generated Level");

                if (rootGameObject == null)
                {
                    rootGameObject = new GameObject("Generated Level");
                }
            }

            foreach (var child in rootGameObject.transform.Cast <Transform>().ToList())
            {
                child.transform.parent = null;
                PostProcessUtils.Destroy(child.gameObject);
            }

            var mapDescription = levelDescription.GetMapDescription();
            var configuration  = new DungeonGeneratorConfiguration <Room>()
            {
                RoomsCanTouch           = false,
                RepeatModeOverride      = GeneratorUtils.GetRepeatMode(config.RepeatModeOverride),
                EarlyStopIfTimeExceeded = TimeSpan.FromMilliseconds(config.Timeout),
            };

            var generator = new DungeonGenerator <Room>(mapDescription, configuration);

            generator.InjectRandomGenerator(Payload.Random);

            MapLayout <Room> layout = null;
            var task = Task.Run(() => layout = generator.GenerateLayout());

            while (!task.IsCompleted)
            {
                yield return(null);
            }

            if (layout == null)
            {
                throw new InvalidOperationException("Timeout was reached when generating level");
            }

            var generatedLevel = GeneratorUtils.TransformLayout(layout, levelDescription, rootGameObject);
            var stats          = new GeneratorStats()
            {
                Iterations = generator.IterationsCount,
                TimeTotal  = generator.TimeTotal,
            };

            Debug.Log($"Layout generated in {stats.TimeTotal / 1000f:F} seconds");
            Debug.Log($"{stats.Iterations} iterations needed, {stats.Iterations / (stats.TimeTotal / 1000d):0} iterations per second");

            ((IGraphBasedGeneratorPayload)Payload).GeneratedLevel = generatedLevel;
            Payload.GeneratorStats = stats;

            yield return(null);
        }
コード例 #4
0
        public override IEnumerator Process()
        {
            var levelDescription = Payload.LevelDescription;

            if (config.Timeout <= 0)
            {
                throw new ArgumentException($"{nameof(config.Timeout)} must be greater than 0", nameof(config.Timeout));
            }

            var rootGameObject = config.RootGameObject;

            // If the root game objects was not set in the config, we do the following:
            // 1. Check if there already exists a game objects with a name reserved for the generated level
            // 2. Otherwise, we create a new empty game object
            if (rootGameObject == null)
            {
                rootGameObject = GameObject.Find("Generated Level");

                if (rootGameObject == null)
                {
                    rootGameObject = new GameObject("Generated Level");
                }
            }

            // We delete all the children from the root game object - we do not want to combine levels from different runs of the algorithm
            foreach (var child in rootGameObject.transform.Cast <Transform>().ToList())
            {
                child.transform.parent = null;
                PostProcessUtils.Destroy(child.gameObject);
            }

            // The LevelDescription class must be converted to MapDescription
            var mapDescription = levelDescription.GetMapDescription();
            var configuration  = new DungeonGeneratorConfiguration <RoomBase>()
            {
                RoomsCanTouch           = false,
                RepeatModeOverride      = GeneratorUtils.GetRepeatMode(config.RepeatModeOverride),
                EarlyStopIfTimeExceeded = TimeSpan.FromMilliseconds(config.Timeout),
            };

            // We create the instance of the dungeon generator and inject the correct Random instance
            var generator = new DungeonGenerator <RoomBase>(mapDescription, configuration);

            generator.InjectRandomGenerator(Payload.Random);

            // Run the generator in a different class so that the computation is not blocking
            MapLayout <RoomBase> layout = null;
            var task = Task.Run(() => layout = generator.GenerateLayout());

            while (!task.IsCompleted)
            {
                yield return(null);
            }

            // Throw an exception when a timeout is reached
            // TODO: this should be our own exception and not a generic exception
            if (layout == null)
            {
                throw new InvalidOperationException("Timeout was reached when generating level");
            }

            // Transform the level to its Unity representation
            var generatedLevel = GeneratorUtils.TransformLayout(layout, levelDescription, rootGameObject);

            var stats = new GeneratorStats()
            {
                Iterations = generator.IterationsCount,
                TimeTotal  = generator.TimeTotal,
            };

            Debug.Log($"Layout generated in {stats.TimeTotal / 1000f:F} seconds");
            Debug.Log($"{stats.Iterations} iterations needed, {stats.Iterations / (stats.TimeTotal / 1000d):0} iterations per second");

            ((IGraphBasedGeneratorPayload)Payload).GeneratedLevel = generatedLevel;
            Payload.GeneratorStats = stats;

            yield return(null);
        }
コード例 #5
0
 public DungeonGeneratorInput(string name, IMapDescription <TNode> mapDescription, DungeonGeneratorConfiguration <TNode> configuration) : base(name, mapDescription)
 {
     Configuration = configuration;
 }
コード例 #6
0
ファイル: Individual.cs プロジェクト: IvanenkoPetr/TombOfMask
 public Individual(int id, DungeonGeneratorConfiguration <TNode> configuration) : base(id, configuration)
 {
 }
コード例 #7
0
 public OldGraphBasedGeneratorFactory(DungeonGeneratorConfiguration <TNode> configuration, bool benchmarkInitialization = false)
 {
     this.configuration           = configuration;
     this.benchmarkInitialization = benchmarkInitialization;
     Name = "Old generator" + (benchmarkInitialization ? " with init" : "");
 }
 public BeforeMasterThesisGraphBasedGeneratorFactory(DungeonGeneratorConfiguration <TNode> configuration, bool benchmarkInitialization = false)
 {
     this.configuration           = configuration;
     this.benchmarkInitialization = benchmarkInitialization;
     Name = "Pre-master" + (benchmarkInitialization ? " with init" : "");
 }
コード例 #9
0
 protected override Individual <TNode> CreateInitialIndividual(int id, DungeonGeneratorConfiguration <TNode> configuration)
 {
     return(new Individual <TNode>(id, configuration));
 }
コード例 #10
0
        public void Run()
        {
            var inputs = new List <GeneratorInput <IMapDescription <int> > >();


            var settings = new JsonSerializerSettings()
            {
                PreserveReferencesHandling = PreserveReferencesHandling.All,
                TypeNameHandling           = TypeNameHandling.All,
            };

            inputs.Add(new GeneratorInput <IMapDescription <int> >(
                           "DeadCells Ramparts",
                           JsonConvert.DeserializeObject <MapDescription <int> >(
                               File.ReadAllText("Resources/MapDescriptions/deadCells_ramparts.json"), settings)));
            inputs.Add(new GeneratorInput <IMapDescription <int> >(
                           "DeadCells Underground",
                           JsonConvert.DeserializeObject <MapDescription <int> >(
                               File.ReadAllText("Resources/MapDescriptions/deadCells_underground.json"), settings)));

            var layoutDrawer = new SVGLayoutDrawer <int>();

            var benchmarkRunner   = new BenchmarkRunner <IMapDescription <int> >();
            var benchmarkScenario = new BenchmarkScenario <IMapDescription <int> >("Platformers", input =>
            {
                var configuration = new DungeonGeneratorConfiguration <int>()
                {
                    RepeatModeOverride              = RoomTemplateRepeatMode.NoImmediate,
                    ThrowIfRepeatModeNotSatisfied   = true,
                    SimulatedAnnealingConfiguration = new SimulatedAnnealingConfigurationProvider(new SimulatedAnnealingConfiguration()
                    {
                        HandleTreesGreedily = true,
                    })
                };
                // var layoutGenerator = new PlatformersGenerator<int>(input.MapDescription, configuration);
                var layoutGenerator = new PlatformersGenerator <int>(input.MapDescription, configuration);
                layoutGenerator.InjectRandomGenerator(new Random(0));

                //return new LambdaGeneratorRunner(() =>
                //{
                //    var layouts = layoutGenerator.GenerateLayout();

                //    return new GeneratorRun(layouts != null, layoutGenerator.TimeTotal, layoutGenerator.IterationsCount);
                //});
                return(new LambdaGeneratorRunner(() =>
                {
                    var simulatedAnnealingArgsContainer = new List <SimulatedAnnealingEventArgs>();
                    void SimulatedAnnealingEventHandler(object sender, SimulatedAnnealingEventArgs eventArgs)
                    {
                        simulatedAnnealingArgsContainer.Add(eventArgs);
                    }

                    layoutGenerator.OnSimulatedAnnealingEvent += SimulatedAnnealingEventHandler;
                    var layout = layoutGenerator.GenerateLayout();
                    layoutGenerator.OnSimulatedAnnealingEvent -= SimulatedAnnealingEventHandler;

                    var additionalData = new AdditionalRunData()
                    {
                        SimulatedAnnealingEventArgs = simulatedAnnealingArgsContainer,
                        GeneratedLayoutSvg = layoutDrawer.DrawLayout(layout, 800, forceSquare: true),
                        // GeneratedLayout = layout,
                    };

                    var generatorRun = new GeneratorRun <AdditionalRunData>(layout != null, layoutGenerator.TimeTotal, layoutGenerator.IterationsCount, additionalData);

                    return generatorRun;
                }));
            });
コード例 #11
0
 public DungeonGeneratorInput(string name, IMapDescription <TNode> mapDescription, DungeonGeneratorConfiguration <TNode> configuration, List <int> offsets) : base(name, mapDescription)
 {
     Configuration = configuration;
     Offsets       = offsets;
 }