OpenTTD
genworld.cpp
Go to the documentation of this file.
1 /* $Id$ */
2 
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  */
9 
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"
37 #include "thread.h"
38 
39 #include "safeguards.h"
40 
41 
42 void GenerateClearTile();
43 void GenerateIndustries();
44 void GenerateObjects();
45 void GenerateTrees();
46 
47 void StartupEconomy();
48 void StartupCompanies();
49 void StartupDisasters();
50 
51 void InitializeGame(uint size_x, uint size_y, bool reset_date, bool reset_settings);
52 
60 
63 
69 {
70  return _gw.threaded && !_gw.quit_thread;
71 }
72 
77 static void CleanupGeneration()
78 {
79  _generating_world = false;
80 
81  SetMouseCursorBusy(false);
82  /* Show all vital windows again, because we have hidden them */
83  if (_gw.threaded && _game_mode != GM_MENU) ShowVitalWindows();
84  SetModalProgress(false);
85  _gw.proc = nullptr;
86  _gw.abortp = nullptr;
87  _gw.threaded = false;
88 
92 }
93 
97 static void _GenerateWorld()
98 {
99  /* Make sure everything is done via OWNER_NONE. */
100  Backup<CompanyID> _cur_company(_current_company, OWNER_NONE, FILE_LINE);
101 
102  std::unique_lock<std::mutex> lock(_modal_progress_work_mutex, std::defer_lock);
103  try {
104  _generating_world = true;
105  lock.lock();
106  if (_network_dedicated) DEBUG(net, 1, "Generating map, please wait...");
107  /* Set the Random() seed to generation_seed so we produce the same map with the same seed */
111  SetObjectToPlace(SPR_CURSOR_ZZZ, PAL_NONE, HT_NONE, WC_MAIN_WINDOW, 0);
112 
114 
116  /* Must start economy early because of the costs. */
117  StartupEconomy();
118 
119  /* Don't generate landscape items when in the scenario editor. */
120  if (_gw.mode == GWM_EMPTY) {
122 
123  /* Make sure the tiles at the north border are void tiles if needed. */
125  for (uint x = 0; x < MapSizeX(); x++) MakeVoid(TileXY(x, 0));
126  for (uint y = 0; y < MapSizeY(); y++) MakeVoid(TileXY(0, y));
127  }
128 
129  /* Make the map the height of the setting */
131 
132  ConvertGroundTilesIntoWaterTiles();
134  } else {
135  GenerateLandscape(_gw.mode);
136  GenerateClearTile();
137 
138  /* only generate towns, tree and industries in newgame mode. */
139  if (_game_mode != GM_EDITOR) {
141  _cur_company.Restore();
143  return;
144  }
146  GenerateObjects();
147  GenerateTrees();
148  }
149  }
150 
151  /* These are probably pointless when inside the scenario editor. */
155  StartupEngines();
157  StartupDisasters();
158  _generating_world = false;
159 
160  /* No need to run the tile loop in the scenario editor. */
161  if (_gw.mode != GWM_EMPTY) {
162  uint i;
163 
165  for (i = 0; i < 0x500; i++) {
166  RunTileLoop();
167  _tick_counter++;
169  }
170 
171  if (_game_mode != GM_EDITOR) {
172  Game::StartNew();
173 
174  if (Game::GetInstance() != nullptr) {
176  _generating_world = true;
177  for (i = 0; i < 2500; i++) {
178  Game::GameLoop();
180  if (Game::GetInstance()->IsSleeping()) break;
181  }
182  _generating_world = false;
183  }
184  }
185  }
186 
188 
190  _cur_company.Trash();
192 
194  /* Call any callback */
195  if (_gw.proc != nullptr) _gw.proc();
197 
199  lock.unlock();
200 
201  ShowNewGRFError();
202 
203  if (_network_dedicated) DEBUG(net, 1, "Map generated, starting game");
204  DEBUG(desync, 1, "new_map: %08x", _settings_game.game_creation.generation_seed);
205 
206  if (_debug_desync_level > 0) {
207  char name[MAX_PATH];
208  seprintf(name, lastof(name), "dmp_cmds_%08x_%08x.sav", _settings_game.game_creation.generation_seed, _date);
210  }
211  } catch (...) {
213  if (_cur_company.IsValid()) _cur_company.Restore();
214  _generating_world = false;
215  throw;
216  }
217 }
218 
225 {
226  _gw.proc = proc;
227 }
228 
235 {
236  _gw.abortp = proc;
237 }
238 
244 {
245  if (!_gw.thread.joinable()) return;
246 
249  _gw.quit_thread = true;
250  _gw.thread.join();
251  _gw.threaded = false;
254 }
255 
260 {
261  _gw.abort = true;
262 }
263 
269 {
270  return _gw.abort;
271 }
272 
277 {
278  /* Clean up - in SE create an empty map, otherwise, go to intro menu */
279  _switch_mode = (_game_mode == GM_EDITOR) ? SM_EDITOR : SM_MENU;
280 
281  if (_gw.abortp != nullptr) _gw.abortp();
282 
284 
285  if (_gw.thread.joinable() && _gw.thread.get_id() == std::this_thread::get_id()) throw OTTDThreadExitSignal();
286 
287  SwitchToMode(_switch_mode);
288 }
289 
297 void GenerateWorld(GenWorldMode mode, uint size_x, uint size_y, bool reset_settings)
298 {
299  if (HasModalProgress()) return;
300  _gw.mode = mode;
301  _gw.size_x = size_x;
302  _gw.size_y = size_y;
303  SetModalProgress(true);
304  _gw.abort = false;
305  _gw.abortp = nullptr;
306  _gw.lc = _local_company;
307  _gw.quit_thread = false;
308  _gw.threaded = true;
309 
310  /* This disables some commands and stuff */
312 
313  InitializeGame(_gw.size_x, _gw.size_y, true, reset_settings);
315 
316  /* Load the right landscape stuff, and the NewGRFs! */
317  GfxLoadSprites();
319 
320  /* Re-init the windowing system */
322 
323  /* Create toolbars */
325  SetObjectToPlace(SPR_CURSOR_ZZZ, PAL_NONE, HT_NONE, WC_MAIN_WINDOW, 0);
326 
327  if (_gw.thread.joinable()) _gw.thread.join();
328 
329  if (!UseThreadedModelProgress() || !VideoDriver::GetInstance()->HasGUI() || !StartNewThread(&_gw.thread, "ottd:genworld", &_GenerateWorld)) {
330  DEBUG(misc, 1, "Cannot create genworld thread, reverting to single-threaded mode");
331  _gw.threaded = false;
333  _GenerateWorld();
335  return;
336  }
337 
339  /* Remove any open window */
341  /* Hide vital windows, because we don't allow to use them */
343 
344  /* Don't show the dialog if we don't have a thread */
346 
347  /* Centre the view on the map */
348  if (FindWindowById(WC_MAIN_WINDOW, 0) != nullptr) {
349  ScrollMainWindowToTile(TileXY(MapSizeX() / 2, MapSizeY() / 2), true);
350  }
351 }
void SetupColoursAndInitialWindow()
Initialise the default colours (remaps and the likes), and load the main windows. ...
Definition: main_gui.cpp:554
void GenerateIndustries()
This function will create random industries during game creation.
void PrepareGenerateWorldProgress()
Initializes the progress counters to the starting point.
static uint MapSizeX()
Get the size of the map along the X.
Definition: map_func.h:74
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition: settings.cpp:81
Base of all video drivers.
static uint MapSizeY()
Get the size of the map along the Y.
Definition: map_func.h:84
static void MakeVoid(TileIndex t)
Make a nice void tile ;)
Definition: void_map.h:21
void GWDoneProc()
Procedure called when the genworld process finishes.
Definition: genworld.h:51
static void GameLoop()
Called every game-tick to let Game do something.
Definition: game_core.cpp:33
void SetMouseCursorBusy(bool busy)
Set or unset the ZZZ cursor.
Definition: gfx.cpp:1600
EconomySettings economy
settings to change the economy
Generate objects (radio tower, light houses)
Definition: genworld.h:76
Switch to game intro menu.
Definition: openttd.h:32
Functions related to dates.
int CDECL seprintf(char *str, const char *last, const char *format,...)
Safer implementation of snprintf; same as snprintf except:
Definition: string.cpp:409
Progress report of landscape generation; Window numbers:
Definition: window_type.h:458
Window * FindWindowById(WindowClass cls, WindowNumber number)
Find a window by its class and window number.
Definition: window.cpp:1114
bool IsValid() const
Checks whether the variable was already restored.
Definition: backup_type.hpp:65
uint size_y
Y-size of the map.
Definition: genworld.h:62
GenWorldMode
Modes for GenerateWorld.
Definition: genworld.h:29
Initialize/allocate the map, start economy.
Definition: genworld.h:70
GenWorldInfo _gw
Please only use this variable in genworld.h and genworld.cpp and nowhere else.
Definition: genworld.cpp:59
std::thread thread
The thread we are in (joinable if a thread was created)
Definition: genworld.h:65
void ShowGenerateWorldProgress()
Show the window where a user can follow the process of the map generation.
void GenerateTrees()
Place new trees.
Definition: tree_cmd.cpp:300
bool IsGenerateWorldThreaded()
Tells if the world generation is done in a thread or not.
Definition: genworld.cpp:68
GenWorldMode mode
What mode are we making a world in.
Definition: genworld.h:59
bool IsGeneratingWorldAborted()
Is the generation being aborted?
Definition: genworld.cpp:268
bool quit_thread
Do we want to quit the active thread.
Definition: genworld.h:57
TownLayout town_layout
select town layout,
#define lastof(x)
Get the last element of an fixed size array.
Definition: depend.cpp:50
Functions related to world/map generation.
bool GenerateTowns(TownLayout layout)
This function will generate a certain amount of towns, with a certain layout It can be called from th...
Definition: town_cmd.cpp:2139
void AbortGeneratingWorld()
Initializes the abortion process.
Definition: genworld.cpp:259
void DeleteAllNonVitalWindows()
It is possible that a stickied window gets to a position where the &#39;close&#39; button is outside the gami...
Definition: window.cpp:3375
byte se_flat_world_height
land height a flat world gets in SE
File is being saved.
Definition: fileio_type.h:52
uint size_x
X-size of the map.
Definition: genworld.h:61
static const uint32 GENERATE_NEW_SEED
Create a new random seed.
Definition: genworld.h:26
bool _network_dedicated
are we a dedicated server?
Definition: network.cpp:57
Class to backup a specific variable and restore it later.
Definition: backup_type.hpp:23
Functions related to (drawing on) viewports.
Pseudo random number generator.
void GenerateWorldSetAbortCallback(GWAbortProc *proc)
Set here the function, if any, that you want to be called when landscape generation is aborted...
Definition: genworld.cpp:234
std::mutex _modal_progress_work_mutex
Rights for the performing work.
Definition: progress.cpp:23
bool freeform_edges
allow terraforming the tiles at the map edges
Save game or scenario file.
Definition: fileio_type.h:33
bool StartNewThread(std::thread *thr, const char *name, TFn &&_Fx, TArgs &&... _Ax)
Start a new thread.
Definition: thread.h:50
bool abort
Whether to abort the thread ASAP.
Definition: genworld.h:56
Main window; Window numbers:
Definition: window_type.h:46
Functions related to low-level strings.
The tile has no ownership.
Definition: company_type.h:27
Functions/types related to saving and loading games.
void GenerateWorld(GenWorldMode mode, uint size_x, uint size_y, bool reset_settings)
Generate a world.
Definition: genworld.cpp:297
Functions related to errors.
Base of all threads.
Switch to scenario editor.
Definition: openttd.h:30
void HideVitalWindows()
Delete all always on-top windows to get an empty screen.
Definition: window.cpp:3428
static bool UseThreadedModelProgress()
Check if we can use a thread for modal progress.
Definition: progress.h:33
GWDoneProc * proc
Proc that is called when done (can be nullptr)
Definition: genworld.h:63
The client is spectating.
Definition: company_type.h:37
Functions related to engines.
static void SwitchMode(PersistentStorageMode mode, bool ignore_prev_mode=false)
Clear temporary changes made since the last call to SwitchMode, and set whether subsequent changes sh...
std::mutex lock
synchronization for playback status fields
Definition: win32_m.cpp:36
Functions related to modal progress.
Definition of base types and functions in a cross-platform compatible way.
void LoadStringWidthTable(bool monospace)
Initialize _stringwidth_table cache.
Definition: gfx.cpp:1130
Enter the gameloop, changes will be permanent.
A number of safeguards to prevent using unsafe methods.
void SetLocalCompany(CompanyID new_company)
Sets the local company and updates the settings that are set on a per-company basis to reflect the co...
GameSettings _settings_newgame
Game settings for new games (updated from the intro screen).
Definition: settings.cpp:82
Subdirectory of save for autosaves.
Definition: fileio_type.h:113
The GameInstance tracks games.
bool threaded
Whether we run _GenerateWorld threaded.
Definition: genworld.h:58
Properties of current genworld process.
Definition: genworld.h:55
Generate an empty map (sea-level)
Definition: genworld.h:31
Basic functions/variables used all over the place.
void SetSeed(uint32 seed)
(Re)set the state of the random number generator.
Definition: random_func.cpp:57
static class GameInstance * GetInstance()
Get the current active instance.
Definition: game.hpp:113
SaveOrLoadResult SaveOrLoad(const char *filename, SaveLoadOperation fop, DetailedFileType dft, Subdirectory sb, bool threaded)
Main Save or Load function where the high-level saveload functions are handled.
Definition: saveload.cpp:2719
Runs the tile loop 1280 times to make snow etc.
Definition: genworld.h:79
void GWAbortProc()
Called when genworld is aborted.
Definition: genworld.h:52
void DeleteWindowByClass(WindowClass cls)
Delete all windows of a given class.
Definition: window.cpp:1159
void StartupCompanies()
Start the next competitor now.
static void StartNew()
Start up a new GameScript.
Definition: game_core.cpp:74
GWAbortProc * abortp
Proc that is called when aborting (can be nullptr)
Definition: genworld.h:64
static void CleanupGeneration()
Clean up the &#39;mess&#39; of generation.
Definition: genworld.cpp:77
void WaitTillGeneratedWorld()
This will wait for the thread to finish up his work.
Definition: genworld.cpp:243
#define DEBUG(name, level,...)
Output a line of debugging information.
Definition: debug.h:37
void StartupEngines()
Start/initialise all our engines.
Definition: engine.cpp:697
Functions related to the graphics initialization.
uint16 _tick_counter
Ever incrementing (and sometimes wrapping) tick counter for setting off various events.
Definition: date.cpp:30
void ShowNewGRFError()
Show the first NewGRF error we can find.
Definition: newgrf_gui.cpp:46
void UnshowCriticalError()
Unshow the critical error.
Definition: error_gui.cpp:361
void GenerateWorldSetCallback(GWDoneProc *proc)
Set here the function, if any, that you want to be called when landscape generation is done...
Definition: genworld.cpp:224
void Trash()
Trash the backup.
Functions related to companies.
default
bool _generating_world
Whether we are generating the map or not.
Definition: genworld.cpp:62
Leave the gameloop, changes will be temporary.
uint32 generation_seed
noise seed for world generation
Functions related to creating heightmaps from files.
Randomizer _random
Random used in the game state calculations.
Definition: random_func.cpp:27
Map accessors for void tiles.
static VideoDriver * GetInstance()
Get the currently active instance of the video driver.
Runs the game script at most 2500 times, or when ever the script sleeps.
Definition: genworld.h:80
CompanyID lc
The local_company before generating.
Definition: genworld.h:60
void FlatEmptyWorld(byte tile_height)
Make an empty world where all tiles are of height &#39;tile_height&#39;.
Definition: heightmap.cpp:512
static void _GenerateWorld()
The internal, real, generate function.
Definition: genworld.cpp:97
SwitchMode _switch_mode
The next mainloop command.
Definition: gfx.cpp:48
Functions related to OTTD&#39;s landscape.
bool ScrollMainWindowToTile(TileIndex tile, bool instant)
Scrolls the viewport of the main window to a given location.
Definition: viewport.cpp:2417
Base functions for all Games.
CompanyID _current_company
Company currently doing an action.
Definition: company_cmd.cpp:47
void SetObjectToPlace(CursorID icon, PaletteID pal, HighLightStyle mode, WindowClass window_class, WindowNumber window_num)
Change the cursor and mouse click/drag handling to a mode for performing special operations like tile...
Definition: viewport.cpp:3326
ConstructionSettings construction
construction of things in-game
void SetModalProgress(bool state)
Set the modal progress state.
Definition: progress.cpp:32
void HandleGeneratingWorldAbortion()
Really handle the abortion, i.e.
Definition: genworld.cpp:276
void Restore()
Restore the variable.
Base of the town class.
std::mutex _modal_progress_paint_mutex
Rights for the painting.
Definition: progress.cpp:25
void RunTileLoop()
Gradually iterate over all tiles on the map, calling their TileLoopProcs once every 256 ticks...
Definition: landscape.cpp:803
GameCreationSettings game_creation
settings used during the creation of a game (map)
void ResetObjectToPlace()
Reset the cursor and mouse mode handling back to default (normal cursor, only clicking in windows)...
Definition: viewport.cpp:3374
Functions related to tile highlights.
void ResetWindowSystem()
Reset the windowing system, by means of shutting it down followed by re-initialization.
Definition: window.cpp:1918
Window functions not directly related to making/drawing windows.
void SetGeneratingWorldProgress(GenWorldProgress cls, uint total)
Set the total of a stage of the world generation.
Functions related to water (management)
void GenerateLandscape(byte mode)
Definition: landscape.cpp:1295
void IncreaseGeneratingWorldProgress(GenWorldProgress cls)
Increases the current stage of the world generation with one.
Initialize the game.
Definition: genworld.h:78
Date _date
Current date in days (day counter)
Definition: date.cpp:28
void ShowVitalWindows()
Show the vital in-game windows.
Definition: main_gui.cpp:582
Signal used for signalling we knowingly want to end the thread.
Definition: thread.h:20
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Definition: company_cmd.cpp:46
Class for backupping variables and making sure they are restored later.
static TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
Definition: map_func.h:165
static bool HasModalProgress()
Check if we are currently in a modal progress state.
Definition: progress.h:23
Really prepare to start the game.
Definition: genworld.h:81
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition: gfx.cpp:1459
void GfxLoadSprites()
Initialise and load all the sprites.
Definition: gfxinit.cpp:340
void ShowFirstError()
Show the first error of the queue.
Definition: error_gui.cpp:347
Base for the NewGRF implementation.