Silence uninitialised variable warnings in SSE blitters
[openttd/fttd.git] / src / timetable_cmd.cpp
blob5b7a69d8eabd51851aec88abae716d1d75ced9bf
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
10 /** @file timetable_cmd.cpp Commands related to time tabling. */
12 #include "stdafx.h"
13 #include "command_func.h"
14 #include "company_func.h"
15 #include "date_func.h"
16 #include "window_func.h"
17 #include "vehicle_base.h"
18 #include "cmd_helper.h"
19 #include "core/sort_func.hpp"
21 #include "table/strings.h"
23 /**
24 * Change/update a particular timetable entry.
25 * @param v The vehicle to change the timetable of.
26 * @param order_number The index of the timetable in the order list.
27 * @param val The new data of the timetable entry.
28 * @param mtf Which part of the timetable entry to change.
30 static void ChangeTimetable(Vehicle *v, VehicleOrderID order_number, uint16 val, ModifyTimetableFlags mtf)
32 Order *order = v->GetOrder(order_number);
33 int delta = 0;
35 switch (mtf) {
36 case MTF_WAIT_TIME:
37 delta = val - order->wait_time;
38 order->wait_time = val;
39 break;
41 case MTF_TRAVEL_TIME:
42 delta = val - order->travel_time;
43 order->travel_time = val;
44 break;
46 case MTF_TRAVEL_SPEED:
47 order->max_speed = val;
48 break;
50 default:
51 NOT_REACHED();
53 v->orders.list->UpdateOrderTimetable(delta);
55 for (v = v->FirstShared(); v != NULL; v = v->NextShared()) {
56 if (v->cur_real_order_index == order_number && v->current_order.Equals(*order)) {
57 switch (mtf) {
58 case MTF_WAIT_TIME:
59 v->current_order.wait_time = val;
60 break;
62 case MTF_TRAVEL_TIME:
63 v->current_order.travel_time = val;
64 break;
66 case MTF_TRAVEL_SPEED:
67 v->current_order.max_speed = val;
68 break;
70 default:
71 NOT_REACHED();
74 SetWindowDirty(WC_VEHICLE_TIMETABLE, v->index);
78 /**
79 * Change timetable data of an order.
80 * @param tile Not used.
81 * @param flags Operation to perform.
82 * @param p1 Various bitstuffed elements
83 * - p1 = (bit 0-19) - Vehicle with the orders to change.
84 * - p1 = (bit 20-27) - Order index to modify.
85 * - p1 = (bit 28-29) - Timetable data to change (@see ModifyTimetableFlags)
86 * @param p2 The amount of time to wait.
87 * - p2 = (bit 0-15) - The data to modify as specified by p1 bits 28-29.
88 * @param text unused
89 * @return the cost of this operation or an error
91 CommandCost CmdChangeTimetable(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
93 VehicleID veh = GB(p1, 0, 20);
95 Vehicle *v = Vehicle::GetIfValid(veh);
96 if (v == NULL || !v->IsPrimaryVehicle()) return CMD_ERROR;
98 CommandCost ret = CheckOwnership(v->owner);
99 if (ret.Failed()) return ret;
101 VehicleOrderID order_number = GB(p1, 20, 8);
102 Order *order = v->GetOrder(order_number);
103 if (order == NULL || order->IsType(OT_IMPLICIT)) return CMD_ERROR;
105 ModifyTimetableFlags mtf = Extract<ModifyTimetableFlags, 28, 2>(p1);
106 if (mtf >= MTF_END) return CMD_ERROR;
108 int wait_time = order->wait_time;
109 int travel_time = order->travel_time;
110 int max_speed = order->max_speed;
111 switch (mtf) {
112 case MTF_WAIT_TIME:
113 wait_time = GB(p2, 0, 16);
114 break;
116 case MTF_TRAVEL_TIME:
117 travel_time = GB(p2, 0, 16);
118 break;
120 case MTF_TRAVEL_SPEED:
121 max_speed = GB(p2, 0, 16);
122 if (max_speed == 0) max_speed = UINT16_MAX; // Disable speed limit.
123 break;
125 default:
126 NOT_REACHED();
129 if (wait_time != order->wait_time) {
130 switch (order->GetType()) {
131 case OT_GOTO_STATION:
132 if (order->GetNonStopType() & ONSF_NO_STOP_AT_DESTINATION_STATION) return_cmd_error(STR_ERROR_TIMETABLE_NOT_STOPPING_HERE);
133 break;
135 case OT_CONDITIONAL:
136 break;
138 default: return_cmd_error(STR_ERROR_TIMETABLE_ONLY_WAIT_AT_STATIONS);
142 if (travel_time != order->travel_time && order->IsType(OT_CONDITIONAL)) return CMD_ERROR;
143 if (max_speed != order->max_speed && (order->IsType(OT_CONDITIONAL) || v->type == VEH_AIRCRAFT)) return CMD_ERROR;
145 if (flags & DC_EXEC) {
146 if (wait_time != order->wait_time) ChangeTimetable(v, order_number, wait_time, MTF_WAIT_TIME);
147 if (travel_time != order->travel_time) ChangeTimetable(v, order_number, travel_time, MTF_TRAVEL_TIME);
148 if (max_speed != order->max_speed) ChangeTimetable(v, order_number, max_speed, MTF_TRAVEL_SPEED);
151 return CommandCost();
155 * Clear the lateness counter to make the vehicle on time.
156 * @param tile Not used.
157 * @param flags Operation to perform.
158 * @param p1 Various bitstuffed elements
159 * - p1 = (bit 0-19) - Vehicle with the orders to change.
160 * @param p2 unused
161 * @param text unused
162 * @return the cost of this operation or an error
164 CommandCost CmdSetVehicleOnTime(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
166 VehicleID veh = GB(p1, 0, 20);
168 Vehicle *v = Vehicle::GetIfValid(veh);
169 if (v == NULL || !v->IsPrimaryVehicle() || v->orders.list == NULL) return CMD_ERROR;
171 CommandCost ret = CheckOwnership(v->owner);
172 if (ret.Failed()) return ret;
174 if (flags & DC_EXEC) {
175 v->lateness_counter = 0;
176 SetWindowDirty(WC_VEHICLE_TIMETABLE, v->index);
179 return CommandCost();
183 * Order vehicles based on their timetable. The vehicles will be sorted in order
184 * they would reach the first station.
186 * @param ap First Vehicle pointer.
187 * @param bp Second Vehicle pointer.
188 * @return Comparison value.
190 static int CDECL VehicleTimetableSorter(Vehicle * const *ap, Vehicle * const *bp)
192 const Vehicle *a = *ap;
193 const Vehicle *b = *bp;
195 VehicleOrderID a_order = a->cur_real_order_index;
196 VehicleOrderID b_order = b->cur_real_order_index;
197 int j = (int)b_order - (int)a_order;
199 /* Are we currently at an ordered station (un)loading? */
200 bool a_load = a->current_order.IsType(OT_LOADING) && a->current_order.GetNonStopType() != ONSF_STOP_EVERYWHERE;
201 bool b_load = b->current_order.IsType(OT_LOADING) && b->current_order.GetNonStopType() != ONSF_STOP_EVERYWHERE;
203 /* If the current order is not loading at the ordered station, decrease the order index by one since we have
204 * not yet arrived at the station (and thus the timetable entry; still in the travelling of the previous one).
205 * Since the ?_order variables are unsigned the -1 will flow under and place the vehicles going to order #0 at
206 * the begin of the list with vehicles arriving at #0. */
207 if (!a_load) a_order--;
208 if (!b_load) b_order--;
210 /* First check the order index that accounted for loading, then just the raw one. */
211 int i = (int)b_order - (int)a_order;
212 if (i != 0) return i;
213 if (j != 0) return j;
215 /* Look at the time we spent in this order; the higher, the closer to its destination. */
216 i = b->current_order_time - a->current_order_time;
217 if (i != 0) return i;
219 /* If all else is equal, use some unique index to sort it the same way. */
220 return b->unitnumber - a->unitnumber;
224 * Set the start date of the timetable.
225 * @param tile Not used.
226 * @param flags Operation to perform.
227 * @param p2 Various bitstuffed elements
228 * - p2 = (bit 0-19) - Vehicle ID.
229 * - p2 = (bit 20) - Set to 1 to set timetable start for all vehicles sharing this order
230 * @param p2 The timetable start date.
231 * @param text Not used.
232 * @return The error or cost of the operation.
234 CommandCost CmdSetTimetableStart(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
236 bool timetable_all = HasBit(p1, 20);
237 Vehicle *v = Vehicle::GetIfValid(GB(p1, 0, 20));
238 if (v == NULL || !v->IsPrimaryVehicle() || v->orders.list == NULL) return CMD_ERROR;
240 CommandCost ret = CheckOwnership(v->owner);
241 if (ret.Failed()) return ret;
243 /* Don't let a timetable start more than 15 years into the future or 1 year in the past. */
244 Date start_date = (Date)p2;
245 if (start_date < 0 || start_date > MAX_DAY) return CMD_ERROR;
246 if (start_date - _date > 15 * DAYS_IN_LEAP_YEAR) return CMD_ERROR;
247 if (_date - start_date > DAYS_IN_LEAP_YEAR) return CMD_ERROR;
248 if (timetable_all && !v->orders.list->IsCompleteTimetable()) return CMD_ERROR;
250 if (flags & DC_EXEC) {
251 SmallVector<Vehicle *, 8> vehs;
253 if (timetable_all) {
254 for (Vehicle *w = v->orders.list->GetFirstSharedVehicle(); w != NULL; w = w->NextShared()) {
255 *vehs.Append() = w;
257 } else {
258 *vehs.Append() = v;
261 int total_duration = v->orders.list->GetTimetableTotalDuration();
262 int num_vehs = vehs.Length();
264 if (num_vehs >= 2) {
265 QSortT(vehs.Begin(), vehs.Length(), &VehicleTimetableSorter);
268 int base = vehs.FindIndex(v);
270 for (Vehicle **viter = vehs.Begin(); viter != vehs.End(); viter++) {
271 int idx = (viter - vehs.Begin()) - base;
272 Vehicle *w = *viter;
274 w->lateness_counter = 0;
275 ClrBit(w->vehicle_flags, VF_TIMETABLE_STARTED);
276 /* Do multiplication, then division to reduce rounding errors. */
277 w->timetable_start = start_date + idx * total_duration / num_vehs / DAY_TICKS;
278 SetWindowDirty(WC_VEHICLE_TIMETABLE, w->index);
283 return CommandCost();
288 * Start or stop filling the timetable automatically from the time the vehicle
289 * actually takes to complete it. When starting to autofill the current times
290 * are cleared and the timetable will start again from scratch.
291 * @param tile Not used.
292 * @param flags Operation to perform.
293 * @param p1 Vehicle index.
294 * @param p2 Various bitstuffed elements
295 * - p2 = (bit 0) - Set to 1 to enable, 0 to disable autofill.
296 * - p2 = (bit 1) - Set to 1 to preserve waiting times in non-destructive mode
297 * @param text unused
298 * @return the cost of this operation or an error
300 CommandCost CmdAutofillTimetable(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
302 VehicleID veh = GB(p1, 0, 20);
304 Vehicle *v = Vehicle::GetIfValid(veh);
305 if (v == NULL || !v->IsPrimaryVehicle() || v->orders.list == NULL) return CMD_ERROR;
307 CommandCost ret = CheckOwnership(v->owner);
308 if (ret.Failed()) return ret;
310 if (flags & DC_EXEC) {
311 if (HasBit(p2, 0)) {
312 /* Start autofilling the timetable, which clears the
313 * "timetable has started" bit. Times are not cleared anymore, but are
314 * overwritten when the order is reached now. */
315 SetBit(v->vehicle_flags, VF_AUTOFILL_TIMETABLE);
316 ClrBit(v->vehicle_flags, VF_TIMETABLE_STARTED);
318 /* Overwrite waiting times only if they got longer */
319 if (HasBit(p2, 1)) SetBit(v->vehicle_flags, VF_AUTOFILL_PRES_WAIT_TIME);
321 v->timetable_start = 0;
322 v->lateness_counter = 0;
323 } else {
324 ClrBit(v->vehicle_flags, VF_AUTOFILL_TIMETABLE);
325 ClrBit(v->vehicle_flags, VF_AUTOFILL_PRES_WAIT_TIME);
328 for (Vehicle *v2 = v->FirstShared(); v2 != NULL; v2 = v2->NextShared()) {
329 if (v2 != v) {
330 /* Stop autofilling; only one vehicle at a time can perform autofill */
331 ClrBit(v2->vehicle_flags, VF_AUTOFILL_TIMETABLE);
332 ClrBit(v2->vehicle_flags, VF_AUTOFILL_PRES_WAIT_TIME);
334 SetWindowDirty(WC_VEHICLE_TIMETABLE, v2->index);
338 return CommandCost();
342 * Update the timetable for the vehicle.
343 * @param v The vehicle to update the timetable for.
344 * @param travelling Whether we just travelled or waited at a station.
346 void UpdateVehicleTimetable(Vehicle *v, bool travelling)
348 uint timetabled = travelling ? v->current_order.travel_time : v->current_order.wait_time;
349 uint time_taken = v->current_order_time;
351 v->current_order_time = 0;
353 if (v->current_order.IsType(OT_IMPLICIT)) return; // no timetabling of auto orders
355 VehicleOrderID first_manual_order = 0;
356 for (Order *o = v->GetFirstOrder(); o != NULL && o->IsType(OT_IMPLICIT); o = o->next) {
357 ++first_manual_order;
360 bool just_started = false;
362 /* This vehicle is arriving at the first destination in the timetable. */
363 if (v->cur_real_order_index == first_manual_order && travelling) {
364 /* If the start date hasn't been set, or it was set automatically when
365 * the vehicle last arrived at the first destination, update it to the
366 * current time. Otherwise set the late counter appropriately to when
367 * the vehicle should have arrived. */
368 just_started = !HasBit(v->vehicle_flags, VF_TIMETABLE_STARTED);
370 if (v->timetable_start != 0) {
371 v->lateness_counter = (_date - v->timetable_start) * DAY_TICKS + _date_fract;
372 v->timetable_start = 0;
375 SetBit(v->vehicle_flags, VF_TIMETABLE_STARTED);
376 SetWindowDirty(WC_VEHICLE_TIMETABLE, v->index);
379 if (!HasBit(v->vehicle_flags, VF_TIMETABLE_STARTED)) return;
381 if (HasBit(v->vehicle_flags, VF_AUTOFILL_TIMETABLE)) {
382 if (travelling && !HasBit(v->vehicle_flags, VF_AUTOFILL_PRES_WAIT_TIME)) {
383 /* Need to clear that now as otherwise we are not able to reduce the wait time */
384 v->current_order.wait_time = 0;
387 if (just_started) return;
389 /* Modify station waiting time only if our new value is larger (this is
390 * always the case when we cleared the timetable). */
391 if (!v->current_order.IsType(OT_CONDITIONAL) && (travelling || time_taken > v->current_order.wait_time)) {
392 /* Round the time taken up to the nearest day, as this will avoid
393 * confusion for people who are timetabling in days, and can be
394 * adjusted later by people who aren't.
395 * For trains/aircraft multiple movement cycles are done in one
396 * tick. This makes it possible to leave the station and process
397 * e.g. a depot order in the same tick, causing it to not fill
398 * the timetable entry like is done for road vehicles/ships.
399 * Thus always make sure at least one tick is used between the
400 * processing of different orders when filling the timetable. */
401 time_taken = CeilDiv(max(time_taken, 1U), DAY_TICKS) * DAY_TICKS;
403 ChangeTimetable(v, v->cur_real_order_index, time_taken, travelling ? MTF_TRAVEL_TIME : MTF_WAIT_TIME);
406 if (v->cur_real_order_index == first_manual_order && travelling) {
407 /* If we just started we would have returned earlier and have not reached
408 * this code. So obviously, we have completed our round: So turn autofill
409 * off again. */
410 ClrBit(v->vehicle_flags, VF_AUTOFILL_TIMETABLE);
411 ClrBit(v->vehicle_flags, VF_AUTOFILL_PRES_WAIT_TIME);
413 return;
416 if (just_started) return;
418 /* Vehicles will wait at stations if they arrive early even if they are not
419 * timetabled to wait there, so make sure the lateness counter is updated
420 * when this happens. */
421 if (timetabled == 0 && (travelling || v->lateness_counter >= 0)) return;
423 v->lateness_counter -= (timetabled - time_taken);
425 /* When we are more late than this timetabled bit takes we (somewhat expensively)
426 * check how many ticks the (fully filled) timetable has. If a timetable cycle is
427 * shorter than the amount of ticks we are late we reduce the lateness by the
428 * length of a full cycle till lateness is less than the length of a timetable
429 * cycle. When the timetable isn't fully filled the cycle will be INVALID_TICKS. */
430 if (v->lateness_counter > (int)timetabled) {
431 Ticks cycle = v->orders.list->GetTimetableTotalDuration();
432 if (cycle != INVALID_TICKS && v->lateness_counter > cycle) {
433 v->lateness_counter %= cycle;
437 for (v = v->FirstShared(); v != NULL; v = v->NextShared()) {
438 SetWindowDirty(WC_VEHICLE_TIMETABLE, v->index);