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/>.
8 /** @file tree_cmd.cpp Handling of tree tiles. */
11 #include "clear_map.h"
12 #include "landscape.h"
14 #include "viewport_func.h"
15 #include "command_func.h"
18 #include "clear_func.h"
19 #include "company_func.h"
20 #include "sound_func.h"
22 #include "company_base.h"
23 #include "core/random_func.hpp"
24 #include "newgrf_generic.h"
25 #include "timer/timer_game_tick.h"
27 #include "landscape_cmd.h"
29 #include "table/strings.h"
30 #include "table/tree_land.h"
31 #include "table/clear_land.h"
33 #include "safeguards.h"
36 * List of tree placer algorithm.
38 * This enumeration defines all possible tree placer algorithm in the game.
41 TP_NONE
, ///< No tree placer algorithm
42 TP_ORIGINAL
, ///< The original algorithm
43 TP_IMPROVED
, ///< A 'improved' algorithm
46 /** Where to place trees while in-game? */
47 enum ExtraTreePlacement
{
48 ETP_NO_SPREAD
, ///< Grow trees on tiles that have them but don't spread to new ones
49 ETP_SPREAD_RAINFOREST
, ///< Grow trees on tiles that have them, only spread to new ones in rainforests
50 ETP_SPREAD_ALL
, ///< Grow trees and spread them without restrictions
51 ETP_NO_GROWTH_NO_SPREAD
, ///< Don't grow trees and don't spread them at all
54 /** Determines when to consider building more trees. */
55 uint8_t _trees_tick_ctr
;
57 static const uint16_t DEFAULT_TREE_STEPS
= 1000; ///< Default number of attempts for placing trees.
58 static const uint16_t DEFAULT_RAINFOREST_TREE_STEPS
= 15000; ///< Default number of attempts for placing extra trees at rainforest in tropic.
59 static const uint16_t EDITOR_TREE_DIV
= 5; ///< Game editor tree generation divisor factor.
62 * Tests if a tile can be converted to MP_TREES
63 * This is true for clear ground without farms or rocks.
65 * @param tile the tile of interest
66 * @param allow_desert Allow planting trees on CLEAR_DESERT?
67 * @return true if trees can be built.
69 static bool CanPlantTreesOnTile(TileIndex tile
, bool allow_desert
)
71 switch (GetTileType(tile
)) {
73 return !IsBridgeAbove(tile
) && IsCoast(tile
) && !IsSlopeWithOneCornerRaised(GetTileSlope(tile
));
76 return !IsBridgeAbove(tile
) && !IsClearGround(tile
, CLEAR_FIELDS
) && GetRawClearGround(tile
) != CLEAR_ROCKS
&&
77 (allow_desert
|| !IsClearGround(tile
, CLEAR_DESERT
));
79 default: return false;
85 * Ground type and density is preserved.
87 * @pre the tile must be suitable for trees.
89 * @param tile where to plant the trees.
90 * @param treetype The type of the tree
91 * @param count the number of trees (minus 1)
92 * @param growth the growth status
94 static void PlantTreesOnTile(TileIndex tile
, TreeType treetype
, uint count
, TreeGrowthStage growth
)
96 assert(treetype
!= TREE_INVALID
);
97 assert(CanPlantTreesOnTile(tile
, true));
102 switch (GetTileType(tile
)) {
104 ground
= TREE_GROUND_SHORE
;
105 ClearNeighbourNonFloodingStates(tile
);
109 switch (GetClearGround(tile
)) {
110 case CLEAR_GRASS
: ground
= TREE_GROUND_GRASS
; break;
111 case CLEAR_ROUGH
: ground
= TREE_GROUND_ROUGH
; break;
112 case CLEAR_SNOW
: ground
= GetRawClearGround(tile
) == CLEAR_ROUGH
? TREE_GROUND_ROUGH_SNOW
: TREE_GROUND_SNOW_DESERT
; break;
113 default: ground
= TREE_GROUND_SNOW_DESERT
; break;
115 if (GetClearGround(tile
) != CLEAR_ROUGH
) density
= GetClearDensity(tile
);
118 default: NOT_REACHED();
121 MakeTree(tile
, treetype
, count
, growth
, ground
, density
);
125 * Get a random TreeType for the given tile based on a given seed
127 * This function returns a random TreeType which can be placed on the given tile.
128 * The seed for randomness must be less or equal 256, use #GB on the value of Random()
129 * to get such a value.
131 * @param tile The tile to get a random TreeType from
132 * @param seed The seed for randomness, must be less or equal 256
133 * @return The random tree type
135 static TreeType
GetRandomTreeType(TileIndex tile
, uint seed
)
137 switch (_settings_game
.game_creation
.landscape
) {
139 return static_cast<TreeType
>(seed
* TREE_COUNT_TEMPERATE
/ 256 + TREE_TEMPERATE
);
142 return static_cast<TreeType
>(seed
* TREE_COUNT_SUB_ARCTIC
/ 256 + TREE_SUB_ARCTIC
);
145 switch (GetTropicZone(tile
)) {
146 case TROPICZONE_NORMAL
: return static_cast<TreeType
>(seed
* TREE_COUNT_SUB_TROPICAL
/ 256 + TREE_SUB_TROPICAL
);
147 case TROPICZONE_DESERT
: return static_cast<TreeType
>((seed
> 12) ? TREE_INVALID
: TREE_CACTUS
);
148 default: return static_cast<TreeType
>(seed
* TREE_COUNT_RAINFOREST
/ 256 + TREE_RAINFOREST
);
152 return static_cast<TreeType
>(seed
* TREE_COUNT_TOYLAND
/ 256 + TREE_TOYLAND
);
157 * Make a random tree tile of the given tile
159 * Create a new tree-tile for the given tile. The second parameter is used for
160 * randomness like type and number of trees.
162 * @param tile The tile to make a tree-tile from
163 * @param r The randomness value from a Random() value
165 static void PlaceTree(TileIndex tile
, uint32_t r
)
167 TreeType tree
= GetRandomTreeType(tile
, GB(r
, 24, 8));
169 if (tree
!= TREE_INVALID
) {
170 PlantTreesOnTile(tile
, tree
, GB(r
, 22, 2), static_cast<TreeGrowthStage
>(std::min
<uint8_t>(GB(r
, 16, 3), 6)));
171 MarkTileDirtyByTile(tile
);
173 /* Rerandomize ground, if neither snow nor shore */
174 TreeGround ground
= GetTreeGround(tile
);
175 if (ground
!= TREE_GROUND_SNOW_DESERT
&& ground
!= TREE_GROUND_ROUGH_SNOW
&& ground
!= TREE_GROUND_SHORE
) {
176 SetTreeGroundDensity(tile
, (TreeGround
)GB(r
, 28, 1), 3);
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
)
190 TileIndex center_tile
= RandomTile();
192 for (uint i
= 0; i
< DEFAULT_TREE_STEPS
; i
++) {
193 uint32_t 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_t 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
);
243 * Place some trees randomly
245 * This function just place some trees randomly on the map.
247 void PlaceTreesRandomly()
251 i
= Map::ScaleBySize(DEFAULT_TREE_STEPS
);
252 if (_game_mode
== GM_EDITOR
) i
/= EDITOR_TREE_DIV
;
254 uint32_t r
= Random();
255 TileIndex tile
= RandomTileSeed(r
);
257 IncreaseGeneratingWorldProgress(GWP_TREE
);
259 if (CanPlantTreesOnTile(tile
, true)) {
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 ;) */
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;
272 PlaceTreeAtSameHeight(tile
, ht
);
277 /* place extra trees at rainforest area */
278 if (_settings_game
.game_creation
.landscape
== LT_TROPIC
) {
279 i
= Map::ScaleBySize(DEFAULT_RAINFOREST_TREE_STEPS
);
280 if (_game_mode
== GM_EDITOR
) i
/= EDITOR_TREE_DIV
;
283 uint32_t r
= Random();
284 TileIndex tile
= RandomTileSeed(r
);
286 IncreaseGeneratingWorldProgress(GWP_TREE
);
288 if (GetTropicZone(tile
) == TROPICZONE_RAINFOREST
&& CanPlantTreesOnTile(tile
, false)) {
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 * @param set_zone Whether to create a rainforest zone when placing rainforest trees.
305 * @return Number of trees actually placed.
307 uint
PlaceTreeGroupAroundTile(TileIndex tile
, TreeType treetype
, uint radius
, uint count
, bool set_zone
)
309 assert(_game_mode
== GM_EDITOR
); // Due to InteractiveRandom being used in this function
310 assert(treetype
< TREE_TOYLAND
+ TREE_COUNT_TOYLAND
);
311 const bool allow_desert
= treetype
== TREE_CACTUS
;
314 for (; count
> 0; count
--) {
315 /* Simple quasi-normal distribution with range [-radius; radius) */
316 auto mkcoord
= [&]() -> int32_t {
317 const uint32_t rand
= InteractiveRandom();
318 const int32_t dist
= GB
<int32_t>(rand
, 0, 8) + GB
<int32_t>(rand
, 8, 8) + GB
<int32_t>(rand
, 16, 8) + GB
<int32_t>(rand
, 24, 8);
319 const int32_t scu
= dist
* radius
/ 512;
322 const int32_t xofs
= mkcoord();
323 const int32_t yofs
= mkcoord();
324 const TileIndex tile_to_plant
= TileAddWrap(tile
, xofs
, yofs
);
325 if (tile_to_plant
!= INVALID_TILE
) {
326 if (IsTileType(tile_to_plant
, MP_TREES
) && GetTreeCount(tile_to_plant
) < 4) {
327 AddTreeCount(tile_to_plant
, 1);
328 SetTreeGrowth(tile_to_plant
, TreeGrowthStage::Growing1
);
329 MarkTileDirtyByTile(tile_to_plant
, 0);
331 } else if (CanPlantTreesOnTile(tile_to_plant
, allow_desert
)) {
332 PlantTreesOnTile(tile_to_plant
, treetype
, 0, TreeGrowthStage::Grown
);
333 MarkTileDirtyByTile(tile_to_plant
, 0);
339 if (set_zone
&& IsInsideMM(treetype
, TREE_RAINFOREST
, TREE_CACTUS
)) {
340 for (TileIndex t
: TileArea(tile
).Expand(radius
)) {
341 if (GetTileType(t
) != MP_VOID
&& DistanceSquare(tile
, t
) < radius
* radius
) SetTropicZone(t
, TROPICZONE_RAINFOREST
);
351 * This function takes care of the selected tree placer algorithm and
352 * place randomly the trees for a new game.
358 if (_settings_game
.game_creation
.tree_placer
== TP_NONE
) return;
360 switch (_settings_game
.game_creation
.tree_placer
) {
361 case TP_ORIGINAL
: i
= _settings_game
.game_creation
.landscape
== LT_ARCTIC
? 15 : 6; break;
362 case TP_IMPROVED
: i
= _settings_game
.game_creation
.landscape
== LT_ARCTIC
? 4 : 2; break;
363 default: NOT_REACHED();
366 total
= Map::ScaleBySize(DEFAULT_TREE_STEPS
);
367 if (_settings_game
.game_creation
.landscape
== LT_TROPIC
) total
+= Map::ScaleBySize(DEFAULT_RAINFOREST_TREE_STEPS
);
369 uint num_groups
= (_settings_game
.game_creation
.landscape
!= LT_TOYLAND
) ? Map::ScaleBySize(GB(Random(), 0, 5) + 25) : 0;
370 total
+= num_groups
* DEFAULT_TREE_STEPS
;
371 SetGeneratingWorldProgress(GWP_TREE
, total
);
373 if (num_groups
!= 0) PlaceTreeGroups(num_groups
);
375 for (; i
!= 0; i
--) {
376 PlaceTreesRandomly();
382 * @param flags type of operation
383 * @param tile end tile of area-drag
384 * @param start_tile start tile of area-drag of tree plantation
385 * @param tree_to_plant tree type, TREE_INVALID means random.
386 * @param diagonal Whether to use the Orthogonal (false) or Diagonal (true) iterator.
387 * @return the cost of this operation or an error
389 CommandCost
CmdPlantTree(DoCommandFlag flags
, TileIndex tile
, TileIndex start_tile
, uint8_t tree_to_plant
, bool diagonal
)
391 StringID msg
= INVALID_STRING_ID
;
392 CommandCost
cost(EXPENSES_OTHER
);
394 if (start_tile
>= Map::Size()) return CMD_ERROR
;
395 /* Check the tree type within the current climate */
396 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
;
398 Company
*c
= (_game_mode
!= GM_EDITOR
) ? Company::GetIfValid(_current_company
) : nullptr;
399 int limit
= (c
== nullptr ? INT32_MAX
: GB(c
->tree_limit
, 16, 16));
401 std::unique_ptr
<TileIterator
> iter
= TileIterator::Create(tile
, start_tile
, diagonal
);
402 for (; *iter
!= INVALID_TILE
; ++(*iter
)) {
403 TileIndex current_tile
= *iter
;
404 switch (GetTileType(current_tile
)) {
406 /* no more space for trees? */
407 if (GetTreeCount(current_tile
) == 4) {
408 msg
= STR_ERROR_TREE_ALREADY_HERE
;
412 /* Test tree limit. */
414 msg
= STR_ERROR_TREE_PLANT_LIMIT_REACHED
;
418 if (flags
& DC_EXEC
) {
419 AddTreeCount(current_tile
, 1);
420 MarkTileDirtyByTile(current_tile
);
421 if (c
!= nullptr) c
->tree_limit
-= 1 << 16;
423 /* 2x as expensive to add more trees to an existing tile */
424 cost
.AddCost(_price
[PR_BUILD_TREES
] * 2);
428 if (!IsCoast(current_tile
) || IsSlopeWithOneCornerRaised(GetTileSlope(current_tile
))) {
429 msg
= STR_ERROR_CAN_T_BUILD_ON_WATER
;
435 if (IsBridgeAbove(current_tile
)) {
436 msg
= STR_ERROR_SITE_UNSUITABLE
;
440 TreeType treetype
= (TreeType
)tree_to_plant
;
441 /* Be a bit picky about which trees go where. */
442 if (_settings_game
.game_creation
.landscape
== LT_TROPIC
&& treetype
!= TREE_INVALID
&& (
443 /* No cacti outside the desert */
444 (treetype
== TREE_CACTUS
&& GetTropicZone(current_tile
) != TROPICZONE_DESERT
) ||
445 /* No rain forest trees outside the rain forest, except in the editor mode where it makes those tiles rain forest tile */
446 (IsInsideMM(treetype
, TREE_RAINFOREST
, TREE_CACTUS
) && GetTropicZone(current_tile
) != TROPICZONE_RAINFOREST
&& _game_mode
!= GM_EDITOR
) ||
447 /* And no subtropical trees in the desert/rain forest */
448 (IsInsideMM(treetype
, TREE_SUB_TROPICAL
, TREE_TOYLAND
) && GetTropicZone(current_tile
) != TROPICZONE_NORMAL
))) {
449 msg
= STR_ERROR_TREE_WRONG_TERRAIN_FOR_TREE_TYPE
;
453 /* Test tree limit. */
455 msg
= STR_ERROR_TREE_PLANT_LIMIT_REACHED
;
459 if (IsTileType(current_tile
, MP_CLEAR
)) {
460 /* Remove fields or rocks. Note that the ground will get barrened */
461 switch (GetRawClearGround(current_tile
)) {
464 CommandCost ret
= Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
, current_tile
);
465 if (ret
.Failed()) return ret
;
474 if (_game_mode
!= GM_EDITOR
&& Company::IsValidID(_current_company
)) {
475 Town
*t
= ClosestTownFromTile(current_tile
, _settings_game
.economy
.dist_local_authority
);
476 if (t
!= nullptr) ChangeTownRating(t
, RATING_TREE_UP_STEP
, RATING_TREE_MAXIMUM
, flags
);
479 if (flags
& DC_EXEC
) {
480 if (treetype
== TREE_INVALID
) {
481 treetype
= GetRandomTreeType(current_tile
, GB(Random(), 24, 8));
482 if (treetype
== TREE_INVALID
) treetype
= TREE_CACTUS
;
485 /* Plant full grown trees in scenario editor */
486 PlantTreesOnTile(current_tile
, treetype
, 0, _game_mode
== GM_EDITOR
? TreeGrowthStage::Grown
: TreeGrowthStage::Growing1
);
487 MarkTileDirtyByTile(current_tile
);
488 if (c
!= nullptr) c
->tree_limit
-= 1 << 16;
490 /* When planting rainforest-trees, set tropiczone to rainforest in editor. */
491 if (_game_mode
== GM_EDITOR
&& IsInsideMM(treetype
, TREE_RAINFOREST
, TREE_CACTUS
)) {
492 SetTropicZone(current_tile
, TROPICZONE_RAINFOREST
);
495 cost
.AddCost(_price
[PR_BUILD_TREES
]);
500 msg
= STR_ERROR_SITE_UNSUITABLE
;
504 /* Tree limit used up? No need to check more. */
505 if (limit
< 0) break;
508 if (cost
.GetCost() == 0) {
509 return_cmd_error(msg
);
515 struct TreeListEnt
: PalSpriteID
{
519 static void DrawTile_Trees(TileInfo
*ti
)
521 switch (GetTreeGround(ti
->tile
)) {
522 case TREE_GROUND_SHORE
: DrawShoreTile(ti
->tileh
); break;
523 case TREE_GROUND_GRASS
: DrawClearLandTile(ti
, GetTreeDensity(ti
->tile
)); break;
524 case TREE_GROUND_ROUGH
: DrawHillyLandTile(ti
); break;
525 default: DrawGroundSprite(_clear_land_sprites_snow_desert
[GetTreeDensity(ti
->tile
)] + SlopeToSpriteOffset(ti
->tileh
), PAL_NONE
); break;
528 /* Do not draw trees when the invisible trees setting is set */
529 if (IsInvisibilitySet(TO_TREES
)) return;
531 uint tmp
= CountBits(ti
->tile
.base() + ti
->x
+ ti
->y
);
532 uint index
= GB(tmp
, 0, 2) + (GetTreeType(ti
->tile
) << 2);
534 /* different tree styles above one of the grounds */
535 if ((GetTreeGround(ti
->tile
) == TREE_GROUND_SNOW_DESERT
|| GetTreeGround(ti
->tile
) == TREE_GROUND_ROUGH_SNOW
) &&
536 GetTreeDensity(ti
->tile
) >= 2 &&
537 IsInsideMM(index
, TREE_SUB_ARCTIC
<< 2, TREE_RAINFOREST
<< 2)) {
538 index
+= 164 - (TREE_SUB_ARCTIC
<< 2);
541 assert(index
< lengthof(_tree_layout_sprite
));
543 const PalSpriteID
*s
= _tree_layout_sprite
[index
];
544 const TreePos
*d
= _tree_layout_xy
[GB(tmp
, 2, 2)];
546 /* combine trees into one sprite object */
547 StartSpriteCombine();
551 /* put the trees to draw in a list */
552 uint trees
= GetTreeCount(ti
->tile
);
554 for (uint i
= 0; i
< trees
; i
++) {
555 SpriteID sprite
= s
[0].sprite
+ (i
== trees
- 1 ? static_cast<uint
>(GetTreeGrowth(ti
->tile
)) : 3);
556 PaletteID pal
= s
[0].pal
;
558 te
[i
].sprite
= sprite
;
566 /* draw them in a sorted way */
567 int z
= ti
->z
+ GetSlopeMaxPixelZ(ti
->tileh
) / 2;
569 for (; trees
> 0; trees
--) {
570 uint min
= te
[0].x
+ te
[0].y
;
573 for (uint i
= 1; i
< trees
; i
++) {
574 if ((uint
)(te
[i
].x
+ te
[i
].y
) < min
) {
575 min
= te
[i
].x
+ te
[i
].y
;
580 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
);
582 /* replace the removed one with the last one */
583 te
[mi
] = te
[trees
- 1];
590 static int GetSlopePixelZ_Trees(TileIndex tile
, uint x
, uint y
, bool)
592 auto [tileh
, z
] = GetTilePixelSlope(tile
);
594 return z
+ GetPartialPixelZ(x
& 0xF, y
& 0xF, tileh
);
597 static Foundation
GetFoundation_Trees(TileIndex
, Slope
)
599 return FOUNDATION_NONE
;
602 static CommandCost
ClearTile_Trees(TileIndex tile
, DoCommandFlag flags
)
606 if (Company::IsValidID(_current_company
)) {
607 Town
*t
= ClosestTownFromTile(tile
, _settings_game
.economy
.dist_local_authority
);
608 if (t
!= nullptr) ChangeTownRating(t
, RATING_TREE_DOWN_STEP
, RATING_TREE_MINIMUM
, flags
);
611 num
= GetTreeCount(tile
);
612 if (IsInsideMM(GetTreeType(tile
), TREE_RAINFOREST
, TREE_CACTUS
)) num
*= 4;
614 if (flags
& DC_EXEC
) DoClearSquare(tile
);
616 return CommandCost(EXPENSES_CONSTRUCTION
, num
* _price
[PR_CLEAR_TREES
]);
619 static void GetTileDesc_Trees(TileIndex tile
, TileDesc
*td
)
621 TreeType tt
= GetTreeType(tile
);
623 if (IsInsideMM(tt
, TREE_RAINFOREST
, TREE_CACTUS
)) {
624 td
->str
= STR_LAI_TREE_NAME_RAINFOREST
;
626 td
->str
= tt
== TREE_CACTUS
? STR_LAI_TREE_NAME_CACTUS_PLANTS
: STR_LAI_TREE_NAME_TREES
;
629 td
->owner
[0] = GetTileOwner(tile
);
632 static void TileLoopTreesDesert(TileIndex tile
)
634 switch (GetTropicZone(tile
)) {
635 case TROPICZONE_DESERT
:
636 if (GetTreeGround(tile
) != TREE_GROUND_SNOW_DESERT
) {
637 SetTreeGroundDensity(tile
, TREE_GROUND_SNOW_DESERT
, 3);
638 MarkTileDirtyByTile(tile
);
642 case TROPICZONE_RAINFOREST
: {
643 static const SoundFx forest_sounds
[] = {
649 uint32_t r
= Random();
651 if (Chance16I(1, 200, r
) && _settings_client
.sound
.ambient
) SndPlayTileFx(forest_sounds
[GB(r
, 16, 2)], tile
);
659 static void TileLoopTreesAlps(TileIndex tile
)
661 int k
= GetTileZ(tile
) - GetSnowLine() + 1;
664 switch (GetTreeGround(tile
)) {
665 case TREE_GROUND_SNOW_DESERT
: SetTreeGroundDensity(tile
, TREE_GROUND_GRASS
, 3); break;
666 case TREE_GROUND_ROUGH_SNOW
: SetTreeGroundDensity(tile
, TREE_GROUND_ROUGH
, 3); break;
670 uint density
= std::min
<uint
>(k
, 3);
672 if (GetTreeGround(tile
) != TREE_GROUND_SNOW_DESERT
&& GetTreeGround(tile
) != TREE_GROUND_ROUGH_SNOW
) {
673 TreeGround tg
= GetTreeGround(tile
) == TREE_GROUND_ROUGH
? TREE_GROUND_ROUGH_SNOW
: TREE_GROUND_SNOW_DESERT
;
674 SetTreeGroundDensity(tile
, tg
, density
);
675 } else if (GetTreeDensity(tile
) != density
) {
676 SetTreeGroundDensity(tile
, GetTreeGround(tile
), density
);
678 if (GetTreeDensity(tile
) == 3) {
679 uint32_t r
= Random();
680 if (Chance16I(1, 200, r
) && _settings_client
.sound
.ambient
) {
681 SndPlayTileFx((r
& 0x80000000) ? SND_39_ARCTIC_SNOW_2
: SND_34_ARCTIC_SNOW_1
, tile
);
687 MarkTileDirtyByTile(tile
);
690 static bool CanPlantExtraTrees(TileIndex tile
)
692 return ((_settings_game
.game_creation
.landscape
== LT_TROPIC
&& GetTropicZone(tile
) == TROPICZONE_RAINFOREST
) ?
693 (_settings_game
.construction
.extra_tree_placement
== ETP_SPREAD_ALL
|| _settings_game
.construction
.extra_tree_placement
== ETP_SPREAD_RAINFOREST
) :
694 _settings_game
.construction
.extra_tree_placement
== ETP_SPREAD_ALL
);
697 static void TileLoop_Trees(TileIndex tile
)
699 if (GetTreeGround(tile
) == TREE_GROUND_SHORE
) {
700 TileLoop_Water(tile
);
702 switch (_settings_game
.game_creation
.landscape
) {
703 case LT_TROPIC
: TileLoopTreesDesert(tile
); break;
704 case LT_ARCTIC
: TileLoopTreesAlps(tile
); break;
708 AmbientSoundEffect(tile
);
710 /* TimerGameTick::counter is incremented by 256 between each call, so ignore lower 8 bits.
711 * Also, we use a simple hash to spread the updates evenly over the map.
712 * 11 and 9 are just some co-prime numbers for better spread.
714 uint32_t cycle
= 11 * TileX(tile
) + 9 * TileY(tile
) + (TimerGameTick::counter
>> 8);
716 /* Handle growth of grass (under trees/on MP_TREES tiles) at every 8th processings, like it's done for grass on MP_CLEAR tiles. */
717 if ((cycle
& 7) == 7 && GetTreeGround(tile
) == TREE_GROUND_GRASS
) {
718 uint density
= GetTreeDensity(tile
);
720 SetTreeGroundDensity(tile
, TREE_GROUND_GRASS
, density
+ 1);
721 MarkTileDirtyByTile(tile
);
725 if (_settings_game
.construction
.extra_tree_placement
== ETP_NO_GROWTH_NO_SPREAD
) return;
727 static const uint32_t TREE_UPDATE_FREQUENCY
= 16; // How many tile updates happen for one tree update
728 if (cycle
% TREE_UPDATE_FREQUENCY
!= TREE_UPDATE_FREQUENCY
- 1) return;
730 switch (GetTreeGrowth(tile
)) {
731 case TreeGrowthStage::Grown
: // regular sized tree
732 if (_settings_game
.game_creation
.landscape
== LT_TROPIC
&&
733 GetTreeType(tile
) != TREE_CACTUS
&&
734 GetTropicZone(tile
) == TROPICZONE_DESERT
) {
735 AddTreeGrowth(tile
, 1);
737 switch (GB(Random(), 0, 3)) {
738 case 0: // start destructing
739 AddTreeGrowth(tile
, 1);
742 case 1: // add a tree
743 if (GetTreeCount(tile
) < 4 && CanPlantExtraTrees(tile
)) {
744 AddTreeCount(tile
, 1);
745 SetTreeGrowth(tile
, TreeGrowthStage::Growing1
);
750 case 2: { // add a neighbouring tree
751 if (!CanPlantExtraTrees(tile
)) break;
753 TreeType treetype
= GetTreeType(tile
);
755 tile
+= TileOffsByDir(static_cast<Direction
>(Random() % DIR_END
));
757 /* Cacti don't spread */
758 if (!CanPlantTreesOnTile(tile
, false)) return;
760 /* Don't plant trees, if ground was freshly cleared */
761 if (IsTileType(tile
, MP_CLEAR
) && GetClearGround(tile
) == CLEAR_GRASS
&& GetClearDensity(tile
) != 3) return;
763 PlantTreesOnTile(tile
, treetype
, 0, TreeGrowthStage::Growing1
);
774 case TreeGrowthStage::Dead
: // final stage of tree destruction
775 if (!CanPlantExtraTrees(tile
)) {
776 /* if trees can't spread just plant a new one to prevent deforestation */
777 SetTreeGrowth(tile
, TreeGrowthStage::Growing1
);
778 } else if (GetTreeCount(tile
) > 1) {
779 /* more than one tree, delete it */
780 AddTreeCount(tile
, -1);
781 SetTreeGrowth(tile
, TreeGrowthStage::Grown
);
783 /* just one tree, change type into MP_CLEAR */
784 switch (GetTreeGround(tile
)) {
785 case TREE_GROUND_SHORE
: MakeShore(tile
); break;
786 case TREE_GROUND_GRASS
: MakeClear(tile
, CLEAR_GRASS
, GetTreeDensity(tile
)); break;
787 case TREE_GROUND_ROUGH
: MakeClear(tile
, CLEAR_ROUGH
, 3); break;
788 case TREE_GROUND_ROUGH_SNOW
: {
789 uint density
= GetTreeDensity(tile
);
790 MakeClear(tile
, CLEAR_ROUGH
, 3);
791 MakeSnow(tile
, density
);
794 default: // snow or desert
795 if (_settings_game
.game_creation
.landscape
== LT_TROPIC
) {
796 MakeClear(tile
, CLEAR_DESERT
, GetTreeDensity(tile
));
798 uint density
= GetTreeDensity(tile
);
799 MakeClear(tile
, CLEAR_GRASS
, 3);
800 MakeSnow(tile
, density
);
808 AddTreeGrowth(tile
, 1);
812 MarkTileDirtyByTile(tile
);
816 * Decrement the tree tick counter.
817 * The interval is scaled by map size to allow for the same density regardless of size.
818 * Adjustment for map sizes below the standard 256 * 256 are handled earlier.
819 * @return true if the counter was decremented past zero
821 bool DecrementTreeCounter()
823 /* Ensure _trees_tick_ctr can be decremented past zero only once for the largest map size. */
824 static_assert(2 * (MAX_MAP_SIZE_BITS
- MIN_MAP_SIZE_BITS
) - 4 <= std::numeric_limits
<uint8_t>::digits
);
827 uint8_t old_trees_tick_ctr
= _trees_tick_ctr
;
828 _trees_tick_ctr
-= Map::ScaleBySize(1);
829 return old_trees_tick_ctr
<= _trees_tick_ctr
;
834 /* Don't spread trees if that's not allowed */
835 if (_settings_game
.construction
.extra_tree_placement
== ETP_NO_SPREAD
|| _settings_game
.construction
.extra_tree_placement
== ETP_NO_GROWTH_NO_SPREAD
) return;
841 /* Skip some tree ticks for map sizes below 256 * 256. 64 * 64 is 16 times smaller, so
842 * this is the maximum number of ticks that are skipped. Number of ticks to skip is
843 * inversely proportional to map size, so that is handled to create a mask. */
844 int skip
= Map::ScaleBySize(16);
845 if (skip
< 16 && (TimerGameTick::counter
& (16 / skip
- 1)) != 0) return;
847 /* place a tree at a random rainforest spot */
848 if (_settings_game
.game_creation
.landscape
== LT_TROPIC
) {
849 for (uint c
= Map::ScaleBySize(1); c
> 0; c
--) {
850 if ((r
= Random(), tile
= RandomTileSeed(r
), GetTropicZone(tile
) == TROPICZONE_RAINFOREST
) &&
851 CanPlantTreesOnTile(tile
, false) &&
852 (tree
= GetRandomTreeType(tile
, GB(r
, 24, 8))) != TREE_INVALID
) {
853 PlantTreesOnTile(tile
, tree
, 0, TreeGrowthStage::Growing1
);
858 if (!DecrementTreeCounter() || _settings_game
.construction
.extra_tree_placement
== ETP_SPREAD_RAINFOREST
) return;
860 /* place a tree at a random spot */
862 tile
= RandomTileSeed(r
);
863 if (CanPlantTreesOnTile(tile
, false) && (tree
= GetRandomTreeType(tile
, GB(r
, 24, 8))) != TREE_INVALID
) {
864 PlantTreesOnTile(tile
, tree
, 0, TreeGrowthStage::Growing1
);
868 static TrackStatus
GetTileTrackStatus_Trees(TileIndex
, TransportType
, uint
, DiagDirection
)
873 static void ChangeTileOwner_Trees(TileIndex
, Owner
, Owner
)
878 void InitializeTrees()
883 static CommandCost
TerraformTile_Trees(TileIndex tile
, DoCommandFlag flags
, int, Slope
)
885 return Command
<CMD_LANDSCAPE_CLEAR
>::Do(flags
, tile
);
889 extern const TileTypeProcs _tile_type_trees_procs
= {
890 DrawTile_Trees
, // draw_tile_proc
891 GetSlopePixelZ_Trees
, // get_slope_z_proc
892 ClearTile_Trees
, // clear_tile_proc
893 nullptr, // add_accepted_cargo_proc
894 GetTileDesc_Trees
, // get_tile_desc_proc
895 GetTileTrackStatus_Trees
, // get_tile_track_status_proc
896 nullptr, // click_tile_proc
897 nullptr, // animate_tile_proc
898 TileLoop_Trees
, // tile_loop_proc
899 ChangeTileOwner_Trees
, // change_tile_owner_proc
900 nullptr, // add_produced_cargo_proc
901 nullptr, // vehicle_enter_tile_proc
902 GetFoundation_Trees
, // get_foundation_proc
903 TerraformTile_Trees
, // terraform_tile_proc