Exemple #1
0
        private static void InitializeMetaResourceFactories()
        {
            if (MetaResourceFactories != null)
            {
                return;
            }

            MetaResourceFactories = new Dictionary <string, Func <CreatureAI, Resource, List <Resource>, MaybeNull <Resource> > >();
            foreach (var method in AssetManager.EnumerateModHooks(typeof(MetaResourceFactoryAttribute), typeof(MaybeNull <Resource>), new Type[]
            {
                typeof(CreatureAI),
                typeof(Resource),
                typeof(List <Resource>)
            }))
            {
                var attribute = method.GetCustomAttributes(false).FirstOrDefault(a => a is MetaResourceFactoryAttribute) as MetaResourceFactoryAttribute;
                if (attribute == null)
                {
                    continue;
                }
                MetaResourceFactories[attribute.Name] = (agent, @base, ingredients) =>
                {
                    var r = method.Invoke(null, new Object[] { agent, @base, ingredients }) as MaybeNull <Resource>?;
                    if (r.HasValue)
                    {
                        return(r.Value);
                    }
                    else
                    {
                        return(null);
                    }
                };
            }
        }
Exemple #2
0
        private static void InitializeZoneTypes()
        {
            if (ZoneTypesInitialized)
            {
                return;
            }
            ZoneTypesInitialized = true;

            ZoneTypes            = FileUtils.LoadJsonListFromDirectory <ZoneType>(ContentPaths.room_types, null, d => d.Name);
            ZoneFactoryFunctions = new Dictionary <string, Func <String, WorldManager, Zone> >();

            foreach (var method in AssetManager.EnumerateModHooks(typeof(ZoneFactoryAttribute), typeof(Zone), new Type[]
            {
                typeof(String),
                typeof(WorldManager)
            }))
            {
                var attribute = method.GetCustomAttributes(false).FirstOrDefault(a => a is ZoneFactoryAttribute) as ZoneFactoryAttribute;
                if (attribute == null)
                {
                    continue;
                }
                ZoneFactoryFunctions[attribute.Name] = (data, world) => method.Invoke(null, new Object[] { data, world }) as Zone;
            }
        }
Exemple #3
0
        private static void InitializeStatics()
        {
            if (RoomTypes != null)
            {
                return;
            }

            RoomTypes = FileUtils.LoadJsonListFromDirectory <RoomData>(ContentPaths.room_types, null, d => d.Name);
            RoomFuncs = new Dictionary <string, Func <RoomData, Faction, WorldManager, Room> >();

            foreach (var method in AssetManager.EnumerateModHooks(typeof(RoomFactoryAttribute), typeof(Room), new Type[]
            {
                typeof(RoomData),
                typeof(Faction),
                typeof(WorldManager)
            }))
            {
                var attribute = method.GetCustomAttributes(false).FirstOrDefault(a => a is RoomFactoryAttribute) as RoomFactoryAttribute;
                if (attribute == null)
                {
                    continue;
                }
                RoomFuncs[attribute.Name] = (data, faction, world) => method.Invoke(null, new Object[] { data, faction, world }) as Room;
            }
        }
Exemple #4
0
        public static string ListSettings(String Name)
        {
            var builder = new StringBuilder();

            foreach (var hook in AssetManager.EnumerateModHooks(typeof(ConsoleCommandHandlerAttribute), typeof(String), new Type[] { typeof(String) }))
            {
                var lambdaCopy = hook;
                var attribute  = hook.GetCustomAttributes(false).FirstOrDefault(a => a is ConsoleCommandHandlerAttribute) as ConsoleCommandHandlerAttribute;
                if (attribute == null)
                {
                    continue;
                }
                builder.AppendLine(attribute.Name.ToUpperInvariant());
            }
            return(builder.ToString());
        }
Exemple #5
0
        public YarnEngine(
            String ConversationFile,
            String StartNode,
            Yarn.MemoryVariableStore Memory,
            IYarnPlayerInterface PlayerInterface)
        {
            this.PlayerInterface = PlayerInterface;
            this.Memory          = Memory;

            CommandGrammar = new YarnCommandGrammar();

            foreach (var method in AssetManager.EnumerateModHooks(typeof(YarnCommandAttribute), typeof(void), new Type[]
            {
                typeof(YarnEngine),
                typeof(List <Ancora.AstNode>),
                typeof(Yarn.MemoryVariableStore)
            }))
            {
                var attribute = method.GetCustomAttributes(false).FirstOrDefault(a => a is YarnCommandAttribute) as YarnCommandAttribute;
                if (attribute == null)
                {
                    continue;
                }
                CommandHandlers[attribute.CommandName] = new CommandHandler
                {
                    Action   = (state, args, mem) => method.Invoke(null, new Object[] { state, args, mem }),
                    Settings = attribute
                };
            }

            Dialogue = new Yarn.Dialogue(Memory);

            Dialogue.LogDebugMessage = delegate(string message) { Console.WriteLine(message); };
            Dialogue.LogErrorMessage = delegate(string message) { Console.WriteLine("Yarn Error: " + message); };

            //try
            {
                Dialogue.LoadFile(AssetManager.ResolveContentPath(ConversationFile), false, false, null);
            }
            //catch (Exception e)
            {
                //  Console.Error.WriteLine(e.ToString());
            }

            Runner = Dialogue.Run(StartNode).GetEnumerator();
        }
Exemple #6
0
        public static String HandleConsoleCommand(String Command)
        {
            if (CommandHandlers == null)
            {
                CommandHandlers = new Dictionary <string, Func <string, string> >();
                foreach (var hook in AssetManager.EnumerateModHooks(typeof(ConsoleCommandHandlerAttribute), typeof(String), new Type[] { typeof(String) }))
                {
                    var lambdaCopy = hook;
                    var attribute  = hook.GetCustomAttributes(false).FirstOrDefault(a => a is ConsoleCommandHandlerAttribute) as ConsoleCommandHandlerAttribute;
                    if (attribute == null)
                    {
                        continue;
                    }
                    CommandHandlers[attribute.Name.ToUpperInvariant()] = (s) => lambdaCopy.Invoke(null, new Object[] { s }) as String;
                }
            }

            var commandWord = "";
            var commandArgs = "";
            var space       = Command.IndexOf(' ');

            if (space == -1)
            {
                commandWord = Command;
            }
            else
            {
                commandWord = Command.Substring(0, space);
                commandArgs = Command.Substring(space + 1);
            }

            if (CommandHandlers.ContainsKey(commandWord.ToUpperInvariant()))
            {
                return(CommandHandlers[commandWord.ToUpperInvariant()](commandArgs));
            }
            else
            {
                return("Unknown command.");
            }
        }
