15#include "3rdparty/nlohmann/json.hpp"
46#include "table/strings.h"
60void InitializeGame(uint size_x, uint size_y,
bool reset_date,
bool reset_settings);
66 static inline CompanyID
lc;
110 ScriptObject::InitializeRandomizers();
122 bool landscape_generated =
false;
129 if (!landscape_generated) {
141 ConvertGroundTilesIntoWaterTiles();
142 Map::CountLandTiles();
148 Map::CountLandTiles();
178 for (i = 0; i < 0x500; i++) {
188 for (i = 0; i < 2500; i++) {
313 uint estimated_height = 0;
316 estimated_height =
_settings_game.game_creation.se_flat_world_height;
322 estimated_height = 0;
372 if (x <= 0.0f || y <= 0.0f || x >= 1.0f || y >= 1.0f)
return INVALID_TILE;
397 nlohmann::json town_data;
399 town_data = nlohmann::json::parse(text);
400 }
catch (nlohmann::json::exception &) {
406 if (!town_data.is_array()) {
411 std::vector<ParsedTown> towns;
414 for (
auto &feature : town_data) {
418 if (!feature.is_object()) {
425 if (!feature.contains(
"name") || !feature.at(
"name").is_string()) {
430 feature.at(
"name").get_to(town.
name);
433 if (!feature.contains(
"population") || !feature.at(
"population").is_number() ||
434 !feature.contains(
"city") || !feature.at(
"city").is_boolean() ||
435 !feature.contains(
"x") || !feature.at(
"x").is_number() ||
436 !feature.contains(
"y") || !feature.at(
"y").is_number()) {
442 feature.at(
"population").get_to(town.
population);
443 feature.at(
"city").get_to(town.
is_city);
465 if (!f.has_value()) {
471 std::string text(filesize,
'\0');
472 size_t len = fread(text.data(), filesize, 1, *f);
481 if (town_data.empty())
return;
483 std::vector<std::pair<const Town *, uint> > towns;
484 uint failed_towns = 0;
489 for (
auto &town : town_data) {
495 Command<Commands::PlaceSign>::Post(town.target_tile, town.name);
500 towns.emplace_back(t, town.population);
504 if (failed_towns > 0) {
509 for (
const auto &[t, population] : towns) {
512 int try_limit = 1000;
519 const int HOUSES_TO_GROW = 10;
522 uint before = t->cache.num_houses;
523 Command<Commands::ExpandTown>::Post(t->index, HOUSES_TO_GROW, {TownExpandMode::Buildings, TownExpandMode::Roads});
524 if (t->cache.num_houses <= before) fail_limit--;
525 }
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.
static Date date
Current date in days (day counter).
static TickCounter counter
Monotonic counter, in ticks, since start of game.
void SetLocalCompany(CompanyID new_company, bool switching_game)
Sets the local company and updates the settings that are set on a per-company basis to reflect the co...
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
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.
bool IsVisibleSeverity(Facility facility, Severity severity)
Test if debug severity is visible for the given facility.
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
@ Desync
Desync message facility.
@ Net
Net message facility.
@ Critical
Critical, user should know about this.
@ Error
Error, but we are recovering.
void StartupEngines()
Start/initialise all our engines.
Functions related to engines.
Functions related to errors.
void UnshowCriticalError()
Unshow the critical error.
@ Warning
Other information.
@ 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.
@ Save
File is being saved.
@ GameFile
Save game or scenario file.
@ Autosave
Subdirectory of save for autosaves.
@ Heightmap
Subdirectory of scenario for heightmaps.
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.
void GenerateObjects()
Generate objects, including lighthouses, transmitters, and any NewGRF objects.
static void _GenerateWorld()
The internal, real, generate function.
static std::vector< ParsedTown > ParseTownData(std::string_view text)
Parse town data from json text.
void GenerateIndustries()
This function will create random industries during game creation.
static TileIndex TranslateCoordinates(float x, float y)
Translation coordates from a proportions to TileIndex.
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 StartupDisasters()
Starts up disasters.
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.
void GenerateClearTile()
Generate rough and rocky features on clear tiles.
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.
@ GameStart
Really prepare to start the game.
@ GameScript
Runs the game script at most 2500 times, or when ever the script sleeps.
@ Init
Initialize/allocate the map, start economy.
@ Objects
Generate objects (radio tower, light houses).
@ GameInit
Initialize the game.
@ 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 LoadStringWidthTable(FontSizes fontsizes)
Initialize _stringwidth_table cache for the specified font sizes.
void SetMouseCursorBusy(bool busy)
Set or unset the ZZZ cursor.
SwitchMode _switch_mode
The next mainloop command.
void GfxLoadSprites()
Initialise and load all the sprites.
Functions related to the graphics initialization.
static const CursorID SPR_CURSOR_ZZZ
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 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.
@ Editor
In the scenario editor.
@ Editor
Switch to scenario editor.
@ Menu
Switch to game intro menu.
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.
bool UpdateNearestTownForRoadTiles(bool invalidate)
Updates cached nearest town for all road tiles.
A number of safeguards to prevent using unsafe methods.
SaveLoadResult 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 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 upon destruction of this object to prevent stack v...
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...
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 SizeX()
Get the size of the map along the X.
static uint SizeY()
Get the size of the map along the Y.
static uint MaxY()
Gets the maximum Y coordinate within the map, including TileType::Void.
static uint MaxX()
Gets the maximum X coordinate within the map, including TileType::Void.
uint population
The target population of the town when created in OpenTTD. If input is blank, defaults to 0.
std::string name
The name of the town.
TileIndex target_tile
The target tile of the town.
bool is_city
Should it be created as a city in OpenTTD? If input is blank, defaults to false.
uint GetEstimationTGPMapHeight()
Get an overestimation of the highest peak TGP wants to generate.
Functions for the Perlin noise enhanced map generator.
static constexpr uint DEF_SNOWLINE_HEIGHT
Default snowline height.
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
static constexpr 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.
Town * TryGenerateNamedTownAroundTile(TileIndex target_tile, TownSize size, bool city, TownLayout layout, std::string_view name)
Try to generate a named town around a tile.
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.