* Create a random town somewhere in the world. * @param attempts How many times should we try? * @param townnameparts The name of the town. * @param size The size preset of the town. * @param city Should we build a city? * @param layout The road layout to build. * @return The town object, or nullptr if we failed to create a town anywhere. */
| 2384 | * @return The town object, or nullptr if we failed to create a town anywhere. |
| 2385 | */ |
| 2386 | static Town *CreateRandomTown(uint attempts, uint32_t townnameparts, TownSize size, bool city, TownLayout layout) |
| 2387 | { |
| 2388 | assert(_game_mode == GM_EDITOR || _generating_world); // These are the preconditions for CMD_DELETE_TOWN |
| 2389 | |
| 2390 | if (!Town::CanAllocateItem()) return nullptr; |
| 2391 | |
| 2392 | do { |
| 2393 | /* Generate a tile index not too close from the edge */ |
| 2394 | TileIndex tile = AlignTileToGrid(RandomTile(), layout); |
| 2395 | |
| 2396 | /* If we tried to place the town on water, find a suitable land tile nearby. |
| 2397 | * Otherwise, evaluate the land tile. */ |
| 2398 | if (IsTileType(tile, MP_WATER)) { |
| 2399 | tile = FindNearestGoodCoastalTownSpot(tile, layout); |
| 2400 | if (tile == INVALID_TILE) continue; |
| 2401 | } else if (TownCanBePlacedHere(tile, true).Failed()) continue; |
| 2402 | |
| 2403 | /* Allocate a town struct */ |
| 2404 | Town *t = new Town(tile); |
| 2405 | |
| 2406 | DoCreateTown(t, tile, townnameparts, size, city, layout, false); |
| 2407 | |
| 2408 | /* if the population is still 0 at the point, then the |
| 2409 | * placement is so bad it couldn't grow at all */ |
| 2410 | if (t->cache.population > 0) return t; |
| 2411 | |
| 2412 | Backup<CompanyID> cur_company(_current_company, OWNER_TOWN); |
| 2413 | [[maybe_unused]] CommandCost rc = Command<CMD_DELETE_TOWN>::Do(DoCommandFlag::Execute, t->index); |
| 2414 | cur_company.Restore(); |
| 2415 | assert(rc.Succeeded()); |
| 2416 | |
| 2417 | /* We already know that we can allocate a single town when |
| 2418 | * entering this function. However, we create and delete |
| 2419 | * a town which "resets" the allocation checks. As such we |
| 2420 | * need to check again when assertions are enabled. */ |
| 2421 | assert(Town::CanAllocateItem()); |
| 2422 | } while (--attempts != 0); |
| 2423 | |
| 2424 | return nullptr; |
| 2425 | } |
| 2426 | |
| 2427 | /** |
| 2428 | * Calculate the number of towns which should be on the map according to the current "town density" newgame setting and the map size. |
no test coverage detected