Exemple #7
0
        public static void Initialize(WorldManager world)
        {
            World = world;
            if (EntityFuncs == null)
            {
                EntityFuncs = new Dictionary <string, Func <Vector3, Blackboard, GameComponent> >();
            }

            foreach (var method in AssetManager.EnumerateModHooks(typeof(EntityFactoryAttribute), typeof(GameComponent), new Type[]
            {
                typeof(ComponentManager),
                typeof(Vector3),
                typeof(Blackboard)
            }))
            {
                var attribute = method.GetCustomAttributes(false).FirstOrDefault(a => a is EntityFactoryAttribute) as EntityFactoryAttribute;
                if (attribute == null)
                {
                    continue;
                }
                EntityFuncs[attribute.Name] = (position, data) => method.Invoke(null, new Object[] { world.ComponentManager, position, data }) as GameComponent;
            }
        }
        private void CreateNewWorld()
        {
            SetLoadingMessage("Creating Sky...");

            Renderer.Sky = new SkyRenderer();


            #region Initialize static data

            bool actionComplete = false;

            Game.DoLazyAction(new Action(() =>
            {
                Renderer.InstanceRenderer = new InstanceRenderer();

                Renderer.bloom = new BloomComponent(Game)
                {
                    Settings = BloomSettings.PresetSettings[5]
                };
                Renderer.bloom.Initialize();

                SoundManager.Content = Content;
                if (PlanService != null)
                {
                    PlanService.Restart();
                }

                MonsterSpawner = new MonsterSpawner(this);
                EntityFactory.Initialize(this);
            }), () => { actionComplete = true; return(true); });

            while (!actionComplete)
            {
                Thread.Sleep(10);
            }

            #endregion


            SetLoadingMessage("Creating Planner ...");
            PlanService = new PlanService();


            SetLoadingMessage("Creating Liquids ...");

            #region liquids

            Renderer.WaterRenderer = new WaterRenderer(GraphicsDevice);

            #endregion

            #region Load Components

            // Create updateable systems.
            foreach (var updateSystemFactory in AssetManager.EnumerateModHooks(typeof(UpdateSystemFactoryAttribute), typeof(EngineModule), new Type[] { typeof(WorldManager) }))
            {
                UpdateSystems.Add(updateSystemFactory.Invoke(null, new Object[] { this }) as EngineModule);
            }

            Time = new WorldTime();

            Renderer.Camera = new OrbitCamera(this, // Todo: Is setting the camera position and target redundant here?
                                              new Vector3(VoxelConstants.ChunkSizeX,
                                                          WorldSizeInVoxels.Y - 1.0f,
                                                          VoxelConstants.ChunkSizeZ),
                                              new Vector3(VoxelConstants.ChunkSizeX, WorldSizeInVoxels.Y - 1.0f,
                                                          VoxelConstants.ChunkSizeZ) +
                                              Vector3.Up * 10.0f + Vector3.Backward * 10,
                                              MathHelper.PiOver4, GraphicsDevice.Viewport.AspectRatio, 0.1f,
                                              GameSettings.Default.VertexCullDistance);

            PersistentData = new PersistentWorldData();
            ChunkManager   = new ChunkManager(Content, this);
            Splasher       = new Splasher(ChunkManager);

            Renderer.ChunkRenderer = new ChunkRenderer(ChunkManager);

            Renderer.Camera.Position = new Vector3(0, 10, 0) + new Vector3(WorldSizeInChunks.X * VoxelConstants.ChunkSizeX, 0, WorldSizeInChunks.Z * VoxelConstants.ChunkSizeZ) * 0.5f;
            Renderer.Camera.Target   = new Vector3(0, 10, 1) + new Vector3(WorldSizeInChunks.X * VoxelConstants.ChunkSizeX, 0, WorldSizeInChunks.Z * VoxelConstants.ChunkSizeZ) * 0.5f;

            ComponentManager = new ComponentManager(this);
            ComponentManager.SetRootComponent(new GameComponent(ComponentManager, "root", Matrix.Identity, Vector3.Zero, Vector3.Zero));

            #region Prepare Factions

            Factions = new FactionSet();
            //Factions.Initialize(this, Settings.Company);
            foreach (var faction in Overworld.Natives)
            {
                Factions.AddFaction(new Faction(this, faction));
            }

            Point playerOrigin = new Point((int)(Overworld.InstanceSettings.Origin.X), (int)(Overworld.InstanceSettings.Origin.Y));

            PlayerFaction         = Factions.Factions["Player"];
            PlayerFaction.Economy = new Company(PlayerFaction, 300.0m, Overworld.Company);

            #endregion

            EventScheduler = new Events.Scheduler();

            TutorialManager = new Tutorial.TutorialManager();
            TutorialManager.TutorialEnabled = !GameSettings.Default.TutorialDisabledGlobally;
            Tutorial("new game start");

            foreach (var item in Library.EnumerateCraftables())
            {
                if (!String.IsNullOrEmpty(item.Tutorial))
                {
                    TutorialManager.AddTutorial(item.Name, item.Tutorial, item.Icon);
                }
            }

            Renderer.Camera.World = this;
            //Drawer3D.Camera = Camera;


            #endregion

            SetLoadingMessage("Creating Particles ...");
            Game.DoLazyAction(new Action(() => ParticleManager = new ParticleManager(ComponentManager)));

            SetLoadingMessage("Creating GameMaster ...");

            TaskManager       = new TaskManager();
            TaskManager.World = this;
            Time.NewDay      += (time) => PayEmployees();


            var generatorSettings = new Generation.ChunkGeneratorSettings(MathFunctions.Random.Next(), 0.02f, Overworld)
            {
                WorldSizeInChunks = WorldSizeInChunks,
                SetLoadingMessage = SetLoadingMessage,
                World             = this
            };

            SetLoadingMessage("Generating Chunks...");
            Generation.Generator.Generate(Overworld.InstanceSettings.Cell.Bounds, ChunkManager, this, generatorSettings, SetLoadingMessage);
            CreateInitialEmbarkment(generatorSettings);
            ChunkManager.NeedsMinimapUpdate = true;
            ChunkManager.RecalculateBounds();

            if (PlayerFaction.Economy.Information == null)
            {
                throw new InvalidProgramException();
            }

            if (MathFunctions.RandEvent(0.01f))
            {
                SetLoadingMessage("Reticulating Splines...");
            }

            ChunkManager.StartThreads();
            SetLoadingMessage("Presimulating ...");
            ShowingWorld = false;
            OnLoadedEvent();
            Thread.Sleep(1000);

            ShowingWorld = true;

            SetLoadingMessage("Complete.");

            LoadStatus = LoadingStatus.Success;
        }
        private void LoadFromFile()
        {
            SetLoadingMessage("Creating Sky...");
            Renderer.Sky = new SkyRenderer();

            #region Reading game file

            SetLoadingMessage("Loading " + Overworld.InstanceSettings.ExistingFile);

            var gameFile = SaveGame.LoadMetaFromDirectory(Overworld.InstanceSettings.ExistingFile);

            if (gameFile == null)
            {
                throw new InvalidOperationException("Game File does not exist.");
            }

            if (gameFile.Metadata.Version != Program.Version && !Program.CompatibleVersions.Contains(gameFile.Metadata.Version))
            {
                throw new InvalidOperationException(String.Format("Game file is from version {0}. Compatible versions are {1}.", gameFile.Metadata.Version,
                                                                  TextGenerator.GetListString(Program.CompatibleVersions)));
            }

            Renderer.Sky.TimeOfDay      = gameFile.Metadata.TimeOfDay;
            Renderer.PersistentSettings = gameFile.Metadata.RendererSettings;
            Time = gameFile.Metadata.Time;
            WorldSizeInChunks = new Point3(Overworld.InstanceSettings.Cell.Bounds.Width, Overworld.zLevels, Overworld.InstanceSettings.Cell.Bounds.Height);

            #endregion

            #region Initialize static data

            bool actionComplete = false;

            Game.DoLazyAction(new Action(() =>
            {
                Renderer.InstanceRenderer = new InstanceRenderer();

                Renderer.bloom = new BloomComponent(Game)
                {
                    Settings = BloomSettings.PresetSettings[5]
                };
                Renderer.bloom.Initialize();

                SoundManager.Content = Content;
                if (PlanService != null)
                {
                    PlanService.Restart();
                }

                MonsterSpawner = new MonsterSpawner(this);
                EntityFactory.Initialize(this);
            }), () => { actionComplete = true; return(true); });

            while (!actionComplete)
            {
                Thread.Sleep(10);
            }

            #endregion

            PlanService = new PlanService();

            SetLoadingMessage("Creating Liquids ...");

            #region liquids

            Renderer.WaterRenderer = new WaterRenderer(GraphicsDevice);

            #endregion

            #region Load Components

            // Create updateable systems.
            foreach (var updateSystemFactory in AssetManager.EnumerateModHooks(typeof(UpdateSystemFactoryAttribute), typeof(EngineModule), new Type[] { typeof(WorldManager) }))
            {
                UpdateSystems.Add(updateSystemFactory.Invoke(null, new Object[] { this }) as EngineModule);
            }

            ChunkManager = new ChunkManager(Content, this);
            Splasher     = new Splasher(ChunkManager);

            Renderer.ChunkRenderer = new ChunkRenderer(ChunkManager);

            SetLoadingMessage("Loading Terrain...");
            ChunkManager.LoadChunks(gameFile.LoadChunks(), ChunkManager);

            SetLoadingMessage("Loading Entities...");
            gameFile.LoadPlayData(Overworld.InstanceSettings.ExistingFile, this);

            PersistentData = gameFile.PlayData.PersistentData;

            Renderer.Camera = gameFile.PlayData.Camera;

            if (gameFile.PlayData.Stats != null)
            {
                Stats = gameFile.PlayData.Stats;
            }

            ComponentManager = new ComponentManager(gameFile.PlayData.Components, this);

            foreach (var component in gameFile.PlayData.Components.SaveableComponents)
            {
                if (!ComponentManager.HasComponent(component.GlobalID) &&
                    ComponentManager.HasComponent(component.Parent.GlobalID))
                {
                    // Logically impossible.
                    throw new InvalidOperationException("Component exists in save data but not in manager.");
                }
            }

            ConversationMemory = gameFile.PlayData.ConversationMemory;

            Factions = gameFile.PlayData.Factions;
            ComponentManager.World = this;

            Renderer.Sky.TimeOfDay = gameFile.Metadata.TimeOfDay;
            Time = gameFile.Metadata.Time;

            PlayerFaction = Factions.Factions["Player"];

            EventScheduler = new Events.Scheduler();

            TutorialManager = new Tutorial.TutorialManager();
            TutorialManager.SetFromSaveData(gameFile.PlayData.TutorialSaveData);

            Renderer.Camera.World = this;

            #endregion

            SetLoadingMessage("Creating Particles ...");
            Game.DoLazyAction(new Action(() => ParticleManager = new ParticleManager(ComponentManager)));

            SetLoadingMessage("Creating GameMaster ...");

            TaskManager       = new TaskManager();
            TaskManager.World = this;
            Time.NewDay      += (time) => PayEmployees();

            DwarfGame.LogSentryBreadcrumb("Loading", "Started new game with an existing file.");
            if (gameFile.PlayData.Tasks != null)
            {
                TaskManager       = gameFile.PlayData.Tasks;
                TaskManager.World = this;
            }

            if (PlayerFaction.Economy.Information == null)
            {
                throw new InvalidProgramException();
            }

            if (MathFunctions.RandEvent(0.01f))
            {
                SetLoadingMessage("Reticulating Splines...");
            }

            ChunkManager.StartThreads();
            SetLoadingMessage("Presimulating ...");
            ShowingWorld = false;
            OnLoadedEvent();
            Thread.Sleep(1000);

            ShowingWorld = true;

            SetLoadingMessage("Complete.");

            // GameFile is no longer needed.
            gameFile   = null;
            LoadStatus = LoadingStatus.Success;
        }