waypoint_cmd.cpp

Go to the documentation of this file.
00001 /* $Id: waypoint_cmd.cpp 19665 2010-04-17 22:27:49Z 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 
00014 #include "cmd_helper.h"
00015 #include "command_func.h"
00016 #include "landscape.h"
00017 #include "bridge_map.h"
00018 #include "town.h"
00019 #include "waypoint_base.h"
00020 #include "pathfinder/yapf/yapf_cache.h"
00021 #include "strings_func.h"
00022 #include "functions.h"
00023 #include "window_func.h"
00024 #include "date_func.h"
00025 #include "vehicle_func.h"
00026 #include "string_func.h"
00027 #include "company_func.h"
00028 #include "newgrf_station.h"
00029 #include "company_base.h"
00030 #include "water.h"
00031 
00032 #include "table/strings.h"
00033 
00037 void Waypoint::UpdateVirtCoord()
00038 {
00039   Point pt = RemapCoords2(TileX(this->xy) * TILE_SIZE, TileY(this->xy) * TILE_SIZE);
00040   SetDParam(0, this->index);
00041   this->sign.UpdatePosition(pt.x, pt.y - 0x20, STR_VIEWPORT_WAYPOINT);
00042   /* Recenter viewport */
00043   InvalidateWindowData(WC_WAYPOINT_VIEW, this->index);
00044 }
00045 
00050 static void MakeDefaultWaypointName(Waypoint *wp)
00051 {
00052   uint32 used = 0; // bitmap of used waypoint numbers, sliding window with 'next' as base
00053   uint32 next = 0; // first waypoint number in the bitmap
00054   StationID idx = 0; // index where we will stop
00055 
00056   wp->town = ClosestTownFromTile(wp->xy, UINT_MAX);
00057 
00058   /* Find first unused waypoint number belonging to this town. This can never fail,
00059    * as long as there can be at most 65535 waypoints in total.
00060    *
00061    * This does 'n * m' search, but with 32bit 'used' bitmap, it needs at most 'n * (1 + ceil(m / 32))'
00062    * steps (n - number of waypoints in pool, m - number of waypoints near this town).
00063    * Usually, it needs only 'n' steps.
00064    *
00065    * If it wasn't using 'used' and 'idx', it would just search for increasing 'next',
00066    * but this way it is faster */
00067 
00068   StationID cid = 0; // current index, goes to Waypoint::GetPoolSize()-1, then wraps to 0
00069   do {
00070     Waypoint *lwp = Waypoint::GetIfValid(cid);
00071 
00072     /* check only valid waypoints... */
00073     if (lwp != NULL && wp != lwp) {
00074       /* only waypoints with 'generic' name within the same city */
00075       if (lwp->name == NULL && lwp->town == wp->town && lwp->string_id == wp->string_id) {
00076         /* if lwp->town_cn < next, uint will overflow to '+inf' */
00077         uint i = (uint)lwp->town_cn - next;
00078 
00079         if (i < 32) {
00080           SetBit(used, i); // update bitmap
00081           if (i == 0) {
00082             /* shift bitmap while the lowest bit is '1';
00083              * increase the base of the bitmap too */
00084             do {
00085               used >>= 1;
00086               next++;
00087             } while (HasBit(used, 0));
00088             /* when we are at 'idx' again at end of the loop and
00089              * 'next' hasn't changed, then no waypoint had town_cn == next,
00090              * so we can safely use it */
00091             idx = cid;
00092           }
00093         }
00094       }
00095     }
00096 
00097     cid++;
00098     if (cid == Waypoint::GetPoolSize()) cid = 0; // wrap to zero...
00099   } while (cid != idx);
00100 
00101   wp->town_cn = (uint16)next; // set index...
00102   wp->name = NULL; // ... and use generic name
00103 }
00104 
00112 static Waypoint *FindDeletedWaypointCloseTo(TileIndex tile, StringID str, CompanyID cid)
00113 {
00114   Waypoint *wp, *best = NULL;
00115   uint thres = 8;
00116 
00117   FOR_ALL_WAYPOINTS(wp) {
00118     if (!wp->IsInUse() && wp->string_id == str && wp->owner == cid) {
00119       uint cur_dist = DistanceManhattan(tile, wp->xy);
00120 
00121       if (cur_dist < thres) {
00122         thres = cur_dist;
00123         best = wp;
00124       }
00125     }
00126   }
00127 
00128   return best;
00129 }
00130 
00138 Axis GetAxisForNewWaypoint(TileIndex tile)
00139 {
00140   /* The axis for rail waypoints is easy. */
00141   if (IsRailWaypointTile(tile)) return GetRailStationAxis(tile);
00142 
00143   /* Non-plain rail type, no valid axis for waypoints. */
00144   if (!IsTileType(tile, MP_RAILWAY) || GetRailTileType(tile) != RAIL_TILE_NORMAL) return INVALID_AXIS;
00145 
00146   switch (GetTrackBits(tile)) {
00147     case TRACK_BIT_X: return AXIS_X;
00148     case TRACK_BIT_Y: return AXIS_Y;
00149     default:          return INVALID_AXIS;
00150   }
00151 }
00152 
00153 CommandCost ClearTile_Station(TileIndex tile, DoCommandFlag flags);
00154 
00161 static CommandCost IsValidTileForWaypoint(TileIndex tile, Axis axis, StationID *waypoint)
00162 {
00163   /* if waypoint is set, then we have special handling to allow building on top of already existing waypoints.
00164    * so waypoint points to INVALID_STATION if we can build on any waypoint.
00165    * Or it points to a waypoint if we're only allowed to build on exactly that waypoint. */
00166   if (waypoint != NULL && IsTileType(tile, MP_STATION)) {
00167     if (!IsRailWaypoint(tile)) {
00168       return ClearTile_Station(tile, DC_AUTO); // get error message
00169     } else {
00170       StationID wp = GetStationIndex(tile);
00171       if (*waypoint == INVALID_STATION) {
00172         *waypoint = wp;
00173       } else if (*waypoint != wp) {
00174         return_cmd_error(STR_ERROR_WAYPOINT_ADJOINS_MORE_THAN_ONE_EXISTING);
00175       }
00176     }
00177   }
00178 
00179   if (GetAxisForNewWaypoint(tile) != axis) return_cmd_error(STR_ERROR_NO_SUITABLE_RAILROAD_TRACK);
00180 
00181   Owner owner = GetTileOwner(tile);
00182   if (!CheckOwnership(owner)) return CMD_ERROR;
00183   if (!EnsureNoVehicleOnGround(tile)) return CMD_ERROR;
00184 
00185   Slope tileh = GetTileSlope(tile, NULL);
00186   if (tileh != SLOPE_FLAT &&
00187       (!_settings_game.construction.build_on_slopes || IsSteepSlope(tileh) || !(tileh & (0x3 << axis)) || !(tileh & ~(0x3 << axis)))) {
00188     return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED);
00189   }
00190 
00191   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00192 
00193   return CommandCost();
00194 }
00195 
00196 extern void GetStationLayout(byte *layout, int numtracks, int plat_len, const StationSpec *statspec);
00197 extern CommandCost FindJoiningWaypoint(StationID existing_station, StationID station_to_join, bool adjacent, TileArea ta, Waypoint **wp);
00198 extern bool CanExpandRailStation(const BaseStation *st, TileArea &new_ta, Axis axis);
00199 
00215 CommandCost CmdBuildRailWaypoint(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00216 {
00217   /* Unpack parameters */
00218   Axis axis      = Extract<Axis, 4, 1>(p1);
00219   byte width     = GB(p1,  8, 8);
00220   byte height    = GB(p1, 16, 8);
00221   bool adjacent  = HasBit(p1, 24);
00222 
00223   StationClassID spec_class = Extract<StationClassID, 0, 8>(p2);
00224   byte spec_index           = GB(p2, 8, 8);
00225   StationID station_to_join = GB(p2, 16, 16);
00226 
00227   /* Check if the given station class is valid */
00228   if (spec_class != STAT_CLASS_WAYP) return CMD_ERROR;
00229   if (spec_index >= GetNumCustomStations(spec_class)) return CMD_ERROR;
00230 
00231   /* The number of parts to build */
00232   byte count = axis == AXIS_X ? height : width;
00233 
00234   if ((axis == AXIS_X ? width : height) != 1) return CMD_ERROR;
00235   if (count == 0 || count > _settings_game.station.station_spread) return CMD_ERROR;
00236 
00237   bool reuse = (station_to_join != NEW_STATION);
00238   if (!reuse) station_to_join = INVALID_STATION;
00239   bool distant_join = (station_to_join != INVALID_STATION);
00240 
00241   if (distant_join && (!_settings_game.station.distant_join_stations || !Waypoint::IsValidID(station_to_join))) return CMD_ERROR;
00242 
00243   /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */
00244   StationID est = INVALID_STATION;
00245 
00246   /* Check whether the tiles we're building on are valid rail or not. */
00247   TileIndexDiff offset = TileOffsByDiagDir(AxisToDiagDir(OtherAxis(axis)));
00248   for (int i = 0; i < count; i++) {
00249     TileIndex tile = start_tile + i * offset;
00250     CommandCost ret = IsValidTileForWaypoint(tile, axis, _settings_game.station.nonuniform_stations ? &est : NULL);
00251     if (ret.Failed()) return ret;
00252   }
00253 
00254   Waypoint *wp = NULL;
00255   TileArea new_location(TileArea(start_tile, width, height));
00256   CommandCost ret = FindJoiningWaypoint(est, station_to_join, adjacent, new_location, &wp);
00257   if (ret.Failed()) return ret;
00258 
00259   /* Check if there is an already existing, deleted, waypoint close to us that we can reuse. */
00260   TileIndex center_tile = start_tile + (count / 2) * offset;
00261   if (wp == NULL && reuse) wp = FindDeletedWaypointCloseTo(center_tile, STR_SV_STNAME_WAYPOINT, _current_company);
00262 
00263   if (wp != NULL) {
00264     /* Reuse an existing waypoint. */
00265     if (wp->owner != _current_company) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_WAYPOINT);
00266 
00267     /* check if we want to expand an already existing waypoint? */
00268     if (wp->train_station.tile != INVALID_TILE && !CanExpandRailStation(wp, new_location, axis)) return CMD_ERROR;
00269 
00270     if (!wp->rect.BeforeAddRect(start_tile, width, height, StationRect::ADD_TEST)) return CMD_ERROR;
00271   } else {
00272     /* allocate and initialize new waypoint */
00273     if (!Waypoint::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
00274   }
00275 
00276   if (flags & DC_EXEC) {
00277     if (wp == NULL) {
00278       wp = new Waypoint(start_tile);
00279     } else if (!wp->IsInUse()) {
00280       /* Move existing (recently deleted) waypoint to the new location */
00281       wp->xy = start_tile;
00282     }
00283     wp->owner = GetTileOwner(start_tile);
00284 
00285     wp->rect.BeforeAddRect(start_tile, width, height, StationRect::ADD_TRY);
00286 
00287     wp->delete_ctr = 0;
00288     wp->facilities |= FACIL_TRAIN;
00289     wp->build_date = _date;
00290     wp->string_id = STR_SV_STNAME_WAYPOINT;
00291     wp->train_station = new_location;
00292 
00293     if (wp->town == NULL) MakeDefaultWaypointName(wp);
00294 
00295     wp->UpdateVirtCoord();
00296 
00297     const StationSpec *spec = GetCustomStationSpec(spec_class, spec_index);
00298     byte *layout_ptr = AllocaM(byte, count);
00299     if (spec == NULL) {
00300       /* The layout must be 0 for the 'normal' waypoints by design. */
00301       memset(layout_ptr, 0, count);
00302     } else {
00303       /* But for NewGRF waypoints we like to have their style. */
00304       GetStationLayout(layout_ptr, count, 1, spec);
00305     }
00306     byte map_spec_index = AllocateSpecToStation(spec, wp, true);
00307 
00308     for (int i = 0; i < count; i++) {
00309       TileIndex tile = start_tile + i * offset;
00310       byte old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0;
00311       bool reserved = IsTileType(tile, MP_RAILWAY) ?
00312           HasBit(GetRailReservationTrackBits(tile), AxisToTrack(axis)) :
00313           HasStationReservation(tile);
00314       MakeRailWaypoint(tile, wp->owner, wp->index, axis, layout_ptr[i], GetRailType(tile));
00315       SetCustomStationSpecIndex(tile, map_spec_index);
00316       SetRailStationReservation(tile, reserved);
00317       MarkTileDirtyByTile(tile);
00318 
00319       DeallocateSpecFromStation(wp, old_specindex);
00320       YapfNotifyTrackLayoutChange(tile, AxisToTrack(axis));
00321     }
00322   }
00323 
00324   return CommandCost(EXPENSES_CONSTRUCTION, count * _price[PR_BUILD_WAYPOINT_RAIL]);
00325 }
00326 
00335 CommandCost CmdBuildBuoy(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00336 {
00337   if (!IsWaterTile(tile) || tile == 0) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
00338   if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST);
00339 
00340   if (GetTileSlope(tile, NULL) != SLOPE_FLAT) return_cmd_error(STR_ERROR_SITE_UNSUITABLE);
00341 
00342   /* Check if there is an already existing, deleted, waypoint close to us that we can reuse. */
00343   Waypoint *wp = FindDeletedWaypointCloseTo(tile, STR_SV_STNAME_BUOY, OWNER_NONE);
00344   if (wp == NULL && !Waypoint::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING);
00345 
00346   if (flags & DC_EXEC) {
00347     if (wp == NULL) {
00348       wp = new Waypoint(tile);
00349     } else {
00350       /* Move existing (recently deleted) buoy to the new location */
00351       wp->xy = tile;
00352       InvalidateWindowData(WC_WAYPOINT_VIEW, wp->index);
00353     }
00354     wp->rect.BeforeAddTile(tile, StationRect::ADD_TRY);
00355 
00356     wp->string_id = STR_SV_STNAME_BUOY;
00357 
00358     wp->facilities |= FACIL_DOCK;
00359     wp->owner = OWNER_NONE;
00360 
00361     wp->build_date = _date;
00362 
00363     if (wp->town == NULL) MakeDefaultWaypointName(wp);
00364 
00365     MakeBuoy(tile, wp->index, GetWaterClass(tile));
00366 
00367     wp->UpdateVirtCoord();
00368     InvalidateWindowData(WC_WAYPOINT_VIEW, wp->index);
00369   }
00370 
00371   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_WAYPOINT_BUOY]);
00372 }
00373 
00381 CommandCost RemoveBuoy(TileIndex tile, DoCommandFlag flags)
00382 {
00383   /* XXX: strange stuff, allow clearing as invalid company when clearing landscape */
00384   if (!Company::IsValidID(_current_company) && !(flags & DC_BANKRUPT)) return_cmd_error(INVALID_STRING_ID);
00385 
00386   Waypoint *wp = Waypoint::GetByTile(tile);
00387 
00388   if (HasStationInUse(wp->index, INVALID_COMPANY)) return_cmd_error(STR_ERROR_BUOY_IS_IN_USE);
00389   /* remove the buoy if there is a ship on tile when company goes bankrupt... */
00390   if (!(flags & DC_BANKRUPT) && !EnsureNoVehicleOnGround(tile)) return CMD_ERROR;
00391 
00392   if (flags & DC_EXEC) {
00393     wp->facilities &= ~FACIL_DOCK;
00394 
00395     InvalidateWindowData(WC_WAYPOINT_VIEW, wp->index);
00396 
00397     /* We have to set the water tile's state to the same state as before the
00398      * buoy was placed. Otherwise one could plant a buoy on a canal edge,
00399      * remove it and flood the land (if the canal edge is at level 0) */
00400     MakeWaterKeepingClass(tile, GetTileOwner(tile));
00401     MarkTileDirtyByTile(tile);
00402 
00403     wp->rect.AfterRemoveTile(wp, tile);
00404 
00405     wp->UpdateVirtCoord();
00406     wp->delete_ctr = 0;
00407   }
00408 
00409   return CommandCost(EXPENSES_CONSTRUCTION, _price[PR_CLEAR_WAYPOINT_BUOY]);
00410 }
00411 
00412 
00413 static bool IsUniqueWaypointName(const char *name)
00414 {
00415   const Waypoint *wp;
00416 
00417   FOR_ALL_WAYPOINTS(wp) {
00418     if (wp->name != NULL && strcmp(wp->name, name) == 0) return false;
00419   }
00420 
00421   return true;
00422 }
00423 
00433 CommandCost CmdRenameWaypoint(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
00434 {
00435   Waypoint *wp = Waypoint::GetIfValid(p1);
00436   if (wp == NULL || !(CheckOwnership(wp->owner) || wp->owner == OWNER_NONE)) return CMD_ERROR;
00437 
00438   bool reset = StrEmpty(text);
00439 
00440   if (!reset) {
00441     if (strlen(text) >= MAX_LENGTH_STATION_NAME_BYTES) return CMD_ERROR;
00442     if (!IsUniqueWaypointName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE);
00443   }
00444 
00445   if (flags & DC_EXEC) {
00446     free(wp->name);
00447 
00448     if (reset) {
00449       MakeDefaultWaypointName(wp); // sets wp->name = NULL
00450     } else {
00451       wp->name = strdup(text);
00452     }
00453 
00454     wp->UpdateVirtCoord();
00455   }
00456   return CommandCost();
00457 }

Generated on Sat Jun 19 17:14:57 2010 for OpenTTD by  doxygen 1.6.1