(svn r27950) -Merge: Documentation updates from 1.7 branch
[openttd.git] / src / genworld.cpp
blob5cdb129b9ce2bbcda94bad93400e6714fe68f1db
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /** @file genworld.cpp Functions to generate a map. */
12 #include "stdafx.h"
13 #include "landscape.h"
14 #include "company_func.h"
15 #include "genworld.h"
16 #include "gfxinit.h"
17 #include "window_func.h"
18 #include "network/network.h"
19 #include "heightmap.h"
20 #include "viewport_func.h"
21 #include "date_func.h"
22 #include "engine_func.h"
23 #include "water.h"
24 #include "video/video_driver.hpp"
25 #include "tilehighlight_func.h"
26 #include "saveload/saveload.h"
27 #include "void_map.h"
28 #include "town.h"
29 #include "newgrf.h"
30 #include "core/random_func.hpp"
31 #include "core/backup_type.hpp"
32 #include "progress.h"
33 #include "error.h"
34 #include "game/game.hpp"
35 #include "game/game_instance.hpp"
36 #include "string_func.h"
38 #include "safeguards.h"
41 void GenerateClearTile();
42 void GenerateIndustries();
43 void GenerateObjects();
44 void GenerateTrees();
46 void StartupEconomy();
47 void StartupCompanies();
48 void StartupDisasters();
50 void InitializeGame(uint size_x, uint size_y, bool reset_date, bool reset_settings);
52 /**
53 * Please only use this variable in genworld.h and genworld.cpp and
54 * nowhere else. For speed improvements we need it to be global, but
55 * in no way the meaning of it is to use it anywhere else besides
56 * in the genworld.h and genworld.cpp!
58 GenWorldInfo _gw;
60 /** Whether we are generating the map or not. */
61 bool _generating_world;
63 /**
64 * Tells if the world generation is done in a thread or not.
65 * @return the 'threaded' status
67 bool IsGenerateWorldThreaded()
69 return _gw.threaded && !_gw.quit_thread;
72 /**
73 * Clean up the 'mess' of generation. That is, show windows again, reset
74 * thread variables, and delete the progress window.
76 static void CleanupGeneration()
78 _generating_world = false;
80 SetMouseCursorBusy(false);
81 /* Show all vital windows again, because we have hidden them */
82 if (_gw.threaded && _game_mode != GM_MENU) ShowVitalWindows();
83 SetModalProgress(false);
84 _gw.proc = NULL;
85 _gw.abortp = NULL;
86 _gw.threaded = false;
88 DeleteWindowByClass(WC_MODAL_PROGRESS);
89 ShowFirstError();
90 MarkWholeScreenDirty();
93 /**
94 * The internal, real, generate function.
96 static void _GenerateWorld(void *)
98 /* Make sure everything is done via OWNER_NONE. */
99 Backup<CompanyByte> _cur_company(_current_company, OWNER_NONE, FILE_LINE);
101 try {
102 _generating_world = true;
103 _modal_progress_work_mutex->BeginCritical();
104 if (_network_dedicated) DEBUG(net, 1, "Generating map, please wait...");
105 /* Set the Random() seed to generation_seed so we produce the same map with the same seed */
106 if (_settings_game.game_creation.generation_seed == GENERATE_NEW_SEED) _settings_game.game_creation.generation_seed = _settings_newgame.game_creation.generation_seed = InteractiveRandom();
107 _random.SetSeed(_settings_game.game_creation.generation_seed);
108 SetGeneratingWorldProgress(GWP_MAP_INIT, 2);
109 SetObjectToPlace(SPR_CURSOR_ZZZ, PAL_NONE, HT_NONE, WC_MAIN_WINDOW, 0);
111 BasePersistentStorageArray::SwitchMode(PSM_ENTER_GAMELOOP);
113 IncreaseGeneratingWorldProgress(GWP_MAP_INIT);
114 /* Must start economy early because of the costs. */
115 StartupEconomy();
117 /* Don't generate landscape items when in the scenario editor. */
118 if (_gw.mode == GWM_EMPTY) {
119 SetGeneratingWorldProgress(GWP_OBJECT, 1);
121 /* Make sure the tiles at the north border are void tiles if needed. */
122 if (_settings_game.construction.freeform_edges) {
123 for (uint row = 0; row < MapSizeY(); row++) MakeVoid(TileXY(0, row));
124 for (uint col = 0; col < MapSizeX(); col++) MakeVoid(TileXY(col, 0));
127 /* Make the map the height of the setting */
128 if (_game_mode != GM_MENU) FlatEmptyWorld(_settings_game.game_creation.se_flat_world_height);
130 ConvertGroundTilesIntoWaterTiles();
131 IncreaseGeneratingWorldProgress(GWP_OBJECT);
132 } else {
133 GenerateLandscape(_gw.mode);
134 GenerateClearTile();
136 /* only generate towns, tree and industries in newgame mode. */
137 if (_game_mode != GM_EDITOR) {
138 if (!GenerateTowns(_settings_game.economy.town_layout)) {
139 _cur_company.Restore();
140 HandleGeneratingWorldAbortion();
141 return;
143 GenerateIndustries();
144 GenerateObjects();
145 GenerateTrees();
149 /* These are probably pointless when inside the scenario editor. */
150 SetGeneratingWorldProgress(GWP_GAME_INIT, 3);
151 StartupCompanies();
152 IncreaseGeneratingWorldProgress(GWP_GAME_INIT);
153 StartupEngines();
154 IncreaseGeneratingWorldProgress(GWP_GAME_INIT);
155 StartupDisasters();
156 _generating_world = false;
158 /* No need to run the tile loop in the scenario editor. */
159 if (_gw.mode != GWM_EMPTY) {
160 uint i;
162 SetGeneratingWorldProgress(GWP_RUNTILELOOP, 0x500);
163 for (i = 0; i < 0x500; i++) {
164 RunTileLoop();
165 _tick_counter++;
166 IncreaseGeneratingWorldProgress(GWP_RUNTILELOOP);
169 if (_game_mode != GM_EDITOR) {
170 Game::StartNew();
172 if (Game::GetInstance() != NULL) {
173 SetGeneratingWorldProgress(GWP_RUNSCRIPT, 2500);
174 _generating_world = true;
175 for (i = 0; i < 2500; i++) {
176 Game::GameLoop();
177 IncreaseGeneratingWorldProgress(GWP_RUNSCRIPT);
178 if (Game::GetInstance()->IsSleeping()) break;
180 _generating_world = false;
185 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP);
187 ResetObjectToPlace();
188 _cur_company.Trash();
189 _current_company = _local_company = _gw.lc;
191 SetGeneratingWorldProgress(GWP_GAME_START, 1);
192 /* Call any callback */
193 if (_gw.proc != NULL) _gw.proc();
194 IncreaseGeneratingWorldProgress(GWP_GAME_START);
196 CleanupGeneration();
197 _modal_progress_work_mutex->EndCritical();
199 ShowNewGRFError();
201 if (_network_dedicated) DEBUG(net, 1, "Map generated, starting game");
202 DEBUG(desync, 1, "new_map: %08x", _settings_game.game_creation.generation_seed);
204 if (_debug_desync_level > 0) {
205 char name[MAX_PATH];
206 seprintf(name, lastof(name), "dmp_cmds_%08x_%08x.sav", _settings_game.game_creation.generation_seed, _date);
207 SaveOrLoad(name, SLO_SAVE, DFT_GAME_FILE, AUTOSAVE_DIR, false);
209 } catch (...) {
210 BasePersistentStorageArray::SwitchMode(PSM_LEAVE_GAMELOOP, true);
211 if (_cur_company.IsValid()) _cur_company.Restore();
212 _generating_world = false;
213 _modal_progress_work_mutex->EndCritical();
214 throw;
219 * Set here the function, if any, that you want to be called when landscape
220 * generation is done.
221 * @param proc callback procedure
223 void GenerateWorldSetCallback(GWDoneProc *proc)
225 _gw.proc = proc;
229 * Set here the function, if any, that you want to be called when landscape
230 * generation is aborted.
231 * @param proc callback procedure
233 void GenerateWorldSetAbortCallback(GWAbortProc *proc)
235 _gw.abortp = proc;
239 * This will wait for the thread to finish up his work. It will not continue
240 * till the work is done.
242 void WaitTillGeneratedWorld()
244 if (_gw.thread == NULL) return;
246 _modal_progress_work_mutex->EndCritical();
247 _modal_progress_paint_mutex->EndCritical();
248 _gw.quit_thread = true;
249 _gw.thread->Join();
250 delete _gw.thread;
251 _gw.thread = NULL;
252 _gw.threaded = false;
253 _modal_progress_work_mutex->BeginCritical();
254 _modal_progress_paint_mutex->BeginCritical();
258 * Initializes the abortion process
260 void AbortGeneratingWorld()
262 _gw.abort = true;
266 * Is the generation being aborted?
267 * @return the 'aborted' status
269 bool IsGeneratingWorldAborted()
271 return _gw.abort;
275 * Really handle the abortion, i.e. clean up some of the mess
277 void HandleGeneratingWorldAbortion()
279 /* Clean up - in SE create an empty map, otherwise, go to intro menu */
280 _switch_mode = (_game_mode == GM_EDITOR) ? SM_EDITOR : SM_MENU;
282 if (_gw.abortp != NULL) _gw.abortp();
284 CleanupGeneration();
286 if (_gw.thread != NULL) _gw.thread->Exit();
288 SwitchToMode(_switch_mode);
292 * Generate a world.
293 * @param mode The mode of world generation (see GenWorldMode).
294 * @param size_x The X-size of the map.
295 * @param size_y The Y-size of the map.
296 * @param reset_settings Whether to reset the game configuration (used for restart)
298 void GenerateWorld(GenWorldMode mode, uint size_x, uint size_y, bool reset_settings)
300 if (HasModalProgress()) return;
301 _gw.mode = mode;
302 _gw.size_x = size_x;
303 _gw.size_y = size_y;
304 SetModalProgress(true);
305 _gw.abort = false;
306 _gw.abortp = NULL;
307 _gw.lc = _local_company;
308 _gw.quit_thread = false;
309 _gw.threaded = true;
311 /* This disables some commands and stuff */
312 SetLocalCompany(COMPANY_SPECTATOR);
314 InitializeGame(_gw.size_x, _gw.size_y, true, reset_settings);
315 PrepareGenerateWorldProgress();
317 /* Load the right landscape stuff, and the NewGRFs! */
318 GfxLoadSprites();
319 LoadStringWidthTable();
321 /* Re-init the windowing system */
322 ResetWindowSystem();
324 /* Create toolbars */
325 SetupColoursAndInitialWindow();
326 SetObjectToPlace(SPR_CURSOR_ZZZ, PAL_NONE, HT_NONE, WC_MAIN_WINDOW, 0);
328 if (_gw.thread != NULL) {
329 _gw.thread->Join();
330 delete _gw.thread;
331 _gw.thread = NULL;
334 if (!VideoDriver::GetInstance()->HasGUI() || !ThreadObject::New(&_GenerateWorld, NULL, &_gw.thread, "ottd:genworld")) {
335 DEBUG(misc, 1, "Cannot create genworld thread, reverting to single-threaded mode");
336 _gw.threaded = false;
337 _modal_progress_work_mutex->EndCritical();
338 _GenerateWorld(NULL);
339 _modal_progress_work_mutex->BeginCritical();
340 return;
343 UnshowCriticalError();
344 /* Remove any open window */
345 DeleteAllNonVitalWindows();
346 /* Hide vital windows, because we don't allow to use them */
347 HideVitalWindows();
349 /* Don't show the dialog if we don't have a thread */
350 ShowGenerateWorldProgress();
352 /* Centre the view on the map */
353 if (FindWindowById(WC_MAIN_WINDOW, 0) != NULL) {
354 ScrollMainWindowToTile(TileXY(MapSizeX() / 2, MapSizeY() / 2), true);