/** Build a piece of canal. * @param tile end tile of stretch-dragging * @param flags type of operation * @param p1 start tile of stretch-dragging * @param p2 specifies canal (0), water (1) or river (2); last two can only be built in scenario editor * @param text unused * @return the cost of this operation or an error */ CommandCost CmdBuildCanal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) { CommandCost cost(EXPENSES_CONSTRUCTION); if (p1 >= MapSize()) return CMD_ERROR; /* Outside of the editor you can only build canals, not oceans */ if (p2 != 0 && _game_mode != GM_EDITOR) return CMD_ERROR; TileArea ta(tile, p1); /* Outside the editor you can only drag canals, and not areas */ if (_game_mode != GM_EDITOR && ta.w != 1 && ta.h != 1) return CMD_ERROR; TILE_AREA_LOOP(tile, ta) { CommandCost ret; Slope slope = GetTileSlope(tile, NULL); if (slope != SLOPE_FLAT && (p2 != 2 || !IsInclinedSlope(slope))) { return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED); } /* can't make water of water! */ if (IsTileType(tile, MP_WATER) && (!IsTileOwner(tile, OWNER_WATER) || p2 == 1)) continue; ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR); if (CmdFailed(ret)) return ret; cost.AddCost(ret); if (flags & DC_EXEC) { if (TileHeight(tile) == 0 && p2 == 1) { MakeSea(tile); } else if (p2 == 2) { MakeRiver(tile, Random()); } else { MakeCanal(tile, _current_company, Random()); } MarkTileDirtyByTile(tile); MarkCanalsAndRiversAroundDirty(tile); } cost.AddCost(_price[PR_CLEAR_WATER]); }
/** * Change the name of the company. * @param tile unused * @param flags operation to perform * @param p1 unused * @param p2 unused * @param text the new name or an empty string when resetting to the default * @return the cost of this operation or an error */ CommandCost CmdRenameCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) { bool reset = StrEmpty(text); if (!reset) { if (Utf8StringLength(text) >= MAX_LENGTH_COMPANY_NAME_CHARS) return CMD_ERROR; if (!IsUniqueCompanyName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE); } if (flags & DC_EXEC) { Company *c = Company::Get(_current_company); free(c->name); c->name = reset ? NULL : strdup(text); MarkWholeScreenDirty(); CompanyAdminUpdate(c); } return CommandCost(); }
/** * Rename a depot. * @param tile unused * @param flags type of operation * @param p1 id of depot * @param p2 unused * @param text the new name or an empty string when resetting to the default * @return the cost of this operation or an error */ CommandCost CmdRenameDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) { Depot *d = Depot::GetIfValid(p1); if (d == NULL) return CMD_ERROR; CommandCost ret = CheckTileOwnership(d->xy); if (ret.Failed()) return ret; bool reset = StrEmpty(text); if (!reset) { if (Utf8StringLength(text) >= MAX_LENGTH_DEPOT_NAME_CHARS) return CMD_ERROR; if (!IsUniqueDepotName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE); } if (flags & DC_EXEC) { free(d->name); if (reset) { d->name = NULL; MakeDefaultName(d); } else { d->name = strdup(text); } /* Update the orders and depot */ SetWindowClassesDirty(WC_VEHICLE_ORDERS); SetWindowDirty(WC_VEHICLE_DEPOT, d->xy); /* Update the depot list */ VehicleType vt; switch (GetTileType(d->xy)) { default: NOT_REACHED(); case MP_RAILWAY: vt = VEH_TRAIN; break; case MP_ROAD: vt = VEH_ROAD; break; case MP_WATER: vt = VEH_SHIP; break; } SetWindowDirty(GetWindowClassForVehicleType(vt), VehicleListIdentifier(VL_DEPOT_LIST, vt, GetTileOwner(d->xy), d->index).Pack()); } return CommandCost(); }
/** Give a custom name to your vehicle * @param tile unused * @param flags type of operation * @param p1 vehicle ID to name * @param p2 unused * @param text the new name or an empty string when resetting to the default * @return the cost of this operation or an error */ CommandCost CmdRenameVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) { Vehicle *v = Vehicle::GetIfValid(p1); if (v == NULL || !CheckOwnership(v->owner)) return CMD_ERROR; bool reset = StrEmpty(text); if (!reset) { if (strlen(text) >= MAX_LENGTH_VEHICLE_NAME_BYTES) return CMD_ERROR; if (!(flags & DC_AUTOREPLACE) && !IsUniqueVehicleName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE); } if (flags & DC_EXEC) { free(v->name); v->name = reset ? NULL : strdup(text); InvalidateWindowClassesData(WC_TRAINS_LIST, 1); MarkWholeScreenDirty(); } return CommandCost(); }
/** * Give a custom name to your vehicle * @param tile unused * @param flags type of operation * @param p1 vehicle ID to name * @param p2 unused * @param text the new name or an empty string when resetting to the default * @return the cost of this operation or an error */ CommandCost CmdRenameVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) { Vehicle *v = Vehicle::GetIfValid(p1); if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR; CommandCost ret = CheckOwnership(v->owner); if (ret.Failed()) return ret; bool reset = StrEmpty(text); if (!reset) { if (Utf8StringLength(text) >= MAX_LENGTH_VEHICLE_NAME_CHARS) return CMD_ERROR; if (!(flags & DC_AUTOREPLACE) && !IsUniqueVehicleName(text)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE); } if (flags & DC_EXEC) { free(v->name); v->name = reset ? NULL : strdup(text); InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 1); MarkWholeScreenDirty(); } return CommandCost(); }
/** * Build a vehicle. * @param tile tile of depot where the vehicle is built * @param flags for command * @param p1 various bitstuffed data * bits 0-15: vehicle type being built. * bits 16-31: vehicle type specific bits passed on to the vehicle build functions. * @param p2 User * @param text unused * @return the cost of this operation or an error */ CommandCost CmdBuildVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) { /* Elementary check for valid location. */ if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR; VehicleType type; switch (GetTileType(tile)) { case MP_RAILWAY: type = VEH_TRAIN; break; case MP_ROAD: type = VEH_ROAD; break; case MP_WATER: type = VEH_SHIP; break; case MP_STATION: type = VEH_AIRCRAFT; break; default: NOT_REACHED(); // Safe due to IsDepotTile() } /* Validate the engine type. */ EngineID eid = GB(p1, 0, 16); if (!IsEngineBuildable(eid, type, _current_company)) return_cmd_error(STR_ERROR_RAIL_VEHICLE_NOT_AVAILABLE + type); const Engine *e = Engine::Get(eid); CommandCost value(EXPENSES_NEW_VEHICLES, e->GetCost()); /* Engines without valid cargo should not be available */ if (e->GetDefaultCargoType() == CT_INVALID) return CMD_ERROR; /* Check whether the number of vehicles we need to build can be built according to pool space. */ uint num_vehicles; switch (type) { case VEH_TRAIN: num_vehicles = (e->u.rail.railveh_type == RAILVEH_MULTIHEAD ? 2 : 1) + CountArticulatedParts(eid, false); break; case VEH_ROAD: num_vehicles = 1 + CountArticulatedParts(eid, false); break; case VEH_SHIP: num_vehicles = 1; break; case VEH_AIRCRAFT: num_vehicles = e->u.air.subtype & AIR_CTOL ? 2 : 3; break; default: NOT_REACHED(); // Safe due to IsDepotTile() } if (!Vehicle::CanAllocateItem(num_vehicles)) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME); /* Check whether we can allocate a unit number. Autoreplace does not allocate * an unit number as it will (always) reuse the one of the replaced vehicle * and (train) wagons don't have an unit number in any scenario. */ UnitID unit_num = (flags & DC_AUTOREPLACE || (type == VEH_TRAIN && e->u.rail.railveh_type == RAILVEH_WAGON)) ? 0 : GetFreeUnitNumber(type); if (unit_num == UINT16_MAX) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME); Vehicle *v; switch (type) { case VEH_TRAIN: value.AddCost(CmdBuildRailVehicle(tile, flags, e, GB(p1, 16, 16), &v)); break; case VEH_ROAD: value.AddCost(CmdBuildRoadVehicle(tile, flags, e, GB(p1, 16, 16), &v)); break; case VEH_SHIP: value.AddCost(CmdBuildShip (tile, flags, e, GB(p1, 16, 16), &v)); break; case VEH_AIRCRAFT: value.AddCost(CmdBuildAircraft (tile, flags, e, GB(p1, 16, 16), &v)); break; default: NOT_REACHED(); // Safe due to IsDepotTile() } if (value.Succeeded() && flags & DC_EXEC) { v->unitnumber = unit_num; v->value = value.GetCost(); InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile); InvalidateWindowClassesData(GetWindowClassForVehicleType(type), 0); SetWindowDirty(WC_COMPANY, _current_company); if (IsLocalCompany()) { InvalidateAutoreplaceWindow(v->engine_type, v->group_id); // updates the auto replace window (must be called before incrementing num_engines) } GroupStatistics::CountEngine(v, 1); GroupStatistics::UpdateAutoreplace(_current_company); if (v->IsPrimaryVehicle()) { GroupStatistics::CountVehicle(v, 1); OrderBackup::Restore(v, p2); } } return value; }
/** * Clone a vehicle. If it is a train, it will clone all the cars too * @param tile tile of the depot where the cloned vehicle is build * @param flags type of operation * @param p1 the original vehicle's index * @param p2 1 = shared orders, else copied orders * @param text unused * @return the cost of this operation or an error */ CommandCost CmdCloneVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) { CommandCost total_cost(EXPENSES_NEW_VEHICLES); Vehicle *v = Vehicle::GetIfValid(p1); if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR; Vehicle *v_front = v; Vehicle *w = NULL; Vehicle *w_front = NULL; Vehicle *w_rear = NULL; /* * v_front is the front engine in the original vehicle * v is the car/vehicle of the original vehicle that is currently being copied * w_front is the front engine of the cloned vehicle * w is the car/vehicle currently being cloned * w_rear is the rear end of the cloned train. It's used to add more cars and is only used by trains */ CommandCost ret = CheckOwnership(v->owner); if (ret.Failed()) return ret; if (v->type == VEH_TRAIN && (!v->IsFrontEngine() || Train::From(v)->crash_anim_pos >= 4400)) return CMD_ERROR; /* check that we can allocate enough vehicles */ if (!(flags & DC_EXEC)) { int veh_counter = 0; do { veh_counter++; } while ((v = v->Next()) != NULL); if (!Vehicle::CanAllocateItem(veh_counter)) { return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME); } } v = v_front; do { if (v->type == VEH_TRAIN && Train::From(v)->IsRearDualheaded()) { /* we build the rear ends of multiheaded trains with the front ones */ continue; } /* In case we're building a multi headed vehicle and the maximum number of * vehicles is almost reached (e.g. max trains - 1) not all vehicles would * be cloned. When the non-primary engines were build they were seen as * 'new' vehicles whereas they would immediately be joined with a primary * engine. This caused the vehicle to be not build as 'the limit' had been * reached, resulting in partially build vehicles and such. */ DoCommandFlag build_flags = flags; if ((flags & DC_EXEC) && !v->IsPrimaryVehicle()) build_flags |= DC_AUTOREPLACE; CommandCost cost = DoCommand(tile, v->engine_type | (1 << 16), 0, build_flags, GetCmdBuildVeh(v)); if (cost.Failed()) { /* Can't build a part, then sell the stuff we already made; clear up the mess */ if (w_front != NULL) DoCommand(w_front->tile, w_front->index | (1 << 20), 0, flags, GetCmdSellVeh(w_front)); return cost; } total_cost.AddCost(cost); if (flags & DC_EXEC) { w = Vehicle::Get(_new_vehicle_id); if (v->type == VEH_TRAIN && HasBit(Train::From(v)->flags, VRF_REVERSE_DIRECTION)) { SetBit(Train::From(w)->flags, VRF_REVERSE_DIRECTION); } if (v->type == VEH_TRAIN && !v->IsFrontEngine()) { /* this s a train car * add this unit to the end of the train */ CommandCost result = DoCommand(0, w->index | 1 << 20, w_rear->index, flags, CMD_MOVE_RAIL_VEHICLE); if (result.Failed()) { /* The train can't be joined to make the same consist as the original. * Sell what we already made (clean up) and return an error. */ DoCommand(w_front->tile, w_front->index | 1 << 20, 0, flags, GetCmdSellVeh(w_front)); DoCommand(w_front->tile, w->index | 1 << 20, 0, flags, GetCmdSellVeh(w)); return result; // return error and the message returned from CMD_MOVE_RAIL_VEHICLE } } else { /* this is a front engine or not a train. */ w_front = w; w->service_interval = v->service_interval; w->SetServiceIntervalIsCustom(v->ServiceIntervalIsCustom()); w->SetServiceIntervalIsPercent(v->ServiceIntervalIsPercent()); } w_rear = w; // trains needs to know the last car in the train, so they can add more in next loop } } while (v->type == VEH_TRAIN && (v = v->GetNextVehicle()) != NULL); if ((flags & DC_EXEC) && v_front->type == VEH_TRAIN) { /* for trains this needs to be the front engine due to the callback function */ _new_vehicle_id = w_front->index; } if (flags & DC_EXEC) { /* Cloned vehicles belong to the same group */ DoCommand(0, v_front->group_id, w_front->index, flags, CMD_ADD_VEHICLE_GROUP); } /* Take care of refitting. */ w = w_front; v = v_front; /* Both building and refitting are influenced by newgrf callbacks, which * makes it impossible to accurately estimate the cloning costs. In * particular, it is possible for engines of the same type to be built with * different numbers of articulated parts, so when refitting we have to * loop over real vehicles first, and then the articulated parts of those * vehicles in a different loop. */ do { do { if (flags & DC_EXEC) { assert(w != NULL); /* Find out what's the best sub type */ byte subtype = GetBestFittingSubType(v, w, v->cargo_type); if (w->cargo_type != v->cargo_type || w->cargo_subtype != subtype) { CommandCost cost = DoCommand(0, w->index, v->cargo_type | 1U << 7 | (subtype << 8), flags, GetCmdRefitVeh(v)); if (cost.Succeeded()) total_cost.AddCost(cost); } if (w->IsGroundVehicle() && w->HasArticulatedPart()) { w = w->GetNextArticulatedPart(); } else { break; } } else { const Engine *e = v->GetEngine(); CargoID initial_cargo = (e->CanCarryCargo() ? e->GetDefaultCargoType() : (CargoID)CT_INVALID); if (v->cargo_type != initial_cargo && initial_cargo != CT_INVALID) { bool dummy; total_cost.AddCost(GetRefitCost(NULL, v->engine_type, v->cargo_type, v->cargo_subtype, &dummy)); } } if (v->IsGroundVehicle() && v->HasArticulatedPart()) { v = v->GetNextArticulatedPart(); } else { break; } } while (v != NULL); if ((flags & DC_EXEC) && v->type == VEH_TRAIN) w = w->GetNextVehicle(); } while (v->type == VEH_TRAIN && (v = v->GetNextVehicle()) != NULL); if (flags & DC_EXEC) { /* * Set the orders of the vehicle. Cannot do it earlier as we need * the vehicle refitted before doing this, otherwise the moved * cargo types might not match (passenger vs non-passenger) */ DoCommand(0, w_front->index | (p2 & 1 ? CO_SHARE : CO_COPY) << 30, v_front->index, flags, CMD_CLONE_ORDER); /* Now clone the vehicle's name, if it has one. */ if (v_front->name != NULL) CloneVehicleName(v_front, w_front); } /* Since we can't estimate the cost of cloning a vehicle accurately we must * check whether the company has enough money manually. */ if (!CheckCompanyHasMoney(total_cost)) { if (flags & DC_EXEC) { /* The vehicle has already been bought, so now it must be sold again. */ DoCommand(w_front->tile, w_front->index | 1 << 20, 0, flags, GetCmdSellVeh(w_front)); } return total_cost; } return total_cost; }
/** * Start/Stop a vehicle * @param tile unused * @param flags type of operation * @param p1 vehicle to start/stop, don't forget to change CcStartStopVehicle if you modify this! * @param p2 bit 0: Shall the start/stop newgrf callback be evaluated (only valid with DC_AUTOREPLACE for network safety) * @param text unused * @return the cost of this operation or an error */ CommandCost CmdStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) { /* Disable the effect of p2 bit 0, when DC_AUTOREPLACE is not set */ if ((flags & DC_AUTOREPLACE) == 0) SetBit(p2, 0); Vehicle *v = Vehicle::GetIfValid(p1); if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR; CommandCost ret = CheckOwnership(v->owner); if (ret.Failed()) return ret; if (v->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED); switch (v->type) { case VEH_TRAIN: if ((v->vehstatus & VS_STOPPED) && Train::From(v)->gcache.cached_power == 0) return_cmd_error(STR_ERROR_TRAIN_START_NO_POWER); break; case VEH_SHIP: case VEH_ROAD: break; case VEH_AIRCRAFT: { Aircraft *a = Aircraft::From(v); /* cannot stop airplane when in flight, or when taking off / landing */ if (!(v->vehstatus & VS_CRASHED) && a->state >= STARTTAKEOFF && a->state < TERM7) return_cmd_error(STR_ERROR_AIRCRAFT_IS_IN_FLIGHT); break; } default: return CMD_ERROR; } if (HasBit(p2, 0)) { /* Check if this vehicle can be started/stopped. Failure means 'allow'. */ uint16 callback = GetVehicleCallback(CBID_VEHICLE_START_STOP_CHECK, 0, 0, v->engine_type, v); StringID error = STR_NULL; if (callback != CALLBACK_FAILED) { if (v->GetGRF()->grf_version < 8) { /* 8 bit result 0xFF means 'allow' */ if (callback < 0x400 && GB(callback, 0, 8) != 0xFF) error = GetGRFStringID(v->GetGRFID(), 0xD000 + callback); } else { if (callback < 0x400) { error = GetGRFStringID(v->GetGRFID(), 0xD000 + callback); } else { switch (callback) { case 0x400: // allow break; default: // unknown reason -> disallow error = STR_ERROR_INCOMPATIBLE_RAIL_TYPES; break; } } } } if (error != STR_NULL) return_cmd_error(error); } if (flags & DC_EXEC) { if (v->IsStoppedInDepot() && (flags & DC_AUTOREPLACE) == 0) DeleteVehicleNews(p1, STR_NEWS_TRAIN_IS_WAITING + v->type); v->vehstatus ^= VS_STOPPED; if (v->type != VEH_TRAIN) v->cur_speed = 0; // trains can stop 'slowly' v->MarkDirty(); SetWindowWidgetDirty(WC_VEHICLE_VIEW, v->index, WID_VV_START_STOP); SetWindowDirty(WC_VEHICLE_DEPOT, v->tile); SetWindowClassesDirty(GetWindowClassForVehicleType(v->type)); } return CommandCost(); }
/** * Refits a vehicle to the specified cargo type. * @param tile unused * @param flags type of operation * @param p1 vehicle ID to refit * @param p2 various bitstuffed elements * - p2 = (bit 0-4) - New cargo type to refit to. * - p2 = (bit 6) - Automatic refitting. * - p2 = (bit 7) - Refit only this vehicle. Used only for cloning vehicles. * - p2 = (bit 8-15) - New cargo subtype to refit to. 0xFF means to try keeping the same subtype according to GetBestFittingSubType(). * - p2 = (bit 16-23) - Number of vehicles to refit (not counting articulated parts). Zero means all vehicles. * Only used if "refit only this vehicle" is false. * @param text unused * @return the cost of this operation or an error */ CommandCost CmdRefitVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) { Vehicle *v = Vehicle::GetIfValid(p1); if (v == NULL) return CMD_ERROR; /* Don't allow disasters and sparks and such to be refitted. * We cannot check for IsPrimaryVehicle as autoreplace also refits in free wagon chains. */ if (!IsCompanyBuildableVehicleType(v->type)) return CMD_ERROR; Vehicle *front = v->First(); CommandCost ret = CheckOwnership(front->owner); if (ret.Failed()) return ret; bool auto_refit = HasBit(p2, 6); /* Don't allow shadows and such to be refitted. */ if (v != front && (v->type == VEH_SHIP || v->type == VEH_AIRCRAFT)) return CMD_ERROR; /* Allow auto-refitting only during loading and normal refitting only in a depot. */ if ((!auto_refit || !front->current_order.IsType(OT_LOADING)) && !front->IsStoppedInDepot()) return_cmd_error(STR_ERROR_TRAIN_MUST_BE_STOPPED_INSIDE_DEPOT + front->type); if (front->vehstatus & VS_CRASHED) return_cmd_error(STR_ERROR_VEHICLE_IS_DESTROYED); /* Check cargo */ CargoID new_cid = GB(p2, 0, 5); byte new_subtype = GB(p2, 8, 8); if (new_cid >= NUM_CARGO) return CMD_ERROR; /* For ships and aircrafts there is always only one. */ bool only_this = HasBit(p2, 7) || front->type == VEH_SHIP || front->type == VEH_AIRCRAFT; uint8 num_vehicles = GB(p2, 16, 8); CommandCost cost = RefitVehicle(v, only_this, num_vehicles, new_cid, new_subtype, flags, auto_refit); if (flags & DC_EXEC) { /* Update the cached variables */ switch (v->type) { case VEH_TRAIN: Train::From(front)->ConsistChanged(auto_refit); break; case VEH_ROAD: RoadVehUpdateCache(RoadVehicle::From(front), auto_refit); if (_settings_game.vehicle.roadveh_acceleration_model != AM_ORIGINAL) RoadVehicle::From(front)->CargoChanged(); break; case VEH_SHIP: v->InvalidateNewGRFCacheOfChain(); v->colourmap = PAL_NONE; // invalidate vehicle colour map Ship::From(v)->UpdateCache(); break; case VEH_AIRCRAFT: v->InvalidateNewGRFCacheOfChain(); v->colourmap = PAL_NONE; // invalidate vehicle colour map UpdateAircraftCache(Aircraft::From(v), true); break; default: NOT_REACHED(); } InvalidateWindowData(WC_VEHICLE_DETAILS, front->index); SetWindowDirty(WC_VEHICLE_DEPOT, front->tile); InvalidateWindowClassesData(GetWindowClassForVehicleType(v->type), 0); } else { /* Always invalidate the cache; querycost might have filled it. */ v->InvalidateNewGRFCacheOfChain(); } return cost; }
/** * Terraform land * @param tile tile to terraform * @param flags for this command type * @param p1 corners to terraform (SLOPE_xxx) * @param p2 direction; eg up (non-zero) or down (zero) * @param text unused * @return the cost of this operation or an error */ CommandCost CmdTerraformLand(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) { _terraform_err_tile = INVALID_TILE; CommandCost total_cost(EXPENSES_CONSTRUCTION); int direction = (p2 != 0 ? 1 : -1); TerraformerState ts; /* Compute the costs and the terraforming result in a model of the landscape */ if ((p1 & SLOPE_W) != 0 && tile + TileDiffXY(1, 0) < MapSize()) { TileIndex t = tile + TileDiffXY(1, 0); CommandCost cost = TerraformTileHeight(&ts, t, TileHeight(t) + direction); if (cost.Failed()) return cost; total_cost.AddCost(cost); } if ((p1 & SLOPE_S) != 0 && tile + TileDiffXY(1, 1) < MapSize()) { TileIndex t = tile + TileDiffXY(1, 1); CommandCost cost = TerraformTileHeight(&ts, t, TileHeight(t) + direction); if (cost.Failed()) return cost; total_cost.AddCost(cost); } if ((p1 & SLOPE_E) != 0 && tile + TileDiffXY(0, 1) < MapSize()) { TileIndex t = tile + TileDiffXY(0, 1); CommandCost cost = TerraformTileHeight(&ts, t, TileHeight(t) + direction); if (cost.Failed()) return cost; total_cost.AddCost(cost); } if ((p1 & SLOPE_N) != 0) { TileIndex t = tile + TileDiffXY(0, 0); CommandCost cost = TerraformTileHeight(&ts, t, TileHeight(t) + direction); if (cost.Failed()) return cost; total_cost.AddCost(cost); } /* Check if the terraforming is valid wrt. tunnels, bridges and objects on the surface * Pass == 0: Collect tileareas which are caused to be auto-cleared. * Pass == 1: Collect the actual cost. */ for (int pass = 0; pass < 2; pass++) { for (std::set<TileIndex>::const_iterator it = ts.dirty_tiles.begin(); it != ts.dirty_tiles.end(); it++) { TileIndex tile = *it; assert(tile < MapSize()); /* MP_VOID tiles can be terraformed but as tunnels and bridges * cannot go under / over these tiles they don't need checking. */ if (IsTileType(tile, MP_VOID)) continue; /* Find new heights of tile corners */ int z_N = TerraformGetHeightOfTile(&ts, tile + TileDiffXY(0, 0)); int z_W = TerraformGetHeightOfTile(&ts, tile + TileDiffXY(1, 0)); int z_S = TerraformGetHeightOfTile(&ts, tile + TileDiffXY(1, 1)); int z_E = TerraformGetHeightOfTile(&ts, tile + TileDiffXY(0, 1)); /* Find min and max height of tile */ int z_min = min(min(z_N, z_W), min(z_S, z_E)); int z_max = max(max(z_N, z_W), max(z_S, z_E)); /* Compute tile slope */ Slope tileh = (z_max > z_min + 1 ? SLOPE_STEEP : SLOPE_FLAT); if (z_W > z_min) tileh |= SLOPE_W; if (z_S > z_min) tileh |= SLOPE_S; if (z_E > z_min) tileh |= SLOPE_E; if (z_N > z_min) tileh |= SLOPE_N; if (pass == 0) { /* Check if bridge would take damage */ if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) { int bridge_height = GetBridgeHeight(GetSouthernBridgeEnd(tile)); /* Check if bridge would take damage. */ if (direction == 1 && bridge_height <= z_max) { _terraform_err_tile = tile; ///< highlight the tile under the bridge return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST); } /* Is the bridge above not too high afterwards? * @see tunnelbridge.h for a detailed discussion. */ if (direction == -1 && bridge_height > (z_min + MAX_BRIDGE_HEIGHT)) { _terraform_err_tile = tile; return_cmd_error(STR_ERROR_BRIDGE_TOO_HIGH_AFTER_LOWER_LAND); } } /* Check if tunnel would take damage */ if (direction == -1 && IsTunnelInWay(tile, z_min)) { _terraform_err_tile = tile; // highlight the tile above the tunnel return_cmd_error(STR_ERROR_EXCAVATION_WOULD_DAMAGE); } } /* Is the tile already cleared? */ const ClearedObjectArea *coa = FindClearedObject(tile); bool indirectly_cleared = coa != NULL && coa->first_tile != tile; /* Check tiletype-specific things, and add extra-cost */ const bool curr_gen = _generating_world; if (_game_mode == GM_EDITOR) _generating_world = true; // used to create green terraformed land DoCommandFlag tile_flags = flags | DC_AUTO | DC_FORCE_CLEAR_TILE; if (pass == 0) { tile_flags &= ~DC_EXEC; tile_flags |= DC_NO_MODIFY_TOWN_RATING; } CommandCost cost; if (indirectly_cleared) { cost = DoCommand(tile, 0, 0, tile_flags, CMD_LANDSCAPE_CLEAR); } else { cost = _tile_type_procs[GetTileType(tile)]->terraform_tile_proc(tile, tile_flags, z_min, tileh); } _generating_world = curr_gen; if (cost.Failed()) { _terraform_err_tile = tile; return cost; } if (pass == 1) total_cost.AddCost(cost); } } Company *c = Company::GetIfValid(_current_company); if (c != NULL && (int)GB(c->terraform_limit, 16, 16) < ts.tile_to_new_height.size()) { return_cmd_error(STR_ERROR_TERRAFORM_LIMIT_REACHED); } if (flags & DC_EXEC) { /* change the height */ { for (std::map<TileIndex, int>::const_iterator it = ts.tile_to_new_height.begin(); it != ts.tile_to_new_height.end(); it++) { TileIndex tile = it->first; int height = it->second; SetTileHeight(tile, (uint)height); } } /* finally mark the dirty tiles dirty */ { MarkTilesDirty(ts); } if (c != NULL) c->terraform_limit -= ts.tile_to_new_height.size() << 16; } return total_cost; }
static CommandCost TerraformTile_Void(TileIndex tile, DoCommandFlag flags, int z_new, Slope tileh_new) { return_cmd_error(STR_ERROR_OFF_EDGE_OF_MAP); }
/** * Builds a lock. * @param tile Central tile of the lock. * @param dir Uphill direction. * @param flags Operation to perform. * @return The cost in case of success, or an error code if it failed. */ static CommandCost DoBuildLock(TileIndex tile, DiagDirection dir, DoCommandFlag flags) { CommandCost cost(EXPENSES_CONSTRUCTION); int delta = TileOffsByDiagDir(dir); CommandCost ret = EnsureNoVehicleOnGround(tile); if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile + delta); if (ret.Succeeded()) ret = EnsureNoVehicleOnGround(tile - delta); if (ret.Failed()) return ret; /* middle tile */ WaterClass wc_middle = IsWaterTile(tile) ? GetWaterClass(tile) : WATER_CLASS_CANAL; ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR); if (ret.Failed()) return ret; cost.AddCost(ret); /* lower tile */ if (!IsWaterTile(tile - delta)) { ret = DoCommand(tile - delta, 0, 0, flags, CMD_LANDSCAPE_CLEAR); if (ret.Failed()) return ret; cost.AddCost(ret); cost.AddCost(_price[PR_BUILD_CANAL]); } if (!IsTileFlat(tile - delta)) { return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION); } WaterClass wc_lower = IsWaterTile(tile - delta) ? GetWaterClass(tile - delta) : WATER_CLASS_CANAL; /* upper tile */ if (!IsWaterTile(tile + delta)) { ret = DoCommand(tile + delta, 0, 0, flags, CMD_LANDSCAPE_CLEAR); if (ret.Failed()) return ret; cost.AddCost(ret); cost.AddCost(_price[PR_BUILD_CANAL]); } if (!IsTileFlat(tile + delta)) { return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION); } WaterClass wc_upper = IsWaterTile(tile + delta) ? GetWaterClass(tile + delta) : WATER_CLASS_CANAL; if (IsBridgeAbove(tile) || IsBridgeAbove(tile - delta) || IsBridgeAbove(tile + delta)) { return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST); } if (flags & DC_EXEC) { /* Update company infrastructure counts. */ Company *c = Company::GetIfValid(_current_company); if (c != NULL) { /* Counts for the water. */ if (!IsWaterTile(tile - delta)) c->infrastructure.water++; if (!IsWaterTile(tile + delta)) c->infrastructure.water++; /* Count for the lock itself. */ c->infrastructure.water += 3 * LOCK_DEPOT_TILE_FACTOR; // Lock is three tiles. DirtyCompanyInfrastructureWindows(_current_company); } MakeLock(tile, _current_company, dir, wc_lower, wc_upper, wc_middle); MarkTileDirtyByTile(tile); MarkTileDirtyByTile(tile - delta); MarkTileDirtyByTile(tile + delta); MarkCanalsAndRiversAroundDirty(tile - delta); MarkCanalsAndRiversAroundDirty(tile + delta); } cost.AddCost(_price[PR_BUILD_LOCK]); return cost; }
/** * Change timetable data of an order. * @param tile Not used. * @param flags Operation to perform. * @param p1 Various bitstuffed elements * - p1 = (bit 0-19) - Vehicle with the orders to change. * - p1 = (bit 20-27) - Order index to modify. * - p1 = (bit 28-29) - Timetable data to change (@see ModifyTimetableFlags) * @param p2 The amount of time to wait. * - p2 = (bit 0-15) - The data to modify as specified by p1 bits 28-29. * 0 to clear times, UINT16_MAX to clear speed limit. * @param text unused * @return the cost of this operation or an error */ CommandCost CmdChangeTimetable(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) { VehicleID veh = GB(p1, 0, 20); Vehicle *v = Vehicle::GetIfValid(veh); if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR; CommandCost ret = CheckOwnership(v->owner); if (ret.Failed()) return ret; VehicleOrderID order_number = GB(p1, 20, 8); Order *order = v->GetOrder(order_number); if (order == NULL || order->IsType(OT_IMPLICIT)) return CMD_ERROR; ModifyTimetableFlags mtf = Extract<ModifyTimetableFlags, 28, 2>(p1); if (mtf >= MTF_END) return CMD_ERROR; int wait_time = order->GetWaitTime(); int travel_time = order->GetTravelTime(); int max_speed = order->GetMaxSpeed(); switch (mtf) { case MTF_WAIT_TIME: wait_time = GB(p2, 0, 16); break; case MTF_TRAVEL_TIME: travel_time = GB(p2, 0, 16); break; case MTF_TRAVEL_SPEED: max_speed = GB(p2, 0, 16); if (max_speed == 0) max_speed = UINT16_MAX; // Disable speed limit. break; default: NOT_REACHED(); } if (wait_time != order->GetWaitTime()) { switch (order->GetType()) { case OT_GOTO_STATION: if (order->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) return_cmd_error(STR_ERROR_TIMETABLE_NOT_STOPPING_HERE); break; case OT_CONDITIONAL: break; default: return_cmd_error(STR_ERROR_TIMETABLE_ONLY_WAIT_AT_STATIONS); } } if (travel_time != order->GetTravelTime() && order->IsType(OT_CONDITIONAL)) return CMD_ERROR; if (max_speed != order->GetMaxSpeed() && (order->IsType(OT_CONDITIONAL) || v->type == VEH_AIRCRAFT)) return CMD_ERROR; if (flags & DC_EXEC) { switch (mtf) { case MTF_WAIT_TIME: /* Set time if changing the value or confirming an estimated time as timetabled. */ if (wait_time != order->GetWaitTime() || (wait_time > 0 && !order->IsWaitTimetabled())) { ChangeTimetable(v, order_number, wait_time, MTF_WAIT_TIME, wait_time > 0); } break; case MTF_TRAVEL_TIME: /* Set time if changing the value or confirming an estimated time as timetabled. */ if (travel_time != order->GetTravelTime() || (travel_time > 0 && !order->IsTravelTimetabled())) { ChangeTimetable(v, order_number, travel_time, MTF_TRAVEL_TIME, travel_time > 0); } break; case MTF_TRAVEL_SPEED: if (max_speed != order->GetMaxSpeed()) { ChangeTimetable(v, order_number, max_speed, MTF_TRAVEL_SPEED, max_speed != UINT16_MAX); } break; default: break; } } return CommandCost(); }
/** * Build a ship depot. * @param tile tile where ship depot is built * @param flags type of operation * @param p1 bit 0 depot orientation (Axis) * @param p2 unused * @param text unused * @return the cost of this operation or an error */ CommandCost CmdBuildShipDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) { Axis axis = Extract<Axis, 0, 1>(p1); TileIndex tile2 = tile + (axis == AXIS_X ? TileDiffXY(1, 0) : TileDiffXY(0, 1)); WaterClass wc1, wc2; if ((flags & DC_PASTE) && !(flags & DC_EXEC)) { /* When pasting a ship depot, there may be no water yet (a canal will be placed when DC_EXE'ing). * Ignore that there is no water so we can calculate the cost more precisely. */ wc1 = wc2 = WATER_CLASS_INVALID; } else { if (!HasTileWaterGround(tile) || !HasTileWaterGround(tile2)) return_cmd_error(STR_ERROR_MUST_BE_BUILT_ON_WATER); wc1 = GetWaterClass(tile); wc2 = GetWaterClass(tile2); } if ((MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) || (MayHaveBridgeAbove(tile2) && IsBridgeAbove(tile2))) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST); if (GetTileSlope(tile) != SLOPE_FLAT || GetTileSlope(tile2) != SLOPE_FLAT) { /* Prevent depots on rapids */ return_cmd_error(STR_ERROR_SITE_UNSUITABLE); } if (!Depot::CanAllocateItem()) return CMD_ERROR; CommandCost cost = CommandCost(EXPENSES_CONSTRUCTION, _price[PR_BUILD_DEPOT_SHIP]); bool add_cost = !IsWaterTile(tile); CommandCost ret = DoCommand(tile, 0, 0, flags | DC_AUTO, CMD_LANDSCAPE_CLEAR); if (ret.Failed()) return ret; if (add_cost) { cost.AddCost(ret); } add_cost = !IsWaterTile(tile2); ret = DoCommand(tile2, 0, 0, flags | DC_AUTO, CMD_LANDSCAPE_CLEAR); if (ret.Failed()) return ret; if (add_cost) { cost.AddCost(ret); } if (flags & DC_EXEC) { Depot *depot = new Depot(tile); depot->build_date = _date; if (wc1 == WATER_CLASS_CANAL || wc2 == WATER_CLASS_CANAL) { /* Update infrastructure counts after the unconditional clear earlier. */ Company::Get(_current_company)->infrastructure.water += wc1 == WATER_CLASS_CANAL && wc2 == WATER_CLASS_CANAL ? 2 : 1; } Company::Get(_current_company)->infrastructure.water += 2 * LOCK_DEPOT_TILE_FACTOR; DirtyCompanyInfrastructureWindows(_current_company); assert(wc1 != WATER_CLASS_INVALID && wc2 != WATER_CLASS_INVALID); MakeShipDepot(tile, _current_company, depot->index, DEPOT_PART_NORTH, axis, wc1); MakeShipDepot(tile2, _current_company, depot->index, DEPOT_PART_SOUTH, axis, wc2); MarkTileDirtyByTile(tile); MarkTileDirtyByTile(tile2); MakeDefaultName(depot); } return cost; }
/** * Plant a tree. * @param tile start tile of area-drag of tree plantation * @param flags type of operation * @param p1 tree type, TREE_INVALID means random. * @param p2 end tile of area-drag * @param text unused * @return the cost of this operation or an error */ CommandCost CmdPlantTree(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) { StringID msg = INVALID_STRING_ID; CommandCost cost(EXPENSES_OTHER); const byte tree_to_plant = GB(p1, 0, 8); // We cannot use Extract as min and max are climate specific. if (p2 >= MapSize()) return CMD_ERROR; /* Check the tree type within the current climate */ if (tree_to_plant != TREE_INVALID && !IsInsideBS(tree_to_plant, _tree_base_by_landscape[_settings_game.game_creation.landscape], _tree_count_by_landscape[_settings_game.game_creation.landscape])) return CMD_ERROR; TileArea ta(tile, p2); TILE_AREA_LOOP(tile, ta) { switch (GetTileType(tile)) { case MP_TREES: /* no more space for trees? */ if (_game_mode != GM_EDITOR && GetTreeCount(tile) == 4) { msg = STR_ERROR_TREE_ALREADY_HERE; continue; } if (flags & DC_EXEC) { AddTreeCount(tile, 1); MarkTileDirtyByTile(tile); } /* 2x as expensive to add more trees to an existing tile */ cost.AddCost(_price[PR_BUILD_TREES] * 2); break; case MP_WATER: if (!IsCoast(tile) || IsSlopeWithOneCornerRaised(GetTileSlope(tile, NULL))) { msg = STR_ERROR_CAN_T_BUILD_ON_WATER; continue; } /* FALL THROUGH */ case MP_CLEAR: { if (IsBridgeAbove(tile)) { msg = STR_ERROR_SITE_UNSUITABLE; continue; } TreeType treetype = (TreeType)tree_to_plant; /* Be a bit picky about which trees go where. */ if (_settings_game.game_creation.landscape == LT_TROPIC && treetype != TREE_INVALID && ( /* No cacti outside the desert */ (treetype == TREE_CACTUS && GetTropicZone(tile) != TROPICZONE_DESERT) || /* No rain forest trees outside the rain forest, except in the editor mode where it makes those tiles rain forest tile */ (IsInsideMM(treetype, TREE_RAINFOREST, TREE_CACTUS) && GetTropicZone(tile) != TROPICZONE_RAINFOREST && _game_mode != GM_EDITOR) || /* And no subtropical trees in the desert/rain forest */ (IsInsideMM(treetype, TREE_SUB_TROPICAL, TREE_TOYLAND) && GetTropicZone(tile) != TROPICZONE_NORMAL))) { msg = STR_ERROR_TREE_WRONG_TERRAIN_FOR_TREE_TYPE; continue; } if (IsTileType(tile, MP_CLEAR)) { /* Remove fields or rocks. Note that the ground will get barrened */ switch (GetRawClearGround(tile)) { case CLEAR_FIELDS: case CLEAR_ROCKS: { CommandCost ret = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR); if (ret.Failed()) return ret; cost.AddCost(ret); break; } default: break; } } if (_game_mode != GM_EDITOR && Company::IsValidID(_current_company)) { Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority); if (t != NULL) ChangeTownRating(t, RATING_TREE_UP_STEP, RATING_TREE_MAXIMUM, flags); } if (flags & DC_EXEC) { if (treetype == TREE_INVALID) { treetype = GetRandomTreeType(tile, GB(Random(), 24, 8)); if (treetype == TREE_INVALID) treetype = TREE_CACTUS; } /* Plant full grown trees in scenario editor */ PlantTreesOnTile(tile, treetype, 0, _game_mode == GM_EDITOR ? 3 : 0); MarkTileDirtyByTile(tile); /* When planting rainforest-trees, set tropiczone to rainforest in editor. */ if (_game_mode == GM_EDITOR && IsInsideMM(treetype, TREE_RAINFOREST, TREE_CACTUS)) { SetTropicZone(tile, TROPICZONE_RAINFOREST); } } cost.AddCost(_price[PR_BUILD_TREES]); break; } default: msg = STR_ERROR_SITE_UNSUITABLE; break; } } if (cost.GetCost() == 0) { return_cmd_error(msg); } else { return cost; } }
/** * Build a piece of canal. * @param tile end tile of stretch-dragging * @param flags type of operation * @param p1 start tile of stretch-dragging * @param p2 waterclass to build. sea and river can only be built in scenario editor * @param text unused * @return the cost of this operation or an error */ CommandCost CmdBuildCanal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) { WaterClass wc = Extract<WaterClass, 0, 2>(p2); if (p1 >= MapSize() || wc == WATER_CLASS_INVALID) return CMD_ERROR; /* Outside of the editor you can only build canals, not oceans */ if (wc != WATER_CLASS_CANAL && _game_mode != GM_EDITOR) return CMD_ERROR; TileArea ta(tile, p1); /* Outside the editor you can only drag canals, and not areas */ if (_game_mode != GM_EDITOR && ta.w != 1 && ta.h != 1) return CMD_ERROR; CommandCost cost(EXPENSES_CONSTRUCTION); TILE_AREA_LOOP(tile, ta) { CommandCost ret; Slope slope = GetTileSlope(tile); if (slope != SLOPE_FLAT && (wc != WATER_CLASS_RIVER || !IsInclinedSlope(slope))) { return_cmd_error(STR_ERROR_FLAT_LAND_REQUIRED); } /* can't make water of water! */ if (IsTileType(tile, MP_WATER) && (!IsTileOwner(tile, OWNER_WATER) || wc == WATER_CLASS_SEA)) continue; bool water = IsWaterTile(tile); ret = DoCommand(tile, 0, 0, flags | DC_FORCE_CLEAR_TILE, CMD_LANDSCAPE_CLEAR); if (ret.Failed()) return ret; if (!water) cost.AddCost(ret); if (flags & DC_EXEC) { switch (wc) { case WATER_CLASS_RIVER: MakeRiver(tile, Random()); if (_game_mode == GM_EDITOR) { TileIndex tile2 = tile; CircularTileSearch(&tile2, 5, RiverModifyDesertZone, NULL); } break; case WATER_CLASS_SEA: if (TileHeight(tile) == 0) { MakeSea(tile); break; } FALLTHROUGH; default: MakeCanal(tile, _current_company, Random()); if (Company::IsValidID(_current_company)) { Company::Get(_current_company)->infrastructure.water++; DirtyCompanyInfrastructureWindows(_current_company); } break; } MarkTileDirtyByTile(tile); MarkCanalsAndRiversAroundDirty(tile); } cost.AddCost(_price[PR_BUILD_CANAL]); }
static CommandCost ClearTile_Void(TileIndex tile, DoCommandFlag flags) { return_cmd_error(STR_ERROR_OFF_EDGE_OF_MAP); }
/** Build a ship. * @param tile tile of depot where ship is built * @param flags type of operation * @param p1 ship type being built (engine) * @param p2 unused * @param text unused * @return the cost of this operation or an error */ CommandCost CmdBuildShip(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) { UnitID unit_num; if (!IsEngineBuildable(p1, VEH_SHIP, _current_company)) return_cmd_error(STR_ERROR_SHIP_NOT_AVAILABLE); const Engine *e = Engine::Get(p1); CommandCost value(EXPENSES_NEW_VEHICLES, e->GetCost()); /* Engines without valid cargo should not be available */ if (e->GetDefaultCargoType() == CT_INVALID) return CMD_ERROR; if (flags & DC_QUERY_COST) return value; /* The ai_new queries the vehicle cost before building the route, * so we must check against cheaters no sooner than now. --pasky */ if (!IsShipDepotTile(tile)) return CMD_ERROR; if (!IsTileOwner(tile, _current_company)) return CMD_ERROR; unit_num = (flags & DC_AUTOREPLACE) ? 0 : GetFreeUnitNumber(VEH_SHIP); if (!Vehicle::CanAllocateItem() || unit_num > _settings_game.vehicle.max_ships) return_cmd_error(STR_ERROR_TOO_MANY_VEHICLES_IN_GAME); if (flags & DC_EXEC) { int x; int y; const ShipVehicleInfo *svi = &e->u.ship; Ship *v = new Ship(); v->unitnumber = unit_num; v->owner = _current_company; v->tile = tile; x = TileX(tile) * TILE_SIZE + TILE_SIZE / 2; y = TileY(tile) * TILE_SIZE + TILE_SIZE / 2; v->x_pos = x; v->y_pos = y; v->z_pos = GetSlopeZ(x, y); v->UpdateDeltaXY(v->direction); v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL; v->spritenum = svi->image_index; v->cargo_type = e->GetDefaultCargoType(); v->cargo_cap = svi->capacity; v->value = value.GetCost(); v->last_station_visited = INVALID_STATION; v->max_speed = svi->max_speed; v->engine_type = p1; v->reliability = e->reliability; v->reliability_spd_dec = e->reliability_spd_dec; v->max_age = e->GetLifeLengthInDays(); _new_vehicle_id = v->index; v->state = TRACK_BIT_DEPOT; v->service_interval = Company::Get(_current_company)->settings.vehicle.servint_ships; v->date_of_last_service = _date; v->build_year = _cur_year; v->cur_image = SPR_IMG_QUERY; v->random_bits = VehicleRandomBits(); if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE); v->InvalidateNewGRFCacheOfChain(); v->cargo_cap = GetVehicleCapacity(v); v->InvalidateNewGRFCacheOfChain(); VehicleMove(v, false); InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile); InvalidateWindowClassesData(WC_SHIPS_LIST, 0); SetWindowDirty(WC_COMPANY, v->owner); if (IsLocalCompany()) { InvalidateAutoreplaceWindow(v->engine_type, v->group_id); // updates the replace Ship window } Company::Get(_current_company)->num_engines[p1]++; } return value; }
/** * Convert existing rail to waypoint. Eg build a waypoint station over * piece of rail * @param start_tile northern most tile where waypoint will be built * @param flags type of operation * @param p1 various bitstuffed elements * - p1 = (bit 4) - orientation (Axis) * - p1 = (bit 8-15) - width of waypoint * - p1 = (bit 16-23) - height of waypoint * - p1 = (bit 24) - allow waypoints directly adjacent to other waypoints. * @param p2 various bitstuffed elements * - p2 = (bit 0- 7) - custom station class * - p2 = (bit 8-15) - custom station id * @param text unused * @return the cost of this operation or an error */ CommandCost CmdBuildRailWaypoint(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) { /* Unpack parameters */ Axis axis = Extract<Axis, 4, 1>(p1); byte width = GB(p1, 8, 8); byte height = GB(p1, 16, 8); bool adjacent = HasBit(p1, 24); StationClassID spec_class = Extract<StationClassID, 0, 8>(p2); byte spec_index = GB(p2, 8, 8); StationID station_to_join = GB(p2, 16, 16); /* Check if the given station class is valid */ if (spec_class != STAT_CLASS_WAYP) return CMD_ERROR; if (spec_index >= StationClass::Get(spec_class)->GetSpecCount()) return CMD_ERROR; /* The number of parts to build */ byte count = axis == AXIS_X ? height : width; if ((axis == AXIS_X ? width : height) != 1) return CMD_ERROR; if (count == 0 || count > _settings_game.station.station_spread) return CMD_ERROR; bool reuse = (station_to_join != NEW_STATION); if (!reuse) station_to_join = INVALID_STATION; bool distant_join = (station_to_join != INVALID_STATION); if (distant_join && (!_settings_game.station.distant_join_stations || !Waypoint::IsValidID(station_to_join))) return CMD_ERROR; /* Make sure the area below consists of clear tiles. (OR tiles belonging to a certain rail station) */ StationID est = INVALID_STATION; /* Check whether the tiles we're building on are valid rail or not. */ TileIndexDiff offset = TileOffsByDiagDir(AxisToDiagDir(OtherAxis(axis))); for (int i = 0; i < count; i++) { TileIndex tile = start_tile + i * offset; CommandCost ret = IsValidTileForWaypoint(tile, axis, &est); if (ret.Failed()) return ret; } Waypoint *wp = NULL; TileArea new_location(TileArea(start_tile, width, height)); CommandCost ret = FindJoiningWaypoint(est, station_to_join, adjacent, new_location, &wp); if (ret.Failed()) return ret; /* Check if there is an already existing, deleted, waypoint close to us that we can reuse. */ TileIndex center_tile = start_tile + (count / 2) * offset; if (wp == NULL && reuse) wp = FindDeletedWaypointCloseTo(center_tile, STR_SV_STNAME_WAYPOINT, _current_company); if (wp != NULL) { /* Reuse an existing waypoint. */ if (wp->owner != _current_company) return_cmd_error(STR_ERROR_TOO_CLOSE_TO_ANOTHER_WAYPOINT); /* check if we want to expand an already existing waypoint? */ if (wp->train_station.tile != INVALID_TILE) { CommandCost ret = CanExpandRailStation(wp, new_location, axis); if (ret.Failed()) return ret; } CommandCost ret = wp->rect.BeforeAddRect(start_tile, width, height, StationRect::ADD_TEST); if (ret.Failed()) return ret; } else { /* allocate and initialize new waypoint */ if (!Waypoint::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_STATIONS_LOADING); } if (flags & DC_EXEC) { if (wp == NULL) { wp = new Waypoint(start_tile); } else if (!wp->IsInUse()) { /* Move existing (recently deleted) waypoint to the new location */ wp->xy = start_tile; } wp->owner = GetTileOwner(start_tile); wp->rect.BeforeAddRect(start_tile, width, height, StationRect::ADD_TRY); wp->delete_ctr = 0; wp->facilities |= FACIL_TRAIN; wp->build_date = _date; wp->string_id = STR_SV_STNAME_WAYPOINT; wp->train_station = new_location; if (wp->town == NULL) MakeDefaultName(wp); wp->UpdateVirtCoord(); const StationSpec *spec = StationClass::Get(spec_class)->GetSpec(spec_index); byte *layout_ptr = AllocaM(byte, count); if (spec == NULL) { /* The layout must be 0 for the 'normal' waypoints by design. */ memset(layout_ptr, 0, count); } else { /* But for NewGRF waypoints we like to have their style. */ GetStationLayout(layout_ptr, count, 1, spec); } byte map_spec_index = AllocateSpecToStation(spec, wp, true); Company *c = Company::Get(wp->owner); for (int i = 0; i < count; i++) { TileIndex tile = start_tile + i * offset; byte old_specindex = HasStationTileRail(tile) ? GetCustomStationSpecIndex(tile) : 0; if (!HasStationTileRail(tile)) c->infrastructure.station++; bool reserved = IsTileType(tile, MP_RAILWAY) ? HasBit(GetRailReservationTrackBits(tile), AxisToTrack(axis)) : HasStationReservation(tile); MakeRailWaypoint(tile, wp->owner, wp->index, axis, layout_ptr[i], GetRailType(tile)); SetCustomStationSpecIndex(tile, map_spec_index); SetRailStationReservation(tile, reserved); MarkTileDirtyByTile(tile); DeallocateSpecFromStation(wp, old_specindex); YapfNotifyTrackLayoutChange(tile, AxisToTrack(axis)); } DirtyCompanyInfrastructureWindows(wp->owner); } return CommandCost(EXPENSES_CONSTRUCTION, count * _price[PR_BUILD_WAYPOINT_RAIL]); }
/** * Terraform the north corner of a tile to a specific height. * * @param ts TerraformerState. * @param tile Tile. * @param height Aimed height. * @return Error code or cost. */ static CommandCost TerraformTileHeight(TerraformerState *ts, TileIndex tile, int height) { assert(tile < MapSize()); /* Check range of destination height */ if (height < 0) return_cmd_error(STR_ERROR_ALREADY_AT_SEA_LEVEL); if (height > _settings_game.construction.max_heightlevel) return_cmd_error(STR_ERROR_TOO_HIGH); /* * Check if the terraforming has any effect. * This can only be true, if multiple corners of the start-tile are terraformed (i.e. the terraforming is done by towns/industries etc.). * In this case the terraforming should fail. (Don't know why.) */ if (height == TerraformGetHeightOfTile(ts, tile)) return CMD_ERROR; /* Check "too close to edge of map". Only possible when freeform-edges is off. */ uint x = TileX(tile); uint y = TileY(tile); if (!_settings_game.construction.freeform_edges && ((x <= 1) || (y <= 1) || (x >= MapMaxX() - 1) || (y >= MapMaxY() - 1))) { /* * Determine a sensible error tile */ if (x == 1) x = 0; if (y == 1) y = 0; _terraform_err_tile = TileXY(x, y); return_cmd_error(STR_ERROR_TOO_CLOSE_TO_EDGE_OF_MAP); } /* Mark incident tiles that are involved in the terraforming. */ TerraformAddDirtyTileAround(ts, tile); /* Store the height modification */ TerraformSetHeightOfTile(ts, tile, height); CommandCost total_cost(EXPENSES_CONSTRUCTION); /* Increment cost */ total_cost.AddCost(_price[PR_TERRAFORM]); /* Recurse to neighboured corners if height difference is larger than 1 */ { const TileIndexDiffC *ttm; TileIndex orig_tile = tile; static const TileIndexDiffC _terraform_tilepos[] = { { 1, 0}, // move to tile in SE {-2, 0}, // undo last move, and move to tile in NW { 1, 1}, // undo last move, and move to tile in SW { 0, -2} // undo last move, and move to tile in NE }; for (ttm = _terraform_tilepos; ttm != endof(_terraform_tilepos); ttm++) { tile += ToTileIndexDiff(*ttm); if (tile >= MapSize()) continue; /* Make sure we don't wrap around the map */ if (Delta(TileX(orig_tile), TileX(tile)) == MapSizeX() - 1) continue; if (Delta(TileY(orig_tile), TileY(tile)) == MapSizeY() - 1) continue; /* Get TileHeight of neighboured tile as of current terraform progress */ int r = TerraformGetHeightOfTile(ts, tile); int height_diff = height - r; /* Is the height difference to the neighboured corner greater than 1? */ if (abs(height_diff) > 1) { /* Terraform the neighboured corner. The resulting height difference should be 1. */ height_diff += (height_diff < 0 ? 1 : -1); CommandCost cost = TerraformTileHeight(ts, tile, r + height_diff); if (cost.Failed()) return cost; total_cost.AddCost(cost); } } } return total_cost; }