15#include "3rdparty/nlohmann/json.hpp"
46#include "table/strings.h"
51void GenerateClearTile();
53void GenerateObjects();
58void StartupDisasters();
60void InitializeGame(uint size_x, uint size_y,
bool reset_date,
bool reset_settings);
110 ScriptObject::InitializeRandomizers();
122 bool landscape_generated =
false;
129 if (!landscape_generated) {
141 ConvertGroundTilesIntoWaterTiles();
149 if (_game_mode != GM_EDITOR) {
176 for (i = 0; i < 0x500; i++) {
182 if (_game_mode != GM_EDITOR) {
186 for (i = 0; i < 2500; i++) {
199 _cur_company.
Trash();
216 if (_debug_desync_level > 0) {
228 Debug(net, 0,
"Generating map failed; closing server");
311 uint estimated_height = 0;
320 estimated_height = 0;
363 if (!f.has_value()) {
369 std::string text(filesize,
'\0');
370 size_t len = fread(text.data(), filesize, 1, *f);
379 nlohmann::json town_data;
381 town_data = nlohmann::json::parse(text);
382 }
catch (nlohmann::json::exception &) {
388 if (!town_data.is_array()) {
393 std::vector<std::pair<Town *, uint> > towns;
394 uint failed_towns = 0;
397 for (
auto &feature : town_data) {
405 if (!feature.is_object()) {
412 if (!feature.contains(
"name") || !feature.at(
"name").is_string()) {
418 if (!feature.contains(
"population") || !feature.at(
"population").is_number() ||
419 !feature.contains(
"city") || !feature.at(
"city").is_boolean() ||
420 !feature.contains(
"x") || !feature.at(
"x").is_number() ||
421 !feature.contains(
"y") || !feature.at(
"y").is_number()) {
422 feature.at(
"name").get_to(name);
429 feature.at(
"name").get_to(name);
430 feature.at(
"population").get_to(population);
431 feature.at(
"city").get_to(is_city);
434 feature.at(
"x").get_to(x_proportion);
435 feature.at(
"y").get_to(y_proportion);
438 if (x_proportion <= 0.0f || y_proportion <= 0.0f || x_proportion >= 1.0f || y_proportion >= 1.0f) {
455 default: NOT_REACHED();
464 town_id = std::get<TownID>(result);
467 if (town_id != TownID::Invalid())
break;
472 if (town_id == TownID::Invalid()) {
478 towns.emplace_back(std::make_pair(
Town::Get(town_id), population));
482 if (failed_towns > 0) {
487 for (
const auto &item : towns) {
488 Town *t = item.first;
489 uint population = item.second;
493 int try_limit = 1000;
500 const int HOUSES_TO_GROW = 10;
506 }
while (fail_limit > 0 && try_limit-- > 0 && t->
cache.
population < population);
Class for backupping variables and making sure they are restored later.
static void StartNew()
Start up a new GameScript.
static class GameInstance * GetInstance()
Get the current active instance.
static void GameLoop()
Called every game-tick to let Game do something.
Generate TileIndices around a center tile or tile area, with increasing distance.
static Date date
Current date in days (day counter).
static TickCounter counter
Monotonic counter, in ticks, since start of game.
@ Execute
execute the given command
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
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...
CompanyID _current_company
Company currently doing an action.
Functions related to companies.
static constexpr CompanyID COMPANY_SPECTATOR
The client is spectating.
static constexpr Owner OWNER_NONE
The tile has no ownership.
#define Debug(category, level, format_string,...)
Output a line of debugging information.
void StartupEngines()
Start/initialise all our engines.
Functions related to engines.
Functions related to errors.
void UnshowCriticalError()
Unshow the critical error.
@ WL_WARNING
Other information.
@ WL_ERROR
Errors (eg. saving/loading failed)
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, CommandCost &cc)
Display an error message in a window.
void ShowFirstError()
Show the first error of the queue.
std::optional< FileHandle > FioFOpenFile(std::string_view filename, std::string_view mode, Subdirectory subdir, size_t *filesize)
Opens a OpenTTD file somewhere in a personal or global directory.
@ SLO_SAVE
File is being saved.
@ DFT_GAME_FILE
Save game or scenario file.
@ HEIGHTMAP_DIR
Subdirectory of scenario for heightmaps.
@ AUTOSAVE_DIR
Subdirectory of save for autosaves.
Base functions for all Games.
The GameInstance tracks games.
bool _generating_world
Whether we are generating the map or not.
void GenerateWorldSetCallback(GWDoneProc *proc)
Set here the function, if any, that you want to be called when landscape generation is done.
void GenerateWorldSetAbortCallback(GWAbortProc *proc)
Set here the function, if any, that you want to be called when landscape generation is aborted.
void HandleGeneratingWorldAbortion()
Really handle the abortion, i.e.
void GenerateTrees()
Place new trees.
static void _GenerateWorld()
The internal, real, generate function.
void GenerateIndustries()
This function will create random industries during game creation.
static void CleanupGeneration()
Generation is done; show windows again and delete the progress window.
void GenerateWorld(GenWorldMode mode, uint size_x, uint size_y, bool reset_settings)
Generate a world.
void AbortGeneratingWorld()
Initializes the abortion process.
bool IsGeneratingWorldAborted()
Is the generation being aborted?
void LoadTownData()
Load town data from _file_to_saveload, place towns at the appropriate locations, and expand them to t...
void StartupCompanies()
Start of a new game.
Functions related to world/map generation.
void GWAbortProc()
Called when genworld is aborted.
void IncreaseGeneratingWorldProgress(GenWorldProgress cls)
Increases the current stage of the world generation with one.
static const uint MAP_HEIGHT_LIMIT_AUTO_MINIMUM
When map height limit is auto, make this the lowest possible map height limit.
@ LG_TERRAGENESIS
TerraGenesis Perlin landscape generator.
void ShowGenerateWorldProgress()
Show the window where a user can follow the process of the map generation.
@ GWP_OBJECT
Generate objects (radio tower, light houses)
@ GWP_MAP_INIT
Initialize/allocate the map, start economy.
@ GWP_RUNSCRIPT
Runs the game script at most 2500 times, or when ever the script sleeps.
@ GWP_GAME_START
Really prepare to start the game.
@ GWP_GAME_INIT
Initialize the game.
@ GWP_RUNTILELOOP
Runs the tile loop 1280 times to make snow etc.
void GWDoneProc()
Procedure called when the genworld process finishes.
static const uint MAP_HEIGHT_LIMIT_AUTO_CEILING_ROOM
When map height limit is auto, the map height limit will be the highest peak plus this value.
static const uint32_t GENERATE_NEW_SEED
Create a new random seed.
void SetGeneratingWorldProgress(GenWorldProgress cls, uint total)
Set the total of a stage of the world generation.
void PrepareGenerateWorldProgress()
Initializes the progress counters to the starting point.
GenWorldMode
Modes for GenerateWorld.
@ GWM_HEIGHTMAP
Generate a newgame from a heightmap.
@ GWM_EMPTY
Generate an empty map (sea-level)
void SetMouseCursorBusy(bool busy)
Set or unset the ZZZ cursor.
void LoadStringWidthTable(bool monospace)
Initialize _stringwidth_table cache.
SwitchMode _switch_mode
The next mainloop command.
void GfxLoadSprites()
Initialise and load all the sprites.
Functions related to the graphics initialization.
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
void FlatEmptyWorld(uint8_t tile_height)
Make an empty world where all tiles are of height 'tile_height'.
Functions related to creating heightmaps from files.
@ HM_CLOCKWISE
Rotate the map clockwise 45 degrees.
@ HM_COUNTER_CLOCKWISE
Rotate the map counter clockwise 45 degrees.
void RunTileLoop()
Gradually iterate over all tiles on the map, calling their TileLoopProcs once every TILE_UPDATE_FREQU...
bool GenerateLandscape(uint8_t mode)
Functions related to OTTD's landscape.
void ShowVitalWindows()
Show the vital in-game windows.
void SetupColoursAndInitialWindow()
Initialise the default colours (remaps and the likes), and load the main windows.
static debug_inline TileIndex TileXY(uint x, uint y)
Returns the TileIndex of a coordinate.
bool _network_dedicated
are we a dedicated server?
Basic functions/variables used all over the place.
Base for the NewGRF implementation.
void ShowNewGRFError()
Show the first NewGRF error we can find.
void InitializeBuildingCounts()
Initialise global building counts and all town building counts.
Functions related to NewGRF houses.
void SetCurrentRailTypeLabelList()
Populate railtype label list with current values.
NewGRF handling of rail types.
void SetCurrentRoadTypeLabelList()
Populate road type label list with current values.
NewGRF handling of road types.
@ PSM_ENTER_GAMELOOP
Enter the gameloop, changes will be permanent.
@ PSM_LEAVE_GAMELOOP
Leave the gameloop, changes will be temporary.
@ SM_MENU
Switch to game intro menu.
@ SM_EDITOR
Switch to scenario editor.
void SetModalProgress(bool state)
Set the modal progress state.
Functions related to modal progress.
bool HasModalProgress()
Check if we are currently in a modal progress state.
Randomizer _random
Random used in the game state calculations.
Pseudo random number generator.
A number of safeguards to prevent using unsafe methods.
SaveOrLoadResult SaveOrLoad(std::string_view filename, SaveLoadOperation fop, DetailedFileType dft, Subdirectory sb, bool threaded)
Main Save or Load function where the high-level saveload functions are handled.
FileToSaveLoad _file_to_saveload
File to save or load in the openttd loop.
Functions/types related to saving and loading games.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Command definitions related to signs.
Definition of base types and functions in a cross-platform compatible way.
Functions related to low-level strings.
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Functions related to OTTD's strings.
Class to backup a specific variable and restore it later.
bool IsValid() const
Checks whether the variable was already restored.
void Trash()
Trash the backup.
void Restore()
Restore the variable.
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...
bool freeform_edges
allow terraforming the tiles at the map edges
uint8_t map_height_limit
the maximum allowed heightlevel
TownLayout town_layout
select town layout,
std::string name
Name of the file.
uint8_t snow_line_height
the configured snow line height (deduced from "snow_coverage")
uint8_t land_generator
the landscape generator
uint8_t se_flat_world_height
land height a flat world gets in SE
uint8_t heightmap_rotation
rotation director for the heightmap
uint32_t generation_seed
noise seed for world generation
uint8_t heightmap_height
highest mountain for heightmap (towards what it scales)
EconomySettings economy
settings to change the economy
ConstructionSettings construction
construction of things in-game
GameCreationSettings game_creation
settings used during the creation of a game (map)
Properties of current genworld process.
static GWDoneProc * proc
Proc that is called when done (can be nullptr)
static CompanyID lc
The local_company before generating.
static uint size_x
X-size of the map.
static uint size_y
Y-size of the map.
static bool abort
Whether to abort the thread ASAP.
static GWAbortProc * abortp
Proc that is called when aborting (can be nullptr)
static GenWorldMode mode
What mode are we making a world in.
static uint SizeY()
Get the size of the map along the Y.
static debug_inline uint SizeX()
Get the size of the map along the X.
static uint MaxY()
Gets the maximum Y coordinate within the map, including MP_VOID.
static debug_inline uint MaxX()
Gets the maximum X coordinate within the map, including MP_VOID.
static Titem * Get(auto index)
Returns Titem with given index.
Tindex index
Index of this pool item.
void SetSeed(uint32_t seed)
(Re)set the state of the random number generator.
uint32_t population
Current population of people.
uint32_t num_houses
Amount of houses.
TownCache cache
Container for all cacheable data.
uint GetEstimationTGPMapHeight()
Get an overestimation of the highest peak TGP wants to generate.
Functions for the Perlin noise enhanced map generator.
static const uint DEF_SNOWLINE_HEIGHT
Default snowline height.
static const uint MAX_MAP_HEIGHT_LIMIT
Upper bound of maximum allowed heightlevel (in the construction settings)
Functions related to tile highlights.
void ResetObjectToPlace()
Reset the cursor and mouse mode handling back to default (normal cursor, only clicking in windows).
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 of the game-calendar-timer.
Definition of the tick-based game-timer.
bool GenerateTowns(TownLayout layout, std::optional< uint > number=std::nullopt)
Generate a number of towns with a given layout.
bool CheckTownRoadTypes()
Check if towns are able to build road.
Command definitions related to towns.
Base of all video drivers.
bool ScrollMainWindowToTile(TileIndex tile, bool instant)
Scrolls the viewport of the main window to a given location.
Functions related to (drawing on) viewports.
Map accessors for void tiles.
void MakeVoid(Tile t)
Make a nice void tile ;)
Functions related to water (management)
void CloseWindowByClass(WindowClass cls, int data)
Close all windows of a given class.
void ResetWindowSystem()
Reset the windowing system, by means of shutting it down followed by re-initialization.
void HideVitalWindows()
Close all always on-top windows to get an empty screen.
void CloseAllNonVitalWindows()
It is possible that a stickied window gets to a position where the 'close' button is outside the gami...
Window functions not directly related to making/drawing windows.
@ WC_MAIN_WINDOW
Main window; Window numbers:
@ WC_MODAL_PROGRESS
Progress report of landscape generation; Window numbers: