object_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: object_cmd.cpp 23051 2011-10-22 20:45:19Z 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 "landscape.h"
00014 #include "command_func.h"
00015 #include "viewport_func.h"
00016 #include "company_base.h"
00017 #include "town.h"
00018 #include "bridge_map.h"
00019 #include "genworld.h"
00020 #include "autoslope.h"
00021 #include "clear_func.h"
00022 #include "water.h"
00023 #include "window_func.h"
00024 #include "company_gui.h"
00025 #include "cheat_type.h"
00026 #include "object.h"
00027 #include "cargopacket.h"
00028 #include "sprite.h"
00029 #include "core/random_func.hpp"
00030 #include "core/pool_func.hpp"
00031 #include "object_map.h"
00032 #include "object_base.h"
00033 #include "newgrf_config.h"
00034 #include "newgrf_object.h"
00035 #include "date_func.h"
00036 #include "newgrf_debug.h"
00037 
00038 #include "table/strings.h"
00039 #include "table/object_land.h"
00040 
00041 ObjectPool _object_pool("Object");
00042 INSTANTIATE_POOL_METHODS(Object)
00043 uint16 Object::counts[NUM_OBJECTS];
00044 
00050 /* static */ Object *Object::GetByTile(TileIndex tile)
00051 {
00052   return Object::Get(GetObjectIndex(tile));
00053 }
00054 
00056 void InitializeObjects()
00057 {
00058   _object_pool.CleanPool();
00059   Object::ResetTypeCounts();
00060 }
00061 
00072 void BuildObject(ObjectType type, TileIndex tile, CompanyID owner, Town *town, uint8 view)
00073 {
00074   const ObjectSpec *spec = ObjectSpec::Get(type);
00075 
00076   TileArea ta(tile, GB(spec->size, HasBit(view, 0) ? 4 : 0, 4), GB(spec->size, HasBit(view, 0) ? 0 : 4, 4));
00077   Object *o = new Object();
00078   o->location      = ta;
00079   o->town          = town == NULL ? CalcClosestTownFromTile(tile) : town;
00080   o->build_date    = _date;
00081   o->view          = view;
00082 
00083   /* If nothing owns the object, the colour will be random. Otherwise
00084    * get the colour from the company's livery settings. */
00085   if (owner == OWNER_NONE) {
00086     o->colour = Random();
00087   } else {
00088     const Livery *l = Company::Get(owner)->livery;
00089     o->colour = l->colour1 + l->colour2 * 16;
00090   }
00091 
00092   /* If the object wants only one colour, then give it that colour. */
00093   if ((spec->flags & OBJECT_FLAG_2CC_COLOUR) == 0) o->colour &= 0xF;
00094 
00095   if (HasBit(spec->callback_mask, CBM_OBJ_COLOUR)) {
00096     uint16 res = GetObjectCallback(CBID_OBJECT_COLOUR, o->colour, 0, spec, o, tile);
00097     if (res != CALLBACK_FAILED) o->colour = GB(res, 0, 8);
00098   }
00099 
00100   assert(o->town != NULL);
00101 
00102   TILE_AREA_LOOP(t, ta) {
00103     WaterClass wc = (IsWaterTile(t) ? GetWaterClass(t) : WATER_CLASS_INVALID);
00104     MakeObject(t, type, owner, o->index, wc, Random());
00105     MarkTileDirtyByTile(t);
00106   }
00107 
00108   Object::IncTypeCount(type);
00109   if (spec->flags & OBJECT_FLAG_ANIMATION) TriggerObjectAnimation(o, OAT_BUILT, spec);
00110 }
00111 
00116 static void IncreaseAnimationStage(TileIndex tile)
00117 {
00118   TileArea ta = Object::GetByTile(tile)->location;
00119   TILE_AREA_LOOP(t, ta) {
00120     SetAnimationFrame(t, GetAnimationFrame(t) + 1);
00121     MarkTileDirtyByTile(t);
00122   }
00123 }
00124 
00126 #define GetCompanyHQSize GetAnimationFrame
00127 
00128 #define IncreaseCompanyHQSize IncreaseAnimationStage
00129 
00135 void UpdateCompanyHQ(TileIndex tile, uint score)
00136 {
00137   if (tile == INVALID_TILE) return;
00138 
00139   byte val;
00140   (val = 0, score < 170) ||
00141   (val++, score < 350) ||
00142   (val++, score < 520) ||
00143   (val++, score < 720) ||
00144   (val++, true);
00145 
00146   while (GetCompanyHQSize(tile) < val) {
00147     IncreaseCompanyHQSize(tile);
00148   }
00149 }
00150 
00155 void UpdateObjectColours(const Company *c)
00156 {
00157   Object *obj;
00158   FOR_ALL_OBJECTS(obj) {
00159     Owner owner = GetTileOwner(obj->location.tile);
00160     /* Not the current owner, so colour doesn't change. */
00161     if (owner != c->index) continue;
00162 
00163     const ObjectSpec *spec = ObjectSpec::GetByTile(obj->location.tile);
00164     /* Using the object colour callback, so not using company colour. */
00165     if (HasBit(spec->callback_mask, CBM_OBJ_COLOUR)) continue;
00166 
00167     const Livery *l = c->livery;
00168     obj->colour = ((spec->flags & OBJECT_FLAG_2CC_COLOUR) ? (l->colour2 * 16) : 0) + l->colour1;
00169   }
00170 }
00171 
00172 extern CommandCost CheckBuildableTile(TileIndex tile, uint invalid_dirs, int &allowed_z, bool check_bridge);
00173 static CommandCost ClearTile_Object(TileIndex tile, DoCommandFlag flags);
00174 
00184 CommandCost CmdBuildObject(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00185 {
00186   CommandCost cost(EXPENSES_PROPERTY);
00187 
00188   ObjectType type = (ObjectType)GB(p1, 0, 8);
00189   uint8 view = GB(p2, 0, 2);
00190   const ObjectSpec *spec = ObjectSpec::Get(type);
00191   if (!spec->IsAvailable()) return CMD_ERROR;
00192 
00193   if (spec->flags & OBJECT_FLAG_ONLY_IN_SCENEDIT && (_game_mode != GM_EDITOR || _current_company != OWNER_NONE)) return CMD_ERROR;
00194   if (spec->flags & OBJECT_FLAG_ONLY_IN_GAME && (_game_mode != GM_NORMAL || _current_company > MAX_COMPANIES)) return CMD_ERROR;
00195   if (view >= spec->views) return CMD_ERROR;
00196 
00197   if (!Object::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_OBJECTS);
00198   if (Town::GetNumItems() == 0) return_cmd_error(STR_ERROR_MUST_FOUND_TOWN_FIRST);
00199 
00200   int size_x = GB(spec->size, HasBit(view, 0) ? 4 : 0, 4);
00201   int size_y = GB(spec->size, HasBit(view, 0) ? 0 : 4, 4);
00202   TileArea ta(tile, size_x, size_y);
00203 
00204   if (type == OBJECT_OWNED_LAND) {
00205     /* Owned land is special as it can be placed on any slope. */
00206     cost.AddCost(DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR));
00207   } else {
00208     /* Check the surface to build on. At this time we can't actually execute the
00209      * the CLEAR_TILE commands since the newgrf callback later on can check
00210      * some information about the tiles. */
00211     bool allow_water = (spec->flags & (OBJECT_FLAG_BUILT_ON_WATER | OBJECT_FLAG_NOT_ON_LAND)) != 0;
00212     bool allow_ground = (spec->flags & OBJECT_FLAG_NOT_ON_LAND) == 0;
00213     TILE_AREA_LOOP(t, ta) {
00214       if (HasTileWaterGround(t)) {
00215         if (!allow_water) return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
00216         if (!IsWaterTile(t)) {
00217           /* Normal water tiles don't have to be cleared. For all other tile types clear
00218            * the tile but leave the water. */
00219           cost.AddCost(DoCommand(t, 0, 0, flags & ~DC_NO_WATER & ~DC_EXEC, CMD_LANDSCAPE_CLEAR));
00220         } else {
00221           /* Can't build on water owned by another company. */
00222           Owner o = GetTileOwner(t);
00223           if (o != OWNER_NONE && o != OWNER_WATER) cost.AddCost(CheckOwnership(o, t));
00224         }
00225       } else {
00226         if (!allow_ground) return_cmd_error(STR_ERROR_MUST_BE_BUILT_ON_WATER);
00227         /* For non-water tiles, we'll have to clear it before building. */
00228         cost.AddCost(DoCommand(t, 0, 0, flags & ~DC_EXEC, CMD_LANDSCAPE_CLEAR));
00229       }
00230     }
00231 
00232     /* So, now the surface is checked... check the slope of said surface. */
00233     int allowed_z;
00234     if (GetTileSlope(tile, (uint*)&allowed_z) != SLOPE_FLAT) allowed_z += TILE_HEIGHT;
00235 
00236     TILE_AREA_LOOP(t, ta) {
00237       uint16 callback = CALLBACK_FAILED;
00238       if (HasBit(spec->callback_mask, CBM_OBJ_SLOPE_CHECK)) {
00239         TileIndex diff = t - tile;
00240         callback = GetObjectCallback(CBID_OBJECT_LAND_SLOPE_CHECK, GetTileSlope(t, NULL), TileY(diff) << 4 | TileX(diff), spec, NULL, t, view);
00241       }
00242 
00243       if (callback == CALLBACK_FAILED) {
00244         cost.AddCost(CheckBuildableTile(t, 0, allowed_z, false));
00245       } else if (callback != 0) {
00246         return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION);
00247       }
00248     }
00249 
00250     if (flags & DC_EXEC) {
00251       /* This is basically a copy of the loop above with the exception that we now
00252        * execute the commands and don't check for errors, since that's already done. */
00253       TILE_AREA_LOOP(t, ta) {
00254         if (HasTileWaterGround(t)) {
00255           if (!IsWaterTile(t)) {
00256             DoCommand(t, 0, 0, (flags & ~DC_NO_WATER) | DC_NO_MODIFY_TOWN_RATING, CMD_LANDSCAPE_CLEAR);
00257           }
00258         } else {
00259           DoCommand(t, 0, 0, flags | DC_NO_MODIFY_TOWN_RATING, CMD_LANDSCAPE_CLEAR);
00260         }
00261       }
00262     }
00263   }
00264   if (cost.Failed()) return cost;
00265 
00266   /* Finally do a check for bridges. */
00267   TILE_AREA_LOOP(t, ta) {
00268     if (MayHaveBridgeAbove(t) && IsBridgeAbove(t) && (
00269         !(spec->flags & OBJECT_FLAG_ALLOW_UNDER_BRIDGE) ||
00270         (GetTileMaxZ(t) + spec->height * TILE_HEIGHT >= GetBridgeHeight(GetSouthernBridgeEnd(t))))) {
00271       return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00272     }
00273   }
00274 
00275   int hq_score = 0;
00276   switch (type) {
00277     case OBJECT_TRANSMITTER:
00278     case OBJECT_LIGHTHOUSE:
00279       if (GetTileSlope(tile, NULL) != SLOPE_FLAT) return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00280       break;
00281 
00282     case OBJECT_OWNED_LAND:
00283       if (IsTileType(tile, MP_OBJECT) &&
00284           IsTileOwner(tile, _current_company) &&
00285           IsOwnedLand(tile)) {
00286         return_cmd_error(STR_ERROR_YOU_ALREADY_OWN_IT);
00287       }
00288       break;
00289 
00290     case OBJECT_HQ: {
00291       Company *c = Company::Get(_current_company);
00292       if (c->location_of_HQ != INVALID_TILE) {
00293         /* We need to persuade a bit harder to remove the old HQ. */
00294         _current_company = OWNER_WATER;
00295         cost.AddCost(ClearTile_Object(c->location_of_HQ, flags));
00296         _current_company = c->index;
00297       }
00298 
00299       if (flags & DC_EXEC) {
00300         hq_score = UpdateCompanyRatingAndValue(c, false);
00301         c->location_of_HQ = tile;
00302         SetWindowDirty(WC_COMPANY, c->index);
00303       }
00304       break;
00305     }
00306 
00307     case OBJECT_STATUE:
00308       /* This may never be constructed using this method. */
00309       return CMD_ERROR;
00310 
00311     default: // i.e. NewGRF provided.
00312       break;
00313   }
00314 
00315   if (flags & DC_EXEC) {
00316     BuildObject(type, tile, _current_company, NULL, view);
00317 
00318     /* Make sure the HQ starts at the right size. */
00319     if (type == OBJECT_HQ) UpdateCompanyHQ(tile, hq_score);
00320   }
00321 
00322   cost.AddCost(ObjectSpec::Get(type)->GetBuildCost() * size_x * size_y);
00323   return cost;
00324 }
00325 
00326 
00327 static Foundation GetFoundation_Object(TileIndex tile, Slope tileh);
00328 
00329 static void DrawTile_Object(TileInfo *ti)
00330 {
00331   ObjectType type = GetObjectType(ti->tile);
00332   const ObjectSpec *spec = ObjectSpec::Get(type);
00333 
00334   /* Fall back for when the object doesn't exist anymore. */
00335   if (!spec->enabled) type = OBJECT_TRANSMITTER;
00336 
00337   if ((spec->flags & OBJECT_FLAG_HAS_NO_FOUNDATION) == 0) DrawFoundation(ti, GetFoundation_Object(ti->tile, ti->tileh));
00338 
00339   if (type < NEW_OBJECT_OFFSET) {
00340     const DrawTileSprites *dts = NULL;
00341     Owner to = GetTileOwner(ti->tile);
00342     PaletteID palette = to == OWNER_NONE ? PAL_NONE : COMPANY_SPRITE_COLOUR(to);
00343 
00344     if (type == OBJECT_HQ) {
00345       TileIndex diff = ti->tile - Object::GetByTile(ti->tile)->location.tile;
00346       dts = &_object_hq[GetCompanyHQSize(ti->tile) << 2 | TileY(diff) << 1 | TileX(diff)];
00347     } else {
00348       dts = &_objects[type];
00349     }
00350 
00351     if (spec->flags & OBJECT_FLAG_HAS_NO_FOUNDATION) {
00352       /* If an object has no foundation, but tries to draw a (flat) ground
00353        * type... we have to be nice and convert that for them. */
00354       switch (dts->ground.sprite) {
00355         case SPR_FLAT_BARE_LAND:          DrawClearLandTile(ti, 0); break;
00356         case SPR_FLAT_1_THIRD_GRASS_TILE: DrawClearLandTile(ti, 1); break;
00357         case SPR_FLAT_2_THIRD_GRASS_TILE: DrawClearLandTile(ti, 2); break;
00358         case SPR_FLAT_GRASS_TILE:         DrawClearLandTile(ti, 3); break;
00359         default: DrawGroundSprite(dts->ground.sprite, palette);     break;
00360       }
00361     } else {
00362       DrawGroundSprite(dts->ground.sprite, palette);
00363     }
00364 
00365     if (!IsInvisibilitySet(TO_STRUCTURES)) {
00366       const DrawTileSeqStruct *dtss;
00367       foreach_draw_tile_seq(dtss, dts->seq) {
00368         AddSortableSpriteToDraw(
00369           dtss->image.sprite, palette,
00370           ti->x + dtss->delta_x, ti->y + dtss->delta_y,
00371           dtss->size_x, dtss->size_y,
00372           dtss->size_z, ti->z + dtss->delta_z,
00373           IsTransparencySet(TO_STRUCTURES)
00374         );
00375       }
00376     }
00377   } else {
00378     DrawNewObjectTile(ti, spec);
00379   }
00380 
00381   if (spec->flags & OBJECT_FLAG_ALLOW_UNDER_BRIDGE) DrawBridgeMiddle(ti);
00382 }
00383 
00384 static uint GetSlopeZ_Object(TileIndex tile, uint x, uint y)
00385 {
00386   if (IsOwnedLand(tile)) {
00387     uint z;
00388     Slope tileh = GetTileSlope(tile, &z);
00389 
00390     return z + GetPartialZ(x & 0xF, y & 0xF, tileh);
00391   } else {
00392     return GetTileMaxZ(tile);
00393   }
00394 }
00395 
00396 static Foundation GetFoundation_Object(TileIndex tile, Slope tileh)
00397 {
00398   return IsOwnedLand(tile) ? FOUNDATION_NONE : FlatteningFoundation(tileh);
00399 }
00400 
00405 static void ReallyClearObjectTile(Object *o)
00406 {
00407   Object::DecTypeCount(GetObjectType(o->location.tile));
00408   TILE_AREA_LOOP(tile_cur, o->location) {
00409     DeleteNewGRFInspectWindow(GSF_OBJECTS, tile_cur);
00410 
00411     MakeWaterKeepingClass(tile_cur, GetTileOwner(tile_cur));
00412   }
00413   delete o;
00414 }
00415 
00416 SmallVector<ClearedObjectArea, 4> _cleared_object_areas;
00417 
00423 ClearedObjectArea *FindClearedObject(TileIndex tile)
00424 {
00425   TileArea ta = TileArea(tile, 1, 1);
00426 
00427   const ClearedObjectArea *end = _cleared_object_areas.End();
00428   for (ClearedObjectArea *coa = _cleared_object_areas.Begin(); coa != end; coa++) {
00429     if (coa->area.Intersects(ta)) return coa;
00430   }
00431 
00432   return NULL;
00433 }
00434 
00435 static CommandCost ClearTile_Object(TileIndex tile, DoCommandFlag flags)
00436 {
00437   ObjectType type = GetObjectType(tile);
00438   const ObjectSpec *spec = ObjectSpec::Get(type);
00439 
00440   /* Get to the northern most tile. */
00441   Object *o = Object::GetByTile(tile);
00442   TileArea ta = o->location;
00443 
00444   CommandCost cost(EXPENSES_CONSTRUCTION, spec->GetClearCost() * ta.w * ta.h / 5);
00445   if (spec->flags & OBJECT_FLAG_CLEAR_INCOME) cost.MultiplyCost(-1); // They get an income!
00446 
00447   /* Water can remove everything! */
00448   if (_current_company != OWNER_WATER) {
00449     if ((flags & DC_NO_WATER) && IsTileOnWater(tile)) {
00450       /* There is water under the object, treat it as water tile. */
00451       return_cmd_error(STR_ERROR_CAN_T_BUILD_ON_WATER);
00452     } else if (!(spec->flags & OBJECT_FLAG_AUTOREMOVE) && (flags & DC_AUTO)) {
00453       /* No automatic removal by overbuilding stuff. */
00454       return_cmd_error(type == OBJECT_HQ ? STR_ERROR_COMPANY_HEADQUARTERS_IN : STR_ERROR_OBJECT_IN_THE_WAY);
00455     } else if (_game_mode == GM_EDITOR) {
00456       /* No further limitations for the editor. */
00457     } else if (GetTileOwner(tile) == OWNER_NONE) {
00458       /* Owned by nobody, so we can only remove it with brute force! */
00459       if (!_cheats.magic_bulldozer.value) return CMD_ERROR;
00460     } else if (CheckTileOwnership(tile).Failed()) {
00461       /* We don't own it!. */
00462       return_cmd_error(STR_ERROR_OWNED_BY);
00463     } else if ((spec->flags & OBJECT_FLAG_CANNOT_REMOVE) != 0 && (spec->flags & OBJECT_FLAG_AUTOREMOVE) == 0) {
00464       /* In the game editor or with cheats we can remove, otherwise we can't. */
00465       if (!_cheats.magic_bulldozer.value) return CMD_ERROR;
00466 
00467       /* Removing with the cheat costs more in TTDPatch / the specs. */
00468       cost.MultiplyCost(25);
00469     }
00470   } else if ((spec->flags & (OBJECT_FLAG_BUILT_ON_WATER | OBJECT_FLAG_NOT_ON_LAND)) != 0) {
00471     /* Water can't remove objects that are buildable on water. */
00472     return CMD_ERROR;
00473   }
00474 
00475   switch (type) {
00476     case OBJECT_HQ: {
00477       Company *c = Company::Get(GetTileOwner(tile));
00478       if (flags & DC_EXEC) {
00479         c->location_of_HQ = INVALID_TILE; // reset HQ position
00480         SetWindowDirty(WC_COMPANY, c->index);
00481         CargoPacket::InvalidateAllFrom(ST_HEADQUARTERS, c->index);
00482       }
00483 
00484       /* cost of relocating company is 1% of company value */
00485       cost = CommandCost(EXPENSES_PROPERTY, CalculateCompanyValue(c) / 100);
00486       break;
00487     }
00488 
00489     case OBJECT_STATUE:
00490       if (flags & DC_EXEC) {
00491         Town *town = o->town;
00492         ClrBit(town->statues, GetTileOwner(tile));
00493         SetWindowDirty(WC_TOWN_AUTHORITY, town->index);
00494       }
00495       break;
00496 
00497     default:
00498       break;
00499   }
00500 
00501   ClearedObjectArea *cleared_area = _cleared_object_areas.Append();
00502   cleared_area->first_tile = tile;
00503   cleared_area->area = ta;
00504 
00505   if (flags & DC_EXEC) ReallyClearObjectTile(o);
00506 
00507   return cost;
00508 }
00509 
00510 static void AddAcceptedCargo_Object(TileIndex tile, CargoArray &acceptance, uint32 *always_accepted)
00511 {
00512   if (!IsCompanyHQ(tile)) return;
00513 
00514   /* HQ accepts passenger and mail; but we have to divide the values
00515    * between 4 tiles it occupies! */
00516 
00517   /* HQ level (depends on company performance) in the range 1..5. */
00518   uint level = GetCompanyHQSize(tile) + 1;
00519 
00520   /* Top town building generates 10, so to make HQ interesting, the top
00521    * type makes 20. */
00522   acceptance[CT_PASSENGERS] += max(1U, level);
00523   SetBit(*always_accepted, CT_PASSENGERS);
00524 
00525   /* Top town building generates 4, HQ can make up to 8. The
00526    * proportion passengers:mail is different because such a huge
00527    * commercial building generates unusually high amount of mail
00528    * correspondence per physical visitor. */
00529   acceptance[CT_MAIL] += max(1U, level / 2);
00530   SetBit(*always_accepted, CT_MAIL);
00531 }
00532 
00533 
00534 static void GetTileDesc_Object(TileIndex tile, TileDesc *td)
00535 {
00536   const ObjectSpec *spec = ObjectSpec::GetByTile(tile);
00537   td->str = spec->name;
00538   td->owner[0] = GetTileOwner(tile);
00539   td->build_date = Object::GetByTile(tile)->build_date;
00540 
00541   if (spec->grf_prop.grffile != NULL) {
00542     td->grf = GetGRFConfig(spec->grf_prop.grffile->grfid)->GetName();
00543   }
00544 }
00545 
00546 static void TileLoop_Object(TileIndex tile)
00547 {
00548   const ObjectSpec *spec = ObjectSpec::GetByTile(tile);
00549   if (spec->flags & OBJECT_FLAG_ANIMATION) {
00550     const Object *o = Object::GetByTile(tile);
00551     TriggerObjectTileAnimation(o, tile, OAT_TILELOOP, spec);
00552     if (o->location.tile == tile) TriggerObjectAnimation(o, OAT_256_TICKS, spec);
00553   }
00554 
00555   if (IsTileOnWater(tile)) TileLoop_Water(tile);
00556 
00557   if (!IsCompanyHQ(tile)) return;
00558 
00559   /* HQ accepts passenger and mail; but we have to divide the values
00560    * between 4 tiles it occupies! */
00561 
00562   /* HQ level (depends on company performance) in the range 1..5. */
00563   uint level = GetCompanyHQSize(tile) + 1;
00564   assert(level < 6);
00565 
00566   StationFinder stations(TileArea(tile, 2, 2));
00567 
00568   uint r = Random();
00569   /* Top town buildings generate 250, so the top HQ type makes 256. */
00570   if (GB(r, 0, 8) < (256 / 4 / (6 - level))) {
00571     uint amt = GB(r, 0, 8) / 8 / 4 + 1;
00572     if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
00573     MoveGoodsToStation(CT_PASSENGERS, amt, ST_HEADQUARTERS, GetTileOwner(tile), stations.GetStations());
00574   }
00575 
00576   /* Top town building generates 90, HQ can make up to 196. The
00577    * proportion passengers:mail is about the same as in the acceptance
00578    * equations. */
00579   if (GB(r, 8, 8) < (196 / 4 / (6 - level))) {
00580     uint amt = GB(r, 8, 8) / 8 / 4 + 1;
00581     if (EconomyIsInRecession()) amt = (amt + 1) >> 1;
00582     MoveGoodsToStation(CT_MAIL, amt, ST_HEADQUARTERS, GetTileOwner(tile), stations.GetStations());
00583   }
00584 }
00585 
00586 
00587 static TrackStatus GetTileTrackStatus_Object(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
00588 {
00589   return 0;
00590 }
00591 
00592 static bool ClickTile_Object(TileIndex tile)
00593 {
00594   if (!IsCompanyHQ(tile)) return false;
00595 
00596   ShowCompany(GetTileOwner(tile));
00597   return true;
00598 }
00599 
00600 static void AnimateTile_Object(TileIndex tile)
00601 {
00602   AnimateNewObjectTile(tile);
00603 }
00604 
00611 static bool HasTransmitter(TileIndex tile, void *user)
00612 {
00613   return IsTransmitterTile(tile);
00614 }
00615 
00616 void GenerateObjects()
00617 {
00618   if (_settings_game.game_creation.landscape == LT_TOYLAND) return;
00619 
00620   /* add radio tower */
00621   int radiotower_to_build = ScaleByMapSize(15); // maximum number of radio towers on the map
00622   int lighthouses_to_build = _settings_game.game_creation.landscape == LT_TROPIC ? 0 : ScaleByMapSize1D((Random() & 3) + 7);
00623 
00624   /* Scale the amount of lighthouses with the amount of land at the borders. */
00625   if (_settings_game.construction.freeform_edges && lighthouses_to_build != 0) {
00626     uint num_water_tiles = 0;
00627     for (uint x = 0; x < MapMaxX(); x++) {
00628       if (IsTileType(TileXY(x, 1), MP_WATER)) num_water_tiles++;
00629       if (IsTileType(TileXY(x, MapMaxY() - 1), MP_WATER)) num_water_tiles++;
00630     }
00631     for (uint y = 1; y < MapMaxY() - 1; y++) {
00632       if (IsTileType(TileXY(1, y), MP_WATER)) num_water_tiles++;
00633       if (IsTileType(TileXY(MapMaxX() - 1, y), MP_WATER)) num_water_tiles++;
00634     }
00635     /* The -6 is because the top borders are MP_VOID (-2) and all corners
00636      * are counted twice (-4). */
00637     lighthouses_to_build = lighthouses_to_build * num_water_tiles / (2 * MapMaxY() + 2 * MapMaxX() - 6);
00638   }
00639 
00640   SetGeneratingWorldProgress(GWP_OBJECT, radiotower_to_build + lighthouses_to_build);
00641 
00642   for (uint i = ScaleByMapSize(1000); i != 0 && Object::CanAllocateItem(); i--) {
00643     TileIndex tile = RandomTile();
00644 
00645     uint h;
00646     if (IsTileType(tile, MP_CLEAR) && GetTileSlope(tile, &h) == SLOPE_FLAT && h >= TILE_HEIGHT * 4 && !IsBridgeAbove(tile)) {
00647       TileIndex t = tile;
00648       if (CircularTileSearch(&t, 9, HasTransmitter, NULL)) continue;
00649 
00650       BuildObject(OBJECT_TRANSMITTER, tile);
00651       IncreaseGeneratingWorldProgress(GWP_OBJECT);
00652       if (--radiotower_to_build == 0) break;
00653     }
00654   }
00655 
00656   /* add lighthouses */
00657   uint maxx = MapMaxX();
00658   uint maxy = MapMaxY();
00659   for (int loop_count = 0; loop_count < 1000 && lighthouses_to_build != 0 && Object::CanAllocateItem(); loop_count++) {
00660     uint r = Random();
00661 
00662     /* Scatter the lighthouses more evenly around the perimeter */
00663     int perimeter = (GB(r, 16, 16) % (2 * (maxx + maxy))) - maxy;
00664     DiagDirection dir;
00665     for (dir = DIAGDIR_NE; perimeter > 0; dir++) {
00666       perimeter -= (DiagDirToAxis(dir) == AXIS_X) ? maxx : maxy;
00667     }
00668 
00669     TileIndex tile;
00670     switch (dir) {
00671       default:
00672       case DIAGDIR_NE: tile = TileXY(maxx - 1, r % maxy); break;
00673       case DIAGDIR_SE: tile = TileXY(r % maxx, 1); break;
00674       case DIAGDIR_SW: tile = TileXY(1,        r % maxy); break;
00675       case DIAGDIR_NW: tile = TileXY(r % maxx, maxy - 1); break;
00676     }
00677 
00678     /* Only build lighthouses at tiles where the border is sea. */
00679     if (!IsTileType(tile, MP_WATER)) continue;
00680 
00681     for (int j = 0; j < 19; j++) {
00682       uint h;
00683       if (IsTileType(tile, MP_CLEAR) && GetTileSlope(tile, &h) == SLOPE_FLAT && h <= TILE_HEIGHT * 2 && !IsBridgeAbove(tile)) {
00684         BuildObject(OBJECT_LIGHTHOUSE, tile);
00685         IncreaseGeneratingWorldProgress(GWP_OBJECT);
00686         lighthouses_to_build--;
00687         assert(tile < MapSize());
00688         break;
00689       }
00690       tile = AddTileIndexDiffCWrap(tile, TileIndexDiffCByDiagDir(dir));
00691       if (tile == INVALID_TILE) break;
00692     }
00693   }
00694 }
00695 
00696 static void ChangeTileOwner_Object(TileIndex tile, Owner old_owner, Owner new_owner)
00697 {
00698   if (!IsTileOwner(tile, old_owner)) return;
00699 
00700   if (IsOwnedLand(tile) && new_owner != INVALID_OWNER) {
00701     SetTileOwner(tile, new_owner);
00702   } else if (IsStatueTile(tile)) {
00703     Town *t = Object::GetByTile(tile)->town;
00704     ClrBit(t->statues, old_owner);
00705     if (new_owner != INVALID_OWNER && !HasBit(t->statues, new_owner)) {
00706       /* Transfer ownership to the new company */
00707       SetBit(t->statues, new_owner);
00708       SetTileOwner(tile, new_owner);
00709     } else {
00710       ReallyClearObjectTile(Object::GetByTile(tile));
00711     }
00712 
00713     SetWindowDirty(WC_TOWN_AUTHORITY, t->index);
00714   } else {
00715     ReallyClearObjectTile(Object::GetByTile(tile));
00716   }
00717 }
00718 
00719 static CommandCost TerraformTile_Object(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
00720 {
00721   ObjectType type = GetObjectType(tile);
00722 
00723   if (type == OBJECT_OWNED_LAND) {
00724     /* Owned land remains unsold */
00725     CommandCost ret = CheckTileOwnership(tile);
00726     if (ret.Succeeded()) return CommandCost();
00727   } else if (AutoslopeEnabled() && type != OBJECT_TRANSMITTER && type != OBJECT_LIGHTHOUSE) {
00728     /* Behaviour:
00729      *  - Both new and old slope must not be steep.
00730      *  - TileMaxZ must not be changed.
00731      *  - Allow autoslope by default.
00732      *  - Disallow autoslope if callback succeeds and returns non-zero.
00733      */
00734     Slope tileh_old = GetTileSlope(tile, NULL);
00735     /* TileMaxZ must not be changed. Slopes must not be steep. */
00736     if (!IsSteepSlope(tileh_old) && !IsSteepSlope(tileh_new) && (GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) {
00737       const ObjectSpec *spec = ObjectSpec::Get(type);
00738 
00739       /* Call callback 'disable autosloping for objects'. */
00740       if (HasBit(spec->callback_mask, CBM_OBJ_AUTOSLOPE)) {
00741         /* If the callback fails, allow autoslope. */
00742         uint16 res = GetObjectCallback(CBID_OBJECT_AUTOSLOPE, 0, 0, spec, Object::GetByTile(tile), tile);
00743         if ((res == 0) || (res == CALLBACK_FAILED)) return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
00744       } else if (spec->enabled) {
00745         /* allow autoslope */
00746         return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_FOUNDATION]);
00747       }
00748     }
00749   }
00750 
00751   return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
00752 }
00753 
00754 extern const TileTypeProcs _tile_type_object_procs = {
00755   DrawTile_Object,             // draw_tile_proc
00756   GetSlopeZ_Object,            // get_slope_z_proc
00757   ClearTile_Object,            // clear_tile_proc
00758   AddAcceptedCargo_Object,     // add_accepted_cargo_proc
00759   GetTileDesc_Object,          // get_tile_desc_proc
00760   GetTileTrackStatus_Object,   // get_tile_track_status_proc
00761   ClickTile_Object,            // click_tile_proc
00762   AnimateTile_Object,          // animate_tile_proc
00763   TileLoop_Object,             // tile_loop_clear
00764   ChangeTileOwner_Object,      // change_tile_owner_clear
00765   NULL,                        // add_produced_cargo_proc
00766   NULL,                        // vehicle_enter_tile_proc
00767   GetFoundation_Object,        // get_foundation_proc
00768   TerraformTile_Object,        // terraform_tile_proc
00769 };