# object_cmd.cpp

Go to the documentation of this file.

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