Fix #8316: Make sort industries by production and transported with a cargo filter...
[openttd-github.git] / src / tree_cmd.cpp
blobe2460f3b083af580ab710b8762319187e59a2cab
1 /*
2 * This file is part of OpenTTD.
3 * 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.
4 * 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.
5 * 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/>.
6 */
8 /** @file tree_cmd.cpp Handling of tree tiles. */
10 #include "stdafx.h"
11 #include "clear_map.h"
12 #include "landscape.h"
13 #include "tree_map.h"
14 #include "viewport_func.h"
15 #include "command_func.h"
16 #include "town.h"
17 #include "genworld.h"
18 #include "clear_func.h"
19 #include "company_func.h"
20 #include "sound_func.h"
21 #include "water.h"
22 #include "company_base.h"
23 #include "core/random_func.hpp"
24 #include "newgrf_generic.h"
25 #include "date_func.h"
27 #include "table/strings.h"
28 #include "table/tree_land.h"
29 #include "table/clear_land.h"
31 #include "safeguards.h"
33 /**
34 * List of tree placer algorithm.
36 * This enumeration defines all possible tree placer algorithm in the game.
38 enum TreePlacer {
39 TP_NONE, ///< No tree placer algorithm
40 TP_ORIGINAL, ///< The original algorithm
41 TP_IMPROVED, ///< A 'improved' algorithm
44 /** Where to place trees while in-game? */
45 enum ExtraTreePlacement {
46 ETP_NO_SPREAD, ///< Grow trees on tiles that have them but don't spread to new ones
47 ETP_SPREAD_RAINFOREST, ///< Grow trees on tiles that have them, only spread to new ones in rainforests
48 ETP_SPREAD_ALL, ///< Grow trees and spread them without restrictions
49 ETP_NO_GROWTH_NO_SPREAD, ///< Don't grow trees and don't spread them at all
52 /** Determines when to consider building more trees. */
53 byte _trees_tick_ctr;
55 static const uint16 DEFAULT_TREE_STEPS = 1000; ///< Default number of attempts for placing trees.
56 static const uint16 DEFAULT_RAINFOREST_TREE_STEPS = 15000; ///< Default number of attempts for placing extra trees at rainforest in tropic.
57 static const uint16 EDITOR_TREE_DIV = 5; ///< Game editor tree generation divisor factor.
59 /**
60 * Tests if a tile can be converted to MP_TREES
61 * This is true for clear ground without farms or rocks.
63 * @param tile the tile of interest
64 * @param allow_desert Allow planting trees on CLEAR_DESERT?
65 * @return true if trees can be built.
67 static bool CanPlantTreesOnTile(TileIndex tile, bool allow_desert)
69 switch (GetTileType(tile)) {
70 case MP_WATER:
71 return !IsBridgeAbove(tile) && IsCoast(tile) && !IsSlopeWithOneCornerRaised(GetTileSlope(tile));
73 case MP_CLEAR:
74 return !IsBridgeAbove(tile) && !IsClearGround(tile, CLEAR_FIELDS) && GetRawClearGround(tile) != CLEAR_ROCKS &&
75 (allow_desert || !IsClearGround(tile, CLEAR_DESERT));
77 default: return false;
81 /**
82 * Creates a tree tile
83 * Ground type and density is preserved.
85 * @pre the tile must be suitable for trees.
87 * @param tile where to plant the trees.
88 * @param treetype The type of the tree
89 * @param count the number of trees (minus 1)
90 * @param growth the growth status
92 static void PlantTreesOnTile(TileIndex tile, TreeType treetype, uint count, uint growth)
94 assert(treetype != TREE_INVALID);
95 assert(CanPlantTreesOnTile(tile, true));
97 TreeGround ground;
98 uint density = 3;
100 switch (GetTileType(tile)) {
101 case MP_WATER:
102 ground = TREE_GROUND_SHORE;
103 break;
105 case MP_CLEAR:
106 switch (GetClearGround(tile)) {
107 case CLEAR_GRASS: ground = TREE_GROUND_GRASS; break;
108 case CLEAR_ROUGH: ground = TREE_GROUND_ROUGH; break;
109 case CLEAR_SNOW: ground = GetRawClearGround(tile) == CLEAR_ROUGH ? TREE_GROUND_ROUGH_SNOW : TREE_GROUND_SNOW_DESERT; break;
110 default: ground = TREE_GROUND_SNOW_DESERT; break;
112 if (GetClearGround(tile) != CLEAR_ROUGH) density = GetClearDensity(tile);
113 break;
115 default: NOT_REACHED();
118 MakeTree(tile, treetype, count, growth, ground, density);
122 * Get a random TreeType for the given tile based on a given seed
124 * This function returns a random TreeType which can be placed on the given tile.
125 * The seed for randomness must be less or equal 256, use #GB on the value of Random()
126 * to get such a value.
128 * @param tile The tile to get a random TreeType from
129 * @param seed The seed for randomness, must be less or equal 256
130 * @return The random tree type
132 static TreeType GetRandomTreeType(TileIndex tile, uint seed)
134 switch (_settings_game.game_creation.landscape) {
135 case LT_TEMPERATE:
136 return (TreeType)(seed * TREE_COUNT_TEMPERATE / 256 + TREE_TEMPERATE);
138 case LT_ARCTIC:
139 return (TreeType)(seed * TREE_COUNT_SUB_ARCTIC / 256 + TREE_SUB_ARCTIC);
141 case LT_TROPIC:
142 switch (GetTropicZone(tile)) {
143 case TROPICZONE_NORMAL: return (TreeType)(seed * TREE_COUNT_SUB_TROPICAL / 256 + TREE_SUB_TROPICAL);
144 case TROPICZONE_DESERT: return (TreeType)((seed > 12) ? TREE_INVALID : TREE_CACTUS);
145 default: return (TreeType)(seed * TREE_COUNT_RAINFOREST / 256 + TREE_RAINFOREST);
148 default:
149 return (TreeType)(seed * TREE_COUNT_TOYLAND / 256 + TREE_TOYLAND);
154 * Make a random tree tile of the given tile
156 * Create a new tree-tile for the given tile. The second parameter is used for
157 * randomness like type and number of trees.
159 * @param tile The tile to make a tree-tile from
160 * @param r The randomness value from a Random() value
162 static void PlaceTree(TileIndex tile, uint32 r)
164 TreeType tree = GetRandomTreeType(tile, GB(r, 24, 8));
166 if (tree != TREE_INVALID) {
167 PlantTreesOnTile(tile, tree, GB(r, 22, 2), std::min<byte>(GB(r, 16, 3), 6));
168 MarkTileDirtyByTile(tile);
170 /* Rerandomize ground, if neither snow nor shore */
171 TreeGround ground = GetTreeGround(tile);
172 if (ground != TREE_GROUND_SNOW_DESERT && ground != TREE_GROUND_ROUGH_SNOW && ground != TREE_GROUND_SHORE) {
173 SetTreeGroundDensity(tile, (TreeGround)GB(r, 28, 1), 3);
176 /* Set the counter to a random start value */
177 SetTreeCounter(tile, (TreeGround)GB(r, 24, 4));
182 * Creates a number of tree groups.
183 * The number of trees in each group depends on how many trees are actually placed around the given tile.
185 * @param num_groups Number of tree groups to place.
187 static void PlaceTreeGroups(uint num_groups)
189 do {
190 TileIndex center_tile = RandomTile();
192 for (uint i = 0; i < DEFAULT_TREE_STEPS; i++) {
193 uint32 r = Random();
194 int x = GB(r, 0, 5) - 16;
195 int y = GB(r, 8, 5) - 16;
196 uint dist = abs(x) + abs(y);
197 TileIndex cur_tile = TileAddWrap(center_tile, x, y);
199 IncreaseGeneratingWorldProgress(GWP_TREE);
201 if (cur_tile != INVALID_TILE && dist <= 13 && CanPlantTreesOnTile(cur_tile, true)) {
202 PlaceTree(cur_tile, r);
206 } while (--num_groups);
210 * Place a tree at the same height as an existing tree.
212 * Add a new tree around the given tile which is at the same
213 * height or at some offset (2 units) of it.
215 * @param tile The base tile to add a new tree somewhere around
216 * @param height The height (like the one from the tile)
218 static void PlaceTreeAtSameHeight(TileIndex tile, int height)
220 for (uint i = 0; i < DEFAULT_TREE_STEPS; i++) {
221 uint32 r = Random();
222 int x = GB(r, 0, 5) - 16;
223 int y = GB(r, 8, 5) - 16;
224 TileIndex cur_tile = TileAddWrap(tile, x, y);
225 if (cur_tile == INVALID_TILE) continue;
227 /* Keep in range of the existing tree */
228 if (abs(x) + abs(y) > 16) continue;
230 /* Clear tile, no farm-tiles or rocks */
231 if (!CanPlantTreesOnTile(cur_tile, true)) continue;
233 /* Not too much height difference */
234 if (Delta(GetTileZ(cur_tile), height) > 2) continue;
236 /* Place one tree and quit */
237 PlaceTree(cur_tile, r);
238 break;
243 * Place some trees randomly
245 * This function just place some trees randomly on the map.
247 void PlaceTreesRandomly()
249 int i, j, ht;
251 i = ScaleByMapSize(DEFAULT_TREE_STEPS);
252 if (_game_mode == GM_EDITOR) i /= EDITOR_TREE_DIV;
253 do {
254 uint32 r = Random();
255 TileIndex tile = RandomTileSeed(r);
257 IncreaseGeneratingWorldProgress(GWP_TREE);
259 if (CanPlantTreesOnTile(tile, true)) {
260 PlaceTree(tile, r);
261 if (_settings_game.game_creation.tree_placer != TP_IMPROVED) continue;
263 /* Place a number of trees based on the tile height.
264 * This gives a cool effect of multiple trees close together.
265 * It is almost real life ;) */
266 ht = GetTileZ(tile);
267 /* The higher we get, the more trees we plant */
268 j = GetTileZ(tile) * 2;
269 /* Above snowline more trees! */
270 if (_settings_game.game_creation.landscape == LT_ARCTIC && ht > GetSnowLine()) j *= 3;
271 while (j--) {
272 PlaceTreeAtSameHeight(tile, ht);
275 } while (--i);
277 /* place extra trees at rainforest area */
278 if (_settings_game.game_creation.landscape == LT_TROPIC) {
279 i = ScaleByMapSize(DEFAULT_RAINFOREST_TREE_STEPS);
280 if (_game_mode == GM_EDITOR) i /= EDITOR_TREE_DIV;
282 do {
283 uint32 r = Random();
284 TileIndex tile = RandomTileSeed(r);
286 IncreaseGeneratingWorldProgress(GWP_TREE);
288 if (GetTropicZone(tile) == TROPICZONE_RAINFOREST && CanPlantTreesOnTile(tile, false)) {
289 PlaceTree(tile, r);
291 } while (--i);
296 * Place some trees in a radius around a tile.
297 * The trees are placed in an quasi-normal distribution around the indicated tile, meaning that while
298 * the radius does define a square, the distribution inside the square will be roughly circular.
299 * @note This function the interactive RNG and must only be used in editor and map generation.
300 * @param tile Tile to place trees around.
301 * @param treetype Type of trees to place. Must be a valid tree type for the climate.
302 * @param radius Maximum distance (on each axis) from tile to place trees.
303 * @param count Maximum number of trees to place.
304 * @return Number of trees actually placed.
306 uint PlaceTreeGroupAroundTile(TileIndex tile, TreeType treetype, uint radius, uint count)
308 assert(treetype < TREE_TOYLAND + TREE_COUNT_TOYLAND);
309 const bool allow_desert = treetype == TREE_CACTUS;
310 uint planted = 0;
312 for (; count > 0; count--) {
313 /* Simple quasi-normal distribution with range [-radius; radius) */
314 auto mkcoord = [&]() -> int32 {
315 const uint32 rand = InteractiveRandom();
316 const int32 dist = GB<int32>(rand, 0, 8) + GB<int32>(rand, 8, 8) + GB<int32>(rand, 16, 8) + GB<int32>(rand, 24, 8);
317 const int32 scu = dist * radius / 512;
318 return scu - radius;
320 const int32 xofs = mkcoord();
321 const int32 yofs = mkcoord();
322 const TileIndex tile_to_plant = TileAddWrap(tile, xofs, yofs);
323 if (tile_to_plant != INVALID_TILE) {
324 if (IsTileType(tile_to_plant, MP_TREES) && GetTreeCount(tile_to_plant) < 4) {
325 AddTreeCount(tile_to_plant, 1);
326 SetTreeGrowth(tile_to_plant, 0);
327 MarkTileDirtyByTile(tile_to_plant, 0);
328 planted++;
329 } else if (CanPlantTreesOnTile(tile_to_plant, allow_desert)) {
330 PlantTreesOnTile(tile_to_plant, treetype, 0, 3);
331 MarkTileDirtyByTile(tile_to_plant, 0);
332 planted++;
337 return planted;
341 * Place new trees.
343 * This function takes care of the selected tree placer algorithm and
344 * place randomly the trees for a new game.
346 void GenerateTrees()
348 uint i, total;
350 if (_settings_game.game_creation.tree_placer == TP_NONE) return;
352 switch (_settings_game.game_creation.tree_placer) {
353 case TP_ORIGINAL: i = _settings_game.game_creation.landscape == LT_ARCTIC ? 15 : 6; break;
354 case TP_IMPROVED: i = _settings_game.game_creation.landscape == LT_ARCTIC ? 4 : 2; break;
355 default: NOT_REACHED();
358 total = ScaleByMapSize(DEFAULT_TREE_STEPS);
359 if (_settings_game.game_creation.landscape == LT_TROPIC) total += ScaleByMapSize(DEFAULT_RAINFOREST_TREE_STEPS);
360 total *= i;
361 uint num_groups = (_settings_game.game_creation.landscape != LT_TOYLAND) ? ScaleByMapSize(GB(Random(), 0, 5) + 25) : 0;
362 total += num_groups * DEFAULT_TREE_STEPS;
363 SetGeneratingWorldProgress(GWP_TREE, total);
365 if (num_groups != 0) PlaceTreeGroups(num_groups);
367 for (; i != 0; i--) {
368 PlaceTreesRandomly();
373 * Plant a tree.
374 * @param tile end tile of area-drag
375 * @param flags type of operation
376 * @param p1 tree type, TREE_INVALID means random.
377 * @param p2 start tile of area-drag of tree plantation
378 * @param text unused
379 * @return the cost of this operation or an error
381 CommandCost CmdPlantTree(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text)
383 StringID msg = INVALID_STRING_ID;
384 CommandCost cost(EXPENSES_OTHER);
385 const byte tree_to_plant = GB(p1, 0, 8); // We cannot use Extract as min and max are climate specific.
387 if (p2 >= MapSize()) return CMD_ERROR;
388 /* Check the tree type within the current climate */
389 if (tree_to_plant != TREE_INVALID && !IsInsideBS(tree_to_plant, _tree_base_by_landscape[_settings_game.game_creation.landscape], _tree_count_by_landscape[_settings_game.game_creation.landscape])) return CMD_ERROR;
391 Company *c = (_game_mode != GM_EDITOR) ? Company::GetIfValid(_current_company) : nullptr;
392 int limit = (c == nullptr ? INT32_MAX : GB(c->tree_limit, 16, 16));
394 TileArea ta(tile, p2);
395 for (TileIndex current_tile : ta) {
396 switch (GetTileType(current_tile)) {
397 case MP_TREES:
398 /* no more space for trees? */
399 if (GetTreeCount(current_tile) == 4) {
400 msg = STR_ERROR_TREE_ALREADY_HERE;
401 continue;
404 /* Test tree limit. */
405 if (--limit < 1) {
406 msg = STR_ERROR_TREE_PLANT_LIMIT_REACHED;
407 break;
410 if (flags & DC_EXEC) {
411 AddTreeCount(current_tile, 1);
412 MarkTileDirtyByTile(current_tile);
413 if (c != nullptr) c->tree_limit -= 1 << 16;
415 /* 2x as expensive to add more trees to an existing tile */
416 cost.AddCost(_price[PR_BUILD_TREES] * 2);
417 break;
419 case MP_WATER:
420 if (!IsCoast(current_tile) || IsSlopeWithOneCornerRaised(GetTileSlope(current_tile))) {
421 msg = STR_ERROR_CAN_T_BUILD_ON_WATER;
422 continue;
424 FALLTHROUGH;
426 case MP_CLEAR: {
427 if (IsBridgeAbove(current_tile)) {
428 msg = STR_ERROR_SITE_UNSUITABLE;
429 continue;
432 TreeType treetype = (TreeType)tree_to_plant;
433 /* Be a bit picky about which trees go where. */
434 if (_settings_game.game_creation.landscape == LT_TROPIC && treetype != TREE_INVALID && (
435 /* No cacti outside the desert */
436 (treetype == TREE_CACTUS && GetTropicZone(current_tile) != TROPICZONE_DESERT) ||
437 /* No rain forest trees outside the rain forest, except in the editor mode where it makes those tiles rain forest tile */
438 (IsInsideMM(treetype, TREE_RAINFOREST, TREE_CACTUS) && GetTropicZone(current_tile) != TROPICZONE_RAINFOREST && _game_mode != GM_EDITOR) ||
439 /* And no subtropical trees in the desert/rain forest */
440 (IsInsideMM(treetype, TREE_SUB_TROPICAL, TREE_TOYLAND) && GetTropicZone(current_tile) != TROPICZONE_NORMAL))) {
441 msg = STR_ERROR_TREE_WRONG_TERRAIN_FOR_TREE_TYPE;
442 continue;
445 /* Test tree limit. */
446 if (--limit < 1) {
447 msg = STR_ERROR_TREE_PLANT_LIMIT_REACHED;
448 break;
451 if (IsTileType(current_tile, MP_CLEAR)) {
452 /* Remove fields or rocks. Note that the ground will get barrened */
453 switch (GetRawClearGround(current_tile)) {
454 case CLEAR_FIELDS:
455 case CLEAR_ROCKS: {
456 CommandCost ret = DoCommand(current_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
457 if (ret.Failed()) return ret;
458 cost.AddCost(ret);
459 break;
462 default: break;
466 if (_game_mode != GM_EDITOR && Company::IsValidID(_current_company)) {
467 Town *t = ClosestTownFromTile(current_tile, _settings_game.economy.dist_local_authority);
468 if (t != nullptr) ChangeTownRating(t, RATING_TREE_UP_STEP, RATING_TREE_MAXIMUM, flags);
471 if (flags & DC_EXEC) {
472 if (treetype == TREE_INVALID) {
473 treetype = GetRandomTreeType(current_tile, GB(Random(), 24, 8));
474 if (treetype == TREE_INVALID) treetype = TREE_CACTUS;
477 /* Plant full grown trees in scenario editor */
478 PlantTreesOnTile(current_tile, treetype, 0, _game_mode == GM_EDITOR ? 3 : 0);
479 MarkTileDirtyByTile(current_tile);
480 if (c != nullptr) c->tree_limit -= 1 << 16;
482 /* When planting rainforest-trees, set tropiczone to rainforest in editor. */
483 if (_game_mode == GM_EDITOR && IsInsideMM(treetype, TREE_RAINFOREST, TREE_CACTUS)) {
484 SetTropicZone(current_tile, TROPICZONE_RAINFOREST);
487 cost.AddCost(_price[PR_BUILD_TREES]);
488 break;
491 default:
492 msg = STR_ERROR_SITE_UNSUITABLE;
493 break;
496 /* Tree limit used up? No need to check more. */
497 if (limit < 0) break;
500 if (cost.GetCost() == 0) {
501 return_cmd_error(msg);
502 } else {
503 return cost;
507 struct TreeListEnt : PalSpriteID {
508 byte x, y;
511 static void DrawTile_Trees(TileInfo *ti)
513 switch (GetTreeGround(ti->tile)) {
514 case TREE_GROUND_SHORE: DrawShoreTile(ti->tileh); break;
515 case TREE_GROUND_GRASS: DrawClearLandTile(ti, GetTreeDensity(ti->tile)); break;
516 case TREE_GROUND_ROUGH: DrawHillyLandTile(ti); break;
517 default: DrawGroundSprite(_clear_land_sprites_snow_desert[GetTreeDensity(ti->tile)] + SlopeToSpriteOffset(ti->tileh), PAL_NONE); break;
520 /* Do not draw trees when the invisible trees setting is set */
521 if (IsInvisibilitySet(TO_TREES)) return;
523 uint tmp = CountBits(ti->tile + ti->x + ti->y);
524 uint index = GB(tmp, 0, 2) + (GetTreeType(ti->tile) << 2);
526 /* different tree styles above one of the grounds */
527 if ((GetTreeGround(ti->tile) == TREE_GROUND_SNOW_DESERT || GetTreeGround(ti->tile) == TREE_GROUND_ROUGH_SNOW) &&
528 GetTreeDensity(ti->tile) >= 2 &&
529 IsInsideMM(index, TREE_SUB_ARCTIC << 2, TREE_RAINFOREST << 2)) {
530 index += 164 - (TREE_SUB_ARCTIC << 2);
533 assert(index < lengthof(_tree_layout_sprite));
535 const PalSpriteID *s = _tree_layout_sprite[index];
536 const TreePos *d = _tree_layout_xy[GB(tmp, 2, 2)];
538 /* combine trees into one sprite object */
539 StartSpriteCombine();
541 TreeListEnt te[4];
543 /* put the trees to draw in a list */
544 uint trees = GetTreeCount(ti->tile);
546 for (uint i = 0; i < trees; i++) {
547 SpriteID sprite = s[0].sprite + (i == trees - 1 ? GetTreeGrowth(ti->tile) : 3);
548 PaletteID pal = s[0].pal;
550 te[i].sprite = sprite;
551 te[i].pal = pal;
552 te[i].x = d->x;
553 te[i].y = d->y;
554 s++;
555 d++;
558 /* draw them in a sorted way */
559 int z = ti->z + GetSlopeMaxPixelZ(ti->tileh) / 2;
561 for (; trees > 0; trees--) {
562 uint min = te[0].x + te[0].y;
563 uint mi = 0;
565 for (uint i = 1; i < trees; i++) {
566 if ((uint)(te[i].x + te[i].y) < min) {
567 min = te[i].x + te[i].y;
568 mi = i;
572 AddSortableSpriteToDraw(te[mi].sprite, te[mi].pal, ti->x + te[mi].x, ti->y + te[mi].y, 16 - te[mi].x, 16 - te[mi].y, 0x30, z, IsTransparencySet(TO_TREES), -te[mi].x, -te[mi].y);
574 /* replace the removed one with the last one */
575 te[mi] = te[trees - 1];
578 EndSpriteCombine();
582 static int GetSlopePixelZ_Trees(TileIndex tile, uint x, uint y)
584 int z;
585 Slope tileh = GetTilePixelSlope(tile, &z);
587 return z + GetPartialPixelZ(x & 0xF, y & 0xF, tileh);
590 static Foundation GetFoundation_Trees(TileIndex tile, Slope tileh)
592 return FOUNDATION_NONE;
595 static CommandCost ClearTile_Trees(TileIndex tile, DoCommandFlag flags)
597 uint num;
599 if (Company::IsValidID(_current_company)) {
600 Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
601 if (t != nullptr) ChangeTownRating(t, RATING_TREE_DOWN_STEP, RATING_TREE_MINIMUM, flags);
604 num = GetTreeCount(tile);
605 if (IsInsideMM(GetTreeType(tile), TREE_RAINFOREST, TREE_CACTUS)) num *= 4;
607 if (flags & DC_EXEC) DoClearSquare(tile);
609 return CommandCost(EXPENSES_CONSTRUCTION, num * _price[PR_CLEAR_TREES]);
612 static void GetTileDesc_Trees(TileIndex tile, TileDesc *td)
614 TreeType tt = GetTreeType(tile);
616 if (IsInsideMM(tt, TREE_RAINFOREST, TREE_CACTUS)) {
617 td->str = STR_LAI_TREE_NAME_RAINFOREST;
618 } else {
619 td->str = tt == TREE_CACTUS ? STR_LAI_TREE_NAME_CACTUS_PLANTS : STR_LAI_TREE_NAME_TREES;
622 td->owner[0] = GetTileOwner(tile);
625 static void TileLoopTreesDesert(TileIndex tile)
627 switch (GetTropicZone(tile)) {
628 case TROPICZONE_DESERT:
629 if (GetTreeGround(tile) != TREE_GROUND_SNOW_DESERT) {
630 SetTreeGroundDensity(tile, TREE_GROUND_SNOW_DESERT, 3);
631 MarkTileDirtyByTile(tile);
633 break;
635 case TROPICZONE_RAINFOREST: {
636 static const SoundFx forest_sounds[] = {
637 SND_42_RAINFOREST_1,
638 SND_43_RAINFOREST_2,
639 SND_44_RAINFOREST_3,
640 SND_48_RAINFOREST_4
642 uint32 r = Random();
644 if (Chance16I(1, 200, r) && _settings_client.sound.ambient) SndPlayTileFx(forest_sounds[GB(r, 16, 2)], tile);
645 break;
648 default: break;
652 static void TileLoopTreesAlps(TileIndex tile)
654 int k = GetTileZ(tile) - GetSnowLine() + 1;
656 if (k < 0) {
657 switch (GetTreeGround(tile)) {
658 case TREE_GROUND_SNOW_DESERT: SetTreeGroundDensity(tile, TREE_GROUND_GRASS, 3); break;
659 case TREE_GROUND_ROUGH_SNOW: SetTreeGroundDensity(tile, TREE_GROUND_ROUGH, 3); break;
660 default: return;
662 } else {
663 uint density = std::min<uint>(k, 3);
665 if (GetTreeGround(tile) != TREE_GROUND_SNOW_DESERT && GetTreeGround(tile) != TREE_GROUND_ROUGH_SNOW) {
666 TreeGround tg = GetTreeGround(tile) == TREE_GROUND_ROUGH ? TREE_GROUND_ROUGH_SNOW : TREE_GROUND_SNOW_DESERT;
667 SetTreeGroundDensity(tile, tg, density);
668 } else if (GetTreeDensity(tile) != density) {
669 SetTreeGroundDensity(tile, GetTreeGround(tile), density);
670 } else {
671 if (GetTreeDensity(tile) == 3) {
672 uint32 r = Random();
673 if (Chance16I(1, 200, r) && _settings_client.sound.ambient) {
674 SndPlayTileFx((r & 0x80000000) ? SND_39_ARCTIC_SNOW_2 : SND_34_ARCTIC_SNOW_1, tile);
677 return;
680 MarkTileDirtyByTile(tile);
683 static bool CanPlantExtraTrees(TileIndex tile)
685 return ((_settings_game.game_creation.landscape == LT_TROPIC && GetTropicZone(tile) == TROPICZONE_RAINFOREST) ?
686 (_settings_game.construction.extra_tree_placement == ETP_SPREAD_ALL || _settings_game.construction.extra_tree_placement == ETP_SPREAD_RAINFOREST) :
687 _settings_game.construction.extra_tree_placement == ETP_SPREAD_ALL);
690 static void TileLoop_Trees(TileIndex tile)
692 if (GetTreeGround(tile) == TREE_GROUND_SHORE) {
693 TileLoop_Water(tile);
694 } else {
695 switch (_settings_game.game_creation.landscape) {
696 case LT_TROPIC: TileLoopTreesDesert(tile); break;
697 case LT_ARCTIC: TileLoopTreesAlps(tile); break;
701 AmbientSoundEffect(tile);
703 uint treeCounter = GetTreeCounter(tile);
705 /* Handle growth of grass (under trees/on MP_TREES tiles) at every 8th processings, like it's done for grass on MP_CLEAR tiles. */
706 if ((treeCounter & 7) == 7 && GetTreeGround(tile) == TREE_GROUND_GRASS) {
707 uint density = GetTreeDensity(tile);
708 if (density < 3) {
709 SetTreeGroundDensity(tile, TREE_GROUND_GRASS, density + 1);
710 MarkTileDirtyByTile(tile);
714 if (_settings_game.construction.extra_tree_placement == ETP_NO_GROWTH_NO_SPREAD) return;
716 if (GetTreeCounter(tile) < 15) {
717 AddTreeCounter(tile, 1);
718 return;
720 SetTreeCounter(tile, 0);
722 switch (GetTreeGrowth(tile)) {
723 case 3: // regular sized tree
724 if (_settings_game.game_creation.landscape == LT_TROPIC &&
725 GetTreeType(tile) != TREE_CACTUS &&
726 GetTropicZone(tile) == TROPICZONE_DESERT) {
727 AddTreeGrowth(tile, 1);
728 } else {
729 switch (GB(Random(), 0, 3)) {
730 case 0: // start destructing
731 AddTreeGrowth(tile, 1);
732 break;
734 case 1: // add a tree
735 if (GetTreeCount(tile) < 4 && CanPlantExtraTrees(tile)) {
736 AddTreeCount(tile, 1);
737 SetTreeGrowth(tile, 0);
738 break;
740 FALLTHROUGH;
742 case 2: { // add a neighbouring tree
743 if (!CanPlantExtraTrees(tile)) break;
745 TreeType treetype = GetTreeType(tile);
747 tile += TileOffsByDir((Direction)(Random() & 7));
749 /* Cacti don't spread */
750 if (!CanPlantTreesOnTile(tile, false)) return;
752 /* Don't plant trees, if ground was freshly cleared */
753 if (IsTileType(tile, MP_CLEAR) && GetClearGround(tile) == CLEAR_GRASS && GetClearDensity(tile) != 3) return;
755 PlantTreesOnTile(tile, treetype, 0, 0);
757 break;
760 default:
761 return;
764 break;
766 case 6: // final stage of tree destruction
767 if (!CanPlantExtraTrees(tile)) {
768 /* if trees can't spread just plant a new one to prevent deforestation */
769 SetTreeGrowth(tile, 0);
770 } else if (GetTreeCount(tile) > 1) {
771 /* more than one tree, delete it */
772 AddTreeCount(tile, -1);
773 SetTreeGrowth(tile, 3);
774 } else {
775 /* just one tree, change type into MP_CLEAR */
776 switch (GetTreeGround(tile)) {
777 case TREE_GROUND_SHORE: MakeShore(tile); break;
778 case TREE_GROUND_GRASS: MakeClear(tile, CLEAR_GRASS, GetTreeDensity(tile)); break;
779 case TREE_GROUND_ROUGH: MakeClear(tile, CLEAR_ROUGH, 3); break;
780 case TREE_GROUND_ROUGH_SNOW: {
781 uint density = GetTreeDensity(tile);
782 MakeClear(tile, CLEAR_ROUGH, 3);
783 MakeSnow(tile, density);
784 break;
786 default: // snow or desert
787 if (_settings_game.game_creation.landscape == LT_TROPIC) {
788 MakeClear(tile, CLEAR_DESERT, GetTreeDensity(tile));
789 } else {
790 uint density = GetTreeDensity(tile);
791 MakeClear(tile, CLEAR_GRASS, 3);
792 MakeSnow(tile, density);
794 break;
797 break;
799 default:
800 AddTreeGrowth(tile, 1);
801 break;
804 MarkTileDirtyByTile(tile);
808 * Decrement the tree tick counter.
809 * The interval is scaled by map size to allow for the same density regardless of size.
810 * Adjustment for map sizes below the standard 256 * 256 are handled earlier.
811 * @return true if the counter was decremented past zero
813 bool DecrementTreeCounter()
815 /* Ensure _trees_tick_ctr can be decremented past zero only once for the largest map size. */
816 static_assert(2 * (MAX_MAP_SIZE_BITS - MIN_MAP_SIZE_BITS) - 4 <= std::numeric_limits<byte>::digits);
818 /* byte underflow */
819 byte old_trees_tick_ctr = _trees_tick_ctr;
820 _trees_tick_ctr -= ScaleByMapSize(1);
821 return old_trees_tick_ctr <= _trees_tick_ctr;
824 void OnTick_Trees()
826 /* Don't spread trees if that's not allowed */
827 if (_settings_game.construction.extra_tree_placement == ETP_NO_SPREAD || _settings_game.construction.extra_tree_placement == ETP_NO_GROWTH_NO_SPREAD) return;
829 uint32 r;
830 TileIndex tile;
831 TreeType tree;
833 /* Skip some tree ticks for map sizes below 256 * 256. 64 * 64 is 16 times smaller, so
834 * this is the maximum number of ticks that are skipped. Number of ticks to skip is
835 * inversely proportional to map size, so that is handled to create a mask. */
836 int skip = ScaleByMapSize(16);
837 if (skip < 16 && (_tick_counter & (16 / skip - 1)) != 0) return;
839 /* place a tree at a random rainforest spot */
840 if (_settings_game.game_creation.landscape == LT_TROPIC) {
841 for (uint c = ScaleByMapSize(1); c > 0; c--) {
842 if ((r = Random(), tile = RandomTileSeed(r), GetTropicZone(tile) == TROPICZONE_RAINFOREST) &&
843 CanPlantTreesOnTile(tile, false) &&
844 (tree = GetRandomTreeType(tile, GB(r, 24, 8))) != TREE_INVALID) {
845 PlantTreesOnTile(tile, tree, 0, 0);
850 if (!DecrementTreeCounter() || _settings_game.construction.extra_tree_placement == ETP_SPREAD_RAINFOREST) return;
852 /* place a tree at a random spot */
853 r = Random();
854 tile = RandomTileSeed(r);
855 if (CanPlantTreesOnTile(tile, false) && (tree = GetRandomTreeType(tile, GB(r, 24, 8))) != TREE_INVALID) {
856 PlantTreesOnTile(tile, tree, 0, 0);
860 static TrackStatus GetTileTrackStatus_Trees(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
862 return 0;
865 static void ChangeTileOwner_Trees(TileIndex tile, Owner old_owner, Owner new_owner)
867 /* not used */
870 void InitializeTrees()
872 _trees_tick_ctr = 0;
875 static CommandCost TerraformTile_Trees(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
877 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
881 extern const TileTypeProcs _tile_type_trees_procs = {
882 DrawTile_Trees, // draw_tile_proc
883 GetSlopePixelZ_Trees, // get_slope_z_proc
884 ClearTile_Trees, // clear_tile_proc
885 nullptr, // add_accepted_cargo_proc
886 GetTileDesc_Trees, // get_tile_desc_proc
887 GetTileTrackStatus_Trees, // get_tile_track_status_proc
888 nullptr, // click_tile_proc
889 nullptr, // animate_tile_proc
890 TileLoop_Trees, // tile_loop_proc
891 ChangeTileOwner_Trees, // change_tile_owner_proc
892 nullptr, // add_produced_cargo_proc
893 nullptr, // vehicle_enter_tile_proc
894 GetFoundation_Trees, // get_foundation_proc
895 TerraformTile_Trees, // terraform_tile_proc