Fix some daylength issues, possible division by zero in main menu.
[openttd-joker.git] / src / tree_cmd.cpp
blob8a7afee0ad675de3d084c5bb8c5e0fe88de0b5cf
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or mod/// ify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * 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.
7 * 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 */
10 /** @file tree_cmd.cpp Handling of tree tiles. */
12 #include "stdafx.h"
13 #include "clear_map.h"
14 #include "landscape.h"
15 #include "tree_map.h"
16 #include "viewport_func.h"
17 #include "command_func.h"
18 #include "town.h"
19 #include "genworld.h"
20 #include "clear_func.h"
21 #include "company_func.h"
22 #include "sound_func.h"
23 #include "water.h"
24 #include "company_base.h"
25 #include "core/random_func.hpp"
26 #include "newgrf_generic.h"
28 #include "table/strings.h"
29 #include "table/tree_land.h"
30 #include "table/clear_land.h"
32 #include "safeguards.h"
34 /**
35 * List of tree placer algorithm.
37 * This enumeration defines all possible tree placer algorithm in the game.
39 enum TreePlacer {
40 TP_NONE, ///< No tree placer algorithm
41 TP_ORIGINAL, ///< The original algorithm
42 TP_IMPROVED, ///< A 'improved' algorithm
45 /** Where to place trees while in-game? */
46 enum ExtraTreePlacement {
47 ETP_NONE, ///< Place trees on no tiles
48 ETP_RAINFOREST, ///< Place trees only on rainforest tiles
49 ETP_ALL, ///< Place trees on all tiles
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.
66 *////
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 bool is_above_tree_line = GetTileZ(tile) >= _settings_game.game_creation.tree_line_height;
76 return !is_above_tree_line && !IsBridgeAbove(tile) && !IsClearGround(tile, CLEAR_FIELDS) && GetRawClearGround(tile) != CLEAR_ROCKS &&
77 (allow_desert || !IsClearGround(tile, CLEAR_DESERT));
80 default: return false;
84 /**
85 * Creates a tree tile
86 * Ground type and density is preserved.
88 * @pre the tile must be suitable for trees.
90 * @param tile where to plant the trees.
91 * @param treetype The type of the tree
92 * @param count the number of trees (minus 1)
93 * @param growth the growth status
95 static void PlantTreesOnTile(TileIndex tile, TreeType treetype, uint count, uint growth)
97 assert(treetype != TREE_INVALID);
98 assert(CanPlantTreesOnTile(tile, true));
100 TreeGround ground;
101 uint density = 3;
103 switch (GetTileType(tile)) {
104 case MP_WATER:
105 ground = TREE_GROUND_SHORE;
106 break;
108 case MP_CLEAR:
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);
116 break;
118 default: NOT_REACHED();
121 uint16 tree_line_range = _settings_game.construction.trees_around_snow_line_range;
122 uint16 min_tree_line_height = _settings_game.game_creation.tree_line_height - tree_line_range;
124 if (GetTileZ(tile) >= min_tree_line_height) {
125 // Slowly thin out trees.
126 uint16 height_above_min_tree_line = max(0, GetTileZ(tile) - min_tree_line_height);
127 uint16 percent_of_range = 100u - (height_above_min_tree_line * 100u / tree_line_range);
129 count = max((count * percent_of_range) / 100u, 1u);
132 MakeTree(tile, treetype, count, growth, ground, density);
136 * Previous value of _settings_game.construction.trees_around_snow_line_range
137 * used to calculate _arctic_tree_occurance
139 static uint8 _previous_trees_around_snow_line_range = 255;
142 * Array of probabilities for artic trees to appear,
143 * by normalised distance from snow line
145 static uint8 _arctic_tree_occurance[24];
147 /** Recalculate _arctic_tree_occurance */
148 static void RecalculateArcticTreeOccuranceArray()
151 * Approximate: 256 * exp(-3 * distance / range)
152 * By using:
153 * 256 * ((1 + (-3 * distance / range) / 6) ** 6)
154 * ((256 - (128 * distance / range)) ** 6) >> (5 * 8);
156 uint8 range = _settings_game.construction.trees_around_snow_line_range;
157 _previous_trees_around_snow_line_range = range;
158 _arctic_tree_occurance[0] = 255;
159 uint i = 1;
160 for (; i < lengthof(_arctic_tree_occurance); i++) {
161 if (range == 0) break;
162 uint x = 256 - ((128 * i) / range);
163 uint32 output = x;
164 output *= x;
165 output *= x;
166 output *= x;
167 output >>= 16;
168 output *= x;
169 output *= x;
170 output >>= 24;
171 if (output == 0) break;
172 _arctic_tree_occurance[i] = output;
174 for (; i < lengthof(_arctic_tree_occurance); i++) {
175 _arctic_tree_occurance[i] = 0;
180 * Get a random TreeType for the given tile based on a given seed
182 * This function returns a random TreeType which can be placed on the given tile.
183 * The seed for randomness must be less than 256, use #GB on the value of Random()
184 * to get such a value.
186 * @param tile The tile to get a random TreeType from
187 * @param seed The seed for randomness, must be less than 256
188 * @return The random tree type
190 static TreeType GetRandomTreeType(TileIndex tile, uint seed)
192 switch (_settings_game.game_creation.landscape) {
193 case LT_TEMPERATE:
194 if (!_settings_game.construction.trees_around_snow_line_enabled) {
195 return (TreeType)(seed * TREE_COUNT_TEMPERATE / 256 + TREE_TEMPERATE);
197 case LT_ARCTIC: {
198 // Don't use temperate trees in arctic if a variable snow line is set. That will look awful.
199 if (IsSnowLineSet()) {
200 return (TreeType)(seed * TREE_COUNT_SUB_ARCTIC / 256 + TREE_SUB_ARCTIC);
203 uint8 tree_line_range = _settings_game.construction.trees_around_snow_line_range;
204 if (tree_line_range != _previous_trees_around_snow_line_range) RecalculateArcticTreeOccuranceArray();
206 int z = GetTileZ(tile);
207 int height_above_snow_line = z - _settings_game.game_creation.snow_line_height;
208 uint normalised_distance = (height_above_snow_line < 0) ? -height_above_snow_line : height_above_snow_line + 1;
209 bool arctic_tree = false;
210 if (normalised_distance < lengthof(_arctic_tree_occurance)) {
211 uint adjusted_seed = (seed ^ tile) & 0xFF;
212 arctic_tree = adjusted_seed < _arctic_tree_occurance[normalised_distance];
214 if (height_above_snow_line < 0) {
215 /* Below snow level mixed forest. */
216 return (arctic_tree) ? (TreeType)(seed * TREE_COUNT_SUB_ARCTIC / 256 + TREE_SUB_ARCTIC) : (TreeType)(seed * TREE_COUNT_TEMPERATE / 256 + TREE_TEMPERATE);
218 else {
219 /* Above is Arctic trees and thinning out. */
220 return (arctic_tree) ? (TreeType)(seed * TREE_COUNT_SUB_ARCTIC / 256 + TREE_SUB_ARCTIC) : TREE_INVALID;
224 case LT_TROPIC:
225 switch (GetTropicZone(tile)) {
226 case TROPICZONE_NORMAL: return (TreeType)(seed * TREE_COUNT_SUB_TROPICAL / 256 + TREE_SUB_TROPICAL);
227 case TROPICZONE_DESERT: return (TreeType)((seed > 12) ? TREE_INVALID : TREE_CACTUS);
228 default: return (TreeType)(seed * TREE_COUNT_RAINFOREST / 256 + TREE_RAINFOREST);
231 default:
232 return (TreeType)(seed * TREE_COUNT_TOYLAND / 256 + TREE_TOYLAND);
237 * Make a random tree tile of the given tile
239 * Create a new tree-tile for the given tile. The second parameter is used for
240 * randomness like type and number of trees.
242 * @param tile The tile to make a tree-tile from
243 * @param r The randomness value from a Random() value
245 static void PlaceTree(TileIndex tile, uint32 r)
247 TreeType tree = GetRandomTreeType(tile, GB(r, 24, 8));
249 if (tree != TREE_INVALID) {
250 PlantTreesOnTile(tile, tree, GB(r, 22, 2), min(GB(r, 16, 3), 6));
252 /* Rerandomize ground, if neither snow nor shore */
253 TreeGround ground = GetTreeGround(tile);
254 if (ground != TREE_GROUND_SNOW_DESERT && ground != TREE_GROUND_ROUGH_SNOW && ground != TREE_GROUND_SHORE) {
255 SetTreeGroundDensity(tile, (TreeGround)GB(r, 28, 1), 3);
258 /* Set the counter to a random start value */
259 SetTreeCounter(tile, (TreeGround)GB(r, 24, 4));
264 * Creates a number of tree groups.
265 * The number of trees in each group depends on how many trees are actually placed around the given tile.
267 * @param num_groups Number of tree groups to place.
269 static void PlaceTreeGroups(uint num_groups)
271 do {
272 TileIndex center_tile = RandomTile();
274 for (uint i = 0; i < DEFAULT_TREE_STEPS; i++) {
275 uint32 r = Random();
276 int x = GB(r, 0, 5) - 16;
277 int y = GB(r, 8, 5) - 16;
278 uint dist = abs(x) + abs(y);
279 TileIndex cur_tile = TileAddWrap(center_tile, x, y);
281 IncreaseGeneratingWorldProgress(GWP_TREE);
283 if (cur_tile != INVALID_TILE && dist <= 13 && CanPlantTreesOnTile(cur_tile, true)) {
284 PlaceTree(cur_tile, r);
288 } while (--num_groups);
292 * Place a tree at the same height as an existing tree.
294 * Add a new tree around the given tile which is at the same
295 * height or at some offset (2 units) of it.
297 * @param tile The base tile to add a new tree somewhere around
298 * @param height The height (like the one from the tile)
300 static void PlaceTreeAtSameHeight(TileIndex tile, int height)
302 for (uint i = 0; i < DEFAULT_TREE_STEPS; i++) {
303 uint32 r = Random();
304 int x = GB(r, 0, 5) - 16;
305 int y = GB(r, 8, 5) - 16;
306 TileIndex cur_tile = TileAddWrap(tile, x, y);
308 if (cur_tile == INVALID_TILE) continue;
310 /* Keep in range of the existing tree */
311 if (abs(x) + abs(y) > 16) continue;
313 /* Clear tile, no farm-tiles or rocks */
314 if (!CanPlantTreesOnTile(cur_tile, true)) continue;
316 /* Not too much height difference */
317 if (Delta(GetTileZ(cur_tile), height) > 2) continue;
319 /* Place one tree and quit */
320 PlaceTree(cur_tile, r);
321 break;
326 * Place some trees randomly
328 * This function just place some trees randomly on the map.
330 void PlaceTreesRandomly()
332 int i, j, ht;
334 i = ScaleByMapSize(DEFAULT_TREE_STEPS);
335 if (_game_mode == GM_EDITOR) i /= EDITOR_TREE_DIV;
336 do {
337 uint32 r = Random();
338 TileIndex tile = RandomTileSeed(r);
340 IncreaseGeneratingWorldProgress(GWP_TREE);
342 if (CanPlantTreesOnTile(tile, true)) {
343 PlaceTree(tile, r);
344 if (_settings_game.game_creation.tree_placer != TP_IMPROVED) continue;
346 /* Place a number of trees based on the tile height.
347 * This gives a cool effect of multiple trees close together.
348 * It is almost real life ;) */
349 ht = GetTileZ(tile);
350 /* The higher we get, the more trees we plant */
351 j = max(1, (GetTileZ(tile) - 1) * 2);
353 uint16 tree_line_range = _settings_game.construction.trees_around_snow_line_range;
354 uint16 min_tree_line_height = _settings_game.game_creation.tree_line_height - tree_line_range;
356 if (GetTileZ(tile) >= min_tree_line_height) {
357 // Slowly thin out trees.
358 uint16 height_above_min_tree_line = max(0, GetTileZ(tile) - min_tree_line_height);
359 uint16 percent_of_range = (height_above_min_tree_line * 100u / tree_line_range);
361 j = j - ((j * percent_of_range) / 100u);
362 } else if (_settings_game.game_creation.landscape == LT_ARCTIC && ht > GetSnowLine()) {
363 // Above snowline more trees.
364 j *= 3;
366 while (j--) {
367 PlaceTreeAtSameHeight(tile, ht);
370 } while (--i);
372 /* place extra trees at rainforest area */
373 if (_settings_game.game_creation.landscape == LT_TROPIC) {
374 i = ScaleByMapSize(DEFAULT_RAINFOREST_TREE_STEPS);
375 if (_game_mode == GM_EDITOR) i /= EDITOR_TREE_DIV;
377 do {
378 uint32 r = Random();
379 TileIndex tile = RandomTileSeed(r);
381 IncreaseGeneratingWorldProgress(GWP_TREE);
383 if (GetTropicZone(tile) == TROPICZONE_RAINFOREST && CanPlantTreesOnTile(tile, false)) {
384 PlaceTree(tile, r);
386 } while (--i);
391 * Place new trees.
393 * This function takes care of the selected tree placer algorithm and
394 * place randomly the trees for a new game.
396 void GenerateTrees()
398 uint i, total;
400 if (_settings_game.game_creation.tree_placer == TP_NONE) return;
402 switch (_settings_game.game_creation.tree_placer) {
403 case TP_ORIGINAL: i = _settings_game.game_creation.landscape == LT_ARCTIC ? 15 : 6; break;
404 case TP_IMPROVED: i = _settings_game.game_creation.landscape == LT_ARCTIC ? 4 : 2; break;
405 default: NOT_REACHED();
408 total = ScaleByMapSize(DEFAULT_TREE_STEPS);
409 if (_settings_game.game_creation.landscape == LT_TROPIC) total += ScaleByMapSize(DEFAULT_RAINFOREST_TREE_STEPS);
410 total *= i;
411 uint num_groups = (_settings_game.game_creation.landscape != LT_TOYLAND) ? ScaleByMapSize(GB(Random(), 0, 5) + 25) : 0;
412 total += num_groups * DEFAULT_TREE_STEPS;
413 SetGeneratingWorldProgress(GWP_TREE, total);
415 if (num_groups != 0) PlaceTreeGroups(num_groups);
417 for (; i != 0; i--) {
418 PlaceTreesRandomly();
423 * Plant a tree.
424 * @param tile end tile of area-drag
425 * @param flags type of operation
426 * @param p1 tree type, TREE_INVALID means random.
427 * @param p2 start tile of area-drag of tree plantation
428 * @param text unused
429 * @return the cost of this operation or an error
431 CommandCost CmdPlantTree(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
433 StringID msg = INVALID_STRING_ID;
434 CommandCost cost(EXPENSES_OTHER);
435 const byte tree_to_plant = GB(p1, 0, 8); // We cannot use Extract as min and max are climate specific.
437 if (p2 >= MapSize()) return CMD_ERROR;
438 /* Check the tree type within the current climate */
439 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;
441 Company *c = (_game_mode != GM_EDITOR) ? Company::GetIfValid(_current_company) : NULL;
442 int limit = (c == NULL ? INT32_MAX : GB(c->tree_limit, 16, 16));
444 TileArea ta(tile, p2);
445 TILE_AREA_LOOP(tile, ta) {
446 switch (GetTileType(tile)) {
447 case MP_TREES:
449 bool grow_existing_tree_instead = false;
451 /* no more space for trees? */
452 if (_game_mode != GM_EDITOR && (GetTreeCount(tile) >= 4 || ((int)GetTreeCount(tile) >= (GetTileZ(tile) + (_settings_game.game_creation.landscape != LT_TROPIC ? 0 : 1))))) {
453 if (GetTreeGrowth(tile) < 3) {
454 grow_existing_tree_instead = true;
455 } else {
456 msg = STR_ERROR_TREE_ALREADY_HERE;
457 continue;
461 /* Thin out trees along the tree line range */
462 uint tree_line_range = _settings_game.construction.trees_around_snow_line_range;
463 uint min_tree_line_height = _settings_game.game_creation.tree_line_height - tree_line_range;
464 uint height_above_min_tree_line = max(0u, GetTileZ(tile) - min_tree_line_height);
465 uint percent_of_range = height_above_min_tree_line * 100u / tree_line_range;
466 uint max_tree_count = 4u - ((4u * percent_of_range) / 100u);
468 if (GetTreeCount(tile) >= max_tree_count) {
469 if (GetTreeGrowth(tile) < 3) {
470 grow_existing_tree_instead = true;
472 else {
473 msg = STR_ERROR_TREE_PLANT_LIMIT_REACHED;
474 continue;
478 /* Test tree limit. */
479 if (--limit < 1) {
480 msg = STR_ERROR_TREE_PLANT_LIMIT_REACHED;
481 break;
484 if (flags & DC_EXEC) {
485 if (grow_existing_tree_instead) {
486 SetTreeGrowth(tile, 3);
487 } else {
488 AddTreeCount(tile, 1);
490 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
491 if (c != NULL) c->tree_limit -= 1 << 16;
493 /* 2x as expensive to add more trees to an existing tile */
494 cost.AddCost(_price[PR_BUILD_TREES] * 2);
495 break;
498 case MP_WATER:
499 if (!CanPlantTreesOnTile(tile, false) || !IsCoast(tile) || IsSlopeWithOneCornerRaised(GetTileSlope(tile))) {
500 msg = STR_ERROR_CAN_T_BUILD_ON_WATER;
501 continue;
503 FALLTHROUGH;
505 case MP_CLEAR: {
506 if (!CanPlantTreesOnTile(tile, false) || IsBridgeAbove(tile)) {
507 msg = STR_ERROR_SITE_UNSUITABLE;
508 continue;
511 TreeType treetype = (TreeType)tree_to_plant;
512 /* Be a bit picky about which trees go where. */
513 if (_settings_game.game_creation.landscape == LT_TROPIC && treetype != TREE_INVALID && (
514 /* No cacti outside the desert */
515 (treetype == TREE_CACTUS && GetTropicZone(tile) != TROPICZONE_DESERT) ||
516 /* No rain forest trees outside the rain forest, except in the editor mode where it makes those tiles rain forest tile */
517 (IsInsideMM(treetype, TREE_RAINFOREST, TREE_CACTUS) && GetTropicZone(tile) != TROPICZONE_RAINFOREST && _game_mode != GM_EDITOR) ||
518 /* And no subtropical trees in the desert/rain forest */
519 (IsInsideMM(treetype, TREE_SUB_TROPICAL, TREE_TOYLAND) && GetTropicZone(tile) != TROPICZONE_NORMAL))) {
520 msg = STR_ERROR_TREE_WRONG_TERRAIN_FOR_TREE_TYPE;
521 continue;
524 /* Test tree limit. */
525 if (--limit < 1) {
526 msg = STR_ERROR_TREE_PLANT_LIMIT_REACHED;
527 break;
530 if (IsTileType(tile, MP_CLEAR)) {
531 /* Remove fields or rocks. Note that the ground will get barrened */
532 switch (GetRawClearGround(tile)) {
533 case CLEAR_FIELDS:
534 case CLEAR_ROCKS: {
535 CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
536 if (ret.Failed()) return ret;
537 cost.AddCost(ret);
538 break;
541 default: break;
545 if (_game_mode != GM_EDITOR && Company::IsValidID(_current_company)) {
546 Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
547 if (t != NULL) ChangeTownRating(t, RATING_TREE_UP_STEP, RATING_TREE_MAXIMUM, flags);
550 if (flags & DC_EXEC) {
551 if (treetype == TREE_INVALID) {
552 treetype = GetRandomTreeType(tile, GB(Random(), 24, 8));
554 if (treetype == TREE_INVALID) {
555 if (_settings_game.construction.trees_around_snow_line_enabled && _settings_game.game_creation.landscape != LT_TROPIC) {
556 if (GetTileZ(tile) <= HighestSnowLine()) {
557 treetype = (TreeType)(GB(Random(), 24, 8) * TREE_COUNT_TEMPERATE / 256 + TREE_TEMPERATE);
559 else {
560 treetype = (TreeType)(GB(Random(), 24, 8) * TREE_COUNT_SUB_ARCTIC / 256 + TREE_SUB_ARCTIC);
563 else {
564 treetype = TREE_CACTUS;
569 /* Plant full grown trees in scenario editor */
570 PlantTreesOnTile(tile, treetype, 0, _game_mode == GM_EDITOR ? 3 : 0);
571 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
572 if (c != NULL) c->tree_limit -= 1 << 16;
574 /* When planting rainforest-trees, set tropiczone to rainforest in editor. */
575 if (_game_mode == GM_EDITOR && IsInsideMM(treetype, TREE_RAINFOREST, TREE_CACTUS)) {
576 SetTropicZone(tile, TROPICZONE_RAINFOREST);
579 cost.AddCost(_price[PR_BUILD_TREES]);
580 break;
583 default:
584 msg = STR_ERROR_SITE_UNSUITABLE;
585 break;
588 /* Tree limit used up? No need to check more. */
589 if (limit < 0) break;
592 if (cost.GetCost() == 0) {
593 return_cmd_error(msg);
594 } else {
595 return cost;
599 struct TreeListEnt : PalSpriteID {
600 byte x, y;
603 static void DrawTile_Trees(TileInfo *ti)
605 switch (GetTreeGround(ti->tile)) {
606 case TREE_GROUND_SHORE: DrawShoreTile(ti->tileh); break;
607 case TREE_GROUND_GRASS: DrawClearLandTile(ti, GetTreeDensity(ti->tile)); break;
608 case TREE_GROUND_ROUGH: DrawHillyLandTile(ti); break;
609 default: DrawGroundSprite(_clear_land_sprites_snow_desert[GetTreeDensity(ti->tile)] + SlopeToSpriteOffset(ti->tileh), PAL_NONE); break;
612 DrawOverlay(ti, MP_TREES);
614 /* Do not draw trees when the invisible trees setting is set */
615 if (IsInvisibilitySet(TO_TREES)) return;
617 uint tmp = CountBits(ti->tile + ti->x + ti->y);
618 uint index = GB(tmp, 0, 2) + (GetTreeType(ti->tile) << 2);
620 /* different tree styles above one of the grounds */
621 if ((GetTreeGround(ti->tile) == TREE_GROUND_SNOW_DESERT || GetTreeGround(ti->tile) == TREE_GROUND_ROUGH_SNOW) &&
622 GetTreeDensity(ti->tile) >= 2 &&
623 IsInsideMM(index, TREE_SUB_ARCTIC << 2, TREE_RAINFOREST << 2)) {
624 index += 164 - (TREE_SUB_ARCTIC << 2);
627 assert(index < lengthof(_tree_layout_sprite));
629 const PalSpriteID *s = _tree_layout_sprite[index];
630 const TreePos *d = _tree_layout_xy[GB(tmp, 2, 2)];
632 /* combine trees into one sprite object */
633 StartSpriteCombine();
635 TreeListEnt te[4];
637 /* put the trees to draw in a list */
638 uint trees = GetTreeCount(ti->tile);
640 for (uint i = 0; i < trees; i++) {
641 SpriteID sprite = s[0].sprite + (i == trees - 1 ? GetTreeGrowth(ti->tile) : 3);
642 PaletteID pal = s[0].pal;
644 te[i].sprite = sprite;
645 te[i].pal = pal;
646 te[i].x = d->x;
647 te[i].y = d->y;
648 s++;
649 d++;
652 /* draw them in a sorted way */
653 int z = ti->z + GetSlopeMaxPixelZ(ti->tileh) / 2;
655 for (; trees > 0; trees--) {
656 uint min = te[0].x + te[0].y;
657 uint mi = 0;
659 for (uint i = 1; i < trees; i++) {
660 if ((uint)(te[i].x + te[i].y) < min) {
661 min = te[i].x + te[i].y;
662 mi = i;
666 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);
668 /* replace the removed one with the last one */
669 te[mi] = te[trees - 1];
672 EndSpriteCombine();
676 static int GetSlopePixelZ_Trees(TileIndex tile, uint x, uint y)
678 int z;
679 Slope tileh = GetTilePixelSlope(tile, &z);
681 return z + GetPartialPixelZ(x & 0xF, y & 0xF, tileh);
684 static Foundation GetFoundation_Trees(TileIndex tile, Slope tileh)
686 return FOUNDATION_NONE;
689 static CommandCost ClearTile_Trees(TileIndex tile, DoCommandFlag flags)
691 uint num;
693 if (Company::IsValidID(_current_company)) {
694 Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
695 if (t != NULL) ChangeTownRating(t, RATING_TREE_DOWN_STEP, RATING_TREE_MINIMUM, flags);
698 num = GetTreeCount(tile);
699 if (IsInsideMM(GetTreeType(tile), TREE_RAINFOREST, TREE_CACTUS)) num *= 4;
701 if (flags & DC_EXEC) DoClearSquare(tile);
703 return CommandCost(EXPENSES_CONSTRUCTION, num * _price[PR_CLEAR_TREES]);
706 static void GetTileDesc_Trees(TileIndex tile, TileDesc *td)
708 TreeType tt = GetTreeType(tile);
710 if (IsInsideMM(tt, TREE_RAINFOREST, TREE_CACTUS)) {
711 td->str = STR_LAI_TREE_NAME_RAINFOREST;
712 } else {
713 td->str = tt == TREE_CACTUS ? STR_LAI_TREE_NAME_CACTUS_PLANTS : STR_LAI_TREE_NAME_TREES;
716 td->owner[0] = GetTileOwner(tile);
719 static void TileLoopTreesDesert(TileIndex tile)
721 switch (GetTropicZone(tile)) {
722 case TROPICZONE_DESERT:
723 if (GetTreeGround(tile) != TREE_GROUND_SNOW_DESERT) {
724 SetTreeGroundDensity(tile, TREE_GROUND_SNOW_DESERT, 3);
725 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
727 break;
729 case TROPICZONE_RAINFOREST: {
730 static const SoundFx forest_sounds[] = {
731 SND_42_LOON_BIRD,
732 SND_43_LION,
733 SND_44_MONKEYS,
734 SND_48_DISTANT_BIRD
736 uint32 r = Random();
738 if (Chance16I(1, 200, r) && _settings_client.sound.ambient) SndPlayTileFx(forest_sounds[GB(r, 16, 2)], tile);
739 break;
742 default: break;
746 static void TileLoopTreesAlps(TileIndex tile)
748 int k = GetTileZ(tile) - GetSnowLine() + 1;
750 if (k < 0) {
751 switch (GetTreeGround(tile)) {
752 case TREE_GROUND_SNOW_DESERT: SetTreeGroundDensity(tile, TREE_GROUND_GRASS, 3); break;
753 case TREE_GROUND_ROUGH_SNOW: SetTreeGroundDensity(tile, TREE_GROUND_ROUGH, 3); break;
754 default: return;
756 } else {
757 uint density = min<uint>(k, 3);
759 if (GetTreeGround(tile) != TREE_GROUND_SNOW_DESERT && GetTreeGround(tile) != TREE_GROUND_ROUGH_SNOW) {
760 TreeGround tg = GetTreeGround(tile) == TREE_GROUND_ROUGH ? TREE_GROUND_ROUGH_SNOW : TREE_GROUND_SNOW_DESERT;
761 SetTreeGroundDensity(tile, tg, density);
762 } else if (GetTreeDensity(tile) != density) {
763 SetTreeGroundDensity(tile, GetTreeGround(tile), density);
764 } else {
765 if (GetTreeDensity(tile) == 3) {
766 uint32 r = Random();
767 if (Chance16I(1, 200, r) && _settings_client.sound.ambient) {
768 SndPlayTileFx((r & 0x80000000) ? SND_39_HEAVY_WIND : SND_34_WIND, tile);
771 return;
774 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
777 static void TileLoop_Trees(TileIndex tile)
779 if (GetTreeGround(tile) == TREE_GROUND_SHORE) {
780 TileLoop_Water(tile);
781 } else {
782 switch (_settings_game.game_creation.landscape) {
783 case LT_TROPIC: TileLoopTreesDesert(tile); break;
784 case LT_ARCTIC: TileLoopTreesAlps(tile); break;
788 AmbientSoundEffect(tile);
790 uint treeCounter = GetTreeCounter(tile);
792 /* Handle growth of grass (under trees/on MP_TREES tiles) at every 8th processings, like it's done for grass on MP_CLEAR tiles. */
793 if ((treeCounter & 7) == 7 && GetTreeGround(tile) == TREE_GROUND_GRASS) {
794 uint density = GetTreeDensity(tile);
795 if (density < 3) {
796 SetTreeGroundDensity(tile, TREE_GROUND_GRASS, density + 1);
797 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
801 if (GetTreeCounter(tile) < 15) {
802 AddTreeCounter(tile, 1);
803 return;
806 SetTreeCounter(tile, 0);
808 if (_settings_game.construction.tree_growth_rate > 0) {
809 /* Nature randomness */
810 uint8 grow_slowing_values[3] = { 5, 20, 120 }; // slow, very slow, extremely slow
811 uint16 prob = 0x10000 / grow_slowing_values[_settings_game.construction.tree_growth_rate - 1];
812 if (GB(Random(), 0, 16) >= (prob / 15)) {
813 return;
817 switch (GetTreeGrowth(tile)) {
818 case 3: // regular sized tree
819 if (_settings_game.game_creation.landscape == LT_TROPIC &&
820 GetTreeType(tile) != TREE_CACTUS &&
821 GetTropicZone(tile) == TROPICZONE_DESERT) {
822 AddTreeGrowth(tile, 1);
823 } else {
824 switch (GB(Random(), 0, 3)) {
825 case 0: // start destructing
826 AddTreeGrowth(tile, 1);
827 break;
829 case 1: // add a tree
831 int tree_line_range = _settings_game.construction.trees_around_snow_line_range;
832 int min_tree_line_height = _settings_game.game_creation.tree_line_height - tree_line_range;
833 bool treeline_treecount_exceeded = false;
835 if (GetTileZ(tile) >= min_tree_line_height) {
836 // Slowly thin out trees.
837 int height_above_min_tree_line = max(0, GetTileZ(tile) - min_tree_line_height);
838 int percent_of_range = 100 - (height_above_min_tree_line * 100 / tree_line_range);
840 uint allowed_tree_count = (4u * percent_of_range) / 100u;
842 treeline_treecount_exceeded = GetTreeCount(tile) >= allowed_tree_count;
845 if ((GetTreeCount(tile) < 4) && (GetTreeType(tile) != TREE_CACTUS) && !treeline_treecount_exceeded && ((int)GetTreeCount(tile) < (GetTileZ(tile) + (_settings_game.game_creation.landscape != LT_TROPIC ? 0 : 1)))) {
846 AddTreeCount(tile, 1);
847 SetTreeGrowth(tile, 0);
850 FALLTHROUGH;
852 case 2: { // add a neighbouring tree
853 /* Don't plant extra trees if that's not allowed. */
854 if ((_settings_game.game_creation.landscape == LT_TROPIC && GetTropicZone(tile) == TROPICZONE_RAINFOREST) ?
855 _settings_game.construction.extra_tree_placement == ETP_NONE :
856 _settings_game.construction.extra_tree_placement != ETP_ALL) {
857 break;
860 if ((_settings_game.game_creation.landscape != LT_TROPIC && GetTileZ(tile) < 3) || (GetTreeType(tile) == TREE_CACTUS))
862 uint32 r = Random();
863 int x = GB(r, 0, 5) - 16;
864 int y = GB(r, 8, 5) - 16;
865 TileIndex cur_tile = TileAddWrap(tile, x, y);
867 if (cur_tile == INVALID_TILE) return;
869 /* Keep in range of the existing tree */
870 if (abs(x) + abs(y) > 16) return;
872 /* Clear tile, no farm-tiles or rocks */
873 if (!CanPlantTreesOnTile(cur_tile, true)) return;
875 /* Not too much height difference */
876 if (Delta(GetTileZ(cur_tile), GetTileZ(tile)) > 2) return;
878 /* Place one tree and quit */
879 PlantTreesOnTile(cur_tile, GetTreeType(tile), 0, 0);
880 break;
882 else
884 TreeType treetype = GetTreeType(tile);
886 tile += TileOffsByDir((Direction)(Random() & 7));
888 /* Cacti don't spread */
889 if (!CanPlantTreesOnTile(tile, true)) return;
891 /* Don't plant trees, if ground was freshly cleared */
892 if (IsTileType(tile, MP_CLEAR) && GetClearGround(tile) == CLEAR_GRASS && GetClearDensity(tile) != 3) return;
894 PlantTreesOnTile(tile, treetype, 0, 0);
896 break;
899 default:
900 return;
903 break;
905 case 6: // final stage of tree destruction
906 if (GetTreeCount(tile) > 1) {
907 /* more than one tree, delete it */
908 AddTreeCount(tile, -1);
909 SetTreeGrowth(tile, 3);
910 } else {
911 /* just one tree, change type into MP_CLEAR */
912 switch (GetTreeGround(tile)) {
913 case TREE_GROUND_SHORE: MakeShore(tile); break;
914 case TREE_GROUND_GRASS: MakeClear(tile, CLEAR_GRASS, GetTreeDensity(tile)); break;
915 case TREE_GROUND_ROUGH: MakeClear(tile, CLEAR_ROUGH, 3); break;
916 case TREE_GROUND_ROUGH_SNOW: {
917 uint density = GetTreeDensity(tile);
918 MakeClear(tile, CLEAR_ROUGH, 3);
919 MakeSnow(tile, density);
920 break;
922 default: // snow or desert
923 if (_settings_game.game_creation.landscape == LT_TROPIC) {
924 MakeClear(tile, CLEAR_DESERT, GetTreeDensity(tile));
925 } else {
926 uint density = GetTreeDensity(tile);
927 MakeClear(tile, CLEAR_GRASS, 3);
928 MakeSnow(tile, density);
930 break;
933 break;
935 default:
936 AddTreeGrowth(tile, 1);
937 break;
940 MarkTileDirtyByTile(tile, ZOOM_LVL_DRAW_MAP);
943 void OnTick_Trees()
945 /* Don't place trees if that's not allowed */
946 if (_settings_game.construction.extra_tree_placement == ETP_NONE) return;
948 uint32 r;
949 TileIndex tile;
950 TreeType tree;
952 /* place a tree at a random rainforest spot */
953 if (_settings_game.game_creation.landscape == LT_TROPIC &&
954 (r = Random(), tile = RandomTileSeed(r), GetTropicZone(tile) == TROPICZONE_RAINFOREST) &&
955 CanPlantTreesOnTile(tile, false) &&
956 (tree = GetRandomTreeType(tile, GB(r, 24, 8))) != TREE_INVALID) {
957 PlantTreesOnTile(tile, tree, 0, 0);
960 /* byte underflow */
961 if (--_trees_tick_ctr != 0 || _settings_game.construction.extra_tree_placement != ETP_ALL) return;
963 /* place a tree at a random spot */
964 r = Random();
965 tile = RandomTileSeed(r);
966 if (CanPlantTreesOnTile(tile, false) && (tree = GetRandomTreeType(tile, GB(r, 24, 8))) != TREE_INVALID) {
967 PlantTreesOnTile(tile, tree, 0, 0);
971 static TrackStatus GetTileTrackStatus_Trees(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
973 return 0;
976 static void ChangeTileOwner_Trees(TileIndex tile, Owner old_owner, Owner new_owner)
978 /* not used */
981 void InitializeTrees()
983 _trees_tick_ctr = 0;
986 static CommandCost TerraformTile_Trees(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new)
988 return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
992 extern const TileTypeProcs _tile_type_trees_procs = {
993 DrawTile_Trees, // draw_tile_proc
994 GetSlopePixelZ_Trees, // get_slope_z_proc
995 ClearTile_Trees, // clear_tile_proc
996 NULL, // add_accepted_cargo_proc
997 GetTileDesc_Trees, // get_tile_desc_proc
998 GetTileTrackStatus_Trees, // get_tile_track_status_proc
999 NULL, // click_tile_proc
1000 NULL, // animate_tile_proc
1001 TileLoop_Trees, // tile_loop_proc
1002 ChangeTileOwner_Trees, // change_tile_owner_proc
1003 NULL, // add_produced_cargo_proc
1004 NULL, // vehicle_enter_tile_proc
1005 GetFoundation_Trees, // get_foundation_proc
1006 TerraformTile_Trees, // terraform_tile_proc