terraform_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: terraform_cmd.cpp 21791 2011-01-14 18:45:14Z rubidium $ */
00002 
00003 /*
00004  * This file is part of OpenTTD.
00005  * 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.
00006  * 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.
00007  * 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/>.
00008  */
00009 
00012 #include "stdafx.h"
00013 #include "openttd.h"
00014 #include "command_func.h"
00015 #include "tunnel_map.h"
00016 #include "bridge_map.h"
00017 #include "functions.h"
00018 #include "economy_func.h"
00019 #include "genworld.h"
00020 #include "object_base.h"
00021 #include "company_base.h"
00022 #include "company_func.h"
00023 
00024 #include "table/strings.h"
00025 
00026 /*
00027  * In one terraforming command all four corners of a initial tile can be raised/lowered (though this is not available to the player).
00028  * The maximal amount of height modifications is archieved when raising a complete flat land from sea level to MAX_TILE_HEIGHT or vice versa.
00029  * This affects all corners with a manhatten distance smaller than MAX_TILE_HEIGHT to one of the initial 4 corners.
00030  * Their maximal amount is computed to 4 * \sum_{i=1}^{h_max} i  =  2 * h_max * (h_max + 1).
00031  */
00032 static const int TERRAFORMER_MODHEIGHT_SIZE = 2 * MAX_TILE_HEIGHT * (MAX_TILE_HEIGHT + 1);
00033 
00034 /*
00035  * The maximal amount of affected tiles (i.e. the tiles that incident with one of the corners above, is computed similiar to
00036  * 1 + 4 * \sum_{i=1}^{h_max} (i+1)  =  1 + 2 * h_max + (h_max + 3).
00037  */
00038 static const int TERRAFORMER_TILE_TABLE_SIZE = 1 + 2 * MAX_TILE_HEIGHT * (MAX_TILE_HEIGHT + 3);
00039 
00040 struct TerraformerHeightMod {
00041   TileIndex tile;   
00042   byte height;      
00043 };
00044 
00045 struct TerraformerState {
00046   int modheight_count;  
00047   int tile_table_count; 
00048 
00056   TileIndex tile_table[TERRAFORMER_TILE_TABLE_SIZE];
00057   TerraformerHeightMod modheight[TERRAFORMER_MODHEIGHT_SIZE];  
00058 };
00059 
00060 TileIndex _terraform_err_tile; 
00061 
00069 static int TerraformGetHeightOfTile(const TerraformerState *ts, TileIndex tile)
00070 {
00071   const TerraformerHeightMod *mod = ts->modheight;
00072 
00073   for (int count = ts->modheight_count; count != 0; count--, mod++) {
00074     if (mod->tile == tile) return mod->height;
00075   }
00076 
00077   /* TileHeight unchanged so far, read value from map. */
00078   return TileHeight(tile);
00079 }
00080 
00088 static void TerraformSetHeightOfTile(TerraformerState *ts, TileIndex tile, int height)
00089 {
00090   /* Find tile in the "modheight" table.
00091    * Note: In a normal user-terraform command the tile will not be found in the "modheight" table.
00092    *       But during house- or industry-construction multiple corners can be terraformed at once. */
00093   TerraformerHeightMod *mod = ts->modheight;
00094   int count = ts->modheight_count;
00095 
00096   while ((count > 0) && (mod->tile != tile)) {
00097     mod++;
00098     count--;
00099   }
00100 
00101   /* New entry? */
00102   if (count == 0) {
00103     assert(ts->modheight_count < TERRAFORMER_MODHEIGHT_SIZE);
00104     ts->modheight_count++;
00105   }
00106 
00107   /* Finally store the new value */
00108   mod->tile = tile;
00109   mod->height = (byte)height;
00110 }
00111 
00119 static void TerraformAddDirtyTile(TerraformerState *ts, TileIndex tile)
00120 {
00121   int count = ts->tile_table_count;
00122 
00123   for (TileIndex *t = ts->tile_table; count != 0; count--, t++) {
00124     if (*t == tile) return;
00125   }
00126 
00127   assert(ts->tile_table_count < TERRAFORMER_TILE_TABLE_SIZE);
00128 
00129   ts->tile_table[ts->tile_table_count++] = tile;
00130 }
00131 
00139 static void TerraformAddDirtyTileAround(TerraformerState *ts, TileIndex tile)
00140 {
00141   /* Make sure all tiles passed to TerraformAddDirtyTile are within [0, MapSize()] */
00142   if (TileY(tile) >= 1) TerraformAddDirtyTile(ts, tile + TileDiffXY( 0, -1));
00143   if (TileY(tile) >= 1 && TileX(tile) >= 1) TerraformAddDirtyTile(ts, tile + TileDiffXY(-1, -1));
00144   if (TileX(tile) >= 1) TerraformAddDirtyTile(ts, tile + TileDiffXY(-1,  0));
00145   TerraformAddDirtyTile(ts, tile);
00146 }
00147 
00156 static CommandCost TerraformTileHeight(TerraformerState *ts, TileIndex tile, int height)
00157 {
00158   assert(tile < MapSize());
00159 
00160   /* Check range of destination height */
00161   if (height < 0) return_cmd_error(STR_ERROR_ALREADY_AT_SEA_LEVEL);
00162   if (height > (int)MAX_TILE_HEIGHT) return_cmd_error(STR_ERROR_TOO_HIGH);
00163 
00164   /*
00165    * Check if the terraforming has any effect.
00166    * This can only be true, if multiple corners of the start-tile are terraformed (i.e. the terraforming is done by towns/industries etc.).
00167    * In this case the terraforming should fail. (Don't know why.)
00168    */
00169   if (height == TerraformGetHeightOfTile(ts, tile)) return CMD_ERROR;
00170 
00171   /* Check "too close to edge of map". Only possible when freeform-edges is off. */
00172   uint x = TileX(tile);
00173   uint y = TileY(tile);
00174   if (!_settings_game.construction.freeform_edges && ((x <= 1) || (y <= 1) || (x >= MapMaxX() - 1) || (y >= MapMaxY() - 1))) {
00175     /*
00176      * Determine a sensible error tile
00177      */
00178     if (x == 1) x = 0;
00179     if (y == 1) y = 0;
00180     _terraform_err_tile = TileXY(x, y);
00181     return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP);
00182   }
00183 
00184   /* Mark incident tiles that are involved in the terraforming. */
00185   TerraformAddDirtyTileAround(ts, tile);
00186 
00187   /* Store the height modification */
00188   TerraformSetHeightOfTile(ts, tile, height);
00189 
00190   CommandCost total_cost(EXPENSES_CONSTRUCTION);
00191 
00192   /* Increment cost */
00193   total_cost.AddCost(_price[PR_TERRAFORM]);
00194 
00195   /* Recurse to neighboured corners if height difference is larger than 1 */
00196   {
00197     const TileIndexDiffC *ttm;
00198 
00199     TileIndex orig_tile = tile;
00200     static const TileIndexDiffC _terraform_tilepos[] = {
00201       { 1,  0}, // move to tile in SE
00202       {-2,  0}, // undo last move, and move to tile in NW
00203       { 1,  1}, // undo last move, and move to tile in SW
00204       { 0, -2}  // undo last move, and move to tile in NE
00205     };
00206 
00207     for (ttm = _terraform_tilepos; ttm != endof(_terraform_tilepos); ttm++) {
00208       tile += ToTileIndexDiff(*ttm);
00209 
00210       if (tile >= MapSize()) continue;
00211       /* Make sure we don't wrap around the map */
00212       if (Delta(TileX(orig_tile), TileX(tile)) == MapSizeX() - 1) continue;
00213       if (Delta(TileY(orig_tile), TileY(tile)) == MapSizeY() - 1) continue;
00214 
00215       /* Get TileHeight of neighboured tile as of current terraform progress */
00216       int r = TerraformGetHeightOfTile(ts, tile);
00217       int height_diff = height - r;
00218 
00219       /* Is the height difference to the neighboured corner greater than 1? */
00220       if (abs(height_diff) > 1) {
00221         /* Terraform the neighboured corner. The resulting height difference should be 1. */
00222         height_diff += (height_diff < 0 ? 1 : -1);
00223         CommandCost cost = TerraformTileHeight(ts, tile, r + height_diff);
00224         if (cost.Failed()) return cost;
00225         total_cost.AddCost(cost);
00226       }
00227     }
00228   }
00229 
00230   return total_cost;
00231 }
00232 
00242 CommandCost CmdTerraformLand(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00243 {
00244   _terraform_err_tile = INVALID_TILE;
00245 
00246   CommandCost total_cost(EXPENSES_CONSTRUCTION);
00247   int direction = (p2 != 0 ? 1 : -1);
00248   TerraformerState ts;
00249 
00250   ts.modheight_count = ts.tile_table_count = 0;
00251 
00252   /* Compute the costs and the terraforming result in a model of the landscape */
00253   if ((p1 & SLOPE_W) != 0 && tile + TileDiffXY(1, 0) < MapSize()) {
00254     TileIndex t = tile + TileDiffXY(1, 0);
00255     CommandCost cost = TerraformTileHeight(&ts, t, TileHeight(t) + direction);
00256     if (cost.Failed()) return cost;
00257     total_cost.AddCost(cost);
00258   }
00259 
00260   if ((p1 & SLOPE_S) != 0 && tile + TileDiffXY(1, 1) < MapSize()) {
00261     TileIndex t = tile + TileDiffXY(1, 1);
00262     CommandCost cost = TerraformTileHeight(&ts, t, TileHeight(t) + direction);
00263     if (cost.Failed()) return cost;
00264     total_cost.AddCost(cost);
00265   }
00266 
00267   if ((p1 & SLOPE_E) != 0 && tile + TileDiffXY(0, 1) < MapSize()) {
00268     TileIndex t = tile + TileDiffXY(0, 1);
00269     CommandCost cost = TerraformTileHeight(&ts, t, TileHeight(t) + direction);
00270     if (cost.Failed()) return cost;
00271     total_cost.AddCost(cost);
00272   }
00273 
00274   if ((p1 & SLOPE_N) != 0) {
00275     TileIndex t = tile + TileDiffXY(0, 0);
00276     CommandCost cost = TerraformTileHeight(&ts, t, TileHeight(t) + direction);
00277     if (cost.Failed()) return cost;
00278     total_cost.AddCost(cost);
00279   }
00280 
00281   /* Check if the terraforming is valid wrt. tunnels, bridges and objects on the surface
00282    * Pass == 0: Collect tileareas which are caused to be auto-cleared.
00283    * Pass == 1: Collect the actual cost. */
00284   for (int pass = 0; pass < 2; pass++) {
00285     TileIndex *ti = ts.tile_table;
00286 
00287     for (int count = ts.tile_table_count; count != 0; count--, ti++) {
00288       TileIndex tile = *ti;
00289 
00290       assert(tile < MapSize());
00291       /* MP_VOID tiles can be terraformed but as tunnels and bridges
00292        * cannot go under / over these tiles they don't need checking. */
00293       if (IsTileType(tile, MP_VOID)) continue;
00294 
00295       /* Find new heights of tile corners */
00296       uint z_N = TerraformGetHeightOfTile(&ts, tile + TileDiffXY(0, 0));
00297       uint z_W = TerraformGetHeightOfTile(&ts, tile + TileDiffXY(1, 0));
00298       uint z_S = TerraformGetHeightOfTile(&ts, tile + TileDiffXY(1, 1));
00299       uint z_E = TerraformGetHeightOfTile(&ts, tile + TileDiffXY(0, 1));
00300 
00301       /* Find min and max height of tile */
00302       uint z_min = min(min(z_N, z_W), min(z_S, z_E));
00303       uint z_max = max(max(z_N, z_W), max(z_S, z_E));
00304 
00305       /* Compute tile slope */
00306       Slope tileh = (z_max > z_min + 1 ? SLOPE_STEEP : SLOPE_FLAT);
00307       if (z_W > z_min) tileh |= SLOPE_W;
00308       if (z_S > z_min) tileh |= SLOPE_S;
00309       if (z_E > z_min) tileh |= SLOPE_E;
00310       if (z_N > z_min) tileh |= SLOPE_N;
00311 
00312       /* Check if bridge would take damage */
00313       if (direction == 1 && MayHaveBridgeAbove(tile) && IsBridgeAbove(tile) &&
00314           GetBridgeHeight(GetSouthernBridgeEnd(tile)) <= z_max * TILE_HEIGHT) {
00315         _terraform_err_tile = tile; // highlight the tile under the bridge
00316         return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00317       }
00318       /* Check if tunnel would take damage */
00319       if (direction == -1 && IsTunnelInWay(tile, z_min * TILE_HEIGHT)) {
00320         _terraform_err_tile = tile; // highlight the tile above the tunnel
00321         return_cmd_error(STR_ERROR_EXCAVATION_WOULD_DAMAGE);
00322       }
00323 
00324       /* Is the tile already cleared? */
00325       const ClearedObjectArea *coa = FindClearedObject(tile);
00326       bool indirectly_cleared = coa != NULL && coa->first_tile != tile;
00327 
00328       /* Check tiletype-specific things, and add extra-cost */
00329       const bool curr_gen = _generating_world;
00330       if (_game_mode == GM_EDITOR) _generating_world = true; // used to create green terraformed land
00331       DoCommandFlag tile_flags = flags | DC_AUTO | DC_FORCE_CLEAR_TILE;
00332       if (pass == 0) {
00333         tile_flags &= ~DC_EXEC;
00334         tile_flags |= DC_NO_MODIFY_TOWN_RATING;
00335       }
00336       CommandCost cost;
00337       if (indirectly_cleared) {
00338         cost = DoCommand(tile, 0, 0, tile_flags, CMD_LANDSCAPE_CLEAR);
00339       } else {
00340         cost = _tile_type_procs[GetTileType(tile)]->terraform_tile_proc(tile, tile_flags, z_min * TILE_HEIGHT, tileh);
00341       }
00342       _generating_world = curr_gen;
00343       if (cost.Failed()) {
00344         _terraform_err_tile = tile;
00345         return cost;
00346       }
00347       if (pass == 1) total_cost.AddCost(cost);
00348     }
00349   }
00350 
00351   Company *c = Company::GetIfValid(_current_company);
00352   if (c != NULL && (int)GB(c->terraform_limit, 16, 16) < ts.modheight_count) {
00353     return_cmd_error(STR_ERROR_TERRAFORM_LIMIT_REACHED);
00354   }
00355 
00356   if (flags & DC_EXEC) {
00357     /* change the height */
00358     {
00359       int count;
00360       TerraformerHeightMod *mod;
00361 
00362       mod = ts.modheight;
00363       for (count = ts.modheight_count; count != 0; count--, mod++) {
00364         TileIndex til = mod->tile;
00365 
00366         SetTileHeight(til, mod->height);
00367       }
00368     }
00369 
00370     /* finally mark the dirty tiles dirty */
00371     {
00372       int count;
00373       TileIndex *ti = ts.tile_table;
00374       for (count = ts.tile_table_count; count != 0; count--, ti++) {
00375         MarkTileDirtyByTile(*ti);
00376       }
00377     }
00378 
00379     if (c != NULL) c->terraform_limit -= ts.modheight_count << 16;
00380   }
00381   return total_cost;
00382 }
00383 
00384 
00396 CommandCost CmdLevelLand(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00397 {
00398   if (p1 >= MapSize()) return CMD_ERROR;
00399 
00400   _terraform_err_tile = INVALID_TILE;
00401 
00402   /* remember level height */
00403   uint oldh = TileHeight(p1);
00404 
00405   /* compute new height */
00406   uint h = oldh;
00407   LevelMode lm = (LevelMode)GB(p2, 1, 2);
00408   switch (lm) {
00409     case LM_LEVEL: break;
00410     case LM_RAISE: h++; break;
00411     case LM_LOWER: h--; break;
00412     default: return CMD_ERROR;
00413   }
00414 
00415   /* Check range of destination height */
00416   if (h > MAX_TILE_HEIGHT) return_cmd_error((oldh == 0) ? STR_ERROR_ALREADY_AT_SEA_LEVEL : STR_ERROR_TOO_HIGH);
00417 
00418   Money money = GetAvailableMoneyForCommand();
00419   CommandCost cost(EXPENSES_CONSTRUCTION);
00420   CommandCost last_error(lm == LM_LEVEL ? STR_ERROR_ALREADY_LEVELLED : INVALID_STRING_ID);
00421   bool had_success = false;
00422 
00423   const Company *c = Company::GetIfValid(_current_company);
00424   int limit = (c == NULL ? INT32_MAX : GB(c->terraform_limit, 16, 16));
00425   if (limit == 0) return_cmd_error(STR_ERROR_TERRAFORM_LIMIT_REACHED);
00426 
00427   TileArea ta(tile, p1);
00428   TileIterator *iter = HasBit(p2, 0) ? (TileIterator *)new DiagonalTileIterator(tile, p1) : new OrthogonalTileIterator(ta);
00429   for (; *iter != INVALID_TILE; ++(*iter)) {
00430     TileIndex t = *iter;
00431     uint curh = TileHeight(t);
00432     while (curh != h) {
00433       CommandCost ret = DoCommand(t, SLOPE_N, (curh > h) ? 0 : 1, flags & ~DC_EXEC, CMD_TERRAFORM_LAND);
00434       if (ret.Failed()) {
00435         last_error = ret;
00436 
00437         /* Did we reach the limit? */
00438         if (ret.GetErrorMessage() == STR_ERROR_TERRAFORM_LIMIT_REACHED) limit = 0;
00439         break;
00440       }
00441 
00442       if (flags & DC_EXEC) {
00443         money -= ret.GetCost();
00444         if (money < 0) {
00445           _additional_cash_required = ret.GetCost();
00446           delete iter;
00447           return cost;
00448         }
00449         DoCommand(t, SLOPE_N, (curh > h) ? 0 : 1, flags, CMD_TERRAFORM_LAND);
00450       } else {
00451         /* When we're at the terraform limit we better bail (unneeded) testing as well.
00452          * This will probably cause the terraforming cost to be underestimated, but only
00453          * when it's near the terraforming limit. Even then, the estimation is
00454          * completely off due to it basically counting terraforming double, so it being
00455          * cut off earlier might even give a better estimate in some cases. */
00456         if (--limit <= 0) {
00457           had_success = true;
00458           break;
00459         }
00460       }
00461 
00462       cost.AddCost(ret);
00463       curh += (curh > h) ? -1 : 1;
00464       had_success = true;
00465     }
00466 
00467     if (limit <= 0) break;
00468   }
00469 
00470   delete iter;
00471   return had_success ? cost : last_error;
00472 }

Generated on Thu Jan 20 22:57:42 2011 for OpenTTD by  doxygen 1.6.1