コード例 #1
0
        public void CreateContent()
        {
            SkyTexture   = GameState.Game.Content.Load <TextureCube>(AssetManager.ResolveContentPath(ContentPaths.Sky.day_sky));
            NightTexture = GameState.Game.Content.Load <TextureCube>(AssetManager.ResolveContentPath(ContentPaths.Sky.night_sky));
            SkyMesh      = GameState.Game.Content.Load <Model>(AssetManager.ResolveContentPath(ContentPaths.Models.sphereLowPoly));
            SkyEffect    = GameState.Game.Content.Load <Effect>(ContentPaths.Shaders.SkySphere);
            SkyGrad      = AssetManager.GetContentTexture(ContentPaths.Gradients.skygradient);
            SkyEffect.Parameters["SkyboxTexture"].SetValue(SkyTexture);
            SkyEffect.Parameters["TintTexture"].SetValue(SkyGrad);
            MoonTexture      = AssetManager.GetContentTexture(ContentPaths.Sky.moon);
            SunTexture       = AssetManager.GetContentTexture(ContentPaths.Sky.sun);
            TimeOfDay        = 0.0f;
            CosTime          = 0.0f;
            BackgroundEffect = GameState.Game.Content.Load <Effect>(ContentPaths.Shaders.Background);
            foreach (ModelMesh mesh in SkyMesh.Meshes)
            {
                foreach (ModelMeshPart part in mesh.MeshParts)
                {
                    part.Effect = SkyEffect;
                }
            }
            int numStars = 250;

            StarPositions = new List <Vector3>();
            for (int i = 0; i < numStars; i++)
            {
                var star = MathFunctions.RandVector3Cube();
                star.Normalize();
                star *= 1000;
                StarPositions.Add(star);
            }
        }
コード例 #2
0
        public static SoundEffectInstance PlaySound(string name, float volume = 1.0f, float pitch = 0.0f)
        {
            if (!HasAudioDevice)
            {
                return(null);
            }
            // TODO: Remove this block once the SoundManager is initialized in a better location.
            if (Content == null)
            {
                return(null);
            }

            SoundEffect effect = null;

            if (!EffectLibrary.ContainsKey(name))
            {
                effect = Content.Load <SoundEffect>(AssetManager.ResolveContentPath(name));
                EffectLibrary[name] = effect;
            }
            else
            {
                effect = EffectLibrary[name];
            }
            SFXMixer.Levels     levels   = Mixer.GetOrCreateLevels(name);
            SoundEffectInstance instance = effect.CreateInstance();

            instance.Volume = GameSettings.Default.MasterVolume * GameSettings.Default.SoundEffectVolume * volume * levels.Volume;
            instance.Pitch  = pitch;
            instance.Play();
            instance.Volume = GameSettings.Default.MasterVolume * GameSettings.Default.SoundEffectVolume * volume * levels.Volume;
            instance.Pitch  = pitch;

            ActiveSounds2D.Add(instance);
            return(instance);
        }
コード例 #3
0
 public static T LoadJsonFromResolvedPath <T>(string filePath, object context = null)
 {
     using (var stream = new FileStream(AssetManager.ResolveContentPath(filePath), FileMode.Open))
         using (StreamReader reader = new StreamReader(stream))
         {
             using (JsonReader json = new JsonTextReader(reader))
             {
                 return(GetStandardSerializer(context).Deserialize <T>(json));
             }
         }
 }
コード例 #4
0
ファイル: Drawer2D.cs プロジェクト: fastrocket/dwarfcorp
 public static void Initialize(ContentManager content, GraphicsDevice graphics)
 {
     Content                    = content;
     DefaultFont                = content.Load <SpriteFont>(AssetManager.ResolveContentPath(ContentPaths.Fonts.Default));
     PointMagLinearMin          = new SamplerState();
     PointMagLinearMin.AddressU = TextureAddressMode.Clamp;
     PointMagLinearMin.AddressV = TextureAddressMode.Clamp;
     PointMagLinearMin.Filter   = TextureFilter.MinLinearMagPointMipLinear;
     PointMagLinearMin.Name     = "PointMagLinearMin";
     CreatePixel();
 }
コード例 #5
0
        public override void OnEnter()
        {
            DwarfGame.GumInputMapper.GetInputQueue();

            CurrentScroll = 0;
            CreditsFont   = GameState.Game.Content.Load <SpriteFont>(AssetManager.ResolveContentPath(ContentPaths.Fonts.Default));
            Entries       = FileUtils.LoadJsonFromResolvedPath <List <CreditEntry> >("credits.json");
            IsInitialized = true;
            IsDone        = false;
            base.OnEnter();
        }
