# object_cmd.cpp

Go to the documentation of this file.

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