コード例 #6
0
ファイル: SoundManager.cs プロジェクト: sodomon2/dwarfcorp
        public static void SetActiveSongs(params string[] songs)
        {
            if (!HasAudioDevice)
            {
                return;
            }
            ActiveSongs = new List <Song>();

            foreach (string song in songs)
            {
                ActiveSongs.Add(Content.Load <Song>(AssetManager.ResolveContentPath(song)));
            }
        }
コード例 #7
0
 public static void Initialize(ContentManager content, GraphicsDevice graphics)
 {
     Content     = content;
     DefaultFont = content.Load <SpriteFont>(AssetManager.ResolveContentPath(ContentPaths.Fonts.Default));
     Pixel       = new Texture2D(graphics, 1, 1);
     Color[] white = new Color[1];
     white[0] = Color.White;
     Pixel    = new Texture2D(graphics, 1, 1);
     Pixel.SetData <Color>(white);
     PointMagLinearMin          = new SamplerState();
     PointMagLinearMin.AddressU = TextureAddressMode.Clamp;
     PointMagLinearMin.AddressV = TextureAddressMode.Clamp;
     PointMagLinearMin.Filter   = TextureFilter.MinLinearMagPointMipLinear;
     PointMagLinearMin.Name     = "PointMagLinearMin";
 }
コード例 #8
0
ファイル: YarnEngine.cs プロジェクト: polytronicgr/dwarfcorp
        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();
        }
コード例 #9
0
ファイル: SoundManager.cs プロジェクト: sodomon2/dwarfcorp
        public static Sound3D PlaySound(string name, Vector3 location, bool randomPitch, float volume = 1.0f, float pitch = 0.0f)
        {
            if (!HasAudioDevice)
            {
                return(null);
            }
            if (Content == null)
            {
                return(null);
            }
            SoundEffect effect = null;

            if (!EffectLibrary.ContainsKey(name))
            {
                effect = Content.Load <SoundEffect>(AssetManager.ResolveContentPath(name));
                EffectLibrary[name] = effect;
            }
            else
            {
                effect = EffectLibrary[name];

                if (effect.IsDisposed)
                {
                    effect = Content.Load <SoundEffect>(AssetManager.ResolveContentPath(name));
                    EffectLibrary[name] = effect;
                }
            }

            if (!SoundCounts.ContainsKey(name))
            {
                SoundCounts[name] = 0;
            }

            if (SoundCounts[name] < MaxSounds)
            {
                SoundCounts[name]++;

                Sound3D sound = new Sound3D
                {
                    Position       = location,
                    EffectInstance = effect.CreateInstance(),
                    HasStarted     = false,
                    Name           = name
                };
                SFXMixer.Levels levels = Mixer.GetOrCreateLevels(name);
                sound.EffectInstance.IsLooped = false;
                sound.VolumeMultiplier        = volume * levels.Volume;


                if (randomPitch)
                {
                    sound.EffectInstance.Pitch = MathFunctions.Clamp((float)(MathFunctions.Random.NextDouble() * 1.0f - 0.5f) * levels.RandomPitch + pitch, -1.0f, 1.0f);
                }
                else
                {
                    sound.EffectInstance.Pitch = MathFunctions.Clamp(pitch, -1.0f, 1.0f);
                }
                ActiveSounds.Add(sound);

                return(sound);
            }


            return(null);
        }
コード例 #10
0
ファイル: SoundManager.cs プロジェクト: sodomon2/dwarfcorp
        public static void LoadDefaultSounds()
        {
            try
            {
                string[] defaultSounds =
                {
                    ContentPaths.Audio.pick,
                    ContentPaths.Audio.hit,
                    ContentPaths.Audio.jump,
                    ContentPaths.Audio.ouch,
                    ContentPaths.Audio.gravel,
                    ContentPaths.Audio.river
                };

                foreach (string name in defaultSounds)
                {
                    SoundEffect effect = Content.Load <SoundEffect>(AssetManager.ResolveContentPath(name));
                    EffectLibrary[name] = effect;
                }
                try
                {
                    Mixer = FileUtils.LoadJsonFromResolvedPath <SFXMixer>(ContentPaths.mixer);
                }
                catch (FileNotFoundException)
                {
                    Console.Out.WriteLine("Mixer file didn't exist. Creating a new mixer.");
                    Mixer = new SFXMixer()
                    {
                        Gains = new Dictionary <string, SFXMixer.Levels>()
                    };
                }
                SoundEffect.DistanceScale = 0.25f;
                //SoundEffect.DopplerScale = 0.1f;
                AudioEngine = new AudioEngine("Content\\Audio\\XACT\\Win\\Sounds.xgs");
                SoundBank   = new SoundBank(AudioEngine, "Content\\Audio\\XACT\\Win\\SoundBank.xsb");
                WaveBank    = new WaveBank(AudioEngine, "Content\\Audio\\XACT\\Win\\WaveBank.xwb");

                CurrentMusic = new FancyMusic();
                CurrentMusic.AddTrack("main_theme_day", new MusicTrack(SoundBank)
                {
                    Intro             = "music_1_intro",
                    Loop              = "music_1_loop",
                    PlayLoopOverIntro = false
                });
                CurrentMusic.AddTrack("main_theme_night", new MusicTrack(SoundBank)
                {
                    Intro             = "music_1_night_intro",
                    Loop              = "music_1_night",
                    PlayLoopOverIntro = true
                });
                CurrentMusic.AddTrack("menu_music", new MusicTrack(SoundBank)
                {
                    Loop = "music_menu",
                    PlayLoopOverIntro = true
                });
                CurrentMusic.AddTrack("molemen", new MusicTrack(SoundBank)
                {
                    Loop = "molemen",
                    PlayLoopOverIntro = true
                });
                CurrentMusic.AddTrack("elf", new MusicTrack(SoundBank)
                {
                    Loop = "elf",
                    PlayLoopOverIntro = true
                });
                CurrentMusic.AddTrack("undead", new MusicTrack(SoundBank)
                {
                    Loop = "undead",
                    PlayLoopOverIntro = true
                });
                CurrentMusic.AddTrack("goblin", new MusicTrack(SoundBank)
                {
                    Loop = "goblin",
                    PlayLoopOverIntro = true
                });

                foreach (var cue in ActiveCues)
                {
                    cue.Value.Stop(AudioStopOptions.Immediate);
                }
                ActiveCues.Clear();
            }
            catch (Exception exception)
            {
                Console.Error.WriteLine(exception);
                HasAudioDevice = false;
                AudioError     = exception.Message;
            }
        }
コード例 #11
0
        public override void Construct()
        {
            var bottomBar = AddChild(new Widget()
            {
                AutoLayout  = AutoLayout.DockBottom,
                MinimumSize = new Point(Rect.Width - 128, 24)
            })
            ;

            bottomBar.AddChild(new Button()
            {
                Text        = "Back",
                OnClick     = (sender, args) => this.Close(),
                AutoLayout  = AutoLayout.DockLeft,
                MinimumSize = new Point(64, 24)
            });


            if (SoundManager.Mixer == null)
            {
                Text = "Error. Failed to load audio mixer :(";
                return;
            }

            bottomBar.AddChild(new Button()
            {
                Text    = "Save",
                OnClick = (sender, args) => {
                    try
                    {
                        FileUtils.SaveBasicJson(SoundManager.Mixer, AssetManager.ResolveContentPath(ContentPaths.mixer));
                    }
                    catch (Exception exception)
                    {
                        Console.Out.WriteLine(exception.ToString());
                        Root.ShowModalPopup(new Popup()
                        {
                            Text = "Failed to save audio mixer. This is a debug tool. Are you a dev?",
                        });
                    }
                },
                AutoLayout  = AutoLayout.DockRight,
                MinimumSize = new Point(64, 24)
            });


            var listView = AddChild(new WidgetListView()
            {
                AutoLayout  = AutoLayout.DockBottom,
                MinimumSize = new Point(Rect.Width - 128, 512),
                ItemHeight  = 24
            });

            foreach (var level in SoundManager.Mixer.Gains)
            {
                var row = listView.AddChild(new Widget()
                {
                    AutoLayout  = AutoLayout.DockTop,
                    MinimumSize = new Point(512, 24)
                });

                row.AddChild(new Widget()
                {
                    Text                = level.Key,
                    TextColor           = Color.Black.ToVector4(),
                    AutoLayout          = AutoLayout.DockLeft,
                    TextVerticalAlign   = VerticalAlign.Center,
                    TextHorizontalAlign = HorizontalAlign.Right,
                    MinimumSize         = new Point(256, 24)
                });

                KeyValuePair <string, SFXMixer.Levels> level1 = level;
                row.AddChild(new HorizontalFloatSlider()
                {
                    ScrollArea      = 1.0f,
                    ScrollPosition  = level.Value.Volume,
                    MinimumSize     = new Point(256, 24),
                    AutoLayout      = AutoLayout.DockLeft,
                    OnSliderChanged = (sender) =>
                    {
                        SFXMixer.Levels levels = SoundManager.Mixer.GetOrCreateLevels(level1.Key);
                        SoundManager.Mixer.SetLevels(level1.Key,
                                                     new SFXMixer.Levels()
                        {
                            RandomPitch = level1.Value.RandomPitch,
                            Volume      = (sender as HorizontalFloatSlider).ScrollPosition
                        });
                        if (MathFunctions.RandEvent(0.15f))
                        {
                            SoundManager.PlaySound(level1.Key);
                        }
                    }
                });
            }
            Layout();

            base.Construct();
        }
コード例 #12
0
        private void LoadThreaded()
        {
            // Ensure we're using the invariant culture.
            Thread.CurrentThread.CurrentCulture   = CultureInfo.InvariantCulture;
            Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture;
            LoadStatus = LoadingStatus.Loading;
            SetLoadingMessage("Initializing ...");

            while (GraphicsDevice == null)
            {
                Thread.Sleep(100);
            }
            Thread.Sleep(1000);

#if CREATE_CRASH_LOGS
            try
#endif
#if !DEBUG
            try
            {
#endif
            bool fileExists = !string.IsNullOrEmpty(ExistingFile);

            SetLoadingMessage("Creating Sky...");

            Sky = new SkyRenderer(
                AssetManager.GetContentTexture(ContentPaths.Sky.moon),
                AssetManager.GetContentTexture(ContentPaths.Sky.sun),
                Content.Load <TextureCube>(AssetManager.ResolveContentPath(ContentPaths.Sky.day_sky)),
                Content.Load <TextureCube>(AssetManager.ResolveContentPath(ContentPaths.Sky.night_sky)),
                AssetManager.GetContentTexture(ContentPaths.Gradients.skygradient),
                Content.Load <Model>(AssetManager.ResolveContentPath(ContentPaths.Models.sphereLowPoly)),
                Content.Load <Effect>(ContentPaths.Shaders.SkySphere),
                Content.Load <Effect>(ContentPaths.Shaders.Background));

            #region Reading game file

            if (fileExists)
            {
                SetLoadingMessage("Loading " + ExistingFile);

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

                // Todo: REMOVE THIS WHEN THE NEW SAVE SYSTEM IS COMPLETE.
                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)));
                }

                Sky.TimeOfDay = gameFile.Metadata.TimeOfDay;
                Time          = gameFile.Metadata.Time;
                WorldOrigin   = gameFile.Metadata.WorldOrigin;
                WorldScale    = gameFile.Metadata.WorldScale;
                WorldSize     = gameFile.Metadata.NumChunks;
                GameID        = gameFile.Metadata.GameID;

                if (gameFile.Metadata.OverworldFile != null && gameFile.Metadata.OverworldFile != "flat")
                {
                    SetLoadingMessage("Loading world " + gameFile.Metadata.OverworldFile);
                    Overworld.Name = gameFile.Metadata.OverworldFile;
                    DirectoryInfo worldDirectory =
                        Directory.CreateDirectory(DwarfGame.GetWorldDirectory() +
                                                  Path.DirectorySeparatorChar + Overworld.Name);
                    var overWorldFile = new NewOverworldFile(worldDirectory.FullName);
                    Overworld.Map  = overWorldFile.Data.Data;
                    Overworld.Name = overWorldFile.Data.Name;
                }
                else
                {
                    SetLoadingMessage("Generating flat world..");
                    Overworld.CreateUniformLand(GraphicsDevice);
                }
            }

            #endregion

            #region Initialize static data

            {
                Vector3 origin  = new Vector3(0, 0, 0);
                Vector3 extents = new Vector3(1500, 1500, 1500);
                OctTree = new OctTreeNode(origin - extents, origin + extents);

                PrimitiveLibrary.Initialize(GraphicsDevice, Content);

                InstanceRenderer = new InstanceRenderer(GraphicsDevice, Content);

                Color[] white = new Color[1];
                white[0] = Color.White;
                pixel    = new Texture2D(GraphicsDevice, 1, 1);
                pixel.SetData(white);

                Tilesheet                  = AssetManager.GetContentTexture(ContentPaths.Terrain.terrain_tiles);
                AspectRatio                = GraphicsDevice.Viewport.AspectRatio;
                DefaultShader              = new Shader(Content.Load <Effect>(ContentPaths.Shaders.TexturedShaders), true);
                DefaultShader.ScreenWidth  = GraphicsDevice.Viewport.Width;
                DefaultShader.ScreenHeight = GraphicsDevice.Viewport.Height;
                CraftLibrary.InitializeDefaultLibrary();
                PotionLibrary.Initialize();
                VoxelLibrary.InitializeDefaultLibrary(GraphicsDevice);
                GrassLibrary.InitializeDefaultLibrary();
                DecalLibrary.InitializeDefaultLibrary();

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


                fxaa = new FXAA();
                fxaa.Initialize();

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

                JobLibrary.Initialize();
                MonsterSpawner = new MonsterSpawner(this);
                EntityFactory.Initialize(this);
            }

            #endregion


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

            SetLoadingMessage("Creating Shadows...");
            Shadows = new ShadowRenderer(GraphicsDevice, 1024, 1024);

            SetLoadingMessage("Creating Liquids ...");

            #region liquids

            WaterRenderer = new WaterRenderer(GraphicsDevice);

            #endregion

            SetLoadingMessage("Generating Initial Terrain Chunks ...");

            if (!fileExists)
            {
                GameID = MathFunctions.Random.Next(0, 1024);
            }

            ChunkGenerator = new ChunkGenerator(VoxelLibrary, Seed, 0.02f)
            {
                SeaLevel = SeaLevel
            };


            #region Load Components

            if (fileExists)
            {
                ChunkManager = new ChunkManager(Content, this,
                                                ChunkGenerator, WorldSize.X, WorldSize.Y, WorldSize.Z);
                Splasher = new Splasher(ChunkManager);


                ChunkRenderer = new ChunkRenderer(ChunkManager.ChunkData);

                SetLoadingMessage("Loading Terrain...");
                gameFile.ReadChunks(ExistingFile);
                ChunkManager.ChunkData.LoadFromFile(ChunkManager, gameFile, SetLoadingMessage);

                SetLoadingMessage("Loading Entities...");
                gameFile.LoadPlayData(ExistingFile, this);
                Camera            = gameFile.PlayData.Camera;
                DesignationDrawer = gameFile.PlayData.Designations;

                Vector3 origin  = new Vector3(WorldOrigin.X, 0, WorldOrigin.Y);
                Vector3 extents = new Vector3(1500, 1500, 1500);

                if (gameFile.PlayData.Resources != null)
                {
                    foreach (var resource in gameFile.PlayData.Resources)
                    {
                        if (!ResourceLibrary.Resources.ContainsKey(resource.Key))
                        {
                            ResourceLibrary.Add(resource.Value);
                        }
                    }
                }
                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;

                Sky.TimeOfDay = gameFile.Metadata.TimeOfDay;
                Time          = gameFile.Metadata.Time;
                WorldOrigin   = gameFile.Metadata.WorldOrigin;
                WorldScale    = gameFile.Metadata.WorldScale;

                // Restore native factions from deserialized data.
                Natives = new List <Faction>();

                foreach (Faction faction in Factions.Factions.Values)
                {
                    if (faction.Race.IsNative && faction.Race.IsIntelligent && !faction.IsRaceFaction)
                    {
                        Natives.Add(faction);
                    }
                }

                Diplomacy = gameFile.PlayData.Diplomacy;

                GoalManager = new Goals.GoalManager();
                GoalManager.Initialize(new List <Goals.Goal>());// gameFile.PlayData.Goals);

                TutorialManager = new Tutorial.TutorialManager();
                TutorialManager.SetFromSaveData(gameFile.PlayData.TutorialSaveData);
            }
            else
            {
                Time = new WorldTime();

                Camera = new OrbitCamera(this,
                                         new Vector3(VoxelConstants.ChunkSizeX,
                                                     VoxelConstants.ChunkSizeY - 1.0f,
                                                     VoxelConstants.ChunkSizeZ),
                                         new Vector3(VoxelConstants.ChunkSizeY, VoxelConstants.ChunkSizeY - 1.0f,
                                                     VoxelConstants.ChunkSizeZ) +
                                         Vector3.Up * 10.0f + Vector3.Backward * 10,
                                         MathHelper.PiOver4, AspectRatio, 0.1f,
                                         GameSettings.Default.VertexCullDistance);

                ChunkManager = new ChunkManager(Content, this,
                                                ChunkGenerator, WorldSize.X, WorldSize.Y, WorldSize.Z);
                Splasher = new Splasher(ChunkManager);


                ChunkRenderer = new ChunkRenderer(ChunkManager.ChunkData);

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

                // If there's no file, we have to initialize the first chunk coordinate
                if (gameFile == null)
                {
                    ChunkManager.GenerateInitialChunks(SpawnRect,
                                                       new GlobalChunkCoordinate(0, 0, 0),
                                                       SetLoadingMessage);
                }

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

                if (Natives == null) // Todo: Always true??
                {
                    FactionLibrary library = new FactionLibrary();
                    library.Initialize(this, CompanyMakerState.CompanyInformation);
                    Natives = new List <Faction>();
                    for (int i = 0; i < 10; i++)
                    {
                        Natives.Add(library.GenerateFaction(this, i, 10));
                    }
                }

                #region Prepare Factions

                foreach (Faction faction in Natives)
                {
                    faction.World = this;

                    if (faction.RoomBuilder == null)
                    {
                        faction.RoomBuilder = new RoomBuilder(faction, this);
                    }
                }

                Factions = new FactionLibrary();
                if (Natives != null && Natives.Count > 0)
                {
                    Factions.AddFactions(this, Natives);
                }

                Factions.Initialize(this, CompanyMakerState.CompanyInformation);
                Point playerOrigin = new Point((int)(WorldOrigin.X), (int)(WorldOrigin.Y));

                Factions.Factions["Player"].Center         = playerOrigin;
                Factions.Factions["The Motherland"].Center = new Point(playerOrigin.X + 50, playerOrigin.Y + 50);

                #endregion

                Diplomacy = new Diplomacy(this);
                Diplomacy.Initialize(Time.CurrentDate);

                // Initialize goal manager here.
                GoalManager = new Goals.GoalManager();
                GoalManager.Initialize(new List <Goals.Goal>());

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

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

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


            #endregion

            SetLoadingMessage("Creating Particles ...");
            ParticleManager = new ParticleManager(GraphicsDevice, ComponentManager);

            SetLoadingMessage("Creating GameMaster ...");
            Master = new GameMaster(Factions.Factions["Player"], Game, ComponentManager, ChunkManager,
                                    Camera, GraphicsDevice);

            if (gameFile != null)
            {
                if (gameFile.PlayData.Tasks != null)
                {
                    Master.NewArrivals         = gameFile.PlayData.NewArrivals ?? new List <GameMaster.ApplicantArrival>();
                    Master.TaskManager         = gameFile.PlayData.Tasks;
                    Master.TaskManager.Faction = Master.Faction;
                }
                if (gameFile.PlayData.InitialEmbark != null)
                {
                    InitialEmbark = gameFile.PlayData.InitialEmbark;
                }
                ChunkManager.World.Master.SetMaxViewingLevel(gameFile.Metadata.Slice > 0
                ? gameFile.Metadata.Slice
                : ChunkManager.World.Master.MaxViewingLevel);
            }

            if (Master.Faction.Economy.Company.Information == null)
            {
                Master.Faction.Economy.Company.Information = new CompanyInformation();
            }

            CreateInitialEmbarkment();
            foreach (var chunk in ChunkManager.ChunkData.ChunkMap)
            {
                chunk.CalculateInitialSunlight();
            }

            if (RevealSurface)
            {
                VoxelHelpers.InitialReveal(ChunkManager, ChunkManager.ChunkData, new VoxelHandle(
                                               ChunkManager.ChunkData.GetChunkEnumerator().FirstOrDefault(), new LocalVoxelCoordinate(0, VoxelConstants.ChunkSizeY - 1, 0)));
            }

            foreach (var chunk in ChunkManager.ChunkData.ChunkMap)
            {
                ChunkManager.InvalidateChunk(chunk);
            }

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

            Thread.Sleep(1000);
            ShowingWorld = true;

            SetLoadingMessage("Complete.");

            // GameFile is no longer needed.
            gameFile   = null;
            LoadStatus = LoadingStatus.Success;
#if !DEBUG
        }

        catch (Exception exception)
        {
            Game.CaptureException(exception);
            LoadingException = exception;
            LoadStatus       = LoadingStatus.Failure;
        }
#endif
        }