id
int64 0
877k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
66
| repo_stars
int64 94
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 11
values | repo_extraction_date
stringclasses 197
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1,539,134
|
waypoint_cmd.cpp
|
EnergeticBark_OpenTTD-3DS/src/waypoint_cmd.cpp
|
/* $Id$ */
/** @file waypoint_cmp.cpp Command Handling for waypoints. */
#include "stdafx.h"
#include "command_func.h"
#include "landscape.h"
#include "economy_func.h"
#include "bridge_map.h"
#include "town.h"
#include "waypoint.h"
#include "yapf/yapf.h"
#include "strings_func.h"
#include "gfx_func.h"
#include "functions.h"
#include "window_func.h"
#include "date_func.h"
#include "vehicle_func.h"
#include "string_func.h"
#include "company_func.h"
#include "newgrf_station.h"
#include "viewport_func.h"
#include "train.h"
#include "table/strings.h"
/**
* Update the sign for the waypoint
* @param wp Waypoint to update sign */
void UpdateWaypointSign(Waypoint *wp)
{
Point pt = RemapCoords2(TileX(wp->xy) * TILE_SIZE, TileY(wp->xy) * TILE_SIZE);
SetDParam(0, wp->index);
UpdateViewportSignPos(&wp->sign, pt.x, pt.y - 0x20, STR_WAYPOINT_VIEWPORT);
}
/**
* Redraw the sign of a waypoint
* @param wp Waypoint to redraw sign */
void RedrawWaypointSign(const Waypoint *wp)
{
MarkAllViewportsDirty(
wp->sign.left - 6,
wp->sign.top,
wp->sign.left + (wp->sign.width_1 << 2) + 12,
wp->sign.top + 48);
}
/**
* Set the default name for a waypoint
* @param wp Waypoint to work on
*/
static void MakeDefaultWaypointName(Waypoint *wp)
{
uint32 used = 0; // bitmap of used waypoint numbers, sliding window with 'next' as base
uint32 next = 0; // first waypoint number in the bitmap
WaypointID idx = 0; // index where we will stop
wp->town_index = ClosestTownFromTile(wp->xy, UINT_MAX)->index;
/* Find first unused waypoint number belonging to this town. This can never fail,
* as long as there can be at most 65535 waypoints in total.
*
* This does 'n * m' search, but with 32bit 'used' bitmap, it needs at most 'n * (1 + ceil(m / 32))'
* steps (n - number of waypoints in pool, m - number of waypoints near this town).
* Usually, it needs only 'n' steps.
*
* If it wasn't using 'used' and 'idx', it would just search for increasing 'next',
* but this way it is faster */
WaypointID cid = 0; // current index, goes to GetWaypointPoolSize()-1, then wraps to 0
do {
Waypoint *lwp = GetWaypoint(cid);
/* check only valid waypoints... */
if (lwp->IsValid() && wp != lwp) {
/* only waypoints with 'generic' name within the same city */
if (lwp->name == NULL && lwp->town_index == wp->town_index) {
/* if lwp->town_cn < next, uint will overflow to '+inf' */
uint i = (uint)lwp->town_cn - next;
if (i < 32) {
SetBit(used, i); // update bitmap
if (i == 0) {
/* shift bitmap while the lowest bit is '1';
* increase the base of the bitmap too */
do {
used >>= 1;
next++;
} while (HasBit(used, 0));
/* when we are at 'idx' again at end of the loop and
* 'next' hasn't changed, then no waypoint had town_cn == next,
* so we can safely use it */
idx = cid;
}
}
}
}
cid++;
if (cid == GetWaypointPoolSize()) cid = 0; // wrap to zero...
} while (cid != idx);
wp->town_cn = (uint16)next; // set index...
wp->name = NULL; // ... and use generic name
}
/**
* Find a deleted waypoint close to a tile.
* @param tile to search from
*/
static Waypoint *FindDeletedWaypointCloseTo(TileIndex tile)
{
Waypoint *wp, *best = NULL;
uint thres = 8;
FOR_ALL_WAYPOINTS(wp) {
if (wp->deleted && wp->owner == _current_company) {
uint cur_dist = DistanceManhattan(tile, wp->xy);
if (cur_dist < thres) {
thres = cur_dist;
best = wp;
}
}
}
return best;
}
/** Convert existing rail to waypoint. Eg build a waypoint station over
* piece of rail
* @param tile tile where waypoint will be built
* @param flags type of operation
* @param p1 graphics for waypoint type, 0 indicates standard graphics
* @param p2 unused
*
* @todo When checking for the tile slope,
* distingush between "Flat land required" and "land sloped in wrong direction"
*/
CommandCost CmdBuildTrainWaypoint(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Waypoint *wp;
Slope tileh;
Axis axis;
/* if custom gfx are used, make sure it is within bounds */
if (p1 >= GetNumCustomStations(STAT_CLASS_WAYP)) return CMD_ERROR;
if (!IsTileType(tile, MP_RAILWAY) ||
GetRailTileType(tile) != RAIL_TILE_NORMAL || (
(axis = AXIS_X, GetTrackBits(tile) != TRACK_BIT_X) &&
(axis = AXIS_Y, GetTrackBits(tile) != TRACK_BIT_Y)
)) {
return_cmd_error(STR_1005_NO_SUITABLE_RAILROAD_TRACK);
}
Owner owner = GetTileOwner(tile);
if (!CheckOwnership(owner)) return CMD_ERROR;
if (!EnsureNoVehicleOnGround(tile)) return CMD_ERROR;
tileh = GetTileSlope(tile, NULL);
if (tileh != SLOPE_FLAT &&
(!_settings_game.construction.build_on_slopes || IsSteepSlope(tileh) || !(tileh & (0x3 << axis)) || !(tileh & ~(0x3 << axis)))) {
return_cmd_error(STR_0007_FLAT_LAND_REQUIRED);
}
if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return_cmd_error(STR_5007_MUST_DEMOLISH_BRIDGE_FIRST);
/* Check if there is an already existing, deleted, waypoint close to us that we can reuse. */
wp = FindDeletedWaypointCloseTo(tile);
if (wp == NULL && !Waypoint::CanAllocateItem()) return CMD_ERROR;
if (flags & DC_EXEC) {
if (wp == NULL) {
wp = new Waypoint(tile);
wp->town_index = INVALID_TOWN;
wp->name = NULL;
wp->town_cn = 0;
} else {
/* Move existing (recently deleted) waypoint to the new location */
/* First we update the destination for all vehicles that
* have the old waypoint in their orders. */
Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->type == VEH_TRAIN &&
v->First() == v &&
v->current_order.IsType(OT_GOTO_WAYPOINT) &&
v->dest_tile == wp->xy) {
v->dest_tile = tile;
}
}
RedrawWaypointSign(wp);
wp->xy = tile;
InvalidateWindowData(WC_WAYPOINT_VIEW, wp->index);
}
wp->owner = owner;
const StationSpec *statspec;
bool reserved = HasBit(GetTrackReservation(tile), AxisToTrack(axis));
MakeRailWaypoint(tile, owner, axis, GetRailType(tile), wp->index);
SetDepotWaypointReservation(tile, reserved);
MarkTileDirtyByTile(tile);
statspec = GetCustomStationSpec(STAT_CLASS_WAYP, p1);
if (statspec != NULL) {
wp->stat_id = p1;
wp->grfid = statspec->grffile->grfid;
wp->localidx = statspec->localidx;
} else {
/* Specified custom graphics do not exist, so use default. */
wp->stat_id = 0;
wp->grfid = 0;
wp->localidx = 0;
}
wp->deleted = 0;
wp->build_date = _date;
if (wp->town_index == INVALID_TOWN) MakeDefaultWaypointName(wp);
UpdateWaypointSign(wp);
RedrawWaypointSign(wp);
YapfNotifyTrackLayoutChange(tile, AxisToTrack(axis));
}
return CommandCost(EXPENSES_CONSTRUCTION, _price.build_train_depot);
}
/**
* Remove a waypoint
* @param tile from which to remove waypoint
* @param flags type of operation
* @param justremove will indicate if it is removed from rail or if rails are removed too
* @return cost of operation or error
*/
CommandCost RemoveTrainWaypoint(TileIndex tile, DoCommandFlag flags, bool justremove)
{
Waypoint *wp;
/* Make sure it's a waypoint */
if (!IsRailWaypointTile(tile) ||
(!CheckTileOwnership(tile) && _current_company != OWNER_WATER) ||
!EnsureNoVehicleOnGround(tile)) {
return CMD_ERROR;
}
if (flags & DC_EXEC) {
Track track = GetRailWaypointTrack(tile);
wp = GetWaypointByTile(tile);
wp->deleted = 30; // let it live for this many days before we do the actual deletion.
RedrawWaypointSign(wp);
Vehicle *v = NULL;
if (justremove) {
TrackBits tracks = GetRailWaypointBits(tile);
bool reserved = GetDepotWaypointReservation(tile);
MakeRailNormal(tile, wp->owner, tracks, GetRailType(tile));
if (reserved) SetTrackReservation(tile, tracks);
MarkTileDirtyByTile(tile);
} else {
if (GetDepotWaypointReservation(tile)) {
v = GetTrainForReservation(tile, track);
if (v != NULL) FreeTrainTrackReservation(v);
}
DoClearSquare(tile);
AddTrackToSignalBuffer(tile, track, wp->owner);
}
YapfNotifyTrackLayoutChange(tile, track);
if (v != NULL) TryPathReserve(v, true);
}
return CommandCost(EXPENSES_CONSTRUCTION, _price.remove_train_depot);
}
/**
* Delete a waypoint
* @param tile tile where waypoint is to be deleted
* @param flags type of operation
* @param p1 unused
* @param p2 unused
* @return cost of operation or error
*/
CommandCost CmdRemoveTrainWaypoint(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
return RemoveTrainWaypoint(tile, flags, true);
}
static bool IsUniqueWaypointName(const char *name)
{
const Waypoint *wp;
FOR_ALL_WAYPOINTS(wp) {
if (wp->name != NULL && strcmp(wp->name, name) == 0) return false;
}
return true;
}
/**
* Rename a waypoint.
* @param tile unused
* @param flags type of operation
* @param p1 id of waypoint
* @param p2 unused
* @return cost of operation or error
*/
CommandCost CmdRenameWaypoint(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
if (!IsValidWaypointID(p1)) return CMD_ERROR;
Waypoint *wp = GetWaypoint(p1);
if (!CheckOwnership(wp->owner)) return CMD_ERROR;
bool reset = StrEmpty(text);
if (!reset) {
if (strlen(text) >= MAX_LENGTH_WAYPOINT_NAME_BYTES) return CMD_ERROR;
if (!IsUniqueWaypointName(text)) return_cmd_error(STR_NAME_MUST_BE_UNIQUE);
}
if (flags & DC_EXEC) {
free(wp->name);
if (reset) {
MakeDefaultWaypointName(wp); // sets wp->name = NULL
} else {
wp->name = strdup(text);
}
UpdateWaypointSign(wp);
MarkWholeScreenDirty();
}
return CommandCost();
}
| 9,556
|
C++
|
.cpp
| 288
| 30.260417
| 132
| 0.695355
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,135
|
osk_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/osk_gui.cpp
|
/* $Id$ */
/** @file osk_gui.cpp The On Screen Keyboard GUI */
#include "stdafx.h"
#include "string_func.h"
#include "strings_func.h"
#include "debug.h"
#include "window_func.h"
#include "gfx_func.h"
#include "querystring_gui.h"
#include "table/sprites.h"
#include "table/strings.h"
enum OskWidgets {
OSK_WIDGET_TEXT = 3,
OSK_WIDGET_CANCEL = 5,
OSK_WIDGET_OK,
OSK_WIDGET_BACKSPACE,
OSK_WIDGET_SPECIAL,
OSK_WIDGET_CAPS,
OSK_WIDGET_SHIFT,
OSK_WIDGET_SPACE,
OSK_WIDGET_LEFT,
OSK_WIDGET_RIGHT,
OSK_WIDGET_LETTERS
};
char _keyboard_opt[2][OSK_KEYBOARD_ENTRIES * 4 + 1];
static WChar _keyboard[2][OSK_KEYBOARD_ENTRIES];
enum {
KEYS_NONE,
KEYS_SHIFT,
KEYS_CAPS
};
static byte _keystate = KEYS_NONE;
struct OskWindow : public Window {
StringID caption; ///< the caption for this window.
QueryString *qs; ///< text-input
int text_btn; ///< widget number of parent's text field
int ok_btn; ///< widget number of parent's ok button (=0 when ok shouldn't be passed on)
int cancel_btn; ///< widget number of parent's cancel button (=0 when cancel shouldn't be passed on; text will be reverted to original)
Textbuf *text; ///< pointer to parent's textbuffer (to update caret position)
char *orig_str_buf; ///< Original string.
OskWindow(const WindowDesc *desc, QueryStringBaseWindow *parent, int button, int cancel, int ok) : Window(desc)
{
this->parent = parent;
assert(parent != NULL);
this->caption = (parent->widget[button].data != STR_NULL) ? parent->widget[button].data : parent->caption;
this->qs = parent;
this->text_btn = button;
this->cancel_btn = cancel;
this->ok_btn = ok;
this->text = &parent->text;
/* make a copy in case we need to reset later */
this->orig_str_buf = strdup(this->qs->text.buf);
/* Not needed by default. */
this->DisableWidget(OSK_WIDGET_SPECIAL);
this->FindWindowPlacementAndResize(desc);
}
~OskWindow()
{
free(this->orig_str_buf);
}
/**
* Only show valid characters; do not show characters that would
* only insert a space when we have a spacebar to do that or
* characters that are not allowed to be entered.
*/
void ChangeOskDiabledState(bool shift)
{
for (uint i = 0; i < OSK_KEYBOARD_ENTRIES; i++) {
this->SetWidgetDisabledState(OSK_WIDGET_LETTERS + i,
!IsValidChar(_keyboard[shift][i], this->qs->afilter) || _keyboard[shift][i] == ' ');
}
this->SetWidgetDisabledState(OSK_WIDGET_SPACE, !IsValidChar(' ', this->qs->afilter));
}
virtual void OnPaint()
{
bool shift = HasBit(_keystate, KEYS_CAPS) ^ HasBit(_keystate, KEYS_SHIFT);
this->LowerWidget(OSK_WIDGET_TEXT);
this->SetWidgetLoweredState(OSK_WIDGET_SHIFT, HasBit(_keystate, KEYS_SHIFT));
this->SetWidgetLoweredState(OSK_WIDGET_CAPS, HasBit(_keystate, KEYS_CAPS));
this->ChangeOskDiabledState(shift);
SetDParam(0, this->caption);
this->DrawWidgets();
for (uint i = 0; i < OSK_KEYBOARD_ENTRIES; i++) {
DrawCharCentered(_keyboard[shift][i],
this->widget[OSK_WIDGET_LETTERS + i].left + 8,
this->widget[OSK_WIDGET_LETTERS + i].top + 3,
TC_BLACK);
}
this->qs->DrawEditBox(this, OSK_WIDGET_TEXT);
}
virtual void OnClick(Point pt, int widget)
{
/* clicked a letter */
if (widget >= OSK_WIDGET_LETTERS) {
bool shift = HasBit(_keystate, KEYS_CAPS) ^ HasBit(_keystate, KEYS_SHIFT);
WChar c = _keyboard[shift][widget - OSK_WIDGET_LETTERS];
if (!IsValidChar(c, this->qs->afilter)) return;
if (InsertTextBufferChar(&this->qs->text, c)) this->InvalidateParent();
if (HasBit(_keystate, KEYS_SHIFT)) {
ToggleBit(_keystate, KEYS_SHIFT);
this->widget[OSK_WIDGET_SHIFT].colour = HasBit(_keystate, KEYS_SHIFT) ? COLOUR_WHITE : COLOUR_GREY;
this->SetDirty();
}
return;
}
switch (widget) {
case OSK_WIDGET_TEXT:
/* Find the edit box of the parent window and give focus to that */
for (uint i = 0; i < this->parent->widget_count; i++) {
Widget &wi = this->parent->widget[i];
if (wi.type == WWT_EDITBOX) {
this->parent->focused_widget = &wi;
break;
}
}
/* Give focus to parent window */
SetFocusedWindow(this->parent);
break;
case OSK_WIDGET_BACKSPACE:
if (DeleteTextBufferChar(&this->qs->text, WKC_BACKSPACE)) this->InvalidateParent();
break;
case OSK_WIDGET_SPECIAL:
/*
* Anything device specific can go here.
* The button itself is hidden by default, and when you need it you
* can not hide it in the create event.
*/
break;
case OSK_WIDGET_CAPS:
ToggleBit(_keystate, KEYS_CAPS);
this->SetDirty();
break;
case OSK_WIDGET_SHIFT:
ToggleBit(_keystate, KEYS_SHIFT);
this->SetDirty();
break;
case OSK_WIDGET_SPACE:
if (InsertTextBufferChar(&this->qs->text, ' ')) this->InvalidateParent();
break;
case OSK_WIDGET_LEFT:
if (MoveTextBufferPos(&this->qs->text, WKC_LEFT)) this->InvalidateParent();
break;
case OSK_WIDGET_RIGHT:
if (MoveTextBufferPos(&this->qs->text, WKC_RIGHT)) this->InvalidateParent();
break;
case OSK_WIDGET_OK:
if (this->qs->orig == NULL || strcmp(this->qs->text.buf, this->qs->orig) != 0) {
/* pass information by simulating a button press on parent window */
if (this->ok_btn != 0) {
this->parent->OnClick(pt, this->ok_btn);
/* Window gets deleted when the parent window removes itself. */
return;
}
}
delete this;
break;
case OSK_WIDGET_CANCEL:
if (this->cancel_btn != 0) { // pass a cancel event to the parent window
this->parent->OnClick(pt, this->cancel_btn);
/* Window gets deleted when the parent window removes itself. */
return;
} else { // or reset to original string
strcpy(qs->text.buf, this->orig_str_buf);
UpdateTextBufferSize(&qs->text);
MoveTextBufferPos(&qs->text, WKC_END);
this->InvalidateParent();
delete this;
}
break;
}
}
void InvalidateParent()
{
QueryStringBaseWindow *w = dynamic_cast<QueryStringBaseWindow*>(this->parent);
if (w != NULL) w->OnOSKInput(this->text_btn);
this->InvalidateWidget(OSK_WIDGET_TEXT);
if (this->parent != NULL) this->parent->InvalidateWidget(this->text_btn);
}
virtual void OnMouseLoop()
{
this->qs->HandleEditBox(this, OSK_WIDGET_TEXT);
/* make the caret of the parent window also blink */
this->parent->InvalidateWidget(this->text_btn);
}
virtual void OnInvalidateData(int)
{
this->InvalidateWidget(OSK_WIDGET_TEXT);
}
};
static const Widget _osk_widgets[] = {
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 0, 0x0, STR_NULL},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 0, 255, 0, 13, STR_012D, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 255, 14, 29, 0x0, STR_NULL},
{ WWT_EDITBOX, RESIZE_NONE, COLOUR_GREY, 2, 253, 16, 27, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 255, 30, 139, 0x0, STR_NULL},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 3, 108, 35, 46, STR_012E_CANCEL, STR_NULL},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 111, 216, 35, 46, STR_012F_OK, STR_NULL},
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 219, 252, 35, 46, SPR_OSK_BACKSPACE, STR_NULL},
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 3, 27, 67, 82, SPR_OSK_SPECIAL, STR_NULL},
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 3, 36, 85, 100, SPR_OSK_CAPS, STR_NULL},
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 3, 27, 103, 118, SPR_OSK_SHIFT, STR_NULL},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 75, 189, 121, 136, STR_EMPTY, STR_NULL},
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 219, 234, 121, 136, SPR_OSK_LEFT, STR_NULL},
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 237, 252, 121, 136, SPR_OSK_RIGHT, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 3, 18, 49, 64, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 21, 36, 49, 64, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 39, 54, 49, 64, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 57, 72, 49, 64, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 75, 90, 49, 64, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 93, 108, 49, 64, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 111, 126, 49, 64, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 129, 144, 49, 64, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 147, 162, 49, 64, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 165, 180, 49, 64, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 183, 198, 49, 64, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 201, 216, 49, 64, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 219, 234, 49, 64, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 237, 252, 49, 64, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 30, 45, 67, 82, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 48, 63, 67, 82, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 66, 81, 67, 82, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 84, 99, 67, 82, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 102, 117, 67, 82, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 120, 135, 67, 82, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 138, 153, 67, 82, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 156, 171, 67, 82, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 174, 189, 67, 82, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 192, 207, 67, 82, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 210, 225, 67, 82, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 228, 243, 67, 82, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 39, 54, 85, 100, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 57, 72, 85, 100, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 75, 90, 85, 100, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 93, 108, 85, 100, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 111, 126, 85, 100, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 129, 144, 85, 100, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 147, 162, 85, 100, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 165, 180, 85, 100, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 183, 198, 85, 100, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 201, 216, 85, 100, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 219, 234, 85, 100, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 237, 252, 85, 100, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 30, 45, 103, 118, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 48, 63, 103, 118, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 66, 81, 103, 118, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 84, 99, 103, 118, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 102, 117, 103, 118, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 120, 135, 103, 118, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 138, 153, 103, 118, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 156, 171, 103, 118, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 174, 189, 103, 118, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 192, 207, 103, 118, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 210, 225, 103, 118, 0x0, STR_NULL},
{ WWT_PUSHBTN, RESIZE_NONE, COLOUR_GREY, 228, 243, 103, 118, 0x0, STR_NULL},
{ WIDGETS_END},
};
static const WindowDesc _osk_desc(
WDP_CENTER, WDP_CENTER, 256, 140, 256, 140,
WC_OSK, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
_osk_widgets
);
/**
* Retrieve keyboard layout from language string or (if set) config file.
* Also check for invalid characters.
*/
void GetKeyboardLayout()
{
char keyboard[2][OSK_KEYBOARD_ENTRIES * 4 + 1];
char errormark[2][OSK_KEYBOARD_ENTRIES + 1]; // used for marking invalid chars
bool has_error = false; // true when an invalid char is detected
if (StrEmpty(_keyboard_opt[0])) {
GetString(keyboard[0], STR_OSK_KEYBOARD_LAYOUT, lastof(keyboard[0]));
} else {
strecpy(keyboard[0], _keyboard_opt[0], lastof(keyboard[0]));
}
if (StrEmpty(_keyboard_opt[1])) {
GetString(keyboard[1], STR_OSK_KEYBOARD_LAYOUT_CAPS, lastof(keyboard[1]));
} else {
strecpy(keyboard[1], _keyboard_opt[1], lastof(keyboard[1]));
}
for (uint j = 0; j < 2; j++) {
const char *kbd = keyboard[j];
bool ended = false;
for (uint i = 0; i < OSK_KEYBOARD_ENTRIES; i++) {
_keyboard[j][i] = Utf8Consume(&kbd);
/* Be lenient when the last characters are missing (is quite normal) */
if (_keyboard[j][i] == '\0' || ended) {
ended = true;
_keyboard[j][i] = ' ';
continue;
}
if (IsPrintable(_keyboard[j][i])) {
errormark[j][i] = ' ';
} else {
has_error = true;
errormark[j][i] = '^';
_keyboard[j][i] = ' ';
}
}
}
if (has_error) {
ShowInfoF("The keyboard layout you selected contains invalid chars. Please check those chars marked with ^.");
ShowInfoF("Normal keyboard: %s", keyboard[0]);
ShowInfoF(" %s", errormark[0]);
ShowInfoF("Caps Lock: %s", keyboard[1]);
ShowInfoF(" %s", errormark[1]);
}
}
/**
* Show the on-screen keyboard (osk) associated with a given textbox
* @param parent pointer to the Window where this keyboard originated from
* @param q querystr_d pointer to the query string of the parent, which is
* shared for both windows
* @param button widget number of parent's textbox
* @param cancel widget number of parent's cancel button (0 if cancel events
* should not be passed)
* @param ok widget number of parent's ok button (0 if ok events should not
* be passed)
*/
void ShowOnScreenKeyboard(QueryStringBaseWindow *parent, int button, int cancel, int ok)
{
DeleteWindowById(WC_OSK, 0);
GetKeyboardLayout();
new OskWindow(&_osk_desc, parent, button, cancel, ok);
}
| 15,154
|
C++
|
.cpp
| 326
| 43.54908
| 143
| 0.622012
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,137
|
thread_win32.cpp
|
EnergeticBark_OpenTTD-3DS/src/thread_win32.cpp
|
/* $Id$ */
/** @file thread_win32.cpp Win32 thread implementation of Threads. */
#include "stdafx.h"
#include "thread.h"
#include "debug.h"
#include "core/alloc_func.hpp"
#include <stdlib.h>
#include <windows.h>
#include <process.h>
/**
* Win32 thread version for ThreadObject.
*/
class ThreadObject_Win32 : public ThreadObject {
private:
HANDLE thread; ///< System thread identifier.
uint id; ///< Thread identifier.
OTTDThreadFunc proc; ///< External thread procedure.
void *param; ///< Parameter for the external thread procedure.
bool self_destruct; ///< Free ourselves when done?
public:
/**
* Create a win32 thread and start it, calling proc(param).
*/
ThreadObject_Win32(OTTDThreadFunc proc, void *param, bool self_destruct) :
thread(NULL),
id(0),
proc(proc),
param(param),
self_destruct(self_destruct)
{
this->thread = (HANDLE)_beginthreadex(NULL, 0, &stThreadProc, this, CREATE_SUSPENDED, &this->id);
if (this->thread == NULL) return;
ResumeThread(this->thread);
}
/* virtual */ ~ThreadObject_Win32()
{
if (this->thread != NULL) {
CloseHandle(this->thread);
this->thread = NULL;
}
}
/* virtual */ bool Exit()
{
assert(GetCurrentThreadId() == this->id);
/* For now we terminate by throwing an error, gives much cleaner cleanup */
throw OTTDThreadExitSignal();
}
/* virtual */ void Join()
{
/* You cannot join yourself */
assert(GetCurrentThreadId() != this->id);
WaitForSingleObject(this->thread, INFINITE);
}
private:
/**
* On thread creation, this function is called, which calls the real startup
* function. This to get back into the correct instance again.
*/
static uint CALLBACK stThreadProc(void *thr)
{
((ThreadObject_Win32 *)thr)->ThreadProc();
return 0;
}
/**
* A new thread is created, and this function is called. Call the custom
* function of the creator of the thread.
*/
void ThreadProc()
{
try {
this->proc(this->param);
} catch (OTTDThreadExitSignal) {
} catch (...) {
NOT_REACHED();
}
if (self_destruct) delete this;
}
};
/* static */ bool ThreadObject::New(OTTDThreadFunc proc, void *param, ThreadObject **thread)
{
ThreadObject *to = new ThreadObject_Win32(proc, param, thread == NULL);
if (thread != NULL) *thread = to;
return true;
}
/**
* Win32 thread version of ThreadMutex.
*/
class ThreadMutex_Win32 : public ThreadMutex {
private:
CRITICAL_SECTION critical_section;
public:
ThreadMutex_Win32()
{
InitializeCriticalSection(&this->critical_section);
}
/* virtual */ ~ThreadMutex_Win32()
{
DeleteCriticalSection(&this->critical_section);
}
/* virtual */ void BeginCritical()
{
EnterCriticalSection(&this->critical_section);
}
/* virtual */ void EndCritical()
{
LeaveCriticalSection(&this->critical_section);
}
};
/* static */ ThreadMutex *ThreadMutex::New()
{
return new ThreadMutex_Win32();
}
| 2,901
|
C++
|
.cpp
| 112
| 23.598214
| 99
| 0.703102
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
1,539,138
|
misc_cmd.cpp
|
EnergeticBark_OpenTTD-3DS/src/misc_cmd.cpp
|
/* $Id$ */
/** @file misc_cmd.cpp Some misc functions that are better fitted in other files, but never got moved there... */
#include "stdafx.h"
#include "openttd.h"
#include "command_func.h"
#include "economy_func.h"
#include "window_func.h"
#include "textbuf_gui.h"
#include "network/network.h"
#include "company_manager_face.h"
#include "strings_func.h"
#include "gfx_func.h"
#include "functions.h"
#include "vehicle_func.h"
#include "string_func.h"
#include "company_func.h"
#include "company_gui.h"
#include "settings_type.h"
#include "vehicle_base.h"
#include "table/strings.h"
/** Change the company manager's face.
* @param tile unused
* @param flags operation to perform
* @param p1 unused
* @param p2 face bitmasked
*/
CommandCost CmdSetCompanyManagerFace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
CompanyManagerFace cmf = (CompanyManagerFace)p2;
if (!IsValidCompanyManagerFace(cmf)) return CMD_ERROR;
if (flags & DC_EXEC) {
GetCompany(_current_company)->face = cmf;
MarkWholeScreenDirty();
}
return CommandCost();
}
/** Change the company's company-colour
* @param tile unused
* @param flags operation to perform
* @param p1 bitstuffed:
* p1 bits 0-7 scheme to set
* p1 bits 8-9 set in use state or first/second colour
* @param p2 new colour for vehicles, property, etc.
*/
CommandCost CmdSetCompanyColour(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
if (p2 >= 16) return CMD_ERROR; // max 16 colours
Colours colour = (Colours)p2;
LiveryScheme scheme = (LiveryScheme)GB(p1, 0, 8);
byte state = GB(p1, 8, 2);
if (scheme >= LS_END || state >= 3) return CMD_ERROR;
Company *c = GetCompany(_current_company);
/* Ensure no two companies have the same primary colour */
if (scheme == LS_DEFAULT && state == 0) {
const Company *cc;
FOR_ALL_COMPANIES(cc) {
if (cc != c && cc->colour == colour) return CMD_ERROR;
}
}
if (flags & DC_EXEC) {
switch (state) {
case 0:
c->livery[scheme].colour1 = colour;
/* If setting the first colour of the default scheme, adjust the
* original and cached company colours too. */
if (scheme == LS_DEFAULT) {
_company_colours[_current_company] = colour;
c->colour = colour;
}
break;
case 1:
c->livery[scheme].colour2 = colour;
break;
case 2:
c->livery[scheme].in_use = colour != 0;
/* Now handle setting the default scheme's in_use flag.
* This is different to the other schemes, as it signifies if any
* scheme is active at all. If this flag is not set, then no
* processing of vehicle types occurs at all, and only the default
* colours will be used. */
/* If enabling a scheme, set the default scheme to be in use too */
if (colour != 0) {
c->livery[LS_DEFAULT].in_use = true;
break;
}
/* Else loop through all schemes to see if any are left enabled.
* If not, disable the default scheme too. */
c->livery[LS_DEFAULT].in_use = false;
for (scheme = LS_DEFAULT; scheme < LS_END; scheme++) {
if (c->livery[scheme].in_use) {
c->livery[LS_DEFAULT].in_use = true;
break;
}
}
break;
default:
break;
}
ResetVehicleColourMap();
MarkWholeScreenDirty();
/* Company colour data is indirectly cached. */
Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->owner == _current_company) v->cache_valid = 0;
}
}
return CommandCost();
}
/** Increase the loan of your company.
* @param tile unused
* @param flags operation to perform
* @param p1 amount to increase the loan with, multitude of LOAN_INTERVAL. Only used when p2 == 2.
* @param p2 when 0: loans LOAN_INTERVAL
* when 1: loans the maximum loan permitting money (press CTRL),
* when 2: loans the amount specified in p1
*/
CommandCost CmdIncreaseLoan(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Company *c = GetCompany(_current_company);
if (c->current_loan >= _economy.max_loan) {
SetDParam(0, _economy.max_loan);
return_cmd_error(STR_702B_MAXIMUM_PERMITTED_LOAN);
}
Money loan;
switch (p2) {
default: return CMD_ERROR; // Invalid method
case 0: // Take some extra loan
loan = LOAN_INTERVAL;
break;
case 1: // Take a loan as big as possible
loan = _economy.max_loan - c->current_loan;
break;
case 2: // Take the given amount of loan
if ((((int32)p1 < LOAN_INTERVAL) || c->current_loan + (int32)p1 > _economy.max_loan || (p1 % LOAN_INTERVAL) != 0)) return CMD_ERROR;
loan = p1;
break;
}
/* Overflow protection */
if (c->money + c->current_loan + loan < c->money) return CMD_ERROR;
if (flags & DC_EXEC) {
c->money += loan;
c->current_loan += loan;
InvalidateCompanyWindows(c);
}
return CommandCost(EXPENSES_OTHER);
}
/** Decrease the loan of your company.
* @param tile unused
* @param flags operation to perform
* @param p1 amount to decrease the loan with, multitude of LOAN_INTERVAL. Only used when p2 == 2.
* @param p2 when 0: pays back LOAN_INTERVAL
* when 1: pays back the maximum loan permitting money (press CTRL),
* when 2: pays back the amount specified in p1
*/
CommandCost CmdDecreaseLoan(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Company *c = GetCompany(_current_company);
if (c->current_loan == 0) return_cmd_error(STR_702D_LOAN_ALREADY_REPAYED);
Money loan;
switch (p2) {
default: return CMD_ERROR; // Invalid method
case 0: // Pay back one step
loan = min(c->current_loan, (Money)LOAN_INTERVAL);
break;
case 1: // Pay back as much as possible
loan = max(min(c->current_loan, c->money), (Money)LOAN_INTERVAL);
loan -= loan % LOAN_INTERVAL;
break;
case 2: // Repay the given amount of loan
if ((p1 % LOAN_INTERVAL != 0) || ((int32)p1 < LOAN_INTERVAL)) return CMD_ERROR; // Invalid amount to loan
loan = p1;
break;
}
if (c->money < loan) {
SetDParam(0, loan);
return_cmd_error(STR_702E_REQUIRED);
}
if (flags & DC_EXEC) {
c->money -= loan;
c->current_loan -= loan;
InvalidateCompanyWindows(c);
}
return CommandCost();
}
static bool IsUniqueCompanyName(const char *name)
{
const Company *c;
FOR_ALL_COMPANIES(c) {
if (c->name != NULL && strcmp(c->name, name) == 0) return false;
}
return true;
}
/** Change the name of the company.
* @param tile unused
* @param flags operation to perform
* @param p1 unused
* @param p2 unused
*/
CommandCost CmdRenameCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
bool reset = StrEmpty(text);
if (!reset) {
if (strlen(text) >= MAX_LENGTH_COMPANY_NAME_BYTES) return CMD_ERROR;
if (!IsUniqueCompanyName(text)) return_cmd_error(STR_NAME_MUST_BE_UNIQUE);
}
if (flags & DC_EXEC) {
Company *c = GetCompany(_current_company);
free(c->name);
c->name = reset ? NULL : strdup(text);
MarkWholeScreenDirty();
}
return CommandCost();
}
static bool IsUniquePresidentName(const char *name)
{
const Company *c;
FOR_ALL_COMPANIES(c) {
if (c->president_name != NULL && strcmp(c->president_name, name) == 0) return false;
}
return true;
}
/** Change the name of the president.
* @param tile unused
* @param flags operation to perform
* @param p1 unused
* @param p2 unused
*/
CommandCost CmdRenamePresident(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
bool reset = StrEmpty(text);
if (!reset) {
if (strlen(text) >= MAX_LENGTH_PRESIDENT_NAME_BYTES) return CMD_ERROR;
if (!IsUniquePresidentName(text)) return_cmd_error(STR_NAME_MUST_BE_UNIQUE);
}
if (flags & DC_EXEC) {
Company *c = GetCompany(_current_company);
free(c->president_name);
if (reset) {
c->president_name = NULL;
} else {
c->president_name = strdup(text);
if (c->name_1 == STR_SV_UNNAMED && c->name == NULL) {
char buf[80];
snprintf(buf, lengthof(buf), "%s Transport", text);
DoCommand(0, 0, 0, DC_EXEC, CMD_RENAME_COMPANY, buf);
}
}
MarkWholeScreenDirty();
}
return CommandCost();
}
/**
* In case of an unsafe unpause, we want the
* user to confirm that it might crash.
* @param w unused
* @param confirmed whether the user confirms his/her action
*/
static void AskUnsafeUnpauseCallback(Window *w, bool confirmed)
{
DoCommandP(0, confirmed ? 0 : 1, 0, CMD_PAUSE);
}
/** Pause/Unpause the game (server-only).
* Increase or decrease the pause counter. If the counter is zero,
* the game is unpaused. A counter is used instead of a boolean value
* to have more control over the game when saving/loading, etc.
* @param tile unused
* @param flags operation to perform
* @param p1 0 = decrease pause counter; 1 = increase pause counter
* @param p2 unused
*/
CommandCost CmdPause(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
if (flags & DC_EXEC) {
_pause_game += (p1 == 0) ? -1 : 1;
switch (_pause_game) {
case -4:
case -1:
_pause_game = 0;
break;
case -3:
ShowQuery(
STR_NEWGRF_UNPAUSE_WARNING_TITLE,
STR_NEWGRF_UNPAUSE_WARNING,
NULL,
AskUnsafeUnpauseCallback
);
break;
default: break;
}
InvalidateWindow(WC_STATUS_BAR, 0);
InvalidateWindow(WC_MAIN_TOOLBAR, 0);
}
return CommandCost();
}
/** Change the financial flow of your company.
* This is normally only enabled in offline mode, but if there is a debug
* build, you can cheat (to test).
* @param tile unused
* @param flags operation to perform
* @param p1 the amount of money to receive (if negative), or spend (if positive)
* @param p2 unused
*/
CommandCost CmdMoneyCheat(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
#ifndef _DEBUG
if (_networking) return CMD_ERROR;
#endif
return CommandCost(EXPENSES_OTHER, -(int32)p1);
}
/** Transfer funds (money) from one company to another.
* To prevent abuse in multiplayer games you can only send money to other
* companies if you have paid off your loan (either explicitely, or implicitely
* given the fact that you have more money than loan).
* @param tile unused
* @param flags operation to perform
* @param p1 the amount of money to transfer; max 20.000.000
* @param p2 the company to transfer the money to
*/
CommandCost CmdGiveMoney(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
if (!_settings_game.economy.give_money) return CMD_ERROR;
const Company *c = GetCompany(_current_company);
CommandCost amount(EXPENSES_OTHER, min((Money)p1, (Money)20000000LL));
/* You can only transfer funds that is in excess of your loan */
if (c->money - c->current_loan < amount.GetCost() || amount.GetCost() <= 0) return CMD_ERROR;
if (!_networking || !IsValidCompanyID((CompanyID)p2)) return CMD_ERROR;
if (flags & DC_EXEC) {
/* Add money to company */
CompanyID old_company = _current_company;
_current_company = (CompanyID)p2;
SubtractMoneyFromCompany(CommandCost(EXPENSES_OTHER, -amount.GetCost()));
_current_company = old_company;
}
/* Subtract money from local-company */
return amount;
}
| 11,105
|
C++
|
.cpp
| 336
| 30.276786
| 135
| 0.699384
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,140
|
company_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/company_gui.cpp
|
/* $Id$ */
/** @file company_gui.cpp Company related GUIs. */
#include "stdafx.h"
#include "gui.h"
#include "window_gui.h"
#include "textbuf_gui.h"
#include "viewport_func.h"
#include "gfx_func.h"
#include "company_func.h"
#include "command_func.h"
#include "network/network.h"
#include "network/network_gui.h"
#include "network/network_func.h"
#include "roadveh.h"
#include "train.h"
#include "aircraft.h"
#include "newgrf.h"
#include "company_manager_face.h"
#include "strings_func.h"
#include "date_func.h"
#include "string_func.h"
#include "widgets/dropdown_type.h"
#include "tilehighlight_func.h"
#include "settings_type.h"
#include "table/strings.h"
enum {
FIRST_GUI_CALL = INT_MAX, ///< default value to specify thuis is the first call of the resizable gui
};
static void DoShowCompanyFinances(CompanyID company, bool show_small, bool show_stickied, int top = FIRST_GUI_CALL, int left = FIRST_GUI_CALL);
static void DoSelectCompanyManagerFace(Window *parent, bool show_big, int top = FIRST_GUI_CALL, int left = FIRST_GUI_CALL);
/** Standard unsorted list of expenses. */
static ExpensesType _expenses_list_1[] = {
EXPENSES_CONSTRUCTION,
EXPENSES_NEW_VEHICLES,
EXPENSES_TRAIN_RUN,
EXPENSES_ROADVEH_RUN,
EXPENSES_AIRCRAFT_RUN,
EXPENSES_SHIP_RUN,
EXPENSES_PROPERTY,
EXPENSES_TRAIN_INC,
EXPENSES_ROADVEH_INC,
EXPENSES_AIRCRAFT_INC,
EXPENSES_SHIP_INC,
EXPENSES_LOAN_INT,
EXPENSES_OTHER,
};
/** Grouped list of expenses. */
static ExpensesType _expenses_list_2[] = {
EXPENSES_TRAIN_INC,
EXPENSES_ROADVEH_INC,
EXPENSES_AIRCRAFT_INC,
EXPENSES_SHIP_INC,
INVALID_EXPENSES,
EXPENSES_TRAIN_RUN,
EXPENSES_ROADVEH_RUN,
EXPENSES_AIRCRAFT_RUN,
EXPENSES_SHIP_RUN,
EXPENSES_PROPERTY,
EXPENSES_LOAN_INT,
INVALID_EXPENSES,
EXPENSES_CONSTRUCTION,
EXPENSES_NEW_VEHICLES,
EXPENSES_OTHER,
INVALID_EXPENSES,
};
/** Expense list container. */
struct ExpensesList {
const ExpensesType *et; ///< Expenses items.
const int length; ///< Number of items in list.
const int height; ///< Height of list, 10 pixels per item, plus an additional 12 pixels per subtotal. */
};
static const ExpensesList _expenses_list_types[] = {
{ _expenses_list_1, lengthof(_expenses_list_1), lengthof(_expenses_list_1) * 10 },
{ _expenses_list_2, lengthof(_expenses_list_2), lengthof(_expenses_list_2) * 10 + 3 * 12 },
};
static void DrawCompanyEconomyStats(const Company *c, bool small)
{
int type = _settings_client.gui.expenses_layout;
int x, y, i, j, year;
const Money (*tbl)[EXPENSES_END];
StringID str;
if (!small) { // normal sized economics window
/* draw categories */
DrawStringCenterUnderline(61, 15, STR_700F_EXPENDITURE_INCOME, TC_FROMSTRING);
y = 27;
for (i = 0; i < _expenses_list_types[type].length; i++) {
ExpensesType et = _expenses_list_types[type].et[i];
if (et == INVALID_EXPENSES) {
y += 2;
DrawStringRightAligned(111, y, STR_7020_TOTAL, TC_FROMSTRING);
y += 20;
} else {
DrawString(2, y, STR_7011_CONSTRUCTION + et, TC_FROMSTRING);
y += 10;
}
}
DrawStringRightAligned(111, y + 2, STR_7020_TOTAL, TC_FROMSTRING);
/* draw the price columns */
year = _cur_year - 2;
j = 3;
x = 215;
tbl = c->yearly_expenses + 2;
do {
if (year >= c->inaugurated_year) {
SetDParam(0, year);
DrawStringRightAlignedUnderline(x, 15, STR_7010, TC_FROMSTRING);
Money sum = 0;
Money subtotal = 0;
int y = 27;
for (int i = 0; i < _expenses_list_types[type].length; i++) {
ExpensesType et = _expenses_list_types[type].et[i];
Money cost;
if (et == INVALID_EXPENSES) {
GfxFillRect(x - 75, y, x, y, 215);
cost = subtotal;
subtotal = 0;
y += 2;
} else {
cost = (*tbl)[et];
subtotal += cost;
sum += cost;
}
if (cost != 0 || et == INVALID_EXPENSES) {
str = STR_701E;
if (cost < 0) { cost = -cost; str++; }
SetDParam(0, cost);
DrawStringRightAligned(x, y, str, TC_FROMSTRING);
}
y += (et == INVALID_EXPENSES) ? 20 : 10;
}
str = STR_701E;
if (sum < 0) { sum = -sum; str++; }
SetDParam(0, sum);
DrawStringRightAligned(x, y + 2, str, TC_FROMSTRING);
GfxFillRect(x - 75, y, x, y, 215);
x += 95;
}
year++;
tbl--;
} while (--j != 0);
y += 14;
/* draw max loan aligned to loan below (y += 10) */
SetDParam(0, _economy.max_loan);
DrawString(202, y + 10, STR_MAX_LOAN, TC_FROMSTRING);
} else {
y = 15;
}
DrawString(2, y, STR_7026_BANK_BALANCE, TC_FROMSTRING);
SetDParam(0, c->money);
DrawStringRightAligned(182, y, STR_7028, TC_FROMSTRING);
y += 10;
DrawString(2, y, STR_7027_LOAN, TC_FROMSTRING);
SetDParam(0, c->current_loan);
DrawStringRightAligned(182, y, STR_7028, TC_FROMSTRING);
y += 12;
GfxFillRect(182 - 75, y - 2, 182, y - 2, 215);
SetDParam(0, c->money - c->current_loan);
DrawStringRightAligned(182, y, STR_7028, TC_FROMSTRING);
}
enum CompanyFinancesWindowWidgets {
CFW_WIDGET_TOGGLE_SIZE = 2,
CFW_WIDGET_EXPS_PANEL = 4,
CFW_WIDGET_TOTAL_PANEL = 5,
CFW_WIDGET_INCREASE_LOAN = 6,
CFW_WIDGET_REPAY_LOAN = 7,
};
static const Widget _company_finances_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 11, 379, 0, 13, STR_700E_FINANCES, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 380, 394, 0, 13, SPR_LARGE_SMALL_WINDOW, STR_7075_TOGGLE_LARGE_SMALL_WINDOW},
{ WWT_STICKYBOX, RESIZE_NONE, COLOUR_GREY, 395, 406, 0, 13, 0x0, STR_STICKY_BUTTON},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 406, 14, 13 + 10, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 406, 14 + 10, 47 + 10, 0x0, STR_NULL},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 0, 202, 48 + 10, 59 + 10, STR_7029_BORROW, STR_7035_INCREASE_SIZE_OF_LOAN},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 203, 406, 48 + 10, 59 + 10, STR_702A_REPAY, STR_7036_REPAY_PART_OF_LOAN},
{ WIDGETS_END},
};
static const Widget _company_finances_small_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 11, 253, 0, 13, STR_700E_FINANCES, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 254, 267, 0, 13, SPR_LARGE_SMALL_WINDOW, STR_7075_TOGGLE_LARGE_SMALL_WINDOW},
{ WWT_STICKYBOX, RESIZE_NONE, COLOUR_GREY, 268, 279, 0, 13, 0x0, STR_STICKY_BUTTON},
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 0, 0, 0, 0x0, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 279, 14, 47, STR_NULL, STR_NULL},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 0, 139, 48, 59, STR_7029_BORROW, STR_7035_INCREASE_SIZE_OF_LOAN},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 140, 279, 48, 59, STR_702A_REPAY, STR_7036_REPAY_PART_OF_LOAN},
{ WIDGETS_END},
};
struct CompanyFinancesWindow : Window {
bool small;
CompanyFinancesWindow(const WindowDesc *desc, CompanyID company, bool show_small,
bool show_stickied, int top, int left) :
Window(desc, company),
small(show_small)
{
this->owner = (Owner)this->window_number;
if (show_stickied) this->flags4 |= WF_STICKY;
/* Check if repositioning from default is required */
if (top != FIRST_GUI_CALL && left != FIRST_GUI_CALL) {
this->top = top;
this->left = left;
}
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
CompanyID company = (CompanyID)this->window_number;
const Company *c = GetCompany(company);
if (!small) {
int type = _settings_client.gui.expenses_layout;
int height = this->widget[CFW_WIDGET_EXPS_PANEL].bottom - this->widget[CFW_WIDGET_EXPS_PANEL].top + 1;
if (_expenses_list_types[type].height + 26 != height) {
this->SetDirty();
ResizeWindowForWidget(this, CFW_WIDGET_EXPS_PANEL, 0, _expenses_list_types[type].height - height + 26);
this->SetDirty();
return;
}
}
/* Recheck the size of the window as it might need to be resized due to the local company changing */
int new_height = this->widget[(company == _local_company) ? CFW_WIDGET_INCREASE_LOAN : CFW_WIDGET_TOTAL_PANEL].bottom + 1;
if (this->height != new_height) {
/* Make window dirty before and after resizing */
this->SetDirty();
this->height = new_height;
this->SetDirty();
this->SetWidgetHiddenState(CFW_WIDGET_INCREASE_LOAN, company != _local_company);
this->SetWidgetHiddenState(CFW_WIDGET_REPAY_LOAN, company != _local_company);
}
/* Borrow button only shows when there is any more money to loan */
this->SetWidgetDisabledState(CFW_WIDGET_INCREASE_LOAN, c->current_loan == _economy.max_loan);
/* Repay button only shows when there is any more money to repay */
this->SetWidgetDisabledState(CFW_WIDGET_REPAY_LOAN, company != _local_company || c->current_loan == 0);
SetDParam(0, c->index);
SetDParam(1, c->index);
SetDParam(2, LOAN_INTERVAL);
this->DrawWidgets();
DrawCompanyEconomyStats(c, this->small);
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case CFW_WIDGET_TOGGLE_SIZE: {// toggle size
bool new_mode = !this->small;
bool stickied = !!(this->flags4 & WF_STICKY);
int oldtop = this->top; ///< current top position of the window before closing it
int oldleft = this->left; ///< current left position of the window before closing it
CompanyID company = (CompanyID)this->window_number;
delete this;
/* Open up the (toggled size) Finance window at the same position as the previous */
DoShowCompanyFinances(company, new_mode, stickied, oldtop, oldleft);
}
break;
case CFW_WIDGET_INCREASE_LOAN: // increase loan
DoCommandP(0, 0, _ctrl_pressed, CMD_INCREASE_LOAN | CMD_MSG(STR_702C_CAN_T_BORROW_ANY_MORE_MONEY));
break;
case CFW_WIDGET_REPAY_LOAN: // repay loan
DoCommandP(0, 0, _ctrl_pressed, CMD_DECREASE_LOAN | CMD_MSG(STR_702F_CAN_T_REPAY_LOAN));
break;
}
}
};
static const WindowDesc _company_finances_desc(
WDP_AUTO, WDP_AUTO, 407, 60 + 10, 407, 60 + 10,
WC_FINANCES, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON,
_company_finances_widgets
);
static const WindowDesc _company_finances_small_desc(
WDP_AUTO, WDP_AUTO, 280, 60, 280, 60,
WC_FINANCES, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON,
_company_finances_small_widgets
);
/**
* Open the small/large finance window of the company
*
* @param company the company who's finances are requested to be seen
* @param show_small show large or small version opf the window
* @param show_stickied previous "stickyness" of the window
* @param top previous top position of the window
* @param left previous left position of the window
*
* @pre is company a valid company
*/
static void DoShowCompanyFinances(CompanyID company, bool show_small, bool show_stickied, int top, int left)
{
if (!IsValidCompanyID(company)) return;
if (BringWindowToFrontById(WC_FINANCES, company)) return;
new CompanyFinancesWindow(show_small ? &_company_finances_small_desc : &_company_finances_desc, company, show_small, show_stickied, top, left);
}
void ShowCompanyFinances(CompanyID company)
{
#ifdef N3DS /* Show the small version of the finances page by default on the 3DS */
DoShowCompanyFinances(company, true, false);
#else
DoShowCompanyFinances(company, false, false);
#endif /* N3DS */
}
/* List of colours for the livery window */
static const StringID _colour_dropdown[] = {
STR_00D1_DARK_BLUE,
STR_00D2_PALE_GREEN,
STR_00D3_PINK,
STR_00D4_YELLOW,
STR_00D5_RED,
STR_00D6_LIGHT_BLUE,
STR_00D7_GREEN,
STR_00D8_DARK_GREEN,
STR_00D9_BLUE,
STR_00DA_CREAM,
STR_00DB_MAUVE,
STR_00DC_PURPLE,
STR_00DD_ORANGE,
STR_00DE_BROWN,
STR_00DF_GREY,
STR_00E0_WHITE,
};
/* Association of liveries to livery classes */
static const LiveryClass _livery_class[LS_END] = {
LC_OTHER,
LC_RAIL, LC_RAIL, LC_RAIL, LC_RAIL, LC_RAIL, LC_RAIL, LC_RAIL, LC_RAIL, LC_RAIL, LC_RAIL, LC_RAIL, LC_RAIL, LC_RAIL,
LC_ROAD, LC_ROAD,
LC_SHIP, LC_SHIP,
LC_AIRCRAFT, LC_AIRCRAFT, LC_AIRCRAFT,
LC_ROAD, LC_ROAD,
};
class DropDownListColourItem : public DropDownListItem {
public:
DropDownListColourItem(int result, bool masked) : DropDownListItem(result, masked) {}
virtual ~DropDownListColourItem() {}
StringID String() const
{
return _colour_dropdown[this->result];
}
uint Height(uint width) const
{
return 14;
}
bool Selectable() const
{
return true;
}
void Draw(int x, int y, uint width, uint height, bool sel, int bg_colour) const
{
DrawSprite(SPR_VEH_BUS_SIDE_VIEW, PALETTE_RECOLOUR_START + this->result, x + 16, y + 7);
DrawStringTruncated(x + 32, y + 3, this->String(), sel ? TC_WHITE : TC_BLACK, width - 30);
}
};
struct SelectCompanyLiveryWindow : public Window {
private:
uint32 sel;
LiveryClass livery_class;
enum SelectCompanyLiveryWindowWidgets {
SCLW_WIDGET_CLOSE,
SCLW_WIDGET_CAPTION,
SCLW_WIDGET_CLASS_GENERAL,
SCLW_WIDGET_CLASS_RAIL,
SCLW_WIDGET_CLASS_ROAD,
SCLW_WIDGET_CLASS_SHIP,
SCLW_WIDGET_CLASS_AIRCRAFT,
SCLW_WIDGET_SPACER_CLASS,
SCLW_WIDGET_SPACER_DROPDOWN,
SCLW_WIDGET_PRI_COL_DROPDOWN,
SCLW_WIDGET_SEC_COL_DROPDOWN,
SCLW_WIDGET_MATRIX,
};
void ShowColourDropDownMenu(uint32 widget)
{
uint32 used_colours = 0;
const Livery *livery;
LiveryScheme scheme;
/* Disallow other company colours for the primary colour */
if (HasBit(this->sel, LS_DEFAULT) && widget == SCLW_WIDGET_PRI_COL_DROPDOWN) {
const Company *c;
FOR_ALL_COMPANIES(c) {
if (c->index != _local_company) SetBit(used_colours, c->colour);
}
}
/* Get the first selected livery to use as the default dropdown item */
for (scheme = LS_BEGIN; scheme < LS_END; scheme++) {
if (HasBit(this->sel, scheme)) break;
}
if (scheme == LS_END) scheme = LS_DEFAULT;
livery = &GetCompany((CompanyID)this->window_number)->livery[scheme];
DropDownList *list = new DropDownList();
for (uint i = 0; i < lengthof(_colour_dropdown); i++) {
list->push_back(new DropDownListColourItem(i, HasBit(used_colours, i)));
}
ShowDropDownList(this, list, widget == SCLW_WIDGET_PRI_COL_DROPDOWN ? livery->colour1 : livery->colour2, widget);
}
public:
SelectCompanyLiveryWindow(const WindowDesc *desc, CompanyID company) : Window(desc, company)
{
this->owner = company;
this->livery_class = LC_OTHER;
this->sel = 1;
this->LowerWidget(SCLW_WIDGET_CLASS_GENERAL);
this->OnInvalidateData(_loaded_newgrf_features.has_2CC);
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
const Company *c = GetCompany((CompanyID)this->window_number);
LiveryScheme scheme = LS_DEFAULT;
int y = 51;
/* Disable dropdown controls if no scheme is selected */
this->SetWidgetDisabledState(SCLW_WIDGET_PRI_COL_DROPDOWN, this->sel == 0);
this->SetWidgetDisabledState(SCLW_WIDGET_SEC_COL_DROPDOWN, this->sel == 0);
if (this->sel != 0) {
for (scheme = LS_BEGIN; scheme < LS_END; scheme++) {
if (HasBit(this->sel, scheme)) break;
}
if (scheme == LS_END) scheme = LS_DEFAULT;
}
SetDParam(0, STR_00D1_DARK_BLUE + c->livery[scheme].colour1);
SetDParam(1, STR_00D1_DARK_BLUE + c->livery[scheme].colour2);
this->DrawWidgets();
for (scheme = LS_DEFAULT; scheme < LS_END; scheme++) {
if (_livery_class[scheme] == this->livery_class) {
bool sel = HasBit(this->sel, scheme) != 0;
if (scheme != LS_DEFAULT) {
DrawSprite(c->livery[scheme].in_use ? SPR_BOX_CHECKED : SPR_BOX_EMPTY, PAL_NONE, 2, y);
}
DrawString(15, y, STR_LIVERY_DEFAULT + scheme, sel ? TC_WHITE : TC_BLACK);
DrawSprite(SPR_SQUARE, GENERAL_SPRITE_COLOUR(c->livery[scheme].colour1), 152, y);
DrawString(165, y, STR_00D1_DARK_BLUE + c->livery[scheme].colour1, sel ? TC_WHITE : TC_GOLD);
if (!this->IsWidgetHidden(SCLW_WIDGET_SEC_COL_DROPDOWN)) {
DrawSprite(SPR_SQUARE, GENERAL_SPRITE_COLOUR(c->livery[scheme].colour2), 277, y);
DrawString(290, y, STR_00D1_DARK_BLUE + c->livery[scheme].colour2, sel ? TC_WHITE : TC_GOLD);
}
y += 14;
}
}
}
virtual void OnClick(Point pt, int widget)
{
/* Number of liveries in each class, used to determine the height of the livery window */
static const byte livery_height[] = {
1,
13,
4,
2,
3,
};
switch (widget) {
/* Livery Class buttons */
case SCLW_WIDGET_CLASS_GENERAL:
case SCLW_WIDGET_CLASS_RAIL:
case SCLW_WIDGET_CLASS_ROAD:
case SCLW_WIDGET_CLASS_SHIP:
case SCLW_WIDGET_CLASS_AIRCRAFT: {
LiveryScheme scheme;
this->RaiseWidget(this->livery_class + SCLW_WIDGET_CLASS_GENERAL);
this->livery_class = (LiveryClass)(widget - SCLW_WIDGET_CLASS_GENERAL);
this->sel = 0;
this->LowerWidget(this->livery_class + SCLW_WIDGET_CLASS_GENERAL);
/* Select the first item in the list */
for (scheme = LS_DEFAULT; scheme < LS_END; scheme++) {
if (_livery_class[scheme] == this->livery_class) {
this->sel = 1 << scheme;
break;
}
}
this->height = 49 + livery_height[this->livery_class] * 14;
this->widget[SCLW_WIDGET_MATRIX].bottom = this->height - 1;
this->widget[SCLW_WIDGET_MATRIX].data = livery_height[this->livery_class] << 8 | 1;
MarkWholeScreenDirty();
break;
}
case SCLW_WIDGET_PRI_COL_DROPDOWN: // First colour dropdown
ShowColourDropDownMenu(SCLW_WIDGET_PRI_COL_DROPDOWN);
break;
case SCLW_WIDGET_SEC_COL_DROPDOWN: // Second colour dropdown
ShowColourDropDownMenu(SCLW_WIDGET_SEC_COL_DROPDOWN);
break;
case SCLW_WIDGET_MATRIX: {
LiveryScheme scheme;
LiveryScheme j = (LiveryScheme)((pt.y - 48) / 14);
for (scheme = LS_BEGIN; scheme <= j; scheme++) {
if (_livery_class[scheme] != this->livery_class) j++;
if (scheme >= LS_END) return;
}
if (j >= LS_END) return;
/* If clicking on the left edge, toggle using the livery */
if (pt.x < 10) {
DoCommandP(0, j | (2 << 8), !GetCompany((CompanyID)this->window_number)->livery[j].in_use, CMD_SET_COMPANY_COLOUR);
}
if (_ctrl_pressed) {
ToggleBit(this->sel, j);
} else {
this->sel = 1 << j;
}
this->SetDirty();
break;
}
}
}
virtual void OnDropdownSelect(int widget, int index)
{
for (LiveryScheme scheme = LS_DEFAULT; scheme < LS_END; scheme++) {
if (HasBit(this->sel, scheme)) {
DoCommandP(0, scheme | (widget == SCLW_WIDGET_PRI_COL_DROPDOWN ? 0 : 256), index, CMD_SET_COMPANY_COLOUR);
}
}
}
virtual void OnInvalidateData(int data = 0)
{
static bool has2cc = true;
if (has2cc == !!data) return;
has2cc = !!data;
int r = this->widget[has2cc ? SCLW_WIDGET_SEC_COL_DROPDOWN : SCLW_WIDGET_PRI_COL_DROPDOWN].right;
this->SetWidgetHiddenState(SCLW_WIDGET_SEC_COL_DROPDOWN, !has2cc);
this->widget[SCLW_WIDGET_CAPTION].right = r;
this->widget[SCLW_WIDGET_SPACER_CLASS].right = r;
this->widget[SCLW_WIDGET_MATRIX].right = r;
this->width = r + 1;
}
};
static const Widget _select_company_livery_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW },
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 11, 399, 0, 13, STR_7007_NEW_COLOUR_SCHEME, STR_018C_WINDOW_TITLE_DRAG_THIS },
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 0, 21, 14, 35, SPR_IMG_COMPANY_GENERAL, STR_LIVERY_GENERAL_TIP },
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 22, 43, 14, 35, SPR_IMG_TRAINLIST, STR_LIVERY_TRAIN_TIP },
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 44, 65, 14, 35, SPR_IMG_TRUCKLIST, STR_LIVERY_ROADVEH_TIP },
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 66, 87, 14, 35, SPR_IMG_SHIPLIST, STR_LIVERY_SHIP_TIP },
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 88, 109, 14, 35, SPR_IMG_AIRPLANESLIST, STR_LIVERY_AIRCRAFT_TIP },
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 110, 399, 14, 35, 0x0, STR_NULL },
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 149, 36, 47, 0x0, STR_NULL },
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_GREY, 150, 274, 36, 47, STR_02BD, STR_LIVERY_PRIMARY_TIP },
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_GREY, 275, 399, 36, 47, STR_02E1, STR_LIVERY_SECONDARY_TIP },
{ WWT_MATRIX, RESIZE_NONE, COLOUR_GREY, 0, 399, 48, 48 + 1 * 14, (1 << 8) | 1, STR_LIVERY_PANEL_TIP },
{ WIDGETS_END },
};
static const WindowDesc _select_company_livery_desc(
WDP_AUTO, WDP_AUTO, 400, 49 + 1 * 14, 400, 49 + 1 * 14,
WC_COMPANY_COLOUR, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET,
_select_company_livery_widgets
);
/**
* Draws the face of a company manager's face.
* @param cmf the company manager's face
* @param colour the (background) colour of the gradient
* @param x x-position to draw the face
* @param y y-position to draw the face
*/
void DrawCompanyManagerFace(CompanyManagerFace cmf, int colour, int x, int y)
{
GenderEthnicity ge = (GenderEthnicity)GetCompanyManagerFaceBits(cmf, CMFV_GEN_ETHN, GE_WM);
bool has_moustache = !HasBit(ge, GENDER_FEMALE) && GetCompanyManagerFaceBits(cmf, CMFV_HAS_MOUSTACHE, ge) != 0;
bool has_tie_earring = !HasBit(ge, GENDER_FEMALE) || GetCompanyManagerFaceBits(cmf, CMFV_HAS_TIE_EARRING, ge) != 0;
bool has_glasses = GetCompanyManagerFaceBits(cmf, CMFV_HAS_GLASSES, ge) != 0;
SpriteID pal;
/* Modify eye colour palette only if 2 or more valid values exist */
if (_cmf_info[CMFV_EYE_COLOUR].valid_values[ge] < 2) {
pal = PAL_NONE;
} else {
switch (GetCompanyManagerFaceBits(cmf, CMFV_EYE_COLOUR, ge)) {
default: NOT_REACHED();
case 0: pal = PALETTE_TO_BROWN; break;
case 1: pal = PALETTE_TO_BLUE; break;
case 2: pal = PALETTE_TO_GREEN; break;
}
}
/* Draw the gradient (background) */
DrawSprite(SPR_GRADIENT, GENERAL_SPRITE_COLOUR(colour), x, y);
for (CompanyManagerFaceVariable cmfv = CMFV_CHEEKS; cmfv < CMFV_END; cmfv++) {
switch (cmfv) {
case CMFV_MOUSTACHE: if (!has_moustache) continue; break;
case CMFV_LIPS: // FALL THROUGH
case CMFV_NOSE: if (has_moustache) continue; break;
case CMFV_TIE_EARRING: if (!has_tie_earring) continue; break;
case CMFV_GLASSES: if (!has_glasses) continue; break;
default: break;
}
DrawSprite(GetCompanyManagerFaceSprite(cmf, cmfv, ge), (cmfv == CMFV_EYEBROWS) ? pal : PAL_NONE, x, y);
}
}
/** Widget description for the normal/simple company manager face selection dialog */
static const Widget _select_company_manager_face_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // SCMFW_WIDGET_CLOSEBOX
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 11, 174, 0, 13, STR_7043_FACE_SELECTION, STR_018C_WINDOW_TITLE_DRAG_THIS}, // SCMFW_WIDGET_CAPTION
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 175, 189, 0, 13, SPR_LARGE_SMALL_WINDOW, STR_FACE_ADVANCED_TIP}, // SCMFW_WIDGET_TOGGLE_LARGE_SMALL
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 189, 14, 150, 0x0, STR_NULL}, // SCMFW_WIDGET_SELECT_FACE
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 0, 94, 151, 162, STR_012E_CANCEL, STR_7047_CANCEL_NEW_FACE_SELECTION}, // SCMFW_WIDGET_CANCEL
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 95, 189, 151, 162, STR_012F_OK, STR_7048_ACCEPT_NEW_FACE_SELECTION}, // SCMFW_WIDGET_ACCEPT
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 95, 187, 75, 86, STR_7044_MALE, STR_7049_SELECT_MALE_FACES}, // SCMFW_WIDGET_MALE
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 95, 187, 87, 98, STR_7045_FEMALE, STR_704A_SELECT_FEMALE_FACES}, // SCMFW_WIDGET_FEMALE
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 93, 137, 148, STR_7046_NEW_FACE, STR_704B_GENERATE_RANDOM_NEW_FACE}, // SCMFW_WIDGET_RANDOM_NEW_FACE
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 95, 187, 16, 27, STR_FACE_ADVANCED, STR_FACE_ADVANCED_TIP}, // SCMFW_WIDGET_TOGGLE_LARGE_SMALL_BUTTON
{ WIDGETS_END},
};
/** Widget description for the advanced company manager face selection dialog */
static const Widget _select_company_manager_face_adv_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // SCMFW_WIDGET_CLOSEBOX
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 11, 204, 0, 13, STR_7043_FACE_SELECTION, STR_018C_WINDOW_TITLE_DRAG_THIS}, // SCMFW_WIDGET_CAPTION
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_GREY, 205, 219, 0, 13, SPR_LARGE_SMALL_WINDOW, STR_FACE_SIMPLE_TIP}, // SCMFW_WIDGET_TOGGLE_LARGE_SMALL
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 219, 14, 207, 0x0, STR_NULL}, // SCMFW_WIDGET_SELECT_FACE
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 0, 94, 208, 219, STR_012E_CANCEL, STR_7047_CANCEL_NEW_FACE_SELECTION}, // SCMFW_WIDGET_CANCEL
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 95, 219, 208, 219, STR_012F_OK, STR_7048_ACCEPT_NEW_FACE_SELECTION}, // SCMFW_WIDGET_ACCEPT
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 96, 156, 32, 43, STR_7044_MALE, STR_7049_SELECT_MALE_FACES}, // SCMFW_WIDGET_MALE
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 157, 217, 32, 43, STR_7045_FEMALE, STR_704A_SELECT_FEMALE_FACES}, // SCMFW_WIDGET_FEMALE
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 93, 137, 148, STR_RANDOM, STR_704B_GENERATE_RANDOM_NEW_FACE}, // SCMFW_WIDGET_RANDOM_NEW_FACE
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 95, 217, 16, 27, STR_FACE_SIMPLE, STR_FACE_SIMPLE_TIP}, // SCMFW_WIDGET_TOGGLE_LARGE_SMALL_BUTTON
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 93, 158, 169, STR_FACE_LOAD, STR_FACE_LOAD_TIP}, // SCMFW_WIDGET_LOAD
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 93, 170, 181, STR_FACE_FACECODE, STR_FACE_FACECODE_TIP}, // SCMFW_WIDGET_FACECODE
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 2, 93, 182, 193, STR_FACE_SAVE, STR_FACE_SAVE_TIP}, // SCMFW_WIDGET_SAVE
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 96, 156, 46, 57, STR_FACE_EUROPEAN, STR_FACE_SELECT_EUROPEAN}, // SCMFW_WIDGET_ETHNICITY_EUR
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 157, 217, 46, 57, STR_FACE_AFRICAN, STR_FACE_SELECT_AFRICAN}, // SCMFW_WIDGET_ETHNICITY_AFR
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 175, 217, 60, 71, STR_EMPTY, STR_FACE_MOUSTACHE_EARRING_TIP}, // SCMFW_WIDGET_HAS_MOUSTACHE_EARRING
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 175, 217, 72, 83, STR_EMPTY, STR_FACE_GLASSES_TIP}, // SCMFW_WIDGET_HAS_GLASSES
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 175, 183, 110, 121, SPR_ARROW_LEFT, STR_FACE_EYECOLOUR_TIP}, // SCMFW_WIDGET_EYECOLOUR_L
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 184, 208, 110, 121, STR_EMPTY, STR_FACE_EYECOLOUR_TIP}, // SCMFW_WIDGET_EYECOLOUR
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 209, 217, 110, 121, SPR_ARROW_RIGHT, STR_FACE_EYECOLOUR_TIP}, // SCMFW_WIDGET_EYECOLOUR_R
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 175, 183, 158, 169, SPR_ARROW_LEFT, STR_FACE_CHIN_TIP}, // SCMFW_WIDGET_CHIN_L
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 184, 208, 158, 169, STR_EMPTY, STR_FACE_CHIN_TIP}, // SCMFW_WIDGET_CHIN
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 209, 217, 158, 169, SPR_ARROW_RIGHT, STR_FACE_CHIN_TIP}, // SCMFW_WIDGET_CHIN_R
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 175, 183, 98, 109, SPR_ARROW_LEFT, STR_FACE_EYEBROWS_TIP}, // SCMFW_WIDGET_EYEBROWS_L
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 184, 208, 98, 109, STR_EMPTY, STR_FACE_EYEBROWS_TIP}, // SCMFW_WIDGET_EYEBROWS
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 209, 217, 98, 109, SPR_ARROW_RIGHT, STR_FACE_EYEBROWS_TIP}, // SCMFW_WIDGET_EYEBROWS_R
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 175, 183, 146, 157, SPR_ARROW_LEFT, STR_FACE_LIPS_MOUSTACHE_TIP}, // SCMFW_WIDGET_LIPS_MOUSTACHE_L
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 184, 208, 146, 157, STR_EMPTY, STR_FACE_LIPS_MOUSTACHE_TIP}, // SCMFW_WIDGET_LIPS_MOUSTACHE
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 209, 217, 146, 157, SPR_ARROW_RIGHT, STR_FACE_LIPS_MOUSTACHE_TIP}, // SCMFW_WIDGET_LIPS_MOUSTACHE_R
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 175, 183, 134, 145, SPR_ARROW_LEFT, STR_FACE_NOSE_TIP}, // SCMFW_WIDGET_NOSE_L
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 184, 208, 134, 145, STR_EMPTY, STR_FACE_NOSE_TIP}, // SCMFW_WIDGET_NOSE
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 209, 217, 134, 145, SPR_ARROW_RIGHT, STR_FACE_NOSE_TIP}, // SCMFW_WIDGET_NOSE_R
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 175, 183, 86, 97, SPR_ARROW_LEFT, STR_FACE_HAIR_TIP}, // SCMFW_WIDGET_HAIR_L
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 184, 208, 86, 97, STR_EMPTY, STR_FACE_HAIR_TIP}, // SCMFW_WIDGET_HAIR
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 209, 217, 86, 97, SPR_ARROW_RIGHT, STR_FACE_HAIR_TIP}, // SCMFW_WIDGET_HAIR_R
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 175, 183, 170, 181, SPR_ARROW_LEFT, STR_FACE_JACKET_TIP}, // SCMFW_WIDGET_JACKET_L
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 184, 208, 170, 181, STR_EMPTY, STR_FACE_JACKET_TIP}, // SCMFW_WIDGET_JACKET
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 209, 217, 170, 181, SPR_ARROW_RIGHT, STR_FACE_JACKET_TIP}, // SCMFW_WIDGET_JACKET_R
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 175, 183, 182, 193, SPR_ARROW_LEFT, STR_FACE_COLLAR_TIP}, // SCMFW_WIDGET_COLLAR_L
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 184, 208, 182, 193, STR_EMPTY, STR_FACE_COLLAR_TIP}, // SCMFW_WIDGET_COLLAR
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 209, 217, 182, 193, SPR_ARROW_RIGHT, STR_FACE_COLLAR_TIP}, // SCMFW_WIDGET_COLLAR_R
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 175, 183, 194, 205, SPR_ARROW_LEFT, STR_FACE_TIE_EARRING_TIP}, // SCMFW_WIDGET_TIE_EARRING_L
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 184, 208, 194, 205, STR_EMPTY, STR_FACE_TIE_EARRING_TIP}, // SCMFW_WIDGET_TIE_EARRING
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 209, 217, 194, 205, SPR_ARROW_RIGHT, STR_FACE_TIE_EARRING_TIP}, // SCMFW_WIDGET_TIE_EARRING_R
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 175, 183, 122, 133, SPR_ARROW_LEFT, STR_FACE_GLASSES_TIP_2}, // SCMFW_WIDGET_GLASSES_L
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 184, 208, 122, 133, STR_EMPTY, STR_FACE_GLASSES_TIP_2}, // SCMFW_WIDGET_GLASSES
{ WWT_PUSHIMGBTN, RESIZE_NONE, COLOUR_GREY, 209, 217, 122, 133, SPR_ARROW_RIGHT, STR_FACE_GLASSES_TIP_2}, // SCMFW_WIDGET_GLASSES_R
{ WIDGETS_END},
};
class SelectCompanyManagerFaceWindow : public Window
{
CompanyManagerFace face; ///< company manager face bits
bool advanced; ///< advanced company manager face selection window
GenderEthnicity ge;
bool is_female;
bool is_moust_male;
/**
* Names of the widgets. Keep them in the same order as in the widget array.
* Do not change the order of the widgets from SCMFW_WIDGET_HAS_MOUSTACHE_EARRING to SCMFW_WIDGET_GLASSES_R,
* this order is needed for the WE_CLICK event of DrawFaceStringLabel().
*/
enum SelectCompanyManagerFaceWidgets {
SCMFW_WIDGET_CLOSEBOX = 0,
SCMFW_WIDGET_CAPTION,
SCMFW_WIDGET_TOGGLE_LARGE_SMALL,
SCMFW_WIDGET_SELECT_FACE,
SCMFW_WIDGET_CANCEL,
SCMFW_WIDGET_ACCEPT,
SCMFW_WIDGET_MALE,
SCMFW_WIDGET_FEMALE,
SCMFW_WIDGET_RANDOM_NEW_FACE,
SCMFW_WIDGET_TOGGLE_LARGE_SMALL_BUTTON,
/* from here is the advanced company manager face selection window */
SCMFW_WIDGET_LOAD,
SCMFW_WIDGET_FACECODE,
SCMFW_WIDGET_SAVE,
SCMFW_WIDGET_ETHNICITY_EUR,
SCMFW_WIDGET_ETHNICITY_AFR,
SCMFW_WIDGET_HAS_MOUSTACHE_EARRING,
SCMFW_WIDGET_HAS_GLASSES,
SCMFW_WIDGET_EYECOLOUR_L,
SCMFW_WIDGET_EYECOLOUR,
SCMFW_WIDGET_EYECOLOUR_R,
SCMFW_WIDGET_CHIN_L,
SCMFW_WIDGET_CHIN,
SCMFW_WIDGET_CHIN_R,
SCMFW_WIDGET_EYEBROWS_L,
SCMFW_WIDGET_EYEBROWS,
SCMFW_WIDGET_EYEBROWS_R,
SCMFW_WIDGET_LIPS_MOUSTACHE_L,
SCMFW_WIDGET_LIPS_MOUSTACHE,
SCMFW_WIDGET_LIPS_MOUSTACHE_R,
SCMFW_WIDGET_NOSE_L,
SCMFW_WIDGET_NOSE,
SCMFW_WIDGET_NOSE_R,
SCMFW_WIDGET_HAIR_L,
SCMFW_WIDGET_HAIR,
SCMFW_WIDGET_HAIR_R,
SCMFW_WIDGET_JACKET_L,
SCMFW_WIDGET_JACKET,
SCMFW_WIDGET_JACKET_R,
SCMFW_WIDGET_COLLAR_L,
SCMFW_WIDGET_COLLAR,
SCMFW_WIDGET_COLLAR_R,
SCMFW_WIDGET_TIE_EARRING_L,
SCMFW_WIDGET_TIE_EARRING,
SCMFW_WIDGET_TIE_EARRING_R,
SCMFW_WIDGET_GLASSES_L,
SCMFW_WIDGET_GLASSES,
SCMFW_WIDGET_GLASSES_R,
};
/**
* Draw dynamic a label to the left of the button and a value in the button
*
* @param widget_index index of this widget in the window
* @param str the label which will be draw
* @param val the value which will be draw
* @param is_bool_widget is it a bool button
*/
void DrawFaceStringLabel(byte widget_index, StringID str, uint8 val, bool is_bool_widget)
{
/* Write the label in gold (0x2) to the left of the button. */
DrawStringRightAligned(this->widget[widget_index].left - (is_bool_widget ? 5 : 14), this->widget[widget_index].top + 1, str, TC_GOLD);
if (!this->IsWidgetDisabled(widget_index)) {
if (is_bool_widget) {
/* if it a bool button write yes or no */
str = (val != 0) ? STR_FACE_YES : STR_FACE_NO;
} else {
/* else write the value + 1 */
SetDParam(0, val + 1);
str = STR_JUST_INT;
}
/* Draw the value/bool in white (0xC). If the button clicked adds 1px to x and y text coordinates (IsWindowWidgetLowered()). */
DrawStringCentered(this->widget[widget_index].left + (this->widget[widget_index].right - this->widget[widget_index].left) / 2 +
this->IsWidgetLowered(widget_index), this->widget[widget_index].top + 1 + this->IsWidgetLowered(widget_index), str, TC_WHITE);
}
}
void UpdateData()
{
this->ge = (GenderEthnicity)GB(this->face, _cmf_info[CMFV_GEN_ETHN].offset, _cmf_info[CMFV_GEN_ETHN].length); // get the gender and ethnicity
this->is_female = HasBit(this->ge, GENDER_FEMALE); // get the gender: 0 == male and 1 == female
this->is_moust_male = !is_female && GetCompanyManagerFaceBits(this->face, CMFV_HAS_MOUSTACHE, this->ge) != 0; // is a male face with moustache
}
public:
SelectCompanyManagerFaceWindow(const WindowDesc *desc, Window *parent, bool advanced, int top, int left) : Window(desc, parent->window_number)
{
this->parent = parent;
this->owner = (Owner)this->window_number;
this->face = GetCompany((CompanyID)this->window_number)->face;
this->advanced = advanced;
this->UpdateData();
/* Check if repositioning from default is required */
if (top != FIRST_GUI_CALL && left != FIRST_GUI_CALL) {
this->top = top;
this->left = left;
}
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
/* lower the non-selected gender button */
this->SetWidgetLoweredState(SCMFW_WIDGET_MALE, !this->is_female);
this->SetWidgetLoweredState(SCMFW_WIDGET_FEMALE, this->is_female);
/* advanced company manager face selection window */
if (this->advanced) {
/* lower the non-selected ethnicity button */
this->SetWidgetLoweredState(SCMFW_WIDGET_ETHNICITY_EUR, !HasBit(this->ge, ETHNICITY_BLACK));
this->SetWidgetLoweredState(SCMFW_WIDGET_ETHNICITY_AFR, HasBit(this->ge, ETHNICITY_BLACK));
/* Disable dynamically the widgets which CompanyManagerFaceVariable has less than 2 options
* (or in other words you haven't any choice).
* If the widgets depend on a HAS-variable and this is false the widgets will be disabled, too. */
/* Eye colour buttons */
this->SetWidgetsDisabledState(_cmf_info[CMFV_EYE_COLOUR].valid_values[this->ge] < 2,
SCMFW_WIDGET_EYECOLOUR, SCMFW_WIDGET_EYECOLOUR_L, SCMFW_WIDGET_EYECOLOUR_R, WIDGET_LIST_END);
/* Chin buttons */
this->SetWidgetsDisabledState(_cmf_info[CMFV_CHIN].valid_values[this->ge] < 2,
SCMFW_WIDGET_CHIN, SCMFW_WIDGET_CHIN_L, SCMFW_WIDGET_CHIN_R, WIDGET_LIST_END);
/* Eyebrows buttons */
this->SetWidgetsDisabledState(_cmf_info[CMFV_EYEBROWS].valid_values[this->ge] < 2,
SCMFW_WIDGET_EYEBROWS, SCMFW_WIDGET_EYEBROWS_L, SCMFW_WIDGET_EYEBROWS_R, WIDGET_LIST_END);
/* Lips or (if it a male face with a moustache) moustache buttons */
this->SetWidgetsDisabledState(_cmf_info[this->is_moust_male ? CMFV_MOUSTACHE : CMFV_LIPS].valid_values[this->ge] < 2,
SCMFW_WIDGET_LIPS_MOUSTACHE, SCMFW_WIDGET_LIPS_MOUSTACHE_L, SCMFW_WIDGET_LIPS_MOUSTACHE_R, WIDGET_LIST_END);
/* Nose buttons | male faces with moustache haven't any nose options */
this->SetWidgetsDisabledState(_cmf_info[CMFV_NOSE].valid_values[this->ge] < 2 || this->is_moust_male,
SCMFW_WIDGET_NOSE, SCMFW_WIDGET_NOSE_L, SCMFW_WIDGET_NOSE_R, WIDGET_LIST_END);
/* Hair buttons */
this->SetWidgetsDisabledState(_cmf_info[CMFV_HAIR].valid_values[this->ge] < 2,
SCMFW_WIDGET_HAIR, SCMFW_WIDGET_HAIR_L, SCMFW_WIDGET_HAIR_R, WIDGET_LIST_END);
/* Jacket buttons */
this->SetWidgetsDisabledState(_cmf_info[CMFV_JACKET].valid_values[this->ge] < 2,
SCMFW_WIDGET_JACKET, SCMFW_WIDGET_JACKET_L, SCMFW_WIDGET_JACKET_R, WIDGET_LIST_END);
/* Collar buttons */
this->SetWidgetsDisabledState(_cmf_info[CMFV_COLLAR].valid_values[this->ge] < 2,
SCMFW_WIDGET_COLLAR, SCMFW_WIDGET_COLLAR_L, SCMFW_WIDGET_COLLAR_R, WIDGET_LIST_END);
/* Tie/earring buttons | female faces without earring haven't any earring options */
this->SetWidgetsDisabledState(_cmf_info[CMFV_TIE_EARRING].valid_values[this->ge] < 2 ||
(this->is_female && GetCompanyManagerFaceBits(this->face, CMFV_HAS_TIE_EARRING, this->ge) == 0),
SCMFW_WIDGET_TIE_EARRING, SCMFW_WIDGET_TIE_EARRING_L, SCMFW_WIDGET_TIE_EARRING_R, WIDGET_LIST_END);
/* Glasses buttons | faces without glasses haven't any glasses options */
this->SetWidgetsDisabledState(_cmf_info[CMFV_GLASSES].valid_values[this->ge] < 2 || GetCompanyManagerFaceBits(this->face, CMFV_HAS_GLASSES, this->ge) == 0,
SCMFW_WIDGET_GLASSES, SCMFW_WIDGET_GLASSES_L, SCMFW_WIDGET_GLASSES_R, WIDGET_LIST_END);
}
this->DrawWidgets();
/* Draw dynamic button value and labels for the advanced company manager face selection window */
if (this->advanced) {
if (this->is_female) {
/* Only for female faces */
this->DrawFaceStringLabel(SCMFW_WIDGET_HAS_MOUSTACHE_EARRING, STR_FACE_EARRING, GetCompanyManagerFaceBits(this->face, CMFV_HAS_TIE_EARRING, this->ge), true );
this->DrawFaceStringLabel(SCMFW_WIDGET_TIE_EARRING, STR_FACE_EARRING, GetCompanyManagerFaceBits(this->face, CMFV_TIE_EARRING, this->ge), false);
} else {
/* Only for male faces */
this->DrawFaceStringLabel(SCMFW_WIDGET_HAS_MOUSTACHE_EARRING, STR_FACE_MOUSTACHE, GetCompanyManagerFaceBits(this->face, CMFV_HAS_MOUSTACHE, this->ge), true );
this->DrawFaceStringLabel(SCMFW_WIDGET_TIE_EARRING, STR_FACE_TIE, GetCompanyManagerFaceBits(this->face, CMFV_TIE_EARRING, this->ge), false);
}
if (this->is_moust_male) {
/* Only for male faces with moustache */
this->DrawFaceStringLabel(SCMFW_WIDGET_LIPS_MOUSTACHE, STR_FACE_MOUSTACHE, GetCompanyManagerFaceBits(this->face, CMFV_MOUSTACHE, this->ge), false);
} else {
/* Only for female faces or male faces without moustache */
this->DrawFaceStringLabel(SCMFW_WIDGET_LIPS_MOUSTACHE, STR_FACE_LIPS, GetCompanyManagerFaceBits(this->face, CMFV_LIPS, this->ge), false);
}
/* For all faces */
this->DrawFaceStringLabel(SCMFW_WIDGET_HAS_GLASSES, STR_FACE_GLASSES, GetCompanyManagerFaceBits(this->face, CMFV_HAS_GLASSES, this->ge), true );
this->DrawFaceStringLabel(SCMFW_WIDGET_HAIR, STR_FACE_HAIR, GetCompanyManagerFaceBits(this->face, CMFV_HAIR, this->ge), false);
this->DrawFaceStringLabel(SCMFW_WIDGET_EYEBROWS, STR_FACE_EYEBROWS, GetCompanyManagerFaceBits(this->face, CMFV_EYEBROWS, this->ge), false);
this->DrawFaceStringLabel(SCMFW_WIDGET_EYECOLOUR, STR_FACE_EYECOLOUR, GetCompanyManagerFaceBits(this->face, CMFV_EYE_COLOUR, this->ge), false);
this->DrawFaceStringLabel(SCMFW_WIDGET_GLASSES, STR_FACE_GLASSES, GetCompanyManagerFaceBits(this->face, CMFV_GLASSES, this->ge), false);
this->DrawFaceStringLabel(SCMFW_WIDGET_NOSE, STR_FACE_NOSE, GetCompanyManagerFaceBits(this->face, CMFV_NOSE, this->ge), false);
this->DrawFaceStringLabel(SCMFW_WIDGET_CHIN, STR_FACE_CHIN, GetCompanyManagerFaceBits(this->face, CMFV_CHIN, this->ge), false);
this->DrawFaceStringLabel(SCMFW_WIDGET_JACKET, STR_FACE_JACKET, GetCompanyManagerFaceBits(this->face, CMFV_JACKET, this->ge), false);
this->DrawFaceStringLabel(SCMFW_WIDGET_COLLAR, STR_FACE_COLLAR, GetCompanyManagerFaceBits(this->face, CMFV_COLLAR, this->ge), false);
}
/* Draw the company manager face picture */
DrawCompanyManagerFace(this->face, GetCompany((CompanyID)this->window_number)->colour, 2, 16);
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
/* Toggle size, advanced/simple face selection */
case SCMFW_WIDGET_TOGGLE_LARGE_SMALL:
case SCMFW_WIDGET_TOGGLE_LARGE_SMALL_BUTTON: {
DoCommandP(0, 0, this->face, CMD_SET_COMPANY_MANAGER_FACE);
/* Backup some data before deletion */
int oldtop = this->top; ///< current top position of the window before closing it
int oldleft = this->left; ///< current top position of the window before closing it
bool adv = !this->advanced;
Window *parent = this->parent;
delete this;
/* Open up the (toggled size) Face selection window at the same position as the previous */
DoSelectCompanyManagerFace(parent, adv, oldtop, oldleft);
} break;
/* OK button */
case SCMFW_WIDGET_ACCEPT:
DoCommandP(0, 0, this->face, CMD_SET_COMPANY_MANAGER_FACE);
/* Fall-Through */
/* Cancel button */
case SCMFW_WIDGET_CANCEL:
delete this;
break;
/* Load button */
case SCMFW_WIDGET_LOAD:
this->face = _company_manager_face;
ScaleAllCompanyManagerFaceBits(this->face);
ShowErrorMessage(INVALID_STRING_ID, STR_FACE_LOAD_DONE, 0, 0);
this->UpdateData();
this->SetDirty();
break;
/* 'Company manager face number' button, view and/or set company manager face number */
case SCMFW_WIDGET_FACECODE:
SetDParam(0, this->face);
ShowQueryString(STR_JUST_INT, STR_FACE_FACECODE_CAPTION, 10 + 1, 0, this, CS_NUMERAL, QSF_NONE);
break;
/* Save button */
case SCMFW_WIDGET_SAVE:
_company_manager_face = this->face;
ShowErrorMessage(INVALID_STRING_ID, STR_FACE_SAVE_DONE, 0, 0);
break;
/* Toggle gender (male/female) button */
case SCMFW_WIDGET_MALE:
case SCMFW_WIDGET_FEMALE:
SetCompanyManagerFaceBits(this->face, CMFV_GENDER, this->ge, widget - SCMFW_WIDGET_MALE);
ScaleAllCompanyManagerFaceBits(this->face);
this->UpdateData();
this->SetDirty();
break;
/* Randomize face button */
case SCMFW_WIDGET_RANDOM_NEW_FACE:
RandomCompanyManagerFaceBits(this->face, this->ge, this->advanced);
this->UpdateData();
this->SetDirty();
break;
/* Toggle ethnicity (european/african) button */
case SCMFW_WIDGET_ETHNICITY_EUR:
case SCMFW_WIDGET_ETHNICITY_AFR:
SetCompanyManagerFaceBits(this->face, CMFV_ETHNICITY, this->ge, widget - SCMFW_WIDGET_ETHNICITY_EUR);
ScaleAllCompanyManagerFaceBits(this->face);
this->UpdateData();
this->SetDirty();
break;
default:
/* For all buttons from SCMFW_WIDGET_HAS_MOUSTACHE_EARRING to SCMFW_WIDGET_GLASSES_R is the same function.
* Therefor is this combined function.
* First it checks which CompanyManagerFaceVariable will be change and then
* a: invert the value for boolean variables
* or b: it checks inside of IncreaseCompanyManagerFaceBits() if a left (_L) butten is pressed and then decrease else increase the variable */
if (this->advanced && widget >= SCMFW_WIDGET_HAS_MOUSTACHE_EARRING && widget <= SCMFW_WIDGET_GLASSES_R) {
CompanyManagerFaceVariable cmfv; // which CompanyManagerFaceVariable shall be edited
if (widget < SCMFW_WIDGET_EYECOLOUR_L) { // Bool buttons
switch (widget - SCMFW_WIDGET_HAS_MOUSTACHE_EARRING) {
default: NOT_REACHED();
case 0: cmfv = this->is_female ? CMFV_HAS_TIE_EARRING : CMFV_HAS_MOUSTACHE; break; // Has earring/moustache button
case 1: cmfv = CMFV_HAS_GLASSES; break; // Has glasses button
}
SetCompanyManagerFaceBits(this->face, cmfv, this->ge, !GetCompanyManagerFaceBits(this->face, cmfv, this->ge));
ScaleAllCompanyManagerFaceBits(this->face);
} else { // Value buttons
switch ((widget - SCMFW_WIDGET_EYECOLOUR_L) / 3) {
default: NOT_REACHED();
case 0: cmfv = CMFV_EYE_COLOUR; break; // Eye colour buttons
case 1: cmfv = CMFV_CHIN; break; // Chin buttons
case 2: cmfv = CMFV_EYEBROWS; break; // Eyebrows buttons
case 3: cmfv = this->is_moust_male ? CMFV_MOUSTACHE : CMFV_LIPS; break; // Moustache or lips buttons
case 4: cmfv = CMFV_NOSE; break; // Nose buttons
case 5: cmfv = CMFV_HAIR; break; // Hair buttons
case 6: cmfv = CMFV_JACKET; break; // Jacket buttons
case 7: cmfv = CMFV_COLLAR; break; // Collar buttons
case 8: cmfv = CMFV_TIE_EARRING; break; // Tie/earring buttons
case 9: cmfv = CMFV_GLASSES; break; // Glasses buttons
}
/* 0 == left (_L), 1 == middle or 2 == right (_R) - button click */
IncreaseCompanyManagerFaceBits(this->face, cmfv, this->ge, (((widget - SCMFW_WIDGET_EYECOLOUR_L) % 3) != 0) ? 1 : -1);
}
this->UpdateData();
this->SetDirty();
}
break;
}
}
virtual void OnQueryTextFinished(char *str)
{
if (str == NULL) return;
/* Set a new company manager face number */
if (!StrEmpty(str)) {
this->face = strtoul(str, NULL, 10);
ScaleAllCompanyManagerFaceBits(this->face);
ShowErrorMessage(INVALID_STRING_ID, STR_FACE_FACECODE_SET, 0, 0);
this->UpdateData();
this->SetDirty();
} else {
ShowErrorMessage(INVALID_STRING_ID, STR_FACE_FACECODE_ERR, 0, 0);
}
}
};
/** normal/simple company manager face selection window description */
static const WindowDesc _select_company_manager_face_desc(
WDP_AUTO, WDP_AUTO, 190, 163, 190, 163,
WC_COMPANY_MANAGER_FACE, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_CONSTRUCTION,
_select_company_manager_face_widgets
);
/** advanced company manager face selection window description */
static const WindowDesc _select_company_manager_face_adv_desc(
WDP_AUTO, WDP_AUTO, 220, 220, 220, 220,
WC_COMPANY_MANAGER_FACE, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_CONSTRUCTION,
_select_company_manager_face_adv_widgets
);
/**
* Open the simple/advanced company manager face selection window
*
* @param parent the parent company window
* @param adv simple or advanced face selection window
* @param top previous top position of the window
* @param left previous left position of the window
*/
static void DoSelectCompanyManagerFace(Window *parent, bool adv, int top, int left)
{
if (!IsValidCompanyID((CompanyID)parent->window_number)) return;
if (BringWindowToFrontById(WC_COMPANY_MANAGER_FACE, parent->window_number)) return;
new SelectCompanyManagerFaceWindow(adv ? &_select_company_manager_face_adv_desc : &_select_company_manager_face_desc, parent, adv, top, left); // simple or advanced window
}
/* Names of the widgets. Keep them in the same order as in the widget array */
enum CompanyWindowWidgets {
CW_WIDGET_CLOSEBOX = 0,
CW_WIDGET_CAPTION,
CW_WIDGET_FACE,
CW_WIDGET_NEW_FACE,
CW_WIDGET_COLOUR_SCHEME,
CW_WIDGET_PRESIDENT_NAME,
CW_WIDGET_COMPANY_NAME,
CW_WIDGET_BUILD_VIEW_HQ,
CW_WIDGET_RELOCATE_HQ,
CW_WIDGET_BUY_SHARE,
CW_WIDGET_SELL_SHARE,
CW_WIDGET_COMPANY_PASSWORD,
CW_WIDGET_COMPANY_JOIN,
};
static const Widget _company_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 11, 359, 0, 13, STR_7001, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 359, 14, 157, 0x0, STR_NULL},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 0, 89, 158, 169, STR_7004_NEW_FACE, STR_7030_SELECT_NEW_FACE_FOR_PRESIDENT},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 90, 179, 158, 169, STR_7005_COLOUR_SCHEME, STR_7031_CHANGE_THE_COMPANY_VEHICLE},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 180, 269, 158, 169, STR_7009_PRESIDENT_NAME, STR_7032_CHANGE_THE_PRESIDENT_S},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 270, 359, 158, 169, STR_7008_COMPANY_NAME, STR_7033_CHANGE_THE_COMPANY_NAME},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 266, 355, 18, 29, STR_7072_VIEW_HQ, STR_7070_BUILD_COMPANY_HEADQUARTERS},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 266, 355, 32, 43, STR_RELOCATE_HQ, STR_RELOCATE_COMPANY_HEADQUARTERS},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 0, 179, 158, 169, STR_7077_BUY_25_SHARE_IN_COMPANY, STR_7079_BUY_25_SHARE_IN_THIS_COMPANY},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 180, 359, 158, 169, STR_7078_SELL_25_SHARE_IN_COMPANY, STR_707A_SELL_25_SHARE_IN_THIS_COMPANY},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 266, 355, 138, 149, STR_COMPANY_PASSWORD, STR_COMPANY_PASSWORD_TOOLTIP},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 266, 355, 138, 149, STR_COMPANY_JOIN, STR_COMPANY_JOIN_TIP},
{ WIDGETS_END},
};
/**
* Draws text "Vehicles:" and number of all vehicle types, or "(none)"
* @param company ID of company to print statistics of
*/
static void DrawCompanyVehiclesAmount(CompanyID company)
{
const int x = 110;
int y = 63;
const Vehicle *v;
uint train = 0;
uint road = 0;
uint air = 0;
uint ship = 0;
DrawString(x, y, STR_7039_VEHICLES, TC_FROMSTRING);
FOR_ALL_VEHICLES(v) {
if (v->owner == company) {
switch (v->type) {
case VEH_TRAIN: if (IsFrontEngine(v)) train++; break;
case VEH_ROAD: if (IsRoadVehFront(v)) road++; break;
case VEH_AIRCRAFT: if (IsNormalAircraft(v)) air++; break;
case VEH_SHIP: ship++; break;
default: break;
}
}
}
if (train + road + air + ship == 0) {
DrawString(x + 70, y, STR_7042_NONE, TC_FROMSTRING);
} else {
if (train != 0) {
SetDParam(0, train);
DrawString(x + 70, y, STR_TRAINS, TC_FROMSTRING);
y += 10;
}
if (road != 0) {
SetDParam(0, road);
DrawString(x + 70, y, STR_ROAD_VEHICLES, TC_FROMSTRING);
y += 10;
}
if (air != 0) {
SetDParam(0, air);
DrawString(x + 70, y, STR_AIRCRAFT, TC_FROMSTRING);
y += 10;
}
if (ship != 0) {
SetDParam(0, ship);
DrawString(x + 70, y, STR_SHIPS, TC_FROMSTRING);
}
}
}
int GetAmountOwnedBy(const Company *c, Owner owner)
{
return (c->share_owners[0] == owner) +
(c->share_owners[1] == owner) +
(c->share_owners[2] == owner) +
(c->share_owners[3] == owner);
}
/**
* Draws list of all companies with shares
* @param c pointer to the Company structure
*/
static void DrawCompanyOwnerText(const Company *c)
{
const Company *c2;
uint num = 0;
const byte height = GetCharacterHeight(FS_NORMAL);
FOR_ALL_COMPANIES(c2) {
uint amt = GetAmountOwnedBy(c, c2->index);
if (amt != 0) {
SetDParam(0, amt * 25);
SetDParam(1, c2->index);
DrawString(120, (num++) * height + 116, STR_707D_OWNED_BY, TC_FROMSTRING);
}
}
}
/**
* Window with general information about a company
*/
struct CompanyWindow : Window
{
CompanyWindowWidgets query_widget;
CompanyWindow(const WindowDesc *desc, WindowNumber window_number) : Window(desc, window_number)
{
this->owner = (Owner)this->window_number;
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
const Company *c = GetCompany((CompanyID)this->window_number);
bool local = this->window_number == _local_company;
this->SetWidgetHiddenState(CW_WIDGET_NEW_FACE, !local);
this->SetWidgetHiddenState(CW_WIDGET_COLOUR_SCHEME, !local);
this->SetWidgetHiddenState(CW_WIDGET_PRESIDENT_NAME, !local);
this->SetWidgetHiddenState(CW_WIDGET_COMPANY_NAME, !local);
this->widget[CW_WIDGET_BUILD_VIEW_HQ].data = (local && c->location_of_HQ == INVALID_TILE) ? STR_706F_BUILD_HQ : STR_7072_VIEW_HQ;
if (local && c->location_of_HQ != INVALID_TILE) this->widget[CW_WIDGET_BUILD_VIEW_HQ].type = WWT_PUSHTXTBTN; // HQ is already built.
this->SetWidgetDisabledState(CW_WIDGET_BUILD_VIEW_HQ, !local && c->location_of_HQ == INVALID_TILE);
this->SetWidgetHiddenState(CW_WIDGET_RELOCATE_HQ, !local || c->location_of_HQ == INVALID_TILE);
this->SetWidgetHiddenState(CW_WIDGET_BUY_SHARE, local);
this->SetWidgetHiddenState(CW_WIDGET_SELL_SHARE, local);
this->SetWidgetHiddenState(CW_WIDGET_COMPANY_PASSWORD, !local || !_networking);
this->SetWidgetHiddenState(CW_WIDGET_COMPANY_JOIN, local || !_networking);
this->SetWidgetDisabledState(CW_WIDGET_COMPANY_JOIN, !IsHumanCompany(c->index));
if (!local) {
if (_settings_game.economy.allow_shares) { // Shares are allowed
/* If all shares are owned by someone (none by nobody), disable buy button */
this->SetWidgetDisabledState(CW_WIDGET_BUY_SHARE, GetAmountOwnedBy(c, INVALID_OWNER) == 0 ||
/* Only 25% left to buy. If the company is human, disable buying it up.. TODO issues! */
(GetAmountOwnedBy(c, INVALID_OWNER) == 1 && !c->is_ai) ||
/* Spectators cannot do anything of course */
_local_company == COMPANY_SPECTATOR);
/* If the company doesn't own any shares, disable sell button */
this->SetWidgetDisabledState(CW_WIDGET_SELL_SHARE, (GetAmountOwnedBy(c, _local_company) == 0) ||
/* Spectators cannot do anything of course */
_local_company == COMPANY_SPECTATOR);
} else { // Shares are not allowed, disable buy/sell buttons
this->DisableWidget(CW_WIDGET_BUY_SHARE);
this->DisableWidget(CW_WIDGET_SELL_SHARE);
}
}
SetDParam(0, c->index);
SetDParam(1, c->index);
this->DrawWidgets();
#ifdef ENABLE_NETWORK
if (_networking && NetworkCompanyIsPassworded(c->index)) {
DrawSprite(SPR_LOCK, PAL_NONE, this->widget[CW_WIDGET_COMPANY_JOIN].left - 10, this->widget[CW_WIDGET_COMPANY_JOIN].top + 2);
}
#endif /* ENABLE_NETWORK */
/* Company manager's face */
DrawCompanyManagerFace(c->face, c->colour, 2, 16);
/* "xxx (Manager)" */
SetDParam(0, c->index);
DrawStringMultiCenter(48, 141, STR_7037_PRESIDENT, MAX_LENGTH_PRESIDENT_NAME_PIXELS);
/* "Inaugurated:" */
SetDParam(0, c->inaugurated_year);
DrawString(110, 23, STR_7038_INAUGURATED, TC_FROMSTRING);
/* "Colour scheme:" */
DrawString(110, 43, STR_7006_COLOUR_SCHEME, TC_FROMSTRING);
/* Draw company-colour bus */
DrawSprite(SPR_VEH_BUS_SW_VIEW, COMPANY_SPRITE_COLOUR(c->index), 215, 44);
/* "Vehicles:" */
DrawCompanyVehiclesAmount((CompanyID)this->window_number);
/* "Company value:" */
SetDParam(0, CalculateCompanyValue(c));
DrawString(110, 106, STR_7076_COMPANY_VALUE, TC_FROMSTRING);
/* Shares list */
DrawCompanyOwnerText(c);
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case CW_WIDGET_NEW_FACE: DoSelectCompanyManagerFace(this, false); break;
case CW_WIDGET_COLOUR_SCHEME:
if (BringWindowToFrontById(WC_COMPANY_COLOUR, this->window_number)) break;
new SelectCompanyLiveryWindow(&_select_company_livery_desc, (CompanyID)this->window_number);
break;
case CW_WIDGET_PRESIDENT_NAME:
this->query_widget = CW_WIDGET_PRESIDENT_NAME;
SetDParam(0, this->window_number);
ShowQueryString(STR_PRESIDENT_NAME, STR_700B_PRESIDENT_S_NAME, MAX_LENGTH_PRESIDENT_NAME_BYTES, MAX_LENGTH_PRESIDENT_NAME_PIXELS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT);
break;
case CW_WIDGET_COMPANY_NAME:
this->query_widget = CW_WIDGET_COMPANY_NAME;
SetDParam(0, this->window_number);
ShowQueryString(STR_COMPANY_NAME, STR_700A_COMPANY_NAME, MAX_LENGTH_COMPANY_NAME_BYTES, MAX_LENGTH_COMPANY_NAME_PIXELS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT);
break;
case CW_WIDGET_BUILD_VIEW_HQ: {
TileIndex tile = GetCompany((CompanyID)this->window_number)->location_of_HQ;
if (tile == INVALID_TILE) {
if ((byte)this->window_number != _local_company) return;
SetObjectToPlaceWnd(SPR_CURSOR_HQ, PAL_NONE, VHM_RECT, this);
SetTileSelectSize(2, 2);
this->LowerWidget(CW_WIDGET_BUILD_VIEW_HQ);
this->InvalidateWidget(CW_WIDGET_BUILD_VIEW_HQ);
} else {
if (_ctrl_pressed) {
ShowExtraViewPortWindow(tile);
} else {
ScrollMainWindowToTile(tile);
}
}
break;
}
case CW_WIDGET_RELOCATE_HQ:
SetObjectToPlaceWnd(SPR_CURSOR_HQ, PAL_NONE, VHM_RECT, this);
SetTileSelectSize(2, 2);
this->LowerWidget(CW_WIDGET_RELOCATE_HQ);
this->InvalidateWidget(CW_WIDGET_RELOCATE_HQ);
break;
case CW_WIDGET_BUY_SHARE:
DoCommandP(0, this->window_number, 0, CMD_BUY_SHARE_IN_COMPANY | CMD_MSG(STR_707B_CAN_T_BUY_25_SHARE_IN_THIS));
break;
case CW_WIDGET_SELL_SHARE:
DoCommandP(0, this->window_number, 0, CMD_SELL_SHARE_IN_COMPANY | CMD_MSG(STR_707C_CAN_T_SELL_25_SHARE_IN));
break;
#ifdef ENABLE_NETWORK
case CW_WIDGET_COMPANY_PASSWORD:
if (this->window_number == _local_company) ShowNetworkCompanyPasswordWindow(this);
break;
case CW_WIDGET_COMPANY_JOIN: {
this->query_widget = CW_WIDGET_COMPANY_JOIN;
CompanyID company = (CompanyID)this->window_number;
if (_network_server) {
NetworkServerDoMove(CLIENT_ID_SERVER, company);
MarkWholeScreenDirty();
} else if (NetworkCompanyIsPassworded(company)) {
/* ask for the password */
ShowQueryString(STR_EMPTY, STR_NETWORK_NEED_COMPANY_PASSWORD_CAPTION, 20, 180, this, CS_ALPHANUMERAL, QSF_NONE);
} else {
/* just send the join command */
NetworkClientRequestMove(company);
}
break;
}
#endif /* ENABLE_NETWORK */
}
}
virtual void OnHundredthTick()
{
/* redraw the window every now and then */
this->SetDirty();
}
virtual void OnPlaceObject(Point pt, TileIndex tile)
{
if (DoCommandP(tile, 0, 0, CMD_BUILD_COMPANY_HQ | CMD_MSG(STR_7071_CAN_T_BUILD_COMPANY_HEADQUARTERS)))
ResetObjectToPlace();
this->widget[CW_WIDGET_BUILD_VIEW_HQ].type = WWT_PUSHTXTBTN; // this button can now behave as a normal push button
this->RaiseButtons();
}
virtual void OnPlaceObjectAbort()
{
this->RaiseButtons();
}
virtual void OnQueryTextFinished(char *str)
{
if (str == NULL) return;
switch (this->query_widget) {
default: NOT_REACHED();
case CW_WIDGET_PRESIDENT_NAME:
DoCommandP(0, 0, 0, CMD_RENAME_PRESIDENT | CMD_MSG(STR_700D_CAN_T_CHANGE_PRESIDENT), NULL, str);
break;
case CW_WIDGET_COMPANY_NAME:
DoCommandP(0, 0, 0, CMD_RENAME_COMPANY | CMD_MSG(STR_700C_CAN_T_CHANGE_COMPANY_NAME), NULL, str);
break;
#ifdef ENABLE_NETWORK
case CW_WIDGET_COMPANY_JOIN:
NetworkClientRequestMove((CompanyID)this->window_number, str);
break;
#endif /* ENABLE_NETWORK */
}
}
};
static const WindowDesc _company_desc(
WDP_AUTO, WDP_AUTO, 360, 170, 360, 170,
WC_COMPANY, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
_company_widgets
);
void ShowCompany(CompanyID company)
{
if (!IsValidCompanyID(company)) return;
AllocateWindowDescFront<CompanyWindow>(&_company_desc, company);
}
struct BuyCompanyWindow : Window {
BuyCompanyWindow(const WindowDesc *desc, WindowNumber window_number) : Window(desc, window_number)
{
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
Company *c = GetCompany((CompanyID)this->window_number);
SetDParam(0, STR_COMPANY_NAME);
SetDParam(1, c->index);
this->DrawWidgets();
DrawCompanyManagerFace(c->face, c->colour, 2, 16);
SetDParam(0, c->index);
SetDParam(1, c->bankrupt_value);
DrawStringMultiCenter(214, 65, STR_705B_WE_ARE_LOOKING_FOR_A_TRANSPORT, 238);
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case 3:
delete this;
break;
case 4:
DoCommandP(0, this->window_number, 0, CMD_BUY_COMPANY | CMD_MSG(STR_7060_CAN_T_BUY_COMPANY));
break;
}
}
};
static const Widget _buy_company_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_LIGHT_BLUE, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_LIGHT_BLUE, 11, 333, 0, 13, STR_00B3_MESSAGE_FROM, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PANEL, RESIZE_NONE, COLOUR_LIGHT_BLUE, 0, 333, 14, 136, 0x0, STR_NULL},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_LIGHT_BLUE, 148, 207, 117, 128, STR_00C9_NO, STR_NULL},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_LIGHT_BLUE, 218, 277, 117, 128, STR_00C8_YES, STR_NULL},
{ WIDGETS_END},
};
static const WindowDesc _buy_company_desc(
153, 171, 334, 137, 334, 137,
WC_BUY_COMPANY, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_CONSTRUCTION,
_buy_company_widgets
);
void ShowBuyCompanyDialog(CompanyID company)
{
AllocateWindowDescFront<BuyCompanyWindow>(&_buy_company_desc, company);
}
| 63,550
|
C++
|
.cpp
| 1,316
| 45.045593
| 178
| 0.670139
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,141
|
unmovable_cmd.cpp
|
EnergeticBark_OpenTTD-3DS/src/unmovable_cmd.cpp
|
/* $Id$ */
/** @file unmovable_cmd.cpp Handling of unmovable tiles. */
#include "stdafx.h"
#include "openttd.h"
#include "landscape.h"
#include "command_func.h"
#include "viewport_func.h"
#include "company_base.h"
#include "town.h"
#include "sprite.h"
#include "bridge_map.h"
#include "unmovable_map.h"
#include "genworld.h"
#include "autoslope.h"
#include "transparency.h"
#include "functions.h"
#include "window_func.h"
#include "vehicle_func.h"
#include "company_gui.h"
#include "economy_func.h"
#include "cheat_type.h"
#include "landscape_type.h"
#include "unmovable.h"
#include "table/strings.h"
#include "table/sprites.h"
#include "table/unmovable_land.h"
/**
* Accessor for array _original_unmovable.
* This will ensure at once : proper access and
* not allowing modifications of it.
* @param type of unmovable (which is the index in _original_unmovable)
* @pre type < UNMOVABLE_MAX
* @return a pointer to the corresponding unmovable spec
**/
static inline const UnmovableSpec *GetUnmovableSpec(UnmovableType type)
{
assert(type < UNMOVABLE_MAX);
return &_original_unmovable[type];
}
/** Destroy a HQ.
* During normal gameplay you can only implicitely destroy a HQ when you are
* rebuilding it. Otherwise, only water can destroy it.
* @param cid Company requesting the destruction of his HQ
* @param flags docommand flags of calling function
* @return cost of the operation
*/
static CommandCost DestroyCompanyHQ(CompanyID cid, DoCommandFlag flags)
{
Company *c = GetCompany(cid);
if (flags & DC_EXEC) {
TileIndex t = c->location_of_HQ;
DoClearSquare(t);
DoClearSquare(t + TileDiffXY(0, 1));
DoClearSquare(t + TileDiffXY(1, 0));
DoClearSquare(t + TileDiffXY(1, 1));
c->location_of_HQ = INVALID_TILE; // reset HQ position
InvalidateWindow(WC_COMPANY, cid);
}
/* cost of relocating company is 1% of company value */
return CommandCost(EXPENSES_PROPERTY, CalculateCompanyValue(c) / 100);
}
void UpdateCompanyHQ(Company *c, uint score)
{
byte val;
TileIndex tile = c->location_of_HQ;
if (tile == INVALID_TILE) return;
(val = 0, score < 170) ||
(val++, score < 350) ||
(val++, score < 520) ||
(val++, score < 720) ||
(val++, true);
EnlargeCompanyHQ(tile, val);
MarkTileDirtyByTile(tile);
MarkTileDirtyByTile(tile + TileDiffXY(0, 1));
MarkTileDirtyByTile(tile + TileDiffXY(1, 0));
MarkTileDirtyByTile(tile + TileDiffXY(1, 1));
}
extern CommandCost CheckFlatLandBelow(TileIndex tile, uint w, uint h, DoCommandFlag flags, uint invalid_dirs, StationID *station, bool check_clear = true);
/** Build or relocate the HQ. This depends if the HQ is already built or not
* @param tile tile where the HQ will be built or relocated to
* @param flags type of operation
* @param p1 unused
* @param p2 unused
*/
CommandCost CmdBuildCompanyHQ(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Company *c = GetCompany(_current_company);
CommandCost cost(EXPENSES_PROPERTY);
cost = CheckFlatLandBelow(tile, 2, 2, flags, 0, NULL);
if (CmdFailed(cost)) return cost;
if (c->location_of_HQ != INVALID_TILE) { // Moving HQ
cost.AddCost(DestroyCompanyHQ(_current_company, flags));
}
if (flags & DC_EXEC) {
int score = UpdateCompanyRatingAndValue(c, false);
c->location_of_HQ = tile;
MakeCompanyHQ(tile, _current_company);
UpdateCompanyHQ(c, score);
InvalidateWindow(WC_COMPANY, c->index);
}
return cost;
}
/** Purchase a land area. Actually you only purchase one tile, so
* the name is a bit confusing ;p
* @param tile the tile the company is purchasing
* @param flags for this command type
* @param p1 unused
* @param p2 unused
* @return error of cost of operation
*/
CommandCost CmdPurchaseLandArea(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
CommandCost cost(EXPENSES_CONSTRUCTION);
if (IsOwnedLandTile(tile) && IsTileOwner(tile, _current_company)) {
return_cmd_error(STR_5807_YOU_ALREADY_OWN_IT);
}
cost = DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
if (CmdFailed(cost)) return CMD_ERROR;
if (flags & DC_EXEC) {
MakeOwnedLand(tile, _current_company);
MarkTileDirtyByTile(tile);
}
return cost.AddCost(GetUnmovableSpec(UNMOVABLE_OWNED_LAND)->GetBuildingCost());
}
/** Sell a land area. Actually you only sell one tile, so
* the name is a bit confusing ;p
* @param tile the tile the company is selling
* @param flags for this command type
* @param p1 unused
* @param p2 unused
* @return error or cost of operation
*/
CommandCost CmdSellLandArea(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
if (!IsOwnedLandTile(tile)) return CMD_ERROR;
if (!CheckTileOwnership(tile) && _current_company != OWNER_WATER) return CMD_ERROR;
if (!EnsureNoVehicleOnGround(tile)) return CMD_ERROR;
if (flags & DC_EXEC) DoClearSquare(tile);
return CommandCost(EXPENSES_CONSTRUCTION, - GetUnmovableSpec(UNMOVABLE_OWNED_LAND)->GetRemovalCost());
}
static Foundation GetFoundation_Unmovable(TileIndex tile, Slope tileh);
static void DrawTile_Unmovable(TileInfo *ti)
{
switch (GetUnmovableType(ti->tile)) {
default: NOT_REACHED(); break;
case UNMOVABLE_TRANSMITTER:
case UNMOVABLE_LIGHTHOUSE: {
const DrawTileSeqStruct *dtu = &_draw_tile_transmitterlighthouse_data[GetUnmovableType(ti->tile)];
if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
DrawClearLandTile(ti, 2);
if (IsInvisibilitySet(TO_STRUCTURES)) break;
AddSortableSpriteToDraw(
dtu->image.sprite, PAL_NONE, ti->x | dtu->delta_x, ti->y | dtu->delta_y,
dtu->size_x, dtu->size_y, dtu->size_z, ti->z,
IsTransparencySet(TO_STRUCTURES)
);
break;
}
case UNMOVABLE_STATUE:
/* This should prevent statues from sinking into the ground when on a slope. */
if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, GetFoundation_Unmovable(ti->tile, ti->tileh));
DrawGroundSprite(SPR_CONCRETE_GROUND, PAL_NONE);
if (IsInvisibilitySet(TO_STRUCTURES)) break;
AddSortableSpriteToDraw(SPR_STATUE_COMPANY, COMPANY_SPRITE_COLOUR(GetTileOwner(ti->tile)), ti->x, ti->y, 16, 16, 25, ti->z, IsTransparencySet(TO_STRUCTURES));
break;
case UNMOVABLE_OWNED_LAND:
DrawClearLandTile(ti, 0);
AddSortableSpriteToDraw(
SPR_BOUGHT_LAND, COMPANY_SPRITE_COLOUR(GetTileOwner(ti->tile)),
ti->x + TILE_SIZE / 2, ti->y + TILE_SIZE / 2, 1, 1, BB_HEIGHT_UNDER_BRIDGE, GetSlopeZ(ti->x + TILE_SIZE / 2, ti->y + TILE_SIZE / 2)
);
DrawBridgeMiddle(ti);
break;
case UNMOVABLE_HQ:{
assert(IsCompanyHQ(ti->tile));
if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
SpriteID palette = COMPANY_SPRITE_COLOUR(GetTileOwner(ti->tile));
const DrawTileSprites *t = &_unmovable_display_datas[GetCompanyHQSize(ti->tile) << 2 | GetCompanyHQSection(ti->tile)];
DrawGroundSprite(t->ground.sprite, palette);
if (IsInvisibilitySet(TO_STRUCTURES)) break;
const DrawTileSeqStruct *dtss;
foreach_draw_tile_seq(dtss, t->seq) {
AddSortableSpriteToDraw(
dtss->image.sprite, palette,
ti->x + dtss->delta_x, ti->y + dtss->delta_y,
dtss->size_x, dtss->size_y,
dtss->size_z, ti->z + dtss->delta_z,
IsTransparencySet(TO_STRUCTURES)
);
}
break;
}
}
}
static uint GetSlopeZ_Unmovable(TileIndex tile, uint x, uint y)
{
if (IsOwnedLand(tile)) {
uint z;
Slope tileh = GetTileSlope(tile, &z);
return z + GetPartialZ(x & 0xF, y & 0xF, tileh);
} else {
return GetTileMaxZ(tile);
}
}
static Foundation GetFoundation_Unmovable(TileIndex tile, Slope tileh)
{
return IsOwnedLand(tile) ? FOUNDATION_NONE : FlatteningFoundation(tileh);
}
static CommandCost ClearTile_Unmovable(TileIndex tile, DoCommandFlag flags)
{
if (IsCompanyHQ(tile)) {
if (_current_company == OWNER_WATER) {
return DestroyCompanyHQ(GetTileOwner(tile), DC_EXEC);
} else {
return_cmd_error(flags & DC_AUTO ? STR_5804_COMPANY_HEADQUARTERS_IN : INVALID_STRING_ID);
}
}
if (IsOwnedLand(tile)) {
return DoCommand(tile, 0, 0, flags, CMD_SELL_LAND_AREA);
}
/* checks if you're allowed to remove unmovable things */
if (_game_mode != GM_EDITOR && _current_company != OWNER_WATER && ((flags & DC_AUTO || !_cheats.magic_bulldozer.value)) )
return_cmd_error(flags & DC_AUTO ? STR_5800_OBJECT_IN_THE_WAY : INVALID_STRING_ID);
if (IsStatue(tile)) {
if (flags & DC_AUTO) return_cmd_error(STR_5800_OBJECT_IN_THE_WAY);
TownID town = GetStatueTownID(tile);
ClrBit(GetTown(town)->statues, GetTileOwner(tile));
InvalidateWindow(WC_TOWN_AUTHORITY, town);
}
if (flags & DC_EXEC) {
DoClearSquare(tile);
}
return CommandCost();
}
static void GetAcceptedCargo_Unmovable(TileIndex tile, AcceptedCargo ac)
{
if (!IsCompanyHQ(tile)) return;
/* HQ accepts passenger and mail; but we have to divide the values
* between 4 tiles it occupies! */
/* HQ level (depends on company performance) in the range 1..5. */
uint level = GetCompanyHQSize(tile) + 1;
/* Top town building generates 10, so to make HQ interesting, the top
* type makes 20. */
ac[CT_PASSENGERS] = max(1U, level);
/* Top town building generates 4, HQ can make up to 8. The
* proportion passengers:mail is different because such a huge
* commercial building generates unusually high amount of mail
* correspondence per physical visitor. */
ac[CT_MAIL] = max(1U, level / 2);
}
static void GetTileDesc_Unmovable(TileIndex tile, TileDesc *td)
{
td->str = GetUnmovableSpec(GetUnmovableType(tile))->name;
td->owner[0] = GetTileOwner(tile);
}
static void AnimateTile_Unmovable(TileIndex tile)
{
/* not used */
}
static void TileLoop_Unmovable(TileIndex tile)
{
if (!IsCompanyHQ(tile)) return;
/* HQ accepts passenger and mail; but we have to divide the values
* between 4 tiles it occupies! */
/* HQ level (depends on company performance) in the range 1..5. */
uint level = GetCompanyHQSize(tile) + 1;
assert(level < 6);
uint r = Random();
/* Top town buildings generate 250, so the top HQ type makes 256. */
if (GB(r, 0, 8) < (256 / 4 / (6 - level))) {
uint amt = GB(r, 0, 8) / 8 / 4 + 1;
if (_economy.fluct <= 0) amt = (amt + 1) >> 1;
MoveGoodsToStation(tile, 2, 2, CT_PASSENGERS, amt);
}
/* Top town building generates 90, HQ can make up to 196. The
* proportion passengers:mail is about the same as in the acceptance
* equations. */
if (GB(r, 8, 8) < (196 / 4 / (6 - level))) {
uint amt = GB(r, 8, 8) / 8 / 4 + 1;
if (_economy.fluct <= 0) amt = (amt + 1) >> 1;
MoveGoodsToStation(tile, 2, 2, CT_MAIL, amt);
}
}
static TrackStatus GetTileTrackStatus_Unmovable(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
{
return 0;
}
static bool ClickTile_Unmovable(TileIndex tile)
{
if (!IsCompanyHQ(tile)) return false;
ShowCompany(GetTileOwner(tile));
return true;
}
/* checks, if a radio tower is within a 9x9 tile square around tile */
static bool IsRadioTowerNearby(TileIndex tile)
{
TileIndex tile_s = tile - TileDiffXY(min(TileX(tile), 4U), min(TileY(tile), 4U));
uint w = min(TileX(tile), 4U) + 1 + min(MapMaxX() - TileX(tile), 4U);
uint h = min(TileY(tile), 4U) + 1 + min(MapMaxY() - TileY(tile), 4U);
BEGIN_TILE_LOOP(tile, w, h, tile_s)
if (IsTransmitterTile(tile)) return true;
END_TILE_LOOP(tile, w, h, tile_s)
return false;
}
void GenerateUnmovables()
{
if (_settings_game.game_creation.landscape == LT_TOYLAND) return;
/* add radio tower */
int radiotower_to_build = ScaleByMapSize(15); // maximum number of radio towers on the map
int lighthouses_to_build = _settings_game.game_creation.landscape == LT_TROPIC ? 0 : ScaleByMapSize1D((Random() & 3) + 7);
/* Scale the amount of lighthouses with the amount of land at the borders. */
if (_settings_game.construction.freeform_edges && lighthouses_to_build != 0) {
uint num_water_tiles = 0;
for (uint x = 0; x < MapMaxX(); x++) {
if (IsTileType(TileXY(x, 1), MP_WATER)) num_water_tiles++;
if (IsTileType(TileXY(x, MapMaxY() - 1), MP_WATER)) num_water_tiles++;
}
for (uint y = 1; y < MapMaxY() - 1; y++) {
if (IsTileType(TileXY(1, y), MP_WATER)) num_water_tiles++;
if (IsTileType(TileXY(MapMaxX() - 1, y), MP_WATER)) num_water_tiles++;
}
/* The -6 is because the top borders are MP_VOID (-2) and all corners
* are counted twice (-4). */
lighthouses_to_build = lighthouses_to_build * num_water_tiles / (2 * MapMaxY() + 2 * MapMaxX() - 6);
}
SetGeneratingWorldProgress(GWP_UNMOVABLE, radiotower_to_build + lighthouses_to_build);
for (uint i = ScaleByMapSize(1000); i != 0; i--) {
TileIndex tile = RandomTile();
uint h;
if (IsTileType(tile, MP_CLEAR) && GetTileSlope(tile, &h) == SLOPE_FLAT && h >= TILE_HEIGHT * 4 && !IsBridgeAbove(tile)) {
if (IsRadioTowerNearby(tile)) continue;
MakeTransmitter(tile);
IncreaseGeneratingWorldProgress(GWP_UNMOVABLE);
if (--radiotower_to_build == 0) break;
}
}
/* add lighthouses */
uint maxx = MapMaxX();
uint maxy = MapMaxY();
for (int loop_count = 0; loop_count < 1000 && lighthouses_to_build != 0; loop_count++) {
uint r = Random();
/* Scatter the lighthouses more evenly around the perimeter */
int perimeter = (GB(r, 16, 16) % (2 * (maxx + maxy))) - maxy;
DiagDirection dir;
for (dir = DIAGDIR_NE; perimeter > 0; dir++) {
perimeter -= (DiagDirToAxis(dir) == AXIS_X) ? maxx : maxy;
}
TileIndex tile;
switch (dir) {
default:
case DIAGDIR_NE: tile = TileXY(maxx - 1, r % maxy); break;
case DIAGDIR_SE: tile = TileXY(r % maxx, 1); break;
case DIAGDIR_SW: tile = TileXY(1, r % maxy); break;
case DIAGDIR_NW: tile = TileXY(r % maxx, maxy - 1); break;
}
/* Only build lighthouses at tiles where the border is sea. */
if (!IsTileType(tile, MP_WATER)) continue;
for (int j = 0; j < 19; j++) {
uint h;
if (IsTileType(tile, MP_CLEAR) && GetTileSlope(tile, &h) == SLOPE_FLAT && h <= TILE_HEIGHT * 2 && !IsBridgeAbove(tile)) {
MakeLighthouse(tile);
IncreaseGeneratingWorldProgress(GWP_UNMOVABLE);
lighthouses_to_build--;
assert(tile < MapSize());
break;
}
tile = AddTileIndexDiffCWrap(tile, TileIndexDiffCByDiagDir(dir));
if (tile == INVALID_TILE) break;
}
}
}
static void ChangeTileOwner_Unmovable(TileIndex tile, Owner old_owner, Owner new_owner)
{
if (!IsTileOwner(tile, old_owner)) return;
if (IsOwnedLand(tile) && new_owner != INVALID_OWNER) {
SetTileOwner(tile, new_owner);
} else if (IsStatueTile(tile)) {
TownID town = GetStatueTownID(tile);
Town *t = GetTown(town);
ClrBit(t->statues, old_owner);
if (new_owner != INVALID_OWNER && !HasBit(t->statues, new_owner)) {
/* Transfer ownership to the new company */
SetBit(t->statues, new_owner);
SetTileOwner(tile, new_owner);
} else {
DoClearSquare(tile);
}
InvalidateWindow(WC_TOWN_AUTHORITY, town);
} else {
DoClearSquare(tile);
}
}
static CommandCost TerraformTile_Unmovable(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
{
/* Owned land remains unsold */
if (IsOwnedLand(tile) && CheckTileOwnership(tile)) return CommandCost();
if (AutoslopeEnabled() && (IsStatue(tile) || IsCompanyHQ(tile))) {
if (!IsSteepSlope(tileh_new) && (z_new + GetSlopeMaxZ(tileh_new) == GetTileMaxZ(tile))) return CommandCost(EXPENSES_CONSTRUCTION, _price.terraform);
}
return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
}
extern const TileTypeProcs _tile_type_unmovable_procs = {
DrawTile_Unmovable, // draw_tile_proc
GetSlopeZ_Unmovable, // get_slope_z_proc
ClearTile_Unmovable, // clear_tile_proc
GetAcceptedCargo_Unmovable, // get_accepted_cargo_proc
GetTileDesc_Unmovable, // get_tile_desc_proc
GetTileTrackStatus_Unmovable, // get_tile_track_status_proc
ClickTile_Unmovable, // click_tile_proc
AnimateTile_Unmovable, // animate_tile_proc
TileLoop_Unmovable, // tile_loop_clear
ChangeTileOwner_Unmovable, // change_tile_owner_clear
NULL, // get_produced_cargo_proc
NULL, // vehicle_enter_tile_proc
GetFoundation_Unmovable, // get_foundation_proc
TerraformTile_Unmovable, // terraform_tile_proc
};
| 16,148
|
C++
|
.cpp
| 417
| 36.117506
| 161
| 0.709781
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,142
|
waypoint_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/waypoint_gui.cpp
|
/* $Id$ */
/** @file waypoint_gui.cpp Handling of waypoints gui. */
#include "stdafx.h"
#include "window_gui.h"
#include "gui.h"
#include "textbuf_gui.h"
#include "vehicle_gui.h"
#include "viewport_func.h"
#include "strings_func.h"
#include "gfx_func.h"
#include "command_func.h"
#include "company_func.h"
#include "window_func.h"
#include "table/strings.h"
struct WaypointWindow : Window {
private:
Waypoint *wp;
enum WaypointViewWidget {
WAYPVW_CLOSEBOX = 0,
WAYPVW_CAPTION,
WAYPVW_STICKY,
WAYPVW_VIEWPORTPANEL,
WAYPVW_SPACER,
WAYPVW_CENTERVIEW,
WAYPVW_RENAME,
WAYPVW_SHOW_TRAINS,
};
public:
WaypointWindow(const WindowDesc *desc, WindowNumber window_number) : Window(desc, window_number)
{
this->wp = GetWaypoint(this->window_number);
if (this->wp->owner != OWNER_NONE) this->owner = this->wp->owner;
this->flags4 |= WF_DISABLE_VP_SCROLL;
InitializeWindowViewport(this, 3, 17, 254, 86, this->wp->xy, ZOOM_LVL_MIN);
this->FindWindowPlacementAndResize(desc);
}
~WaypointWindow()
{
DeleteWindowById(WC_TRAINS_LIST, (this->window_number << 16) | (VEH_TRAIN << 11) | VLW_WAYPOINT_LIST | this->wp->owner);
}
virtual void OnPaint()
{
/* You can only change your own waypoints */
this->SetWidgetDisabledState(WAYPVW_RENAME, this->wp->owner != _local_company);
/* Disable the widget for waypoints with no owner (after company bankrupt) */
this->SetWidgetDisabledState(WAYPVW_SHOW_TRAINS, this->wp->owner == OWNER_NONE);
SetDParam(0, this->wp->index);
this->DrawWidgets();
this->DrawViewport();
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case WAYPVW_CENTERVIEW: // scroll to location
if (_ctrl_pressed) {
ShowExtraViewPortWindow(this->wp->xy);
} else {
ScrollMainWindowToTile(this->wp->xy);
}
break;
case WAYPVW_RENAME: // rename
SetDParam(0, this->wp->index);
ShowQueryString(STR_WAYPOINT_RAW, STR_EDIT_WAYPOINT_NAME, MAX_LENGTH_WAYPOINT_NAME_BYTES, MAX_LENGTH_WAYPOINT_NAME_PIXELS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT);
break;
case WAYPVW_SHOW_TRAINS: // show list of trains having this waypoint in their orders
ShowVehicleListWindow(this->wp);
break;
}
}
virtual void OnInvalidateData(int data)
{
int x = TileX(this->wp->xy) * TILE_SIZE;
int y = TileY(this->wp->xy) * TILE_SIZE;
ScrollWindowTo(x, y, -1, this);
}
virtual void OnQueryTextFinished(char *str)
{
if (str == NULL) return;
DoCommandP(0, this->window_number, 0, CMD_RENAME_WAYPOINT | CMD_MSG(STR_CANT_CHANGE_WAYPOINT_NAME), NULL, str);
}
};
static const Widget _waypoint_view_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // WAYPVW_CLOSEBOX
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 11, 247, 0, 13, STR_WAYPOINT_VIEWPORT, STR_018C_WINDOW_TITLE_DRAG_THIS}, // WAYPVW_CAPTION
{ WWT_STICKYBOX, RESIZE_NONE, COLOUR_GREY, 248, 259, 0, 13, 0x0, STR_STICKY_BUTTON}, // WAYPVW_STICKY
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 259, 14, 105, 0x0, STR_NULL}, // WAYPVW_VIEWPORTPANEL
{ WWT_INSET, RESIZE_NONE, COLOUR_GREY, 2, 257, 16, 103, 0x0, STR_NULL}, // WAYPVW_SPACER
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 0, 121, 106, 117, STR_00E4_LOCATION, STR_3053_CENTER_MAIN_VIEW_ON_STATION}, // WAYPVW_CENTERVIEW
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 122, 244, 106, 117, STR_0130_RENAME, STR_CHANGE_WAYPOINT_NAME}, // WAYPVW_RENAME
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 245, 259, 106, 117, STR_TRAIN, STR_SCHEDULED_TRAINS_TIP }, // WAYPVW_SHOW_TRAINS
{ WIDGETS_END},
};
static const WindowDesc _waypoint_view_desc(
WDP_AUTO, WDP_AUTO, 260, 118, 260, 118,
WC_WAYPOINT_VIEW, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON,
_waypoint_view_widgets
);
void ShowWaypointWindow(const Waypoint *wp)
{
if (!wp->IsValid()) return; // little safety
AllocateWindowDescFront<WaypointWindow>(&_waypoint_view_desc, wp->index);
}
| 4,311
|
C++
|
.cpp
| 103
| 39.300971
| 170
| 0.661252
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,143
|
mixer.cpp
|
EnergeticBark_OpenTTD-3DS/src/mixer.cpp
|
/* $Id$ */
/** @file mixer.cpp Mixing of sound samples. */
#include "stdafx.h"
#include "mixer.h"
#include "core/math_func.hpp"
struct MixerChannel {
bool active;
/* pointer to allocated buffer memory */
int8 *memory;
/* current position in memory */
uint32 pos;
uint32 frac_pos;
uint32 frac_speed;
uint32 samples_left;
/* Mixing volume */
int volume_left;
int volume_right;
uint flags;
};
static MixerChannel _channels[8];
static uint32 _play_rate;
/**
* The theoretical maximum volume for a single sound sample. Multiple sound
* samples should not exceed this limit as it will sound too loud. It also
* stops overflowing when too many sounds are played at the same time, which
* causes an even worse sound quality.
*/
static const int MAX_VOLUME = 128 * 128;
static void mix_int8_to_int16(MixerChannel *sc, int16 *buffer, uint samples)
{
int8 *b;
uint32 frac_pos;
uint32 frac_speed;
int volume_left;
int volume_right;
if (samples > sc->samples_left) samples = sc->samples_left;
sc->samples_left -= samples;
assert(samples > 0);
b = sc->memory + sc->pos;
frac_pos = sc->frac_pos;
frac_speed = sc->frac_speed;
volume_left = sc->volume_left;
volume_right = sc->volume_right;
if (frac_speed == 0x10000) {
/* Special case when frac_speed is 0x10000 */
do {
buffer[0] = Clamp(buffer[0] + (*b * volume_left >> 8), -MAX_VOLUME, MAX_VOLUME);
buffer[1] = Clamp(buffer[1] + (*b * volume_right >> 8), -MAX_VOLUME, MAX_VOLUME);
b++;
buffer += 2;
} while (--samples > 0);
} else {
do {
buffer[0] = Clamp(buffer[0] + (*b * volume_left >> 8), -MAX_VOLUME, MAX_VOLUME);
buffer[1] = Clamp(buffer[1] + (*b * volume_right >> 8), -MAX_VOLUME, MAX_VOLUME);
buffer += 2;
frac_pos += frac_speed;
b += frac_pos >> 16;
frac_pos &= 0xffff;
} while (--samples > 0);
}
sc->frac_pos = frac_pos;
sc->pos = b - sc->memory;
}
static void MxCloseChannel(MixerChannel *mc)
{
if (mc->flags & MX_AUTOFREE) free(mc->memory);
mc->active = false;
mc->memory = NULL;
}
void MxMixSamples(void *buffer, uint samples)
{
MixerChannel *mc;
/* Clear the buffer */
memset(buffer, 0, sizeof(int16) * 2 * samples);
/* Mix each channel */
for (mc = _channels; mc != endof(_channels); mc++) {
if (mc->active) {
mix_int8_to_int16(mc, (int16*)buffer, samples);
if (mc->samples_left == 0) MxCloseChannel(mc);
}
}
}
MixerChannel *MxAllocateChannel()
{
MixerChannel *mc;
for (mc = _channels; mc != endof(_channels); mc++)
if (mc->memory == NULL) {
mc->active = false;
return mc;
}
return NULL;
}
void MxSetChannelRawSrc(MixerChannel *mc, int8 *mem, size_t size, uint rate, uint flags)
{
mc->memory = mem;
mc->flags = flags;
mc->frac_pos = 0;
mc->pos = 0;
mc->frac_speed = (rate << 16) / _play_rate;
/* adjust the magnitude to prevent overflow */
while (size & ~0xFFFF) {
size >>= 1;
rate = (rate >> 1) + 1;
}
mc->samples_left = (uint)size * _play_rate / rate;
}
void MxSetChannelVolume(MixerChannel *mc, uint left, uint right)
{
mc->volume_left = left;
mc->volume_right = right;
}
void MxActivateChannel(MixerChannel *mc)
{
mc->active = true;
}
bool MxInitialize(uint rate)
{
_play_rate = rate;
return true;
}
| 3,211
|
C++
|
.cpp
| 121
| 24.264463
| 88
| 0.672329
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,144
|
airport.cpp
|
EnergeticBark_OpenTTD-3DS/src/airport.cpp
|
/* $Id$ */
/** @file airport.cpp Functions related to airports. */
#include "stdafx.h"
#include "debug.h"
#include "airport.h"
#include "airport_movement.h"
#include "core/bitmath_func.hpp"
#include "core/alloc_func.hpp"
#include "date_func.h"
#include "settings_type.h"
/* Uncomment this to print out a full report of the airport-structure
* You should either use
* - true: full-report, print out every state and choice with string-names
* OR
* - false: give a summarized report which only shows current and next position */
//#define DEBUG_AIRPORT false
static AirportFTAClass *DummyAirport;
static AirportFTAClass *CountryAirport;
static AirportFTAClass *CityAirport;
static AirportFTAClass *Oilrig;
static AirportFTAClass *Heliport;
static AirportFTAClass *MetropolitanAirport;
static AirportFTAClass *InternationalAirport;
static AirportFTAClass *CommuterAirport;
static AirportFTAClass *HeliDepot;
static AirportFTAClass *IntercontinentalAirport;
static AirportFTAClass *HeliStation;
void InitializeAirports()
{
DummyAirport = new AirportFTAClass(
_airport_moving_data_dummy,
NULL,
NULL,
_airport_entries_dummy,
AirportFTAClass::ALL,
_airport_fta_dummy,
NULL,
0,
0, 0, 0,
0,
0
);
CountryAirport = new AirportFTAClass(
_airport_moving_data_country,
_airport_terminal_country,
NULL,
_airport_entries_country,
AirportFTAClass::ALL | AirportFTAClass::SHORT_STRIP,
_airport_fta_country,
_airport_depots_country,
lengthof(_airport_depots_country),
4, 3, 3,
0,
4
);
CityAirport = new AirportFTAClass(
_airport_moving_data_town,
_airport_terminal_city,
NULL,
_airport_entries_city,
AirportFTAClass::ALL,
_airport_fta_city,
_airport_depots_city,
lengthof(_airport_depots_city),
6, 6, 5,
0,
5
);
MetropolitanAirport = new AirportFTAClass(
_airport_moving_data_metropolitan,
_airport_terminal_metropolitan,
NULL,
_airport_entries_metropolitan,
AirportFTAClass::ALL,
_airport_fta_metropolitan,
_airport_depots_metropolitan,
lengthof(_airport_depots_metropolitan),
6, 6, 8,
0,
6
);
InternationalAirport = new AirportFTAClass(
_airport_moving_data_international,
_airport_terminal_international,
_airport_helipad_international,
_airport_entries_international,
AirportFTAClass::ALL,
_airport_fta_international,
_airport_depots_international,
lengthof(_airport_depots_international),
7, 7, 17,
0,
8
);
IntercontinentalAirport = new AirportFTAClass(
_airport_moving_data_intercontinental,
_airport_terminal_intercontinental,
_airport_helipad_intercontinental,
_airport_entries_intercontinental,
AirportFTAClass::ALL,
_airport_fta_intercontinental,
_airport_depots_intercontinental,
lengthof(_airport_depots_intercontinental),
9, 11, 25,
0,
10
);
Heliport = new AirportFTAClass(
_airport_moving_data_heliport,
NULL,
_airport_helipad_heliport_oilrig,
_airport_entries_heliport_oilrig,
AirportFTAClass::HELICOPTERS,
_airport_fta_heliport_oilrig,
NULL,
0,
1, 1, 1,
60,
4
);
Oilrig = new AirportFTAClass(
_airport_moving_data_oilrig,
NULL,
_airport_helipad_heliport_oilrig,
_airport_entries_heliport_oilrig,
AirportFTAClass::HELICOPTERS,
_airport_fta_heliport_oilrig,
NULL,
0,
1, 1, 0,
54,
3
);
CommuterAirport = new AirportFTAClass(
_airport_moving_data_commuter,
_airport_terminal_commuter,
_airport_helipad_commuter,
_airport_entries_commuter,
AirportFTAClass::ALL | AirportFTAClass::SHORT_STRIP,
_airport_fta_commuter,
_airport_depots_commuter,
lengthof(_airport_depots_commuter),
5, 4, 4,
0,
4
);
HeliDepot = new AirportFTAClass(
_airport_moving_data_helidepot,
NULL,
_airport_helipad_helidepot,
_airport_entries_helidepot,
AirportFTAClass::HELICOPTERS,
_airport_fta_helidepot,
_airport_depots_helidepot,
lengthof(_airport_depots_helidepot),
2, 2, 2,
0,
4
);
HeliStation = new AirportFTAClass(
_airport_moving_data_helistation,
NULL,
_airport_helipad_helistation,
_airport_entries_helistation,
AirportFTAClass::HELICOPTERS,
_airport_fta_helistation,
_airport_depots_helistation,
lengthof(_airport_depots_helistation),
4, 2, 3,
0,
4
);
}
void UnInitializeAirports()
{
delete DummyAirport;
delete CountryAirport;
delete CityAirport;
delete Heliport;
delete MetropolitanAirport;
delete InternationalAirport;
delete CommuterAirport;
delete HeliDepot;
delete IntercontinentalAirport;
delete HeliStation;
}
static uint16 AirportGetNofElements(const AirportFTAbuildup *apFA);
static AirportFTA *AirportBuildAutomata(uint nofelements, const AirportFTAbuildup *apFA);
static byte AirportGetTerminalCount(const byte *terminals, byte *groups);
static byte AirportTestFTA(uint nofelements, const AirportFTA *layout, const byte *terminals);
#ifdef DEBUG_AIRPORT
static void AirportPrintOut(uint nofelements, const AirportFTA *layout, bool full_report);
#endif
AirportFTAClass::AirportFTAClass(
const AirportMovingData *moving_data_,
const byte *terminals_,
const byte *helipads_,
const byte *entry_points_,
Flags flags_,
const AirportFTAbuildup *apFA,
const TileIndexDiffC *depots_,
const byte nof_depots_,
uint size_x_,
uint size_y_,
byte noise_level_,
byte delta_z_,
byte catchment_
) :
moving_data(moving_data_),
terminals(terminals_),
helipads(helipads_),
airport_depots(depots_),
flags(flags_),
nof_depots(nof_depots_),
nofelements(AirportGetNofElements(apFA)),
entry_points(entry_points_),
size_x(size_x_),
size_y(size_y_),
noise_level(noise_level_),
delta_z(delta_z_),
catchment(catchment_)
{
byte nofterminalgroups, nofhelipadgroups;
/* Set up the terminal and helipad count for an airport.
* TODO: If there are more than 10 terminals or 4 helipads, internal variables
* need to be changed, so don't allow that for now */
uint nofterminals = AirportGetTerminalCount(terminals, &nofterminalgroups);
if (nofterminals > MAX_TERMINALS) {
DEBUG(misc, 0, "[Ap] only a maximum of %d terminals are supported (requested %d)", MAX_TERMINALS, nofterminals);
assert(nofterminals <= MAX_TERMINALS);
}
uint nofhelipads = AirportGetTerminalCount(helipads, &nofhelipadgroups);
if (nofhelipads > MAX_HELIPADS) {
DEBUG(misc, 0, "[Ap] only a maximum of %d helipads are supported (requested %d)", MAX_HELIPADS, nofhelipads);
assert(nofhelipads <= MAX_HELIPADS);
}
/* Get the number of elements from the source table. We also double check this
* with the entry point which must be within bounds and use this information
* later on to build and validate the state machine */
for (DiagDirection i = DIAGDIR_BEGIN; i < DIAGDIR_END; i++) {
if (entry_points[i] >= nofelements) {
DEBUG(misc, 0, "[Ap] entry (%d) must be within the airport (maximum %d)", entry_points[i], nofelements);
assert(entry_points[i] < nofelements);
}
}
/* Build the state machine itself */
layout = AirportBuildAutomata(nofelements, apFA);
DEBUG(misc, 6, "[Ap] #count %3d; #term %2d (%dgrp); #helipad %2d (%dgrp); entries %3d, %3d, %3d, %3d",
nofelements, nofterminals, nofterminalgroups, nofhelipads, nofhelipadgroups,
entry_points[DIAGDIR_NE], entry_points[DIAGDIR_SE], entry_points[DIAGDIR_SW], entry_points[DIAGDIR_NW]);
/* Test if everything went allright. This is only a rude static test checking
* the symantic correctness. By no means does passing the test mean that the
* airport is working correctly or will not deadlock for example */
uint ret = AirportTestFTA(nofelements, layout, terminals);
if (ret != MAX_ELEMENTS) DEBUG(misc, 0, "[Ap] problem with element: %d", ret - 1);
assert(ret == MAX_ELEMENTS);
#ifdef DEBUG_AIRPORT
AirportPrintOut(nofelements, layout, DEBUG_AIRPORT);
#endif
}
AirportFTAClass::~AirportFTAClass()
{
for (uint i = 0; i < nofelements; i++) {
AirportFTA *current = layout[i].next;
while (current != NULL) {
AirportFTA *next = current->next;
free(current);
current = next;
};
}
free(layout);
}
/** Get the number of elements of a source Airport state automata
* Since it is actually just a big array of AirportFTA types, we only
* know one element from the other by differing 'position' identifiers */
static uint16 AirportGetNofElements(const AirportFTAbuildup *apFA)
{
uint16 nofelements = 0;
int temp = apFA[0].position;
for (uint i = 0; i < MAX_ELEMENTS; i++) {
if (temp != apFA[i].position) {
nofelements++;
temp = apFA[i].position;
}
if (apFA[i].position == MAX_ELEMENTS) break;
}
return nofelements;
}
/** We calculate the terminal/helipod count based on the data passed to us
* This data (terminals) contains an index as a first element as to how many
* groups there are, and then the number of terminals for each group */
static byte AirportGetTerminalCount(const byte *terminals, byte *groups)
{
byte nof_terminals = 0;
*groups = 0;
if (terminals != NULL) {
uint i = terminals[0];
*groups = i;
while (i-- > 0) {
terminals++;
assert(*terminals != 0); // no empty groups please
nof_terminals += *terminals;
}
}
return nof_terminals;
}
static AirportFTA *AirportBuildAutomata(uint nofelements, const AirportFTAbuildup *apFA)
{
AirportFTA *FAutomata = MallocT<AirportFTA>(nofelements);
uint16 internalcounter = 0;
for (uint i = 0; i < nofelements; i++) {
AirportFTA *current = &FAutomata[i];
current->position = apFA[internalcounter].position;
current->heading = apFA[internalcounter].heading;
current->block = apFA[internalcounter].block;
current->next_position = apFA[internalcounter].next;
/* outgoing nodes from the same position, create linked list */
while (current->position == apFA[internalcounter + 1].position) {
AirportFTA *newNode = MallocT<AirportFTA>(1);
newNode->position = apFA[internalcounter + 1].position;
newNode->heading = apFA[internalcounter + 1].heading;
newNode->block = apFA[internalcounter + 1].block;
newNode->next_position = apFA[internalcounter + 1].next;
/* create link */
current->next = newNode;
current = current->next;
internalcounter++;
}
current->next = NULL;
internalcounter++;
}
return FAutomata;
}
static byte AirportTestFTA(uint nofelements, const AirportFTA *layout, const byte *terminals)
{
uint next_position = 0;
for (uint i = 0; i < nofelements; i++) {
uint position = layout[i].position;
if (position != next_position) return i;
const AirportFTA *first = &layout[i];
for (const AirportFTA *current = first; current != NULL; current = current->next) {
/* A heading must always be valid. The only exceptions are
* - multiple choices as start, identified by a special value of 255
* - terminal group which is identified by a special value of 255 */
if (current->heading > MAX_HEADINGS) {
if (current->heading != 255) return i;
if (current == first && current->next == NULL) return i;
if (current != first && current->next_position > terminals[0]) return i;
}
/* If there is only one choice, it must be at the end */
if (current->heading == 0 && current->next != NULL) return i;
/* Obviously the elements of the linked list must have the same identifier */
if (position != current->position) return i;
/* A next position must be within bounds */
if (current->next_position >= nofelements) return i;
}
next_position++;
}
return MAX_ELEMENTS;
}
#ifdef DEBUG_AIRPORT
static const char * const _airport_heading_strings[] = {
"TO_ALL",
"HANGAR",
"TERM1",
"TERM2",
"TERM3",
"TERM4",
"TERM5",
"TERM6",
"HELIPAD1",
"HELIPAD2",
"TAKEOFF",
"STARTTAKEOFF",
"ENDTAKEOFF",
"HELITAKEOFF",
"FLYING",
"LANDING",
"ENDLANDING",
"HELILANDING",
"HELIENDLANDING",
"TERM7",
"TERM8",
"HELIPAD3",
"HELIPAD4",
"DUMMY" // extra heading for 255
};
static void AirportPrintOut(uint nofelements, const AirportFTA *layout, bool full_report)
{
if (!full_report) printf("(P = Current Position; NP = Next Position)\n");
for (uint i = 0; i < nofelements; i++) {
for (const AirportFTA *current = &layout[i]; current != NULL; current = current->next) {
if (full_report) {
byte heading = (current->heading == 255) ? MAX_HEADINGS + 1 : current->heading;
printf("\tPos:%2d NPos:%2d Heading:%15s Block:%2d\n", current->position,
current->next_position, _airport_heading_strings[heading],
FindLastBit(current->block));
} else {
printf("P:%2d NP:%2d", current->position, current->next_position);
}
}
printf("\n");
}
}
#endif
const AirportFTAClass *GetAirport(const byte airport_type)
{
/* FIXME -- AircraftNextAirportPos_and_Order -> Needs something nicer, don't like this code
* needs constant change if more airports are added */
switch (airport_type) {
default: NOT_REACHED();
case AT_SMALL: return CountryAirport;
case AT_LARGE: return CityAirport;
case AT_METROPOLITAN: return MetropolitanAirport;
case AT_HELIPORT: return Heliport;
case AT_OILRIG: return Oilrig;
case AT_INTERNATIONAL: return InternationalAirport;
case AT_COMMUTER: return CommuterAirport;
case AT_HELIDEPOT: return HeliDepot;
case AT_INTERCON: return IntercontinentalAirport;
case AT_HELISTATION: return HeliStation;
case AT_DUMMY: return DummyAirport;
}
}
uint32 GetValidAirports()
{
uint32 mask = 0;
if (_cur_year < 1960 || _settings_game.station.always_small_airport) SetBit(mask, 0); // small airport
if (_cur_year >= 1955) SetBit(mask, 1); // city airport
if (_cur_year >= 1963) SetBit(mask, 2); // heliport
if (_cur_year >= 1980) SetBit(mask, 3); // metropolitan airport
if (_cur_year >= 1990) SetBit(mask, 4); // international airport
if (_cur_year >= 1983) SetBit(mask, 5); // commuter airport
if (_cur_year >= 1976) SetBit(mask, 6); // helidepot
if (_cur_year >= 2002) SetBit(mask, 7); // intercontinental airport
if (_cur_year >= 1980) SetBit(mask, 8); // helistation
return mask;
}
| 13,942
|
C++
|
.cpp
| 438
| 29.246575
| 114
| 0.733591
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,145
|
town_cmd.cpp
|
EnergeticBark_OpenTTD-3DS/src/town_cmd.cpp
|
/* $Id$ */
/** @file town_cmd.cpp Handling of town tiles. */
#include "stdafx.h"
#include "openttd.h"
#include "road_type.h"
#include "road_internal.h" /* Cleaning up road bits */
#include "road_cmd.h"
#include "landscape.h"
#include "town_map.h"
#include "viewport_func.h"
#include "command_func.h"
#include "industry.h"
#include "station_base.h"
#include "company_base.h"
#include "news_func.h"
#include "gui.h"
#include "unmovable_map.h"
#include "water_map.h"
#include "variables.h"
#include "slope_func.h"
#include "genworld.h"
#include "newgrf.h"
#include "newgrf_house.h"
#include "newgrf_commons.h"
#include "newgrf_townname.h"
#include "newgrf_text.h"
#include "autoslope.h"
#include "waypoint.h"
#include "transparency.h"
#include "tunnelbridge_map.h"
#include "strings_func.h"
#include "window_func.h"
#include "string_func.h"
#include "newgrf_cargo.h"
#include "oldpool_func.h"
#include "economy_func.h"
#include "station_func.h"
#include "cheat_type.h"
#include "functions.h"
#include "animated_tile_func.h"
#include "date_func.h"
#include "core/smallmap_type.hpp"
#include "table/strings.h"
#include "table/town_land.h"
uint _total_towns;
HouseSpec _house_specs[HOUSE_MAX];
Town *_cleared_town;
int _cleared_town_rating;
uint32 _cur_town_ctr; ///< iterator through all towns in OnTick_Town
uint32 _cur_town_iter; ///< frequency iterator at the same place
/* Initialize the town-pool */
DEFINE_OLD_POOL_GENERIC(Town, Town)
Town::Town(TileIndex tile)
{
if (tile != INVALID_TILE) _total_towns++;
this->xy = tile;
}
Town::~Town()
{
free(this->name);
if (CleaningPool()) return;
Industry *i;
/* Delete town authority window
* and remove from list of sorted towns */
DeleteWindowById(WC_TOWN_VIEW, this->index);
InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
_total_towns--;
/* Delete all industries belonging to the town */
FOR_ALL_INDUSTRIES(i) if (i->town == this) delete i;
/* Go through all tiles and delete those belonging to the town */
for (TileIndex tile = 0; tile < MapSize(); ++tile) {
switch (GetTileType(tile)) {
case MP_HOUSE:
if (GetTownByTile(tile) == this) DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
break;
case MP_ROAD:
/* Cached nearest town is updated later (after this town has been deleted) */
if (HasTownOwnedRoad(tile) && GetTownIndex(tile) == this->index) {
DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
}
break;
case MP_TUNNELBRIDGE:
if (IsTileOwner(tile, OWNER_TOWN) &&
ClosestTownFromTile(tile, UINT_MAX) == this)
DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
break;
default:
break;
}
}
DeleteSubsidyWithTown(this->index);
MarkWholeScreenDirty();
this->xy = INVALID_TILE;
UpdateNearestTownForRoadTiles(false);
}
/**
* Assigns town layout. If Random, generates one based on TileHash.
*/
void Town::InitializeLayout(TownLayout layout)
{
if (layout != TL_RANDOM) {
this->layout = layout;
return;
}
this->layout = TileHash(TileX(this->xy), TileY(this->xy)) % (NUM_TLS - 1);
}
Money HouseSpec::GetRemovalCost() const
{
return (_price.remove_house * this->removal_cost) >> 8;
}
// Local
static int _grow_town_result;
/* Describe the possible states */
enum TownGrowthResult {
GROWTH_SUCCEED = -1,
GROWTH_SEARCH_STOPPED = 0
// GROWTH_SEARCH_RUNNING >= 1
};
static bool BuildTownHouse(Town *t, TileIndex tile);
static void TownDrawHouseLift(const TileInfo *ti)
{
AddChildSpriteScreen(SPR_LIFT, PAL_NONE, 14, 60 - GetLiftPosition(ti->tile));
}
typedef void TownDrawTileProc(const TileInfo *ti);
static TownDrawTileProc * const _town_draw_tile_procs[1] = {
TownDrawHouseLift
};
/**
* Return a random direction
*
* @return a random direction
*/
static inline DiagDirection RandomDiagDir()
{
return (DiagDirection)(3 & Random());
}
/**
* House Tile drawing handler.
* Part of the tile loop process
* @param ti TileInfo of the tile to draw
*/
static void DrawTile_Town(TileInfo *ti)
{
HouseID house_id = GetHouseType(ti->tile);
if (house_id >= NEW_HOUSE_OFFSET) {
/* Houses don't necessarily need new graphics. If they don't have a
* spritegroup associated with them, then the sprite for the substitute
* house id is drawn instead. */
if (GetHouseSpecs(house_id)->spritegroup != NULL) {
DrawNewHouseTile(ti, house_id);
return;
} else {
house_id = GetHouseSpecs(house_id)->substitute_id;
}
}
/* Retrieve pointer to the draw town tile struct */
const DrawBuildingsTileStruct *dcts = &_town_draw_tile_data[house_id << 4 | TileHash2Bit(ti->x, ti->y) << 2 | GetHouseBuildingStage(ti->tile)];
if (ti->tileh != SLOPE_FLAT) DrawFoundation(ti, FOUNDATION_LEVELED);
DrawGroundSprite(dcts->ground.sprite, dcts->ground.pal);
/* If houses are invisible, do not draw the upper part */
if (IsInvisibilitySet(TO_HOUSES)) return;
/* Add a house on top of the ground? */
SpriteID image = dcts->building.sprite;
if (image != 0) {
AddSortableSpriteToDraw(image, dcts->building.pal,
ti->x + dcts->subtile_x,
ti->y + dcts->subtile_y,
dcts->width,
dcts->height,
dcts->dz,
ti->z,
IsTransparencySet(TO_HOUSES)
);
if (IsTransparencySet(TO_HOUSES)) return;
}
{
int proc = dcts->draw_proc - 1;
if (proc >= 0) _town_draw_tile_procs[proc](ti);
}
}
static uint GetSlopeZ_Town(TileIndex tile, uint x, uint y)
{
return GetTileMaxZ(tile);
}
/** Tile callback routine */
static Foundation GetFoundation_Town(TileIndex tile, Slope tileh)
{
return FlatteningFoundation(tileh);
}
/**
* Animate a tile for a town
* Only certain houses can be animated
* The newhouses animation superseeds regular ones
* @param tile TileIndex of the house to animate
*/
static void AnimateTile_Town(TileIndex tile)
{
if (GetHouseType(tile) >= NEW_HOUSE_OFFSET) {
AnimateNewHouseTile(tile);
return;
}
if (_tick_counter & 3) return;
/* If the house is not one with a lift anymore, then stop this animating.
* Not exactly sure when this happens, but probably when a house changes.
* Before this was just a return...so it'd leak animated tiles..
* That bug seems to have been here since day 1?? */
if (!(GetHouseSpecs(GetHouseType(tile))->building_flags & BUILDING_IS_ANIMATED)) {
DeleteAnimatedTile(tile);
return;
}
if (!LiftHasDestination(tile)) {
uint i;
/* Building has 6 floors, number 0 .. 6, where 1 is illegal.
* This is due to the fact that the first floor is, in the graphics,
* the height of 2 'normal' floors.
* Furthermore, there are 6 lift positions from floor N (incl) to floor N + 1 (excl) */
do {
i = RandomRange(7);
} while (i == 1 || i * 6 == GetLiftPosition(tile));
SetLiftDestination(tile, i);
}
int pos = GetLiftPosition(tile);
int dest = GetLiftDestination(tile) * 6;
pos += (pos < dest) ? 1 : -1;
SetLiftPosition(tile, pos);
if (pos == dest) {
HaltLift(tile);
DeleteAnimatedTile(tile);
}
MarkTileDirtyByTile(tile);
}
/**
* Determines if a town is close to a tile
* @param tile TileIndex of the tile to query
* @param dist maximum distance to be accepted
* @returns true if the tile correspond to the distance criteria
*/
static bool IsCloseToTown(TileIndex tile, uint dist)
{
const Town *t;
FOR_ALL_TOWNS(t) {
if (DistanceManhattan(tile, t->xy) < dist) return true;
}
return false;
}
/**
* Marks the town sign as needing a repaint.
*
* This function marks the area of the sign of a town as dirty for repaint.
*
* @param t Town requesting town sign for repaint
* @ingroup dirty
*/
static void MarkTownSignDirty(Town *t)
{
MarkAllViewportsDirty(
t->sign.left - 6,
t->sign.top - 3,
t->sign.left + t->sign.width_1 * 4 + 12,
t->sign.top + 45
);
}
/**
* Resize the sign(label) of the town after changes in
* population (creation or growth or else)
* @param t Town to update
*/
void UpdateTownVirtCoord(Town *t)
{
MarkTownSignDirty(t);
Point pt = RemapCoords2(TileX(t->xy) * TILE_SIZE, TileY(t->xy) * TILE_SIZE);
SetDParam(0, t->index);
SetDParam(1, t->population);
UpdateViewportSignPos(&t->sign, pt.x, pt.y - 24,
_settings_client.gui.population_in_label ? STR_TOWN_LABEL_POP : STR_TOWN_LABEL);
MarkTownSignDirty(t);
}
/** Update the virtual coords needed to draw the town sign for all towns. */
void UpdateAllTownVirtCoords()
{
Town *t;
FOR_ALL_TOWNS(t) {
UpdateTownVirtCoord(t);
}
}
/**
* Change the towns population
* @param t Town which polulation has changed
* @param mod polulation change (can be positive or negative)
*/
static void ChangePopulation(Town *t, int mod)
{
t->population += mod;
InvalidateWindow(WC_TOWN_VIEW, t->index);
UpdateTownVirtCoord(t);
InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
}
/**
* Determines the world population
* Basically, count population of all towns, one by one
* @return uint32 the calculated population of the world
*/
uint32 GetWorldPopulation()
{
uint32 pop = 0;
const Town *t;
FOR_ALL_TOWNS(t) pop += t->population;
return pop;
}
/**
* Helper function for house completion stages progression
* @param tile TileIndex of the house (or parts of it) to "grow"
*/
static void MakeSingleHouseBigger(TileIndex tile)
{
assert(IsTileType(tile, MP_HOUSE));
/* means it is completed, get out. */
if (LiftHasDestination(tile)) return;
/* progress in construction stages */
IncHouseConstructionTick(tile);
if (GetHouseConstructionTick(tile) != 0) return;
const HouseSpec *hs = GetHouseSpecs(GetHouseType(tile));
/* Check and/or */
if (HasBit(hs->callback_mask, CBM_HOUSE_CONSTRUCTION_STATE_CHANGE)) {
uint16 callback_res = GetHouseCallback(CBID_HOUSE_CONSTRUCTION_STATE_CHANGE, 0, 0, GetHouseType(tile), GetTownByTile(tile), tile);
if (callback_res != CALLBACK_FAILED) ChangeHouseAnimationFrame(hs->grffile, tile, callback_res);
}
if (IsHouseCompleted(tile)) {
/* Now that construction is complete, we can add the population of the
* building to the town. */
ChangePopulation(GetTownByTile(tile), hs->population);
ResetHouseAge(tile);
}
MarkTileDirtyByTile(tile);
}
/** Make the house advance in its construction stages until completion
* @param tile TileIndex of house
*/
static void MakeTownHouseBigger(TileIndex tile)
{
uint flags = GetHouseSpecs(GetHouseType(tile))->building_flags;
if (flags & BUILDING_HAS_1_TILE) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 0));
if (flags & BUILDING_2_TILES_Y) MakeSingleHouseBigger(TILE_ADDXY(tile, 0, 1));
if (flags & BUILDING_2_TILES_X) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 0));
if (flags & BUILDING_HAS_4_TILES) MakeSingleHouseBigger(TILE_ADDXY(tile, 1, 1));
}
/**
* Tile callback function.
*
* Periodic tic handler for houses and town
* @param tile been asked to do its stuff
*/
static void TileLoop_Town(TileIndex tile)
{
HouseID house_id = GetHouseType(tile);
/* NewHouseTileLoop returns false if Callback 21 succeeded, i.e. the house
* doesn't exist any more, so don't continue here. */
if (house_id >= NEW_HOUSE_OFFSET && !NewHouseTileLoop(tile)) return;
if (!IsHouseCompleted(tile)) {
/* Construction is not completed. See if we can go further in construction*/
MakeTownHouseBigger(tile);
return;
}
const HouseSpec *hs = GetHouseSpecs(house_id);
/* If the lift has a destination, it is already an animated tile. */
if ((hs->building_flags & BUILDING_IS_ANIMATED) &&
house_id < NEW_HOUSE_OFFSET &&
!LiftHasDestination(tile) &&
Chance16(1, 2)) {
AddAnimatedTile(tile);
}
Town *t = GetTownByTile(tile);
uint32 r = Random();
if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
for (uint i = 0; i < 256; i++) {
uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, r, house_id, t, tile);
if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grffile);
if (cargo == CT_INVALID) continue;
uint amt = GB(callback, 0, 8);
uint moved = MoveGoodsToStation(tile, 1, 1, cargo, amt);
const CargoSpec *cs = GetCargo(cargo);
switch (cs->town_effect) {
case TE_PASSENGERS:
t->new_max_pass += amt;
t->new_act_pass += moved;
break;
case TE_MAIL:
t->new_max_mail += amt;
t->new_act_mail += moved;
break;
default:
break;
}
}
} else {
if (GB(r, 0, 8) < hs->population) {
uint amt = GB(r, 0, 8) / 8 + 1;
if (_economy.fluct <= 0) amt = (amt + 1) >> 1;
t->new_max_pass += amt;
t->new_act_pass += MoveGoodsToStation(tile, 1, 1, CT_PASSENGERS, amt);
}
if (GB(r, 8, 8) < hs->mail_generation) {
uint amt = GB(r, 8, 8) / 8 + 1;
if (_economy.fluct <= 0) amt = (amt + 1) >> 1;
t->new_max_mail += amt;
t->new_act_mail += MoveGoodsToStation(tile, 1, 1, CT_MAIL, amt);
}
}
_current_company = OWNER_TOWN;
if (hs->building_flags & BUILDING_HAS_1_TILE &&
HasBit(t->flags12, TOWN_IS_FUNDED) &&
CanDeleteHouse(tile) &&
GetHouseAge(tile) >= hs->minimum_life &&
--t->time_until_rebuild == 0) {
t->time_until_rebuild = GB(r, 16, 8) + 192;
ClearTownHouse(t, tile);
/* Rebuild with another house? */
if (GB(r, 24, 8) >= 12) BuildTownHouse(t, tile);
}
_current_company = OWNER_NONE;
}
/**
* Dummy tile callback function for handling tile clicks in towns
* @param tile unused
*/
static bool ClickTile_Town(TileIndex tile)
{
/* not used */
return false;
}
static CommandCost ClearTile_Town(TileIndex tile, DoCommandFlag flags)
{
if (flags & DC_AUTO) return_cmd_error(STR_2004_BUILDING_MUST_BE_DEMOLISHED);
if (!CanDeleteHouse(tile)) return CMD_ERROR;
const HouseSpec *hs = GetHouseSpecs(GetHouseType(tile));
CommandCost cost(EXPENSES_CONSTRUCTION);
cost.AddCost(hs->GetRemovalCost());
int rating = hs->remove_rating_decrease;
_cleared_town_rating += rating;
Town *t = _cleared_town = GetTownByTile(tile);
if (IsValidCompanyID(_current_company)) {
if (rating > t->ratings[_current_company] && !(flags & DC_NO_TEST_TOWN_RATING) && !_cheats.magic_bulldozer.value) {
SetDParam(0, t->index);
return_cmd_error(STR_2009_LOCAL_AUTHORITY_REFUSES);
}
}
ChangeTownRating(t, -rating, RATING_HOUSE_MINIMUM, flags);
if (flags & DC_EXEC) {
ClearTownHouse(t, tile);
}
return cost;
}
static void GetProducedCargo_Town(TileIndex tile, CargoID *b)
{
HouseID house_id = GetHouseType(tile);
const HouseSpec *hs = GetHouseSpecs(house_id);
Town *t = GetTownByTile(tile);
if (HasBit(hs->callback_mask, CBM_HOUSE_PRODUCE_CARGO)) {
for (uint i = 0; i < 256; i++) {
uint16 callback = GetHouseCallback(CBID_HOUSE_PRODUCE_CARGO, i, 0, house_id, t, tile);
if (callback == CALLBACK_FAILED || callback == CALLBACK_HOUSEPRODCARGO_END) break;
CargoID cargo = GetCargoTranslation(GB(callback, 8, 7), hs->grffile);
if (cargo == CT_INVALID) continue;
*(b++) = cargo;
}
} else {
if (hs->population > 0) {
*(b++) = CT_PASSENGERS;
}
if (hs->mail_generation > 0) {
*(b++) = CT_MAIL;
}
}
}
static void GetAcceptedCargo_Town(TileIndex tile, AcceptedCargo ac)
{
const HouseSpec *hs = GetHouseSpecs(GetHouseType(tile));
CargoID accepts[3];
/* Set the initial accepted cargo types */
for (uint8 i = 0; i < lengthof(accepts); i++) {
accepts[i] = hs->accepts_cargo[i];
}
/* Check for custom accepted cargo types */
if (HasBit(hs->callback_mask, CBM_HOUSE_ACCEPT_CARGO)) {
uint16 callback = GetHouseCallback(CBID_HOUSE_ACCEPT_CARGO, 0, 0, GetHouseType(tile), GetTownByTile(tile), tile);
if (callback != CALLBACK_FAILED) {
/* Replace accepted cargo types with translated values from callback */
accepts[0] = GetCargoTranslation(GB(callback, 0, 5), hs->grffile);
accepts[1] = GetCargoTranslation(GB(callback, 5, 5), hs->grffile);
accepts[2] = GetCargoTranslation(GB(callback, 10, 5), hs->grffile);
}
}
/* Check for custom cargo acceptance */
if (HasBit(hs->callback_mask, CBM_HOUSE_CARGO_ACCEPTANCE)) {
uint16 callback = GetHouseCallback(CBID_HOUSE_CARGO_ACCEPTANCE, 0, 0, GetHouseType(tile), GetTownByTile(tile), tile);
if (callback != CALLBACK_FAILED) {
if (accepts[0] != CT_INVALID) ac[accepts[0]] = GB(callback, 0, 4);
if (accepts[1] != CT_INVALID) ac[accepts[1]] = GB(callback, 4, 4);
if (_settings_game.game_creation.landscape != LT_TEMPERATE && HasBit(callback, 12)) {
/* The 'S' bit indicates food instead of goods */
ac[CT_FOOD] = GB(callback, 8, 4);
} else {
if (accepts[2] != CT_INVALID) ac[accepts[2]] = GB(callback, 8, 4);
}
return;
}
}
/* No custom acceptance, so fill in with the default values */
for (uint8 i = 0; i < lengthof(accepts); i++) {
if (accepts[i] != CT_INVALID) ac[accepts[i]] = hs->cargo_acceptance[i];
}
}
static void GetTileDesc_Town(TileIndex tile, TileDesc *td)
{
const HouseID house = GetHouseType(tile);
const HouseSpec *hs = GetHouseSpecs(house);
bool house_completed = IsHouseCompleted(tile);
td->str = hs->building_name;
uint16 callback_res = GetHouseCallback(CBID_HOUSE_CUSTOM_NAME, house_completed ? 1 : 0, 0, house, GetTownByTile(tile), tile);
if (callback_res != CALLBACK_FAILED) {
StringID new_name = GetGRFStringID(hs->grffile->grfid, 0xD000 + callback_res);
if (new_name != STR_NULL && new_name != STR_UNDEFINED) {
td->str = new_name;
}
}
if (!house_completed) {
SetDParamX(td->dparam, 0, td->str);
td->str = STR_2058_UNDER_CONSTRUCTION;
}
if (hs->grffile != NULL) {
const GRFConfig *gc = GetGRFConfig(hs->grffile->grfid);
td->grf = gc->name;
}
td->owner[0] = OWNER_TOWN;
}
static TrackStatus GetTileTrackStatus_Town(TileIndex tile, TransportType mode, uint sub_mode, DiagDirection side)
{
/* not used */
return 0;
}
static void ChangeTileOwner_Town(TileIndex tile, Owner old_owner, Owner new_owner)
{
/* not used */
}
static bool GrowTown(Town *t);
static void TownTickHandler(Town *t)
{
if (HasBit(t->flags12, TOWN_IS_FUNDED)) {
int i = t->grow_counter - 1;
if (i < 0) {
if (GrowTown(t)) {
i = t->growth_rate;
} else {
i = 0;
}
}
t->grow_counter = i;
}
UpdateTownRadius(t);
}
void OnTick_Town()
{
if (_game_mode == GM_EDITOR) return;
/* Make sure each town's tickhandler invocation frequency is about the
* same - TOWN_GROWTH_FREQUENCY - independent on the number of towns. */
for (_cur_town_iter += GetMaxTownIndex() + 1;
_cur_town_iter >= TOWN_GROWTH_FREQUENCY;
_cur_town_iter -= TOWN_GROWTH_FREQUENCY) {
uint32 i = _cur_town_ctr;
if (++_cur_town_ctr > GetMaxTownIndex())
_cur_town_ctr = 0;
if (IsValidTownID(i)) TownTickHandler(GetTown(i));
}
}
/**
* Return the RoadBits of a tile
*
* @note There are many other functions doing things like that.
* @note Needs to be checked for needlessness.
* @param tile The tile we want to analyse
* @return The roadbits of the given tile
*/
static RoadBits GetTownRoadBits(TileIndex tile)
{
TrackBits b = GetAnyRoadTrackBits(tile, ROADTYPE_ROAD);
RoadBits r = ROAD_NONE;
if (b == TRACK_BIT_NONE) return r;
if (b & TRACK_BIT_X) r |= ROAD_X;
if (b & TRACK_BIT_Y) r |= ROAD_Y;
if (b & TRACK_BIT_UPPER) r |= ROAD_NE | ROAD_NW;
if (b & TRACK_BIT_LOWER) r |= ROAD_SE | ROAD_SW;
if (b & TRACK_BIT_LEFT) r |= ROAD_NW | ROAD_SW;
if (b & TRACK_BIT_RIGHT) r |= ROAD_NE | ROAD_SE;
return r;
}
/**
* Check for parallel road inside a given distance.
* Assuming a road from (tile - TileOffsByDiagDir(dir)) to tile,
* is there a parallel road left or right of it within distance dist_multi?
*
* @param tile curent tile
* @param dir target direction
* @param dist_multi distance multiplyer
* @return true if there is a parallel road
*/
static bool IsNeighborRoadTile(TileIndex tile, const DiagDirection dir, uint dist_multi)
{
if (!IsValidTile(tile)) return false;
/* Lookup table for the used diff values */
const TileIndexDiff tid_lt[3] = {
TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90RIGHT)),
TileOffsByDiagDir(ChangeDiagDir(dir, DIAGDIRDIFF_90LEFT)),
TileOffsByDiagDir(ReverseDiagDir(dir)),
};
dist_multi = (dist_multi + 1) * 4;
for (uint pos = 4; pos < dist_multi; pos++) {
/* Go (pos / 4) tiles to the left or the right */
TileIndexDiff cur = tid_lt[(pos & 1) ? 0 : 1] * (pos / 4);
/* Use the current tile as origin, or go one tile backwards */
if (pos & 2) cur += tid_lt[2];
/* Test for roadbit parallel to dir and facing towards the middle axis */
if (IsValidTile(tile + cur) &&
GetTownRoadBits(TILE_ADD(tile, cur)) & DiagDirToRoadBits((pos & 2) ? dir : ReverseDiagDir(dir))) return true;
}
return false;
}
/**
* Check if a Road is allowed on a given tile
*
* @param t The current town
* @param tile The target tile
* @param dir The direction in which we want to extend the town
* @return true if it is allowed else false
*/
static bool IsRoadAllowedHere(Town *t, TileIndex tile, DiagDirection dir)
{
if (TileX(tile) < 2 || TileX(tile) >= MapMaxX() || TileY(tile) < 2 || TileY(tile) >= MapMaxY()) return false;
Slope cur_slope, desired_slope;
for (;;) {
/* Check if there already is a road at this point? */
if (GetTownRoadBits(tile) == ROAD_NONE) {
/* No, try if we are able to build a road piece there.
* If that fails clear the land, and if that fails exit.
* This is to make sure that we can build a road here later. */
if (CmdFailed(DoCommand(tile, ((dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? ROAD_X : ROAD_Y), 0, DC_AUTO, CMD_BUILD_ROAD)) &&
CmdFailed(DoCommand(tile, 0, 0, DC_AUTO, CMD_LANDSCAPE_CLEAR)))
return false;
}
cur_slope = _settings_game.construction.build_on_slopes ? GetFoundationSlope(tile, NULL) : GetTileSlope(tile, NULL);
if (cur_slope == SLOPE_FLAT) {
no_slope:
/* Tile has no slope */
switch (t->layout) {
default: NOT_REACHED();
case TL_ORIGINAL: // Disallow the road if any neighboring tile has a road (distance: 1)
return !IsNeighborRoadTile(tile, dir, 1);
case TL_BETTER_ROADS: // Disallow the road if any neighboring tile has a road (distance: 1 and 2).
return !IsNeighborRoadTile(tile, dir, 2);
}
}
/* If the tile is not a slope in the right direction, then
* maybe terraform some. */
desired_slope = (dir == DIAGDIR_NW || dir == DIAGDIR_SE) ? SLOPE_NW : SLOPE_NE;
if (desired_slope != cur_slope && ComplementSlope(desired_slope) != cur_slope) {
if (Chance16(1, 8)) {
CommandCost res = CMD_ERROR;
if (!_generating_world && Chance16(1, 10)) {
/* Note: Do not replace "^ SLOPE_ELEVATED" with ComplementSlope(). The slope might be steep. */
res = DoCommand(tile, Chance16(1, 16) ? cur_slope : cur_slope ^ SLOPE_ELEVATED, 0,
DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
}
if (CmdFailed(res) && Chance16(1, 3)) {
/* We can consider building on the slope, though. */
goto no_slope;
}
}
return false;
}
return true;
}
}
static bool TerraformTownTile(TileIndex tile, int edges, int dir)
{
assert(tile < MapSize());
CommandCost r = DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER, CMD_TERRAFORM_LAND);
if (CmdFailed(r) || r.GetCost() >= (_price.terraform + 2) * 8) return false;
DoCommand(tile, edges, dir, DC_AUTO | DC_NO_WATER | DC_EXEC, CMD_TERRAFORM_LAND);
return true;
}
static void LevelTownLand(TileIndex tile)
{
assert(tile < MapSize());
/* Don't terraform if land is plain or if there's a house there. */
if (IsTileType(tile, MP_HOUSE)) return;
Slope tileh = GetTileSlope(tile, NULL);
if (tileh == SLOPE_FLAT) return;
/* First try up, then down */
if (!TerraformTownTile(tile, ~tileh & SLOPE_ELEVATED, 1)) {
TerraformTownTile(tile, tileh & SLOPE_ELEVATED, 0);
}
}
/**
* Generate the RoadBits of a grid tile
*
* @param t current town
* @param tile tile in reference to the town
* @param dir The direction to which we are growing ATM
* @return the RoadBit of the current tile regarding
* the selected town layout
*/
static RoadBits GetTownRoadGridElement(Town *t, TileIndex tile, DiagDirection dir)
{
/* align the grid to the downtown */
TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile); // Vector from downtown to the tile
RoadBits rcmd = ROAD_NONE;
switch (t->layout) {
default: NOT_REACHED();
case TL_2X2_GRID:
if ((grid_pos.x % 3) == 0) rcmd |= ROAD_Y;
if ((grid_pos.y % 3) == 0) rcmd |= ROAD_X;
break;
case TL_3X3_GRID:
if ((grid_pos.x % 4) == 0) rcmd |= ROAD_Y;
if ((grid_pos.y % 4) == 0) rcmd |= ROAD_X;
break;
}
/* Optimise only X-junctions */
if (rcmd != ROAD_ALL) return rcmd;
RoadBits rb_template;
switch (GetTileSlope(tile, NULL)) {
default: rb_template = ROAD_ALL; break;
case SLOPE_W: rb_template = ROAD_NW | ROAD_SW; break;
case SLOPE_SW: rb_template = ROAD_Y | ROAD_SW; break;
case SLOPE_S: rb_template = ROAD_SW | ROAD_SE; break;
case SLOPE_SE: rb_template = ROAD_X | ROAD_SE; break;
case SLOPE_E: rb_template = ROAD_SE | ROAD_NE; break;
case SLOPE_NE: rb_template = ROAD_Y | ROAD_NE; break;
case SLOPE_N: rb_template = ROAD_NE | ROAD_NW; break;
case SLOPE_NW: rb_template = ROAD_X | ROAD_NW; break;
case SLOPE_STEEP_W:
case SLOPE_STEEP_S:
case SLOPE_STEEP_E:
case SLOPE_STEEP_N:
rb_template = ROAD_NONE;
break;
}
/* Stop if the template is compatible to the growth dir */
if (DiagDirToRoadBits(ReverseDiagDir(dir)) & rb_template) return rb_template;
/* If not generate a straight road in the direction of the growth */
return DiagDirToRoadBits(dir) | DiagDirToRoadBits(ReverseDiagDir(dir));
}
/**
* Grows the town with an extra house.
* Check if there are enough neighbor house tiles
* next to the current tile. If there are enough
* add another house.
*
* @param t The current town
* @param tile The target tile for the extra house
* @return true if an extra house has been added
*/
static bool GrowTownWithExtraHouse(Town *t, TileIndex tile)
{
/* We can't look further than that. */
if (TileX(tile) < 2 || TileY(tile) < 2 || MapMaxX() <= TileX(tile) || MapMaxY() <= TileY(tile)) return false;
uint counter = 0; // counts the house neighbor tiles
/* Check the tiles E,N,W and S of the current tile for houses */
for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
if (IsTileType(TileAddByDiagDir(tile, dir), MP_HOUSE)) counter++;
/* If there are enough neighbors stop here */
if (counter >= 3) {
if (BuildTownHouse(t, tile)) {
_grow_town_result = GROWTH_SUCCEED;
return true;
}
return false;
}
}
return false;
}
/**
* Grows the town with a road piece.
*
* @param t The current town
* @param tile The current tile
* @param rcmd The RoadBits we want to build on the tile
* @return true if the RoadBits have been added else false
*/
static bool GrowTownWithRoad(const Town *t, TileIndex tile, RoadBits rcmd)
{
if (CmdSucceeded(DoCommand(tile, rcmd, t->index, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_BUILD_ROAD))) {
_grow_town_result = GROWTH_SUCCEED;
return true;
}
return false;
}
/**
* Grows the town with a bridge.
* At first we check if a bridge is reasonable.
* If so we check if we are able to build it.
*
* @param t The current town
* @param tile The current tile
* @param bridge_dir The valid direction in which to grow a bridge
* @return true if a bridge has been build else false
*/
static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDirection bridge_dir)
{
assert(bridge_dir < DIAGDIR_END);
const Slope slope = GetTileSlope(tile, NULL);
if (slope == SLOPE_FLAT) return false; // no slope, no bridge
/* Make sure the direction is compatible with the slope.
* Well we check if the slope has an up bit set in the
* reverse direction. */
if (HASBITS(slope, InclinedSlope(bridge_dir))) return false;
/* Assure that the bridge is connectable to the start side */
if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false;
/* We are in the right direction */
uint8 bridge_length = 0; // This value stores the length of the possible bridge
TileIndex bridge_tile = tile; // Used to store the other waterside
const int delta = TileOffsByDiagDir(bridge_dir);
do {
if (bridge_length++ >= 11) {
/* Max 11 tile long bridges */
return false;
}
bridge_tile += delta;
} while (TileX(bridge_tile) != 0 && TileY(bridge_tile) != 0 && IsWaterTile(bridge_tile));
/* no water tiles in between? */
if (bridge_length == 1) return false;
for (uint8 times = 0; times <= 22; times++) {
byte bridge_type = RandomRange(MAX_BRIDGES - 1);
/* Can we actually build the bridge? */
if (CmdSucceeded(DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_AUTO, CMD_BUILD_BRIDGE))) {
DoCommand(tile, bridge_tile, bridge_type | ROADTYPES_ROAD << 8 | TRANSPORT_ROAD << 15, DC_EXEC | DC_AUTO, CMD_BUILD_BRIDGE);
_grow_town_result = GROWTH_SUCCEED;
return true;
}
}
/* Quit if it selecting an appropiate bridge type fails a large number of times. */
return false;
}
/**
* Grows the given town.
* There are at the moment 3 possible way's for
* the town expansion:
* @li Generate a random tile and check if there is a road allowed
* @li TL_ORIGINAL
* @li TL_BETTER_ROADS
* @li Check if the town geometry allows a road and which one
* @li TL_2X2_GRID
* @li TL_3X3_GRID
* @li Forbid roads, only build houses
*
* @param tile_ptr The current tile
* @param cur_rb The current tiles RoadBits
* @param target_dir The target road dir
* @param t1 The current town
*/
static void GrowTownInTile(TileIndex *tile_ptr, RoadBits cur_rb, DiagDirection target_dir, Town *t1)
{
RoadBits rcmd = ROAD_NONE; // RoadBits for the road construction command
TileIndex tile = *tile_ptr; // The main tile on which we base our growth
assert(tile < MapSize());
if (cur_rb == ROAD_NONE) {
/* Tile has no road. First reset the status counter
* to say that this is the last iteration. */
_grow_town_result = GROWTH_SEARCH_STOPPED;
if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
/* Remove hills etc */
if (!_settings_game.construction.build_on_slopes || Chance16(1, 6)) LevelTownLand(tile);
/* Is a road allowed here? */
switch (t1->layout) {
default: NOT_REACHED();
case TL_3X3_GRID:
case TL_2X2_GRID:
rcmd = GetTownRoadGridElement(t1, tile, target_dir);
if (rcmd == ROAD_NONE) return;
break;
case TL_BETTER_ROADS:
case TL_ORIGINAL:
if (!IsRoadAllowedHere(t1, tile, target_dir)) return;
DiagDirection source_dir = ReverseDiagDir(target_dir);
if (Chance16(1, 4)) {
/* Randomize a new target dir */
do target_dir = RandomDiagDir(); while (target_dir == source_dir);
}
if (!IsRoadAllowedHere(t1, TileAddByDiagDir(tile, target_dir), target_dir)) {
/* A road is not allowed to continue the randomized road,
* return if the road we're trying to build is curved. */
if (target_dir != ReverseDiagDir(source_dir)) return;
/* Return if neither side of the new road is a house */
if (!IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90RIGHT)), MP_HOUSE) &&
!IsTileType(TileAddByDiagDir(tile, ChangeDiagDir(target_dir, DIAGDIRDIFF_90LEFT)), MP_HOUSE)) {
return;
}
/* That means that the road is only allowed if there is a house
* at any side of the new road. */
}
rcmd = DiagDirToRoadBits(target_dir) | DiagDirToRoadBits(source_dir);
break;
}
} else if (target_dir < DIAGDIR_END && !(cur_rb & DiagDirToRoadBits(ReverseDiagDir(target_dir)))) {
/* Continue building on a partial road.
* Should be allways OK, so we only generate
* the fitting RoadBits */
_grow_town_result = GROWTH_SEARCH_STOPPED;
if (!_settings_game.economy.allow_town_roads && !_generating_world) return;
switch (t1->layout) {
default: NOT_REACHED();
case TL_3X3_GRID:
case TL_2X2_GRID:
rcmd = GetTownRoadGridElement(t1, tile, target_dir);
break;
case TL_BETTER_ROADS:
case TL_ORIGINAL:
rcmd = DiagDirToRoadBits(ReverseDiagDir(target_dir));
break;
}
} else {
bool allow_house = true; // Value which decides if we want to construct a house
/* Reached a tunnel/bridge? Then continue at the other side of it. */
if (IsTileType(tile, MP_TUNNELBRIDGE)) {
if (GetTunnelBridgeTransportType(tile) == TRANSPORT_ROAD) {
*tile_ptr = GetOtherTunnelBridgeEnd(tile);
}
return;
}
/* Possibly extend the road in a direction.
* Randomize a direction and if it has a road, bail out. */
target_dir = RandomDiagDir();
if (cur_rb & DiagDirToRoadBits(target_dir)) return;
/* This is the tile we will reach if we extend to this direction. */
TileIndex house_tile = TileAddByDiagDir(tile, target_dir); // position of a possible house
/* Don't walk into water. */
if (IsWaterTile(house_tile)) return;
if (!IsValidTile(house_tile) || !IsValidTile(house_tile + TileOffsByDiagDir(target_dir))) return;
if (_settings_game.economy.allow_town_roads || _generating_world) {
switch (t1->layout) {
default: NOT_REACHED();
case TL_3X3_GRID: // Use 2x2 grid afterwards!
GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
/* FALL THROUGH */
case TL_2X2_GRID:
rcmd = GetTownRoadGridElement(t1, house_tile, target_dir);
allow_house = (rcmd == ROAD_NONE);
break;
case TL_BETTER_ROADS: // Use original afterwards!
GrowTownWithExtraHouse(t1, TileAddByDiagDir(house_tile, target_dir));
/* FALL THROUGH */
case TL_ORIGINAL:
/* Allow a house at the edge. 60% chance or
* always ok if no road allowed. */
rcmd = DiagDirToRoadBits(target_dir);
allow_house = (!IsRoadAllowedHere(t1, house_tile, target_dir) || Chance16(6, 10));
break;
}
}
if (allow_house) {
/* Build a house, but not if there already is a house there. */
if (!IsTileType(house_tile, MP_HOUSE)) {
/* Level the land if possible */
if (Chance16(1, 6)) LevelTownLand(house_tile);
/* And build a house.
* Set result to -1 if we managed to build it. */
if (BuildTownHouse(t1, house_tile)) {
_grow_town_result = GROWTH_SUCCEED;
}
}
return;
}
_grow_town_result = GROWTH_SEARCH_STOPPED;
}
/* Return if a water tile */
if (IsWaterTile(tile)) return;
/* Make the roads look nicer */
rcmd = CleanUpRoadBits(tile, rcmd);
if (rcmd == ROAD_NONE) return;
/* Only use the target direction for bridges to ensure they're connected.
* The target_dir is as computed previously according to town layout, so
* it will match it perfectly. */
if (GrowTownWithBridge(t1, tile, target_dir)) return;
GrowTownWithRoad(t1, tile, rcmd);
}
/** Returns "growth" if a house was built, or no if the build failed.
* @param t town to inquiry
* @param tile to inquiry
* @return something other than zero(0)if town expansion was possible
*/
static int GrowTownAtRoad(Town *t, TileIndex tile)
{
/* Special case.
* @see GrowTownInTile Check the else if
*/
DiagDirection target_dir = DIAGDIR_END; // The direction in which we want to extend the town
assert(tile < MapSize());
/* Number of times to search.
* Better roads, 2X2 and 3X3 grid grow quite fast so we give
* them a little handicap. */
switch (t->layout) {
case TL_BETTER_ROADS:
_grow_town_result = 10 + t->num_houses * 2 / 9;
break;
case TL_3X3_GRID:
case TL_2X2_GRID:
_grow_town_result = 10 + t->num_houses * 1 / 9;
break;
default:
_grow_town_result = 10 + t->num_houses * 4 / 9;
break;
}
do {
RoadBits cur_rb = GetTownRoadBits(tile); // The RoadBits of the current tile
/* Try to grow the town from this point */
GrowTownInTile(&tile, cur_rb, target_dir, t);
/* Exclude the source position from the bitmask
* and return if no more road blocks available */
cur_rb &= ~DiagDirToRoadBits(ReverseDiagDir(target_dir));
if (cur_rb == ROAD_NONE)
return _grow_town_result;
/* Select a random bit from the blockmask, walk a step
* and continue the search from there. */
do target_dir = RandomDiagDir(); while (!(cur_rb & DiagDirToRoadBits(target_dir)));
tile = TileAddByDiagDir(tile, target_dir);
if (IsTileType(tile, MP_ROAD) && !IsRoadDepot(tile) && HasTileRoadType(tile, ROADTYPE_ROAD)) {
/* Don't allow building over roads of other cities */
if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN) && GetTownByTile(tile) != t) {
_grow_town_result = GROWTH_SUCCEED;
} else if (IsRoadOwner(tile, ROADTYPE_ROAD, OWNER_NONE) && _game_mode == GM_EDITOR) {
/* If we are in the SE, and this road-piece has no town owner yet, it just found an
* owner :) (happy happy happy road now) */
SetRoadOwner(tile, ROADTYPE_ROAD, OWNER_TOWN);
SetTownIndex(tile, t->index);
}
}
/* Max number of times is checked. */
} while (--_grow_town_result >= 0);
return (_grow_town_result == -2);
}
/**
* Generate a random road block.
* The probability of a straight road
* is somewhat higher than a curved.
*
* @return A RoadBits value with 2 bits set
*/
static RoadBits GenRandomRoadBits()
{
uint32 r = Random();
uint a = GB(r, 0, 2);
uint b = GB(r, 8, 2);
if (a == b) b ^= 2;
return (RoadBits)((ROAD_NW << a) + (ROAD_NW << b));
}
/** Grow the town
* @param t town to grow
* @return true iff a house was built
*/
static bool GrowTown(Town *t)
{
static const TileIndexDiffC _town_coord_mod[] = {
{-1, 0},
{ 1, 1},
{ 1, -1},
{-1, -1},
{-1, 0},
{ 0, 2},
{ 2, 0},
{ 0, -2},
{-1, -1},
{-2, 2},
{ 2, 2},
{ 2, -2},
{ 0, 0}
};
/* Current "company" is a town */
CompanyID old_company = _current_company;
_current_company = OWNER_TOWN;
TileIndex tile = t->xy; // The tile we are working with ATM
/* Find a road that we can base the construction on. */
const TileIndexDiffC *ptr;
for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
if (GetTownRoadBits(tile) != ROAD_NONE) {
int r = GrowTownAtRoad(t, tile);
_current_company = old_company;
return r != 0;
}
tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
}
/* No road available, try to build a random road block by
* clearing some land and then building a road there. */
tile = t->xy;
for (ptr = _town_coord_mod; ptr != endof(_town_coord_mod); ++ptr) {
/* Only work with plain land that not already has a house */
if (!IsTileType(tile, MP_HOUSE) && GetTileSlope(tile, NULL) == SLOPE_FLAT) {
if (CmdSucceeded(DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR))) {
DoCommand(tile, GenRandomRoadBits(), t->index, DC_EXEC | DC_AUTO, CMD_BUILD_ROAD);
_current_company = old_company;
return true;
}
}
tile = TILE_ADD(tile, ToTileIndexDiff(*ptr));
}
_current_company = old_company;
return false;
}
void UpdateTownRadius(Town *t)
{
static const uint32 _town_squared_town_zone_radius_data[23][5] = {
{ 4, 0, 0, 0, 0}, // 0
{ 16, 0, 0, 0, 0},
{ 25, 0, 0, 0, 0},
{ 36, 0, 0, 0, 0},
{ 49, 0, 4, 0, 0},
{ 64, 0, 4, 0, 0}, // 20
{ 64, 0, 9, 0, 1},
{ 64, 0, 9, 0, 4},
{ 64, 0, 16, 0, 4},
{ 81, 0, 16, 0, 4},
{ 81, 0, 16, 0, 4}, // 40
{ 81, 0, 25, 0, 9},
{ 81, 36, 25, 0, 9},
{ 81, 36, 25, 16, 9},
{ 81, 49, 0, 25, 9},
{ 81, 64, 0, 25, 9}, // 60
{ 81, 64, 0, 36, 9},
{ 81, 64, 0, 36, 16},
{100, 81, 0, 49, 16},
{100, 81, 0, 49, 25},
{121, 81, 0, 49, 25}, // 80
{121, 81, 0, 49, 25},
{121, 81, 0, 49, 36}, // 88
};
if (t->num_houses < 92) {
memcpy(t->squared_town_zone_radius, _town_squared_town_zone_radius_data[t->num_houses / 4], sizeof(t->squared_town_zone_radius));
} else {
int mass = t->num_houses / 8;
/* Actually we are proportional to sqrt() but that's right because we are covering an area.
* The offsets are to make sure the radii do not decrease in size when going from the table
* to the calculated value.*/
t->squared_town_zone_radius[0] = mass * 15 - 40;
t->squared_town_zone_radius[1] = mass * 9 - 15;
t->squared_town_zone_radius[2] = 0;
t->squared_town_zone_radius[3] = mass * 5 - 5;
t->squared_town_zone_radius[4] = mass * 3 + 5;
}
}
extern int _nb_orig_names;
/**
* Struct holding a parameters used to generate town name.
* Speeds things up a bit because these values are computed only once per name generation.
*/
struct TownNameParams {
uint32 grfid; ///< newgrf ID
uint16 townnametype; ///< town name style
bool grf; ///< true iff a newgrf is used to generate town name
TownNameParams(byte town_name)
{
this->grf = town_name >= _nb_orig_names;
this->grfid = this->grf ? GetGRFTownNameId(town_name - _nb_orig_names) : 0;
this->townnametype = this->grf ? GetGRFTownNameType(town_name - _nb_orig_names) : SPECSTR_TOWNNAME_START + town_name;
}
};
/**
* Verifies the town name is valid and unique.
* @param r random bits
* @param par town name parameters
* @return true iff name is valid and unique
*/
static bool VerifyTownName(uint32 r, const TownNameParams *par)
{
/* reserve space for extra unicode character and terminating '\0' */
char buf1[MAX_LENGTH_TOWN_NAME_BYTES + 4 + 1];
char buf2[MAX_LENGTH_TOWN_NAME_BYTES + 4 + 1];
SetDParam(0, r);
if (par->grf && par->grfid != 0) {
GRFTownNameGenerate(buf1, par->grfid, par->townnametype, r, lastof(buf1));
} else {
GetString(buf1, par->townnametype, lastof(buf1));
}
/* Check size and width */
if (strlen(buf1) >= MAX_LENGTH_TOWN_NAME_BYTES) return false;
const Town *t;
FOR_ALL_TOWNS(t) {
/* We can't just compare the numbers since
* several numbers may map to a single name. */
SetDParam(0, t->index);
GetString(buf2, STR_TOWN, lastof(buf2));
if (strcmp(buf1, buf2) == 0) return false;
}
return true;
}
/**
* Generates valid town name.
* @param townnameparts if a name is generated, it's stored there
* @return true iff a name was generated
*/
bool GenerateTownName(uint32 *townnameparts)
{
/* Do not set too low tries, since when we run out of names, we loop
* for #tries only one time anyway - then we stop generating more
* towns. Do not show it too high neither, since looping through all
* the other towns may take considerable amount of time (10000 is
* too much). */
int tries = 1000;
TownNameParams par(_settings_game.game_creation.town_name);
assert(townnameparts != NULL);
for (;;) {
uint32 r = InteractiveRandom();
if (!VerifyTownName(r, &par)) {
if (tries-- < 0) return false;
continue;
}
*townnameparts = r;
return true;
}
}
void UpdateTownMaxPass(Town *t)
{
t->max_pass = t->population >> 3;
t->max_mail = t->population >> 4;
}
/**
* Does the actual town creation.
*
* @param t The town
* @param tile Where to put it
* @param townnameparts The town name
* @param size_mode How the size should be determined
* @param size Parameter for size determination
*/
static void DoCreateTown(Town *t, TileIndex tile, uint32 townnameparts, TownSize size, bool city, TownLayout layout)
{
t->xy = tile;
t->num_houses = 0;
t->time_until_rebuild = 10;
UpdateTownRadius(t);
t->flags12 = 0;
t->population = 0;
t->grow_counter = 0;
t->growth_rate = 250;
t->new_max_pass = 0;
t->new_max_mail = 0;
t->new_act_pass = 0;
t->new_act_mail = 0;
t->max_pass = 0;
t->max_mail = 0;
t->act_pass = 0;
t->act_mail = 0;
t->pct_pass_transported = 0;
t->pct_mail_transported = 0;
t->fund_buildings_months = 0;
t->new_act_food = 0;
t->new_act_water = 0;
t->act_food = 0;
t->act_water = 0;
for (uint i = 0; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
t->have_ratings = 0;
t->exclusivity = INVALID_COMPANY;
t->exclusive_counter = 0;
t->statues = 0;
if (_settings_game.game_creation.town_name < _nb_orig_names) {
/* Original town name */
t->townnamegrfid = 0;
t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
} else {
/* Newgrf town name */
t->townnamegrfid = GetGRFTownNameId(_settings_game.game_creation.town_name - _nb_orig_names);
t->townnametype = GetGRFTownNameType(_settings_game.game_creation.town_name - _nb_orig_names);
}
t->townnameparts = townnameparts;
UpdateTownVirtCoord(t);
InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 0);
t->InitializeLayout(layout);
t->larger_town = city;
int x = (int)size * 16 + 3;
if (size == TS_RANDOM) x = (Random() & 0xF) + 8;
if (city) x *= _settings_game.economy.initial_city_size;
t->num_houses += x;
UpdateTownRadius(t);
int i = x * 4;
do {
GrowTown(t);
} while (--i);
t->num_houses -= x;
UpdateTownRadius(t);
UpdateTownMaxPass(t);
UpdateAirportsNoise();
}
/** Create a new town.
* This obviously only works in the scenario editor. Function not removed
* as it might be possible in the future to fund your own town :)
* @param tile coordinates where town is built
* @param flags type of operation
* @param p1 0..1 size of the town (@see TownSize)
* 2 true iff it should be a city
* 3..5 town road layout (@see TownLayout)
* @param p2 town name parts
*/
CommandCost CmdBuildTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
/* Only in the scenario editor */
if (_game_mode != GM_EDITOR) return CMD_ERROR;
TownSize size = (TownSize)GB(p1, 0, 2);
bool city = HasBit(p1, 2);
TownLayout layout = (TownLayout)GB(p1, 3, 3);
TownNameParams par(_settings_game.game_creation.town_name);
uint32 townnameparts = p2;
if (size > TS_RANDOM) return CMD_ERROR;
if (layout > TL_RANDOM) return CMD_ERROR;
if (!VerifyTownName(townnameparts, &par)) return_cmd_error(STR_NAME_MUST_BE_UNIQUE);
/* Check if too close to the edge of map */
if (DistanceFromEdge(tile) < 12) {
return_cmd_error(STR_0237_TOO_CLOSE_TO_EDGE_OF_MAP);
}
/* Check distance to all other towns. */
if (IsCloseToTown(tile, 20)) {
return_cmd_error(STR_0238_TOO_CLOSE_TO_ANOTHER_TOWN);
}
/* Can only build on clear flat areas, possibly with trees. */
if ((!IsTileType(tile, MP_CLEAR) && !IsTileType(tile, MP_TREES)) || GetTileSlope(tile, NULL) != SLOPE_FLAT) {
return_cmd_error(STR_0239_SITE_UNSUITABLE);
}
/* Allocate town struct */
if (!Town::CanAllocateItem()) return_cmd_error(STR_023A_TOO_MANY_TOWNS);
/* Create the town */
if (flags & DC_EXEC) {
Town *t = new Town(tile);
_generating_world = true;
UpdateNearestTownForRoadTiles(true);
DoCreateTown(t, tile, townnameparts, size, city, layout);
UpdateNearestTownForRoadTiles(false);
_generating_world = false;
}
return CommandCost();
}
Town *CreateRandomTown(uint attempts, TownSize size, bool city, TownLayout layout)
{
if (!Town::CanAllocateItem()) return NULL;
do {
/* Generate a tile index not too close from the edge */
TileIndex tile = RandomTile();
switch (layout) {
case TL_2X2_GRID:
tile = TileXY(TileX(tile) - TileX(tile) % 3, TileY(tile) - TileY(tile) % 3);
break;
case TL_3X3_GRID:
tile = TileXY(TileX(tile) & ~3, TileY(tile) & ~3);
break;
default: break;
}
if (DistanceFromEdge(tile) < 20) continue;
/* Make sure the tile is plain */
if (!IsTileType(tile, MP_CLEAR) || GetTileSlope(tile, NULL) != SLOPE_FLAT) continue;
/* Check not too close to a town */
if (IsCloseToTown(tile, 20)) continue;
uint32 townnameparts;
/* Get a unique name for the town. */
if (!GenerateTownName(&townnameparts)) break;
/* Allocate a town struct */
Town *t = new Town(tile);
DoCreateTown(t, tile, townnameparts, size, city, layout);
return t;
} while (--attempts != 0);
return NULL;
}
static const byte _num_initial_towns[4] = {5, 11, 23, 46}; // very low, low, normal, high
bool GenerateTowns(TownLayout layout)
{
uint num = 0;
uint difficulty = _settings_game.difficulty.number_towns;
uint n = (difficulty == (uint)CUSTOM_TOWN_NUMBER_DIFFICULTY) ? _settings_game.game_creation.custom_town_number : ScaleByMapSize(_num_initial_towns[difficulty] + (Random() & 7));
SetGeneratingWorldProgress(GWP_TOWN, n);
do {
bool city = (_settings_game.economy.larger_towns != 0 && Chance16(1, _settings_game.economy.larger_towns));
IncreaseGeneratingWorldProgress(GWP_TOWN);
/* try 20 times to create a random-sized town for the first loop. */
if (CreateRandomTown(20, TS_RANDOM, city, layout) != NULL) num++;
} while (--n);
/* give it a last try, but now more aggressive */
if (num == 0 && CreateRandomTown(10000, TS_RANDOM, _settings_game.economy.larger_towns != 0, layout) == NULL) {
if (GetNumTowns() == 0) {
if (_game_mode != GM_EDITOR) {
extern StringID _switch_mode_errorstr;
_switch_mode_errorstr = STR_COULD_NOT_CREATE_TOWN;
}
return false;
}
}
return true;
}
/** Returns the bit corresponding to the town zone of the specified tile
* @param t Town on which town zone is to be found
* @param tile TileIndex where town zone needs to be found
* @return the bit position of the given zone, as defined in HouseZones
*/
HouseZonesBits GetTownRadiusGroup(const Town *t, TileIndex tile)
{
uint dist = DistanceSquare(tile, t->xy);
if (t->fund_buildings_months && dist <= 25) return HZB_TOWN_CENTRE;
HouseZonesBits smallest = HZB_TOWN_EDGE;
for (HouseZonesBits i = HZB_BEGIN; i < HZB_END; i++) {
if (dist < t->squared_town_zone_radius[i]) smallest = i;
}
return smallest;
}
/**
* Clears tile and builds a house or house part.
* @param t tile index
* @param tid Town index
* @param counter of construction step
* @param stage of construction (used for drawing)
* @param type of house. Index into house specs array
* @param random_bits required for newgrf houses
* @pre house can be built here
*/
static inline void ClearMakeHouseTile(TileIndex tile, Town *t, byte counter, byte stage, HouseID type, byte random_bits)
{
CommandCost cc = DoCommand(tile, 0, 0, DC_EXEC | DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR);
assert(CmdSucceeded(cc));
IncreaseBuildingCount(t, type);
MakeHouseTile(tile, t->index, counter, stage, type, random_bits);
if (GetHouseSpecs(type)->building_flags & BUILDING_IS_ANIMATED) AddAnimatedTile(tile);
MarkTileDirtyByTile(tile);
}
/**
* Write house information into the map. For houses > 1 tile, all tiles are marked.
* @param t tile index
* @param tid Town index
* @param counter of construction step
* @param stage of construction (used for drawing)
* @param type of house. Index into house specs array
* @param random_bits required for newgrf houses
* @pre house can be built here
*/
static void MakeTownHouse(TileIndex t, Town *town, byte counter, byte stage, HouseID type, byte random_bits)
{
BuildingFlags size = GetHouseSpecs(type)->building_flags;
ClearMakeHouseTile(t, town, counter, stage, type, random_bits);
if (size & BUILDING_2_TILES_Y) ClearMakeHouseTile(t + TileDiffXY(0, 1), town, counter, stage, ++type, random_bits);
if (size & BUILDING_2_TILES_X) ClearMakeHouseTile(t + TileDiffXY(1, 0), town, counter, stage, ++type, random_bits);
if (size & BUILDING_HAS_4_TILES) ClearMakeHouseTile(t + TileDiffXY(1, 1), town, counter, stage, ++type, random_bits);
}
/**
* Checks if a house can be built here. Important is slope, bridge above
* and ability to clear the land.
* @param tile tile to check
* @param town town that is checking
* @param noslope are slopes (foundations) allowed?
* @return true iff house can be built here
*/
static inline bool CanBuildHouseHere(TileIndex tile, TownID town, bool noslope)
{
/* cannot build on these slopes... */
Slope slope = GetTileSlope(tile, NULL);
if ((noslope && slope != SLOPE_FLAT) || IsSteepSlope(slope)) return false;
/* building under a bridge? */
if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
/* do not try to build over house owned by another town */
if (IsTileType(tile, MP_HOUSE) && GetTownIndex(tile) != town) return false;
/* can we clear the land? */
return CmdSucceeded(DoCommand(tile, 0, 0, DC_AUTO | DC_NO_WATER, CMD_LANDSCAPE_CLEAR));
}
/**
* Checks if a house can be built at this tile, must have the same max z as parameter.
* @param tile tile to check
* @param town town that is checking
* @param z max z of this tile so more parts of a house are at the same height (with foundation)
* @param noslope are slopes (foundations) allowed?
* @return true iff house can be built here
* @see CanBuildHouseHere()
*/
static inline bool CheckBuildHouseSameZ(TileIndex tile, TownID town, uint z, bool noslope)
{
if (!CanBuildHouseHere(tile, town, noslope)) return false;
/* if building on slopes is allowed, there will be flattening foundation (to tile max z) */
if (GetTileMaxZ(tile) != z) return false;
return true;
}
/**
* Checks if a house of size 2x2 can be built at this tile
* @param tile tile, N corner
* @param town town that is checking
* @param z maximum tile z so all tile have the same max z
* @param noslope are slopes (foundations) allowed?
* @return true iff house can be built
* @see CheckBuildHouseSameZ()
*/
static bool CheckFree2x2Area(TileIndex tile, TownID town, uint z, bool noslope)
{
/* we need to check this tile too because we can be at different tile now */
if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
for (DiagDirection d = DIAGDIR_SE; d < DIAGDIR_END; d++) {
tile += TileOffsByDiagDir(d);
if (!CheckBuildHouseSameZ(tile, town, z, noslope)) return false;
}
return true;
}
/**
* Checks if current town layout allows building here
* @param t town
* @param tile tile to check
* @return true iff town layout allows building here
* @note see layouts
*/
static inline bool TownLayoutAllowsHouseHere(Town *t, TileIndex tile)
{
/* Allow towns everywhere when we don't build roads */
if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
TileIndexDiffC grid_pos = TileIndexToTileIndexDiffC(t->xy, tile);
switch (t->layout) {
case TL_2X2_GRID:
if ((grid_pos.x % 3) == 0 || (grid_pos.y % 3) == 0) return false;
break;
case TL_3X3_GRID:
if ((grid_pos.x % 4) == 0 || (grid_pos.y % 4) == 0) return false;
break;
default:
break;
}
return true;
}
/**
* Checks if current town layout allows 2x2 building here
* @param t town
* @param tile tile to check
* @return true iff town layout allows 2x2 building here
* @note see layouts
*/
static inline bool TownLayoutAllows2x2HouseHere(Town *t, TileIndex tile)
{
/* Allow towns everywhere when we don't build roads */
if (!_settings_game.economy.allow_town_roads && !_generating_world) return true;
/* MapSize() is sure dividable by both MapSizeX() and MapSizeY(),
* so to do only one memory access, use MapSize() */
uint dx = MapSize() + TileX(t->xy) - TileX(tile);
uint dy = MapSize() + TileY(t->xy) - TileY(tile);
switch (t->layout) {
case TL_2X2_GRID:
if ((dx % 3) != 0 || (dy % 3) != 0) return false;
break;
case TL_3X3_GRID:
if ((dx % 4) < 2 || (dy % 4) < 2) return false;
break;
default:
break;
}
return true;
}
/**
* Checks if 1x2 or 2x1 building is allowed here, also takes into account current town layout
* Also, tests both building positions that occupy this tile
* @param tile tile where the building should be built
* @param t town
* @param maxz all tiles should have the same height
* @param noslope are slopes forbidden?
* @param second diagdir from first tile to second tile
**/
static bool CheckTownBuild2House(TileIndex *tile, Town *t, uint maxz, bool noslope, DiagDirection second)
{
/* 'tile' is already checked in BuildTownHouse() - CanBuildHouseHere() and slope test */
TileIndex tile2 = *tile + TileOffsByDiagDir(second);
if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) return true;
tile2 = *tile + TileOffsByDiagDir(ReverseDiagDir(second));
if (TownLayoutAllowsHouseHere(t, tile2) && CheckBuildHouseSameZ(tile2, t->index, maxz, noslope)) {
*tile = tile2;
return true;
}
return false;
}
/**
* Checks if 2x2 building is allowed here, also takes into account current town layout
* Also, tests all four building positions that occupy this tile
* @param tile tile where the building should be built
* @param t town
* @param maxz all tiles should have the same height
* @param noslope are slopes forbidden?
**/
static bool CheckTownBuild2x2House(TileIndex *tile, Town *t, uint maxz, bool noslope)
{
TileIndex tile2 = *tile;
for (DiagDirection d = DIAGDIR_SE;;d++) { // 'd' goes through DIAGDIR_SE, DIAGDIR_SW, DIAGDIR_NW, DIAGDIR_END
if (TownLayoutAllows2x2HouseHere(t, tile2) && CheckFree2x2Area(tile2, t->index, maxz, noslope)) {
*tile = tile2;
return true;
}
if (d == DIAGDIR_END) break;
tile2 += TileOffsByDiagDir(ReverseDiagDir(d)); // go clockwise
}
return false;
}
/**
* Tries to build a house at this tile
* @param t town the house will belong to
* @param tile where the house will be built
* @return false iff no house can be built at this tile
*/
static bool BuildTownHouse(Town *t, TileIndex tile)
{
/* forbidden building here by town layout */
if (!TownLayoutAllowsHouseHere(t, tile)) return false;
/* no house allowed at all, bail out */
if (!CanBuildHouseHere(tile, t->index, false)) return false;
uint z;
Slope slope = GetTileSlope(tile, &z);
/* Get the town zone type of the current tile, as well as the climate.
* This will allow to easily compare with the specs of the new house to build */
HouseZonesBits rad = GetTownRadiusGroup(t, tile);
/* Above snow? */
int land = _settings_game.game_creation.landscape;
if (land == LT_ARCTIC && z >= _settings_game.game_creation.snow_line) land = -1;
uint bitmask = (1 << rad) + (1 << (land + 12));
/* bits 0-4 are used
* bits 11-15 are used
* bits 5-10 are not used. */
HouseID houses[HOUSE_MAX];
uint num = 0;
uint probs[HOUSE_MAX];
uint probability_max = 0;
/* Generate a list of all possible houses that can be built. */
for (uint i = 0; i < HOUSE_MAX; i++) {
const HouseSpec *hs = GetHouseSpecs(i);
/* Verify that the candidate house spec matches the current tile status */
if ((~hs->building_availability & bitmask) != 0 || !hs->enabled) continue;
/* Don't let these counters overflow. Global counters are 32bit, there will never be that many houses. */
if (hs->class_id != HOUSE_NO_CLASS) {
/* id_count is always <= class_count, so it doesn't need to be checked */
if (t->building_counts.class_count[hs->class_id] == UINT16_MAX) continue;
} else {
/* If the house has no class, check id_count instead */
if (t->building_counts.id_count[i] == UINT16_MAX) continue;
}
/* Without NewHouses, all houses have probability '1' */
uint cur_prob = (_loaded_newgrf_features.has_newhouses ? hs->probability : 1);
probability_max += cur_prob;
probs[num] = cur_prob;
houses[num++] = (HouseID)i;
}
uint maxz = GetTileMaxZ(tile);
while (probability_max > 0) {
uint r = RandomRange(probability_max);
uint i;
for (i = 0; i < num; i++) {
if (probs[i] > r) break;
r -= probs[i];
}
HouseID house = houses[i];
probability_max -= probs[i];
/* remove tested house from the set */
num--;
houses[i] = houses[num];
probs[i] = probs[num];
const HouseSpec *hs = GetHouseSpecs(house);
if (_loaded_newgrf_features.has_newhouses) {
if (hs->override != 0) {
house = hs->override;
hs = GetHouseSpecs(house);
}
if ((hs->extra_flags & BUILDING_IS_HISTORICAL) && !_generating_world && _game_mode != GM_EDITOR) continue;
}
if (_cur_year < hs->min_year || _cur_year > hs->max_year) continue;
/* Special houses that there can be only one of. */
uint oneof = 0;
if (hs->building_flags & BUILDING_IS_CHURCH) {
SetBit(oneof, TOWN_HAS_CHURCH);
} else if (hs->building_flags & BUILDING_IS_STADIUM) {
SetBit(oneof, TOWN_HAS_STADIUM);
}
if (HASBITS(t->flags12, oneof)) continue;
/* Make sure there is no slope? */
bool noslope = (hs->building_flags & TILE_NOT_SLOPED) != 0;
if (noslope && slope != SLOPE_FLAT) continue;
if (hs->building_flags & TILE_SIZE_2x2) {
if (!CheckTownBuild2x2House(&tile, t, maxz, noslope)) continue;
} else if (hs->building_flags & TILE_SIZE_2x1) {
if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SW)) continue;
} else if (hs->building_flags & TILE_SIZE_1x2) {
if (!CheckTownBuild2House(&tile, t, maxz, noslope, DIAGDIR_SE)) continue;
} else {
/* 1x1 house checks are already done */
}
if (HasBit(hs->callback_mask, CBM_HOUSE_ALLOW_CONSTRUCTION)) {
uint16 callback_res = GetHouseCallback(CBID_HOUSE_ALLOW_CONSTRUCTION, 0, 0, house, t, tile);
if (callback_res != CALLBACK_FAILED && GB(callback_res, 0, 8) == 0) continue;
}
/* build the house */
t->num_houses++;
/* Special houses that there can be only one of. */
t->flags12 |= oneof;
byte construction_counter = 0;
byte construction_stage = 0;
if (_generating_world || _game_mode == GM_EDITOR) {
uint32 r = Random();
construction_stage = TOWN_HOUSE_COMPLETED;
if (Chance16(1, 7)) construction_stage = GB(r, 0, 2);
if (construction_stage == TOWN_HOUSE_COMPLETED) {
ChangePopulation(t, hs->population);
} else {
construction_counter = GB(r, 2, 2);
}
}
MakeTownHouse(tile, t, construction_counter, construction_stage, house, Random());
return true;
}
return false;
}
/**
* Update data structures when a house is removed
* @param tile Tile of the house
* @param t Town owning the house
* @param house House type
*/
static void DoClearTownHouseHelper(TileIndex tile, Town *t, HouseID house)
{
assert(IsTileType(tile, MP_HOUSE));
DecreaseBuildingCount(t, house);
DoClearSquare(tile);
DeleteAnimatedTile(tile);
}
/**
* Determines if a given HouseID is part of a multitile house.
* The given ID is set to the ID of the north tile and the TileDiff to the north tile is returned.
*
* @param house Is changed to the HouseID of the north tile of the same house
* @return TileDiff from the tile of the given HouseID to the north tile
*/
TileIndexDiff GetHouseNorthPart(HouseID &house)
{
if (house >= 3) { // house id 0,1,2 MUST be single tile houses, or this code breaks.
if (GetHouseSpecs(house - 1)->building_flags & TILE_SIZE_2x1) {
house--;
return TileDiffXY(-1, 0);
} else if (GetHouseSpecs(house - 1)->building_flags & BUILDING_2_TILES_Y) {
house--;
return TileDiffXY(0, -1);
} else if (GetHouseSpecs(house - 2)->building_flags & BUILDING_HAS_4_TILES) {
house -= 2;
return TileDiffXY(-1, 0);
} else if (GetHouseSpecs(house - 3)->building_flags & BUILDING_HAS_4_TILES) {
house -= 3;
return TileDiffXY(-1, -1);
}
}
return 0;
}
void ClearTownHouse(Town *t, TileIndex tile)
{
assert(IsTileType(tile, MP_HOUSE));
HouseID house = GetHouseType(tile);
/* need to align the tile to point to the upper left corner of the house */
tile += GetHouseNorthPart(house); // modifies house to the ID of the north tile
const HouseSpec *hs = GetHouseSpecs(house);
/* Remove population from the town if the house is finished. */
if (IsHouseCompleted(tile)) {
ChangePopulation(t, -hs->population);
}
t->num_houses--;
/* Clear flags for houses that only may exist once/town. */
if (hs->building_flags & BUILDING_IS_CHURCH) {
ClrBit(t->flags12, TOWN_HAS_CHURCH);
} else if (hs->building_flags & BUILDING_IS_STADIUM) {
ClrBit(t->flags12, TOWN_HAS_STADIUM);
}
/* Do the actual clearing of tiles */
uint eflags = hs->building_flags;
DoClearTownHouseHelper(tile, t, house);
if (eflags & BUILDING_2_TILES_Y) DoClearTownHouseHelper(tile + TileDiffXY(0, 1), t, ++house);
if (eflags & BUILDING_2_TILES_X) DoClearTownHouseHelper(tile + TileDiffXY(1, 0), t, ++house);
if (eflags & BUILDING_HAS_4_TILES) DoClearTownHouseHelper(tile + TileDiffXY(1, 1), t, ++house);
}
static bool IsUniqueTownName(const char *name)
{
const Town *t;
FOR_ALL_TOWNS(t) {
if (t->name != NULL && strcmp(t->name, name) == 0) return false;
}
return true;
}
/** Rename a town (server-only).
* @param tile unused
* @param flags type of operation
* @param p1 town ID to rename
* @param p2 unused
*/
CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
if (!IsValidTownID(p1)) return CMD_ERROR;
bool reset = StrEmpty(text);
if (!reset) {
if (strlen(text) >= MAX_LENGTH_TOWN_NAME_BYTES) return CMD_ERROR;
if (!IsUniqueTownName(text)) return_cmd_error(STR_NAME_MUST_BE_UNIQUE);
}
if (flags & DC_EXEC) {
Town *t = GetTown(p1);
free(t->name);
t->name = reset ? NULL : strdup(text);
UpdateTownVirtCoord(t);
InvalidateWindowData(WC_TOWN_DIRECTORY, 0, 1);
UpdateAllStationVirtCoord();
UpdateAllWaypointSigns();
MarkWholeScreenDirty();
}
return CommandCost();
}
/** Called from GUI */
void ExpandTown(Town *t)
{
/* Warn the users if towns are not allowed to build roads,
* but do this only onces per openttd run. */
static bool warned_no_roads = false;
if (!_settings_game.economy.allow_town_roads && !warned_no_roads) {
ShowErrorMessage(INVALID_STRING_ID, STR_TOWN_EXPAND_WARN_NO_ROADS, 0, 0);
warned_no_roads = true;
}
/* The more houses, the faster we grow */
uint amount = RandomRange(ClampToU16(t->num_houses / 10)) + 3;
t->num_houses += amount;
UpdateTownRadius(t);
uint n = amount * 10;
do GrowTown(t); while (--n);
t->num_houses -= amount;
UpdateTownRadius(t);
UpdateTownMaxPass(t);
}
extern const byte _town_action_costs[8] = {
2, 4, 9, 35, 48, 53, 117, 175
};
static void TownActionAdvertiseSmall(Town *t)
{
ModifyStationRatingAround(t->xy, _current_company, 0x40, 10);
}
static void TownActionAdvertiseMedium(Town *t)
{
ModifyStationRatingAround(t->xy, _current_company, 0x70, 15);
}
static void TownActionAdvertiseLarge(Town *t)
{
ModifyStationRatingAround(t->xy, _current_company, 0xA0, 20);
}
static void TownActionRoadRebuild(Town *t)
{
t->road_build_months = 6;
char company_name[MAX_LENGTH_COMPANY_NAME_BYTES];
SetDParam(0, _current_company);
GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
char *cn = strdup(company_name);
SetDParam(0, t->index);
SetDParamStr(1, cn);
AddNewsItem(STR_2055_TRAFFIC_CHAOS_IN_ROAD_REBUILDING, NS_GENERAL, t->xy, 0, cn);
}
static bool DoBuildStatueOfCompany(TileIndex tile, TownID town_id)
{
/* Statues can be build on slopes, just like houses. Only the steep slopes is a no go. */
if (IsSteepSlope(GetTileSlope(tile, NULL))) return false;
/* Don't build statues under bridges. */
if (MayHaveBridgeAbove(tile) && IsBridgeAbove(tile)) return false;
if (!IsTileType(tile, MP_HOUSE) &&
!IsTileType(tile, MP_CLEAR) &&
!IsTileType(tile, MP_TREES)) {
return false;
}
CompanyID old = _current_company;
_current_company = OWNER_NONE;
CommandCost r = DoCommand(tile, 0, 0, DC_EXEC, CMD_LANDSCAPE_CLEAR);
_current_company = old;
if (CmdFailed(r)) return false;
MakeStatue(tile, _current_company, town_id);
MarkTileDirtyByTile(tile);
return true;
}
/**
* Search callback function for TownActionBuildStatue
* @param tile on which to perform the search
* @param user_data The town_id for which we want a statue
* @return the result of the test
*/
static bool SearchTileForStatue(TileIndex tile, void *user_data)
{
TownID *town_id = (TownID *)user_data;
return DoBuildStatueOfCompany(tile, *town_id);
}
/**
* Perform a 9x9 tiles circular search from the center of the town
* in order to find a free tile to place a statue
* @param t town to search in
*/
static void TownActionBuildStatue(Town *t)
{
TileIndex tile = t->xy;
if (CircularTileSearch(&tile, 9, SearchTileForStatue, &t->index)) {
SetBit(t->statues, _current_company); // Once found and built, "inform" the Town
}
}
static void TownActionFundBuildings(Town *t)
{
/* Build next tick */
t->grow_counter = 1;
/* If we were not already growing */
SetBit(t->flags12, TOWN_IS_FUNDED);
/* And grow for 3 months */
t->fund_buildings_months = 3;
}
static void TownActionBuyRights(Town *t)
{
/* Check if it's allowed to by the rights */
if (!_settings_game.economy.exclusive_rights) return;
t->exclusive_counter = 12;
t->exclusivity = _current_company;
ModifyStationRatingAround(t->xy, _current_company, 130, 17);
}
static void TownActionBribe(Town *t)
{
if (Chance16(1, 14)) {
/* set as unwanted for 6 months */
t->unwanted[_current_company] = 6;
/* set all close by station ratings to 0 */
Station *st;
FOR_ALL_STATIONS(st) {
if (st->town == t && st->owner == _current_company) {
for (CargoID i = 0; i < NUM_CARGO; i++) st->goods[i].rating = 0;
}
}
/* only show errormessage to the executing player. All errors are handled command.c
* but this is special, because it can only 'fail' on a DC_EXEC */
if (IsLocalCompany()) ShowErrorMessage(STR_BRIBE_FAILED_2, STR_BRIBE_FAILED, 0, 0);
/* decrease by a lot!
* ChangeTownRating is only for stuff in demolishing. Bribe failure should
* be independent of any cheat settings
*/
if (t->ratings[_current_company] > RATING_BRIBE_DOWN_TO) {
t->ratings[_current_company] = RATING_BRIBE_DOWN_TO;
InvalidateWindow(WC_TOWN_AUTHORITY, t->index);
}
} else {
ChangeTownRating(t, RATING_BRIBE_UP_STEP, RATING_BRIBE_MAXIMUM, DC_EXEC);
}
}
typedef void TownActionProc(Town *t);
static TownActionProc * const _town_action_proc[] = {
TownActionAdvertiseSmall,
TownActionAdvertiseMedium,
TownActionAdvertiseLarge,
TownActionRoadRebuild,
TownActionBuildStatue,
TownActionFundBuildings,
TownActionBuyRights,
TownActionBribe
};
enum TownActions {
TACT_NONE = 0x00,
TACT_ADVERTISE_SMALL = 0x01,
TACT_ADVERTISE_MEDIUM = 0x02,
TACT_ADVERTISE_LARGE = 0x04,
TACT_ROAD_REBUILD = 0x08,
TACT_BUILD_STATUE = 0x10,
TACT_FOUND_BUILDINGS = 0x20,
TACT_BUY_RIGHTS = 0x40,
TACT_BRIBE = 0x80,
TACT_ADVERTISE = TACT_ADVERTISE_SMALL | TACT_ADVERTISE_MEDIUM | TACT_ADVERTISE_LARGE,
TACT_CONSTRUCTION = TACT_ROAD_REBUILD | TACT_BUILD_STATUE | TACT_FOUND_BUILDINGS,
TACT_FUNDS = TACT_BUY_RIGHTS | TACT_BRIBE,
TACT_ALL = TACT_ADVERTISE | TACT_CONSTRUCTION | TACT_FUNDS,
};
DECLARE_ENUM_AS_BIT_SET(TownActions);
/** Get a list of available actions to do at a town.
* @param nump if not NULL add put the number of available actions in it
* @param cid the company that is querying the town
* @param t the town that is queried
* @return bitmasked value of enabled actions
*/
uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t)
{
int num = 0;
TownActions buttons = TACT_NONE;
/* Spectators and unwanted have no options */
if (cid != COMPANY_SPECTATOR && !(_settings_game.economy.bribe && t->unwanted[cid])) {
/* Things worth more than this are not shown */
Money avail = GetCompany(cid)->money + _price.station_value * 200;
Money ref = _price.build_industry >> 8;
/* Check the action bits for validity and
* if they are valid add them */
for (uint i = 0; i != lengthof(_town_action_costs); i++) {
const TownActions cur = (TownActions)(1 << i);
/* Is the company not able to bribe ? */
if (cur == TACT_BRIBE && (!_settings_game.economy.bribe || t->ratings[cid] >= RATING_BRIBE_MAXIMUM))
continue;
/* Is the company not able to buy exclusive rights ? */
if (cur == TACT_BUY_RIGHTS && !_settings_game.economy.exclusive_rights)
continue;
/* Is the company not able to build a statue ? */
if (cur == TACT_BUILD_STATUE && HasBit(t->statues, cid))
continue;
if (avail >= _town_action_costs[i] * ref) {
buttons |= cur;
num++;
}
}
}
if (nump != NULL) *nump = num;
return buttons;
}
/** Do a town action.
* This performs an action such as advertising, building a statue, funding buildings,
* but also bribing the town-council
* @param tile unused
* @param flags type of operation
* @param p1 town to do the action at
* @param p2 action to perform, @see _town_action_proc for the list of available actions
*/
CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
if (!IsValidTownID(p1) || p2 > lengthof(_town_action_proc)) return CMD_ERROR;
Town *t = GetTown(p1);
if (!HasBit(GetMaskOfTownActions(NULL, _current_company, t), p2)) return CMD_ERROR;
CommandCost cost(EXPENSES_OTHER, (_price.build_industry >> 8) * _town_action_costs[p2]);
if (flags & DC_EXEC) {
_town_action_proc[p2](t);
InvalidateWindow(WC_TOWN_AUTHORITY, p1);
}
return cost;
}
static void UpdateTownGrowRate(Town *t)
{
/* Increase company ratings if they're low */
const Company *c;
FOR_ALL_COMPANIES(c) {
if (t->ratings[c->index] < RATING_GROWTH_MAXIMUM) {
t->ratings[c->index] = min((int)RATING_GROWTH_MAXIMUM, t->ratings[c->index] + RATING_GROWTH_UP_STEP);
}
}
int n = 0;
const Station *st;
FOR_ALL_STATIONS(st) {
if (DistanceSquare(st->xy, t->xy) <= t->squared_town_zone_radius[0]) {
if (st->time_since_load <= 20 || st->time_since_unload <= 20) {
n++;
if (IsValidCompanyID(st->owner)) {
int new_rating = t->ratings[st->owner] + RATING_STATION_UP_STEP;
t->ratings[st->owner] = min(new_rating, INT16_MAX); // do not let it overflow
}
} else {
if (IsValidCompanyID(st->owner)) {
int new_rating = t->ratings[st->owner] + RATING_STATION_DOWN_STEP;
t->ratings[st->owner] = max(new_rating, INT16_MIN);
}
}
}
}
/* clamp all ratings to valid values */
for (uint i = 0; i < MAX_COMPANIES; i++) {
t->ratings[i] = Clamp(t->ratings[i], RATING_MINIMUM, RATING_MAXIMUM);
}
InvalidateWindow(WC_TOWN_AUTHORITY, t->index);
ClrBit(t->flags12, TOWN_IS_FUNDED);
if (_settings_game.economy.town_growth_rate == 0 && t->fund_buildings_months == 0) return;
/** Towns are processed every TOWN_GROWTH_FREQUENCY ticks, and this is the
* number of times towns are processed before a new building is built. */
static const uint16 _grow_count_values[2][6] = {
{ 120, 120, 120, 100, 80, 60 }, // Fund new buildings has been activated
{ 320, 420, 300, 220, 160, 100 } // Normal values
};
uint16 m;
if (t->fund_buildings_months != 0) {
m = _grow_count_values[0][min(n, 5)];
t->fund_buildings_months--;
} else {
m = _grow_count_values[1][min(n, 5)];
if (n == 0 && !Chance16(1, 12)) return;
}
if (_settings_game.game_creation.landscape == LT_ARCTIC) {
if (TilePixelHeight(t->xy) >= GetSnowLine() && t->act_food == 0 && t->population > 90)
return;
} else if (_settings_game.game_creation.landscape == LT_TROPIC) {
if (GetTropicZone(t->xy) == TROPICZONE_DESERT && (t->act_food == 0 || t->act_water == 0) && t->population > 60)
return;
}
/* Use the normal growth rate values if new buildings have been funded in
* this town and the growth rate is set to none. */
uint growth_multiplier = _settings_game.economy.town_growth_rate != 0 ? _settings_game.economy.town_growth_rate - 1 : 1;
m >>= growth_multiplier;
if (t->larger_town) m /= 2;
t->growth_rate = m / (t->num_houses / 50 + 1);
if (m <= t->grow_counter)
t->grow_counter = m;
SetBit(t->flags12, TOWN_IS_FUNDED);
}
static void UpdateTownAmounts(Town *t)
{
/* Using +1 here to prevent overflow and division by zero */
t->pct_pass_transported = t->new_act_pass * 256 / (t->new_max_pass + 1);
t->max_pass = t->new_max_pass; t->new_max_pass = 0;
t->act_pass = t->new_act_pass; t->new_act_pass = 0;
t->act_food = t->new_act_food; t->new_act_food = 0;
t->act_water = t->new_act_water; t->new_act_water = 0;
/* Using +1 here to prevent overflow and division by zero */
t->pct_mail_transported = t->new_act_mail * 256 / (t->new_max_mail + 1);
t->max_mail = t->new_max_mail; t->new_max_mail = 0;
t->act_mail = t->new_act_mail; t->new_act_mail = 0;
InvalidateWindow(WC_TOWN_VIEW, t->index);
}
static void UpdateTownUnwanted(Town *t)
{
const Company *c;
FOR_ALL_COMPANIES(c) {
if (t->unwanted[c->index] > 0) t->unwanted[c->index]--;
}
}
/**
* Checks whether the local authority allows construction of a new station (rail, road, airport, dock) on the given tile
* @param tile The tile where the station shall be constructed.
* @param flags Command flags. DC_NO_TEST_TOWN_RATING is tested.
*/
bool CheckIfAuthorityAllowsNewStation(TileIndex tile, DoCommandFlag flags)
{
if (!IsValidCompanyID(_current_company) || (flags & DC_NO_TEST_TOWN_RATING)) return true;
Town *t = ClosestTownFromTile(tile, _settings_game.economy.dist_local_authority);
if (t == NULL) return true;
if (t->ratings[_current_company] > RATING_VERYPOOR) return true;
_error_message = STR_2009_LOCAL_AUTHORITY_REFUSES;
SetDParam(0, t->index);
return false;
}
Town *CalcClosestTownFromTile(TileIndex tile, uint threshold)
{
Town *t;
uint best = threshold;
Town *best_town = NULL;
FOR_ALL_TOWNS(t) {
uint dist = DistanceManhattan(tile, t->xy);
if (dist < best) {
best = dist;
best_town = t;
}
}
return best_town;
}
Town *ClosestTownFromTile(TileIndex tile, uint threshold)
{
switch (GetTileType(tile)) {
case MP_ROAD:
if (!HasTownOwnedRoad(tile)) {
TownID tid = GetTownIndex(tile);
if (tid == (TownID)INVALID_TOWN) {
/* in the case we are generating "many random towns", this value may be INVALID_TOWN */
if (_generating_world) return CalcClosestTownFromTile(tile, threshold);
assert(GetNumTowns() == 0);
return NULL;
}
Town *town = GetTown(tid);
assert(town->IsValid());
assert(town == CalcClosestTownFromTile(tile));
if (DistanceManhattan(tile, town->xy) >= threshold) town = NULL;
return town;
}
/* FALL THROUGH */
case MP_HOUSE:
return GetTownByTile(tile);
default:
return CalcClosestTownFromTile(tile, threshold);
}
}
static bool _town_rating_test = false;
SmallMap<const Town *, int, 4> _town_test_ratings;
void SetTownRatingTestMode(bool mode)
{
static int ref_count = 0;
if (mode) {
if (ref_count == 0) {
_town_test_ratings.Clear();
}
ref_count++;
} else {
assert(ref_count > 0);
ref_count--;
}
_town_rating_test = !(ref_count == 0);
}
static int GetRating(const Town *t)
{
if (_town_rating_test) {
SmallMap<const Town *, int>::iterator it = _town_test_ratings.Find(t);
if (it != _town_test_ratings.End()) {
return it->second;
}
}
return t->ratings[_current_company];
}
/**
* Changes town rating of the current company
* @param t Town to affect
* @param add Value to add
* @param max Minimum (add < 0) resp. maximum (add > 0) rating that should be archievable with this change
* @param flags Command flags, especially DC_NO_MODIFY_TOWN_RATING is tested
*/
void ChangeTownRating(Town *t, int add, int max, DoCommandFlag flags)
{
/* if magic_bulldozer cheat is active, town doesn't penaltize for removing stuff */
if (t == NULL || (flags & DC_NO_MODIFY_TOWN_RATING) ||
!IsValidCompanyID(_current_company) ||
(_cheats.magic_bulldozer.value && add < 0)) {
return;
}
int rating = GetRating(t);
if (add < 0) {
if (rating > max) {
rating += add;
if (rating < max) rating = max;
}
} else {
if (rating < max) {
rating += add;
if (rating > max) rating = max;
}
}
if (_town_rating_test) {
_town_test_ratings[t] = rating;
} else {
SetBit(t->have_ratings, _current_company);
t->ratings[_current_company] = rating;
InvalidateWindow(WC_TOWN_AUTHORITY, t->index);
}
}
/* penalty for removing town-owned stuff */
static const int _default_rating_settings [3][3] = {
/* ROAD_REMOVE, TUNNELBRIDGE_REMOVE, INDUSTRY_REMOVE */
{ 0, 128, 384}, // Permissive
{ 48, 192, 480}, // Neutral
{ 96, 384, 768}, // Hostile
};
bool CheckforTownRating(DoCommandFlag flags, Town *t, byte type)
{
/* if magic_bulldozer cheat is active, town doesn't restrict your destructive actions */
if (t == NULL || !IsValidCompanyID(_current_company) || _cheats.magic_bulldozer.value)
return true;
/* check if you're allowed to remove the street/bridge/tunnel/industry
* owned by a town no removal if rating is lower than ... depends now on
* difficulty setting. Minimum town rating selected by difficulty level
*/
int modemod = _default_rating_settings[_settings_game.difficulty.town_council_tolerance][type];
if (GetRating(t) < 16 + modemod && !(flags & DC_NO_TEST_TOWN_RATING)) {
SetDParam(0, t->index);
_error_message = STR_2009_LOCAL_AUTHORITY_REFUSES;
return false;
}
return true;
}
void TownsMonthlyLoop()
{
Town *t;
FOR_ALL_TOWNS(t) {
if (t->road_build_months != 0) t->road_build_months--;
if (t->exclusive_counter != 0)
if (--t->exclusive_counter == 0) t->exclusivity = INVALID_COMPANY;
UpdateTownGrowRate(t);
UpdateTownAmounts(t);
UpdateTownUnwanted(t);
}
}
void TownsYearlyLoop()
{
/* Increment house ages */
for (TileIndex t = 0; t < MapSize(); t++) {
if (!IsTileType(t, MP_HOUSE)) continue;
IncrementHouseAge(t);
}
}
void InitializeTowns()
{
/* Clean the town pool and create 1 block in it */
_Town_pool.CleanPool();
_Town_pool.AddBlockToPool();
memset(_subsidies, 0, sizeof(_subsidies));
for (Subsidy *s = _subsidies; s != endof(_subsidies); s++) {
s->cargo_type = CT_INVALID;
}
_cur_town_ctr = 0;
_cur_town_iter = 0;
_total_towns = 0;
}
static CommandCost TerraformTile_Town(TileIndex tile, DoCommandFlag flags, uint z_new, Slope tileh_new)
{
if (AutoslopeEnabled()) {
HouseID house = GetHouseType(tile);
GetHouseNorthPart(house); // modifies house to the ID of the north tile
const HouseSpec *hs = GetHouseSpecs(house);
/* Here we differ from TTDP by checking TILE_NOT_SLOPED */
if (((hs->building_flags & TILE_NOT_SLOPED) == 0) && !IsSteepSlope(tileh_new) &&
(GetTileMaxZ(tile) == z_new + GetSlopeMaxZ(tileh_new))) return CommandCost(EXPENSES_CONSTRUCTION, _price.terraform);
}
return DoCommand(tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR);
}
/** Tile callback functions for a town */
extern const TileTypeProcs _tile_type_town_procs = {
DrawTile_Town, // draw_tile_proc
GetSlopeZ_Town, // get_slope_z_proc
ClearTile_Town, // clear_tile_proc
GetAcceptedCargo_Town, // get_accepted_cargo_proc
GetTileDesc_Town, // get_tile_desc_proc
GetTileTrackStatus_Town, // get_tile_track_status_proc
ClickTile_Town, // click_tile_proc
AnimateTile_Town, // animate_tile_proc
TileLoop_Town, // tile_loop_clear
ChangeTileOwner_Town, // change_tile_owner_clear
GetProducedCargo_Town, // get_produced_cargo_proc
NULL, // vehicle_enter_tile_proc
GetFoundation_Town, // get_foundation_proc
TerraformTile_Town, // terraform_tile_proc
};
void ResetHouses()
{
memset(&_house_specs, 0, sizeof(_house_specs));
memcpy(&_house_specs, &_original_house_specs, sizeof(_original_house_specs));
/* Reset any overrides that have been set. */
_house_mngr.ResetOverride();
}
| 82,531
|
C++
|
.cpp
| 2,316
| 32.981434
| 178
| 0.695672
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,146
|
newgrf_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/newgrf_gui.cpp
|
/* $Id$ */
/** @file newgrf_gui.cpp GUI to change NewGRF settings. */
#include "stdafx.h"
#include "gui.h"
#include "window_gui.h"
#include "textbuf_gui.h"
#include "newgrf.h"
#include "strings_func.h"
#include "window_func.h"
#include "string_func.h"
#include "gfx_func.h"
#include "gamelog.h"
#include "settings_func.h"
#include "widgets/dropdown_type.h"
#include "network/network.h"
#include "network/network_content.h"
#include "table/strings.h"
#include "table/sprites.h"
/** Parse an integerlist string and set each found value
* @param p the string to be parsed. Each element in the list is seperated by a
* comma or a space character
* @param items pointer to the integerlist-array that will be filled with values
* @param maxitems the maximum number of elements the integerlist-array has
* @return returns the number of items found, or -1 on an error */
static int parse_intlist(const char *p, int *items, int maxitems)
{
int n = 0, v;
char *end;
for (;;) {
v = strtol(p, &end, 0);
if (p == end || n == maxitems) return -1;
p = end;
items[n++] = v;
if (*p == '\0') break;
if (*p != ',' && *p != ' ') return -1;
p++;
}
return n;
}
static void ShowNewGRFInfo(const GRFConfig *c, uint x, uint y, uint w, uint bottom, bool show_params)
{
char buff[256];
if (c->error != NULL) {
char message[512];
SetDParamStr(0, c->error->custom_message); // is skipped by built-in messages
SetDParam (1, STR_JUST_RAW_STRING);
SetDParamStr(2, c->filename);
SetDParam (3, STR_JUST_RAW_STRING);
SetDParamStr(4, c->error->data);
for (uint i = 0; i < c->error->num_params; i++) {
uint32 param = 0;
byte param_number = c->error->param_number[i];
if (param_number < c->num_params) param = c->param[param_number];
SetDParam(5 + i, param);
}
GetString(message, c->error->custom_message == NULL ? c->error->message : STR_JUST_RAW_STRING, lastof(message));
SetDParamStr(0, message);
y += DrawStringMultiLine(x, y, c->error->severity, w, bottom - y);
}
/* Draw filename or not if it is not known (GRF sent over internet) */
if (c->filename != NULL) {
SetDParamStr(0, c->filename);
y += DrawStringMultiLine(x, y, STR_NEWGRF_FILENAME, w, bottom - y);
}
/* Prepare and draw GRF ID */
snprintf(buff, lengthof(buff), "%08X", BSWAP32(c->grfid));
SetDParamStr(0, buff);
y += DrawStringMultiLine(x, y, STR_NEWGRF_GRF_ID, w, bottom - y);
/* Prepare and draw MD5 sum */
md5sumToString(buff, lastof(buff), c->md5sum);
SetDParamStr(0, buff);
y += DrawStringMultiLine(x, y, STR_NEWGRF_MD5SUM, w, bottom - y);
/* Show GRF parameter list */
if (show_params) {
if (c->num_params > 0) {
GRFBuildParamList(buff, c, lastof(buff));
SetDParam(0, STR_JUST_RAW_STRING);
SetDParamStr(1, buff);
} else {
SetDParam(0, STR_01A9_NONE);
}
y += DrawStringMultiLine(x, y, STR_NEWGRF_PARAMETER, w, bottom - y);
/* Draw the palette of the NewGRF */
SetDParamStr(0, c->windows_paletted ? "Windows" : "DOS");
y += DrawStringMultiLine(x, y, STR_NEWGRF_PALETTE, w, bottom - y);
}
/* Show flags */
if (c->status == GCS_NOT_FOUND) y += DrawStringMultiLine(x, y, STR_NEWGRF_NOT_FOUND, w, bottom - y);
if (c->status == GCS_DISABLED) y += DrawStringMultiLine(x, y, STR_NEWGRF_DISABLED, w, bottom - y);
if (HasBit(c->flags, GCF_COMPATIBLE)) y += DrawStringMultiLine(x, y, STR_NEWGRF_COMPATIBLE_LOADED, w, bottom - y);
/* Draw GRF info if it exists */
if (c->info != NULL && !StrEmpty(c->info)) {
SetDParam(0, STR_JUST_RAW_STRING);
SetDParamStr(1, c->info);
y += DrawStringMultiLine(x, y, STR_02BD, w, bottom - y);
} else {
y += DrawStringMultiLine(x, y, STR_NEWGRF_NO_INFO, w, bottom - y);
}
}
/**
* Window for adding NewGRF files
*/
struct NewGRFAddWindow : public Window {
/* Names of the add a newgrf window widgets */
enum AddNewGRFWindowWidgets {
ANGRFW_CLOSEBOX = 0,
ANGRFW_CAPTION,
ANGRFW_BACKGROUND,
ANGRFW_GRF_LIST,
ANGRFW_SCROLLBAR,
ANGRFW_GRF_INFO,
ANGRFW_ADD,
ANGRFW_RESCAN,
ANGRFW_RESIZE,
};
GRFConfig **list;
const GRFConfig *sel;
NewGRFAddWindow(const WindowDesc *desc, GRFConfig **list) : Window(desc, 0)
{
this->list = list;
this->resize.step_height = 10;
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
const GRFConfig *c;
const Widget *wl = &this->widget[ANGRFW_GRF_LIST];
int n = 0;
/* Count the number of GRFs */
for (c = _all_grfs; c != NULL; c = c->next) n++;
this->vscroll.cap = (wl->bottom - wl->top) / 10;
SetVScrollCount(this, n);
this->SetWidgetDisabledState(ANGRFW_ADD, this->sel == NULL || this->sel->IsOpenTTDBaseGRF());
this->DrawWidgets();
GfxFillRect(wl->left + 1, wl->top + 1, wl->right, wl->bottom, 0xD7);
uint y = wl->top + 1;
for (c = _all_grfs, n = 0; c != NULL && n < (this->vscroll.pos + this->vscroll.cap); c = c->next, n++) {
if (n >= this->vscroll.pos) {
bool h = c == this->sel;
const char *text = (c->name != NULL && !StrEmpty(c->name)) ? c->name : c->filename;
/* Draw selection background */
if (h) GfxFillRect(3, y, this->width - 15, y + 9, 156);
DoDrawStringTruncated(text, 4, y, h ? TC_WHITE : TC_ORANGE, this->width - 18);
y += 10;
}
}
if (this->sel != NULL) {
const Widget *wi = &this->widget[ANGRFW_GRF_INFO];
ShowNewGRFInfo(this->sel, wi->left + 2, wi->top + 2, wi->right - wi->left - 2, wi->bottom, false);
}
}
virtual void OnDoubleClick(Point pt, int widget)
{
if (widget == ANGRFW_GRF_LIST) this->OnClick(pt, ANGRFW_ADD);
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case ANGRFW_GRF_LIST: {
/* Get row... */
const GRFConfig *c;
uint i = (pt.y - this->widget[ANGRFW_GRF_LIST].top) / 10 + this->vscroll.pos;
for (c = _all_grfs; c != NULL && i > 0; c = c->next, i--) {}
this->sel = c;
this->SetDirty();
break;
}
case ANGRFW_ADD: // Add selection to list
if (this->sel != NULL) {
const GRFConfig *src = this->sel;
GRFConfig **list;
/* Find last entry in the list, checking for duplicate grfid on the way */
for (list = this->list; *list != NULL; list = &(*list)->next) {
if ((*list)->grfid == src->grfid) {
ShowErrorMessage(INVALID_STRING_ID, STR_NEWGRF_DUPLICATE_GRFID, 0, 0);
return;
}
}
/* Copy GRF details from scanned list */
GRFConfig *c = CallocT<GRFConfig>(1);
*c = *src;
c->filename = strdup(src->filename);
if (src->name != NULL) c->name = strdup(src->name);
if (src->info != NULL) c->info = strdup(src->info);
c->next = NULL;
/* Append GRF config to configuration list */
*list = c;
DeleteWindowByClass(WC_SAVELOAD);
InvalidateWindowData(WC_GAME_OPTIONS, 0);
}
break;
case ANGRFW_RESCAN: // Rescan list
this->sel = NULL;
ScanNewGRFFiles();
this->SetDirty();
break;
}
}
};
/* Widget definition for the add a newgrf window */
static const Widget _newgrf_add_dlg_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW }, // ANGRFW_CLOSEBOX
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_GREY, 11, 306, 0, 13, STR_NEWGRF_ADD_CAPTION, STR_018C_WINDOW_TITLE_DRAG_THIS }, // ANGRFW_CAPTION
{ WWT_PANEL, RESIZE_RB, COLOUR_GREY, 0, 294, 14, 121, 0x0, STR_NULL }, // ANGRFW_BACKGROUND
{ WWT_INSET, RESIZE_RB, COLOUR_GREY, 2, 292, 16, 119, 0x0, STR_NULL }, // ANGRFW_GRF_LIST
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_GREY, 295, 306, 14, 121, 0x0, STR_NULL }, // ANGRFW_SCROLLBAR
{ WWT_PANEL, RESIZE_RTB, COLOUR_GREY, 0, 306, 122, 224, 0x0, STR_NULL }, // ANGRFW_GRF_INFO
{ WWT_PUSHTXTBTN, RESIZE_RTB, COLOUR_GREY, 0, 146, 225, 236, STR_NEWGRF_ADD_FILE, STR_NEWGRF_ADD_FILE_TIP }, // ANGRFW_ADD
{ WWT_PUSHTXTBTN, RESIZE_LRTB, COLOUR_GREY, 147, 294, 225, 236, STR_NEWGRF_RESCAN_FILES, STR_NEWGRF_RESCAN_FILES_TIP }, // ANGRFW_RESCAN
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_GREY, 295, 306, 225, 236, 0x0, STR_RESIZE_BUTTON }, // ANGRFW_RESIZE
{ WIDGETS_END },
};
/* Window definition for the add a newgrf window */
static const WindowDesc _newgrf_add_dlg_desc(
WDP_CENTER, WDP_CENTER, 307, 237, 307, 337,
WC_SAVELOAD, WC_NONE,
WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_STD_BTN | WDF_UNCLICK_BUTTONS | WDF_RESIZABLE,
_newgrf_add_dlg_widgets
);
static GRFPresetList _grf_preset_list;
class DropDownListPresetItem : public DropDownListItem {
public:
DropDownListPresetItem(int result) : DropDownListItem(result, false) {}
virtual ~DropDownListPresetItem() {}
bool Selectable() const
{
return true;
}
void Draw(int x, int y, uint width, uint height, bool sel, int bg_colour) const
{
DoDrawStringTruncated(_grf_preset_list[this->result], x + 2, y, sel ? TC_WHITE : TC_BLACK, x + width);
}
};
static void NewGRFConfirmationCallback(Window *w, bool confirmed);
/**
* Window for showing NewGRF files
*/
struct NewGRFWindow : public Window {
/* Names of the manage newgrfs window widgets */
enum ShowNewGRFStateWidgets {
SNGRFS_CLOSEBOX = 0,
SNGRFS_CAPTION,
SNGRFS_BACKGROUND1,
SNGRFS_PRESET_LIST,
SNGRFS_PRESET_SAVE,
SNGRFS_PRESET_DELETE,
SNGRFS_BACKGROUND2,
SNGRFS_ADD,
SNGRFS_REMOVE,
SNGRFS_MOVE_UP,
SNGRFS_MOVE_DOWN,
SNGRFS_FILE_LIST,
SNGRFS_SCROLLBAR,
SNGRFS_NEWGRF_INFO,
SNGRFS_SET_PARAMETERS,
SNGRFS_TOGGLE_PALETTE,
SNGRFS_APPLY_CHANGES,
SNGRFS_CONTENT_DOWNLOAD,
SNGRFS_RESIZE,
};
GRFConfig **orig_list; ///< grf list the window is shown with
GRFConfig *list; ///< temporary grf list to which changes are made
GRFConfig *sel; ///< selected grf item
bool editable; ///< is the window editable
bool show_params; ///< are the grf-parameters shown in the info-panel
bool execute; ///< on pressing 'apply changes' are grf changes applied immediately, or only list is updated
int query_widget; ///< widget that opened a query
int preset; ///< selected preset
NewGRFWindow(const WindowDesc *desc, bool editable, bool show_params, bool exec_changes, GRFConfig **config) : Window(desc, 0)
{
this->resize.step_height = 14;
this->sel = NULL;
this->list = NULL;
this->orig_list = config;
this->editable = editable;
this->execute = exec_changes;
this->show_params = show_params;
this->preset = -1;
CopyGRFConfigList(&this->list, *config, false);
GetGRFPresetList(&_grf_preset_list);
this->FindWindowPlacementAndResize(desc);
this->SetupNewGRFWindow();
}
~NewGRFWindow()
{
if (this->editable && !this->execute) {
CopyGRFConfigList(this->orig_list, this->list, true);
ResetGRFConfig(false);
ReloadNewGRFData();
}
/* Remove the temporary copy of grf-list used in window */
ClearGRFConfigList(&this->list);
_grf_preset_list.Clear();
}
void SetupNewGRFWindow()
{
const GRFConfig *c;
int i;
for (c = this->list, i = 0; c != NULL; c = c->next, i++) {}
this->vscroll.cap = (this->widget[SNGRFS_FILE_LIST].bottom - this->widget[SNGRFS_FILE_LIST].top) / 14 + 1;
SetVScrollCount(this, i);
this->SetWidgetsDisabledState(!this->editable,
SNGRFS_PRESET_LIST,
SNGRFS_ADD,
SNGRFS_APPLY_CHANGES,
SNGRFS_TOGGLE_PALETTE,
WIDGET_LIST_END
);
}
virtual void OnPaint()
{
bool disable_all = this->sel == NULL || !this->editable;
this->SetWidgetsDisabledState(disable_all,
SNGRFS_REMOVE,
SNGRFS_MOVE_UP,
SNGRFS_MOVE_DOWN,
WIDGET_LIST_END
);
this->SetWidgetDisabledState(SNGRFS_SET_PARAMETERS, !this->show_params || disable_all);
this->SetWidgetDisabledState(SNGRFS_TOGGLE_PALETTE, disable_all);
if (!disable_all) {
/* All widgets are now enabled, so disable widgets we can't use */
if (this->sel == this->list) this->DisableWidget(SNGRFS_MOVE_UP);
if (this->sel->next == NULL) this->DisableWidget(SNGRFS_MOVE_DOWN);
if (this->sel->IsOpenTTDBaseGRF()) this->DisableWidget(SNGRFS_REMOVE);
}
if (this->preset == -1) {
this->widget[SNGRFS_PRESET_LIST].data = STR_02BF_CUSTOM;
} else {
SetDParamStr(0, _grf_preset_list[this->preset]);
this->widget[SNGRFS_PRESET_LIST].data = STR_JUST_RAW_STRING;
}
this->SetWidgetDisabledState(SNGRFS_PRESET_DELETE, this->preset == -1);
bool has_missing = false;
bool has_compatible = false;
for (const GRFConfig *c = this->list; !has_missing && c != NULL; c = c->next) {
has_missing |= c->status == GCS_NOT_FOUND;
has_compatible |= HasBit(c->flags, GCF_COMPATIBLE);
}
if (has_missing || has_compatible) {
this->widget[SNGRFS_CONTENT_DOWNLOAD].data = STR_CONTENT_INTRO_MISSING_BUTTON;
this->widget[SNGRFS_CONTENT_DOWNLOAD].tooltips = STR_CONTENT_INTRO_MISSING_BUTTON_TIP;
} else {
this->widget[SNGRFS_CONTENT_DOWNLOAD].data = STR_CONTENT_INTRO_BUTTON;
this->widget[SNGRFS_CONTENT_DOWNLOAD].tooltips = STR_CONTENT_INTRO_BUTTON_TIP;
}
this->SetWidgetDisabledState(SNGRFS_PRESET_SAVE, has_missing);
this->DrawWidgets();
/* Draw NewGRF list */
int y = this->widget[SNGRFS_FILE_LIST].top;
int i = 0;
for (const GRFConfig *c = this->list; c != NULL; c = c->next, i++) {
if (i >= this->vscroll.pos && i < this->vscroll.pos + this->vscroll.cap) {
const char *text = (c->name != NULL && !StrEmpty(c->name)) ? c->name : c->filename;
SpriteID pal;
byte txtoffset;
/* Pick a colour */
switch (c->status) {
case GCS_NOT_FOUND:
case GCS_DISABLED:
pal = PALETTE_TO_RED;
break;
case GCS_ACTIVATED:
pal = PALETTE_TO_GREEN;
break;
default:
pal = PALETTE_TO_BLUE;
break;
}
/* Do not show a "not-failure" colour when it actually failed to load */
if (pal != PALETTE_TO_RED) {
if (HasBit(c->flags, GCF_STATIC)) {
pal = PALETTE_TO_GREY;
} else if (HasBit(c->flags, GCF_COMPATIBLE)) {
pal = PALETTE_TO_ORANGE;
}
}
DrawSprite(SPR_SQUARE, pal, 5, y + 2);
if (c->error != NULL) DrawSprite(SPR_WARNING_SIGN, 0, 20, y + 2);
txtoffset = c->error != NULL ? 35 : 25;
DoDrawStringTruncated(text, txtoffset, y + 3, this->sel == c ? TC_WHITE : TC_BLACK, this->width - txtoffset - 10);
y += 14;
}
}
if (this->sel != NULL) {
/* Draw NewGRF file info */
const Widget *wi = &this->widget[SNGRFS_NEWGRF_INFO];
ShowNewGRFInfo(this->sel, wi->left + 2, wi->top + 2, wi->right - wi->left - 2, wi->bottom, this->show_params);
}
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case SNGRFS_PRESET_LIST: {
DropDownList *list = new DropDownList();
/* Add 'None' option for clearing list */
list->push_back(new DropDownListStringItem(STR_NONE, -1, false));
for (uint i = 0; i < _grf_preset_list.Length(); i++) {
if (_grf_preset_list[i] != NULL) {
list->push_back(new DropDownListPresetItem(i));
}
}
ShowDropDownList(this, list, this->preset, SNGRFS_PRESET_LIST);
break;
}
case SNGRFS_PRESET_SAVE:
this->query_widget = widget;
ShowQueryString(STR_EMPTY, STR_NEWGRF_PRESET_SAVE_QUERY, 32, 100, this, CS_ALPHANUMERAL, QSF_NONE);
break;
case SNGRFS_PRESET_DELETE:
if (this->preset == -1) return;
DeleteGRFPresetFromConfig(_grf_preset_list[this->preset]);
GetGRFPresetList(&_grf_preset_list);
this->preset = -1;
this->SetDirty();
break;
case SNGRFS_ADD: // Add GRF
DeleteWindowByClass(WC_SAVELOAD);
new NewGRFAddWindow(&_newgrf_add_dlg_desc, &this->list);
break;
case SNGRFS_REMOVE: { // Remove GRF
GRFConfig **pc, *c, *newsel;
/* Choose the next GRF file to be the selected file */
newsel = this->sel->next;
for (pc = &this->list; (c = *pc) != NULL; pc = &c->next) {
/* If the new selection is empty (i.e. we're deleting the last item
* in the list, pick the file just before the selected file */
if (newsel == NULL && c->next == this->sel) newsel = c;
if (c == this->sel) {
*pc = c->next;
free(c);
break;
}
}
this->sel = newsel;
this->preset = -1;
this->SetupNewGRFWindow();
this->SetDirty();
break;
}
case SNGRFS_MOVE_UP: { // Move GRF up
GRFConfig **pc, *c;
if (this->sel == NULL) break;
for (pc = &this->list; (c = *pc) != NULL; pc = &c->next) {
if (c->next == this->sel) {
c->next = this->sel->next;
this->sel->next = c;
*pc = this->sel;
break;
}
}
this->preset = -1;
this->SetDirty();
break;
}
case SNGRFS_MOVE_DOWN: { // Move GRF down
GRFConfig **pc, *c;
if (this->sel == NULL) break;
for (pc = &this->list; (c = *pc) != NULL; pc = &c->next) {
if (c == this->sel) {
*pc = c->next;
c->next = c->next->next;
(*pc)->next = c;
break;
}
}
this->preset = -1;
this->SetDirty();
break;
}
case SNGRFS_FILE_LIST: { // Select a GRF
GRFConfig *c;
uint i = (pt.y - this->widget[SNGRFS_FILE_LIST].top) / 14 + this->vscroll.pos;
for (c = this->list; c != NULL && i > 0; c = c->next, i--) {}
this->sel = c;
this->SetDirty();
break;
}
case SNGRFS_APPLY_CHANGES: // Apply changes made to GRF list
if (this->execute) {
ShowQuery(
STR_POPUP_CAUTION_CAPTION,
STR_NEWGRF_CONFIRMATION_TEXT,
this,
NewGRFConfirmationCallback
);
} else {
CopyGRFConfigList(this->orig_list, this->list, true);
ResetGRFConfig(false);
ReloadNewGRFData();
}
break;
case SNGRFS_SET_PARAMETERS: { // Edit parameters
if (this->sel == NULL) break;
this->query_widget = widget;
static char buff[512];
GRFBuildParamList(buff, this->sel, lastof(buff));
SetDParamStr(0, buff);
ShowQueryString(STR_JUST_RAW_STRING, STR_NEWGRF_PARAMETER_QUERY, 63, 250, this, CS_ALPHANUMERAL, QSF_NONE);
break;
}
case SNGRFS_TOGGLE_PALETTE:
if (this->sel != NULL) {
this->sel->windows_paletted ^= true;
this->SetDirty();
}
break;
case SNGRFS_CONTENT_DOWNLOAD:
if (!_network_available) {
ShowErrorMessage(INVALID_STRING_ID, STR_NETWORK_ERR_NOTAVAILABLE, 0, 0);
} else {
#if defined(ENABLE_NETWORK)
/* Only show the things in the current list, or everything when nothing's selected */
ContentVector cv;
for (const GRFConfig *c = this->list; c != NULL; c = c->next) {
if (c->status != GCS_NOT_FOUND && !HasBit(c->flags, GCF_COMPATIBLE)) continue;
ContentInfo *ci = new ContentInfo();
ci->type = CONTENT_TYPE_NEWGRF;
ci->state = ContentInfo::DOES_NOT_EXIST;
ttd_strlcpy(ci->name, c->name != NULL ? c->name : c->filename, lengthof(ci->name));
ci->unique_id = BSWAP32(c->grfid);
memcpy(ci->md5sum, c->md5sum, sizeof(ci->md5sum));
if (HasBit(c->flags, GCF_COMPATIBLE)) GamelogGetOriginalGRFMD5Checksum(c->grfid, ci->md5sum);
*cv.Append() = ci;
}
ShowNetworkContentListWindow(cv.Length() == 0 ? NULL : &cv, CONTENT_TYPE_NEWGRF);
#endif
}
break;
}
}
virtual void OnDropdownSelect(int widget, int index)
{
if (index == -1) {
ClearGRFConfigList(&this->list);
this->preset = -1;
} else {
GRFConfig *c = LoadGRFPresetFromConfig(_grf_preset_list[index]);
if (c != NULL) {
this->sel = NULL;
ClearGRFConfigList(&this->list);
this->list = c;
this->preset = index;
}
}
this->sel = NULL;
this->SetupNewGRFWindow();
this->SetDirty();
}
virtual void OnQueryTextFinished(char *str)
{
if (str == NULL) return;
switch (this->query_widget) {
case SNGRFS_PRESET_SAVE:
SaveGRFPresetToConfig(str, this->list);
GetGRFPresetList(&_grf_preset_list);
/* Switch to this preset */
for (uint i = 0; i < _grf_preset_list.Length(); i++) {
if (_grf_preset_list[i] != NULL && strcmp(_grf_preset_list[i], str) == 0) {
this->preset = i;
break;
}
}
this->SetDirty();
break;
case SNGRFS_SET_PARAMETERS: {
/* Parse our new "int list" */
GRFConfig *c = this->sel;
c->num_params = parse_intlist(str, (int*)c->param, lengthof(c->param));
/* parse_intlist returns -1 on error */
if (c->num_params == (byte)-1) c->num_params = 0;
this->preset = -1;
this->SetDirty();
break;
}
}
}
virtual void OnResize(Point new_size, Point delta)
{
if (delta.x != 0) {
ResizeButtons(this, SNGRFS_ADD, SNGRFS_MOVE_DOWN);
ResizeButtons(this, SNGRFS_SET_PARAMETERS, SNGRFS_APPLY_CHANGES);
}
this->vscroll.cap += delta.y / 14;
this->widget[SNGRFS_FILE_LIST].data = (this->vscroll.cap << 8) + 1;
this->SetupNewGRFWindow();
}
virtual void OnInvalidateData(int data)
{
switch (data) {
default: NOT_REACHED();
case 0:
this->preset = -1;
this->SetupNewGRFWindow();
break;
case 1:
/* Search the list for items that are now found and mark them as such. */
for (GRFConfig *c = this->list; c != NULL; c = c->next) {
if (c->status != GCS_NOT_FOUND) continue;
const GRFConfig *f = FindGRFConfig(c->grfid, c->md5sum);
if (f == NULL) continue;
free(c->filename);
free(c->name);
free(c->info);
c->filename = f->filename == NULL ? NULL : strdup(f->filename);
c->name = f->name == NULL ? NULL : strdup(f->name);;
c->info = f->info == NULL ? NULL : strdup(f->info);;
c->status = GCS_UNKNOWN;
}
break;
}
}
};
/* Widget definition of the manage newgrfs window */
static const Widget _newgrf_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_MAUVE, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW }, // SNGRFS_CLOSEBOX
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_MAUVE, 11, 299, 0, 13, STR_NEWGRF_SETTINGS_CAPTION, STR_018C_WINDOW_TITLE_DRAG_THIS }, // SNGRFS_CAPTION
{ WWT_PANEL, RESIZE_RIGHT, COLOUR_MAUVE, 0, 299, 14, 41, STR_NULL, STR_NULL }, // SNGRFS_BACKGROUND1
{ WWT_DROPDOWN, RESIZE_RIGHT, COLOUR_YELLOW, 10, 103, 16, 27, STR_EMPTY, STR_NEWGRF_PRESET_LIST_TIP }, // SNGRFS_PRESET_LIST
{ WWT_PUSHTXTBTN, RESIZE_LR, COLOUR_YELLOW, 104, 196, 16, 27, STR_NEWGRF_PRESET_SAVE, STR_NEWGRF_PRESET_SAVE_TIP }, // SNGRFS_PRESET_SAVE
{ WWT_PUSHTXTBTN, RESIZE_LR, COLOUR_YELLOW, 197, 289, 16, 27, STR_NEWGRF_PRESET_DELETE, STR_NEWGRF_PRESET_DELETE_TIP }, // SNGRFS_PRESET_DELETE
{ WWT_PANEL, RESIZE_RIGHT, COLOUR_MAUVE, 0, 299, 30, 45, STR_NULL, STR_NULL }, // SNGRFS_BACKGROUND
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_YELLOW, 10, 79, 32, 43, STR_NEWGRF_ADD, STR_NEWGRF_ADD_TIP }, // SNGRFS_ADD
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_YELLOW, 80, 149, 32, 43, STR_NEWGRF_REMOVE, STR_NEWGRF_REMOVE_TIP }, // SNGRFS_REMOVE
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_YELLOW, 150, 219, 32, 43, STR_NEWGRF_MOVEUP, STR_NEWGRF_MOVEUP_TIP }, // SNGRFS_MOVE_UP
{ WWT_PUSHTXTBTN, RESIZE_RIGHT, COLOUR_YELLOW, 220, 289, 32, 43, STR_NEWGRF_MOVEDOWN, STR_NEWGRF_MOVEDOWN_TIP }, // SNGRFS_MOVE_DOWN
{ WWT_MATRIX, RESIZE_RB, COLOUR_MAUVE, 0, 287, 46, 115, 0x501, STR_NEWGRF_FILE_TIP }, // SNGRFS_FILE_LIST
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_MAUVE, 288, 299, 46, 115, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST }, // SNGRFS_SCROLLBAR
{ WWT_PANEL, RESIZE_RTB, COLOUR_MAUVE, 0, 299, 116, 238, STR_NULL, STR_NULL }, // SNGRFS_NEWGRF_INFO
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_MAUVE, 0, 99, 239, 250, STR_NEWGRF_SET_PARAMETERS, STR_NULL }, // SNGRFS_SET_PARAMETERS
{ WWT_PUSHTXTBTN, RESIZE_RTB, COLOUR_MAUVE, 100, 199, 239, 250, STR_NEWGRF_TOGGLE_PALETTE, STR_NEWGRF_TOGGLE_PALETTE_TIP }, // SNGRFS_TOGGLE_PALETTE
{ WWT_PUSHTXTBTN, RESIZE_RTB, COLOUR_MAUVE, 200, 299, 239, 250, STR_NEWGRF_APPLY_CHANGES, STR_NULL }, // SNGRFS_APPLY_CHANGES
{ WWT_PUSHTXTBTN, RESIZE_RTB, COLOUR_MAUVE, 0, 287, 251, 262, STR_CONTENT_INTRO_BUTTON, STR_CONTENT_INTRO_BUTTON_TIP }, // SNGRFS_DOWNLOAD_CONTENT
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_MAUVE, 288, 299, 251, 262, 0x0, STR_RESIZE_BUTTON }, // SNGRFS_RESIZE
{ WIDGETS_END },
};
/* Window definition of the manage newgrfs window */
static const WindowDesc _newgrf_desc(
WDP_CENTER, WDP_CENTER, 300, 263, 300, 263,
WC_GAME_OPTIONS, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_RESIZABLE,
_newgrf_widgets
);
/** Callback function for the newgrf 'apply changes' confirmation window
* @param w Window which is calling this callback
* @param confirmed boolean value, true when yes was clicked, false otherwise
*/
static void NewGRFConfirmationCallback(Window *w, bool confirmed)
{
if (confirmed) {
NewGRFWindow *nw = dynamic_cast<NewGRFWindow*>(w);
GRFConfig *c;
int i = 0;
GamelogStartAction(GLAT_GRF);
GamelogGRFUpdate(_grfconfig, nw->list); // log GRF changes
CopyGRFConfigList(nw->orig_list, nw->list, false);
ReloadNewGRFData();
GamelogStopAction();
/* Show new, updated list */
for (c = nw->list; c != NULL && c != nw->sel; c = c->next, i++) {}
CopyGRFConfigList(&nw->list, *nw->orig_list, false);
for (c = nw->list; c != NULL && i > 0; c = c->next, i--) {}
nw->sel = c;
w->SetDirty();
}
}
/** Setup the NewGRF gui
* @param editable allow the user to make changes to the grfconfig in the window
* @param show_params show information about what parameters are set for the grf files
* @param exec_changes if changes are made to the list (editable is true), apply these
* changes immediately or only update the list
* @param config pointer to a linked-list of grfconfig's that will be shown */
void ShowNewGRFSettings(bool editable, bool show_params, bool exec_changes, GRFConfig **config)
{
DeleteWindowByClass(WC_GAME_OPTIONS);
new NewGRFWindow(&_newgrf_desc, editable, show_params, exec_changes, config);
}
| 26,414
|
C++
|
.cpp
| 677
| 35.288035
| 159
| 0.634781
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,147
|
map.cpp
|
EnergeticBark_OpenTTD-3DS/src/map.cpp
|
/* $Id$ */
/** @file map.cpp Base functions related to the map and distances on them. */
#include "stdafx.h"
#include "debug.h"
#include "core/bitmath_func.hpp"
#include "core/alloc_func.hpp"
#include "core/math_func.hpp"
#include "map_func.h"
#if defined(_MSC_VER)
/* Why the hell is that not in all MSVC headers?? */
extern "C" _CRTIMP void __cdecl _assert(void *, void *, unsigned);
#endif
uint _map_log_x; ///< 2^_map_log_x == _map_size_x
uint _map_log_y; ///< 2^_map_log_y == _map_size_y
uint _map_size_x; ///< Size of the map along the X
uint _map_size_y; ///< Size of the map along the Y
uint _map_size; ///< The number of tiles on the map
uint _map_tile_mask; ///< _map_size - 1 (to mask the mapsize)
Tile *_m = NULL; ///< Tiles of the map
TileExtended *_me = NULL; ///< Extended Tiles of the map
/*!
* (Re)allocates a map with the given dimension
* @param size_x the width of the map along the NE/SW edge
* @param size_y the 'height' of the map along the SE/NW edge
*/
void AllocateMap(uint size_x, uint size_y)
{
/* Make sure that the map size is within the limits and that
* the x axis size is a power of 2. */
if (size_x < 64 || size_x > 2048 ||
size_y < 64 || size_y > 2048 ||
(size_x & (size_x - 1)) != 0 ||
(size_y & (size_y - 1)) != 0)
error("Invalid map size");
DEBUG(map, 1, "Allocating map of size %dx%d", size_x, size_y);
_map_log_x = FindFirstBit(size_x);
_map_log_y = FindFirstBit(size_y);
_map_size_x = size_x;
_map_size_y = size_y;
_map_size = size_x * size_y;
_map_tile_mask = _map_size - 1;
free(_m);
free(_me);
_m = CallocT<Tile>(_map_size);
_me = CallocT<TileExtended>(_map_size);
}
#ifdef _DEBUG
TileIndex TileAdd(TileIndex tile, TileIndexDiff add,
const char *exp, const char *file, int line)
{
int dx;
int dy;
uint x;
uint y;
dx = add & MapMaxX();
if (dx >= (int)MapSizeX() / 2) dx -= MapSizeX();
dy = (add - dx) / (int)MapSizeX();
x = TileX(tile) + dx;
y = TileY(tile) + dy;
if (x >= MapSizeX() || y >= MapSizeY()) {
char buf[512];
snprintf(buf, lengthof(buf), "TILE_ADD(%s) when adding 0x%.4X and 0x%.4X failed",
exp, tile, add);
#if !defined(_MSC_VER) || defined(WINCE)
fprintf(stderr, "%s:%d %s\n", file, line, buf);
#else
_assert(buf, (char*)file, line);
#endif
}
assert(TileXY(x, y) == TILE_MASK(tile + add));
return TileXY(x, y);
}
#endif
/*!
* Scales the given value by the map size, where the given value is
* for a 256 by 256 map.
* @param n the value to scale
* @return the scaled size
*/
uint ScaleByMapSize(uint n)
{
/* First shift by 12 to prevent integer overflow for large values of n.
* >>12 is safe since the min mapsize is 64x64
* Add (1<<4)-1 to round upwards. */
return (n * (MapSize() >> 12) + (1 << 4) - 1) >> 4;
}
/*!
* Scales the given value by the maps circumference, where the given
* value is for a 256 by 256 map
* @param n the value to scale
* @return the scaled size
*/
uint ScaleByMapSize1D(uint n)
{
/* Normal circumference for the X+Y is 256+256 = 1<<9
* Note, not actually taking the full circumference into account,
* just half of it.
* (1<<9) - 1 is there to scale upwards. */
return (n * (MapSizeX() + MapSizeY()) + (1 << 9) - 1) >> 9;
}
/*!
* This function checks if we add addx/addy to tile, if we
* do wrap around the edges. For example, tile = (10,2) and
* addx = +3 and addy = -4. This function will now return
* INVALID_TILE, because the y is wrapped. This is needed in
* for example, farmland. When the tile is not wrapped,
* the result will be tile + TileDiffXY(addx, addy)
*
* @param tile the 'starting' point of the adding
* @param addx the amount of tiles in the X direction to add
* @param addy the amount of tiles in the Y direction to add
* @return translated tile, or INVALID_TILE when it would've wrapped.
*/
TileIndex TileAddWrap(TileIndex tile, int addx, int addy)
{
uint x = TileX(tile) + addx;
uint y = TileY(tile) + addy;
/* Are we about to wrap? */
if (x < MapMaxX() && y < MapMaxY())
return tile + TileDiffXY(addx, addy);
return INVALID_TILE;
}
/** 'Lookup table' for tile offsets given a DiagDirection */
extern const TileIndexDiffC _tileoffs_by_diagdir[] = {
{-1, 0}, ///< DIAGDIR_NE
{ 0, 1}, ///< DIAGDIR_SE
{ 1, 0}, ///< DIAGDIR_SW
{ 0, -1} ///< DIAGDIR_NW
};
/** 'Lookup table' for tile offsets given a Direction */
extern const TileIndexDiffC _tileoffs_by_dir[] = {
{-1, -1}, ///< DIR_N
{-1, 0}, ///< DIR_NE
{-1, 1}, ///< DIR_E
{ 0, 1}, ///< DIR_SE
{ 1, 1}, ///< DIR_S
{ 1, 0}, ///< DIR_SW
{ 1, -1}, ///< DIR_W
{ 0, -1} ///< DIR_NW
};
/*!
* Gets the Manhattan distance between the two given tiles.
* The Manhattan distance is the sum of the delta of both the
* X and Y component.
* Also known as L1-Norm
* @param t0 the start tile
* @param t1 the end tile
* @return the distance
*/
uint DistanceManhattan(TileIndex t0, TileIndex t1)
{
const uint dx = Delta(TileX(t0), TileX(t1));
const uint dy = Delta(TileY(t0), TileY(t1));
return dx + dy;
}
/*!
* Gets the 'Square' distance between the two given tiles.
* The 'Square' distance is the square of the shortest (straight line)
* distance between the two tiles.
* Also known as euclidian- or L2-Norm squared.
* @param t0 the start tile
* @param t1 the end tile
* @return the distance
*/
uint DistanceSquare(TileIndex t0, TileIndex t1)
{
const int dx = TileX(t0) - TileX(t1);
const int dy = TileY(t0) - TileY(t1);
return dx * dx + dy * dy;
}
/*!
* Gets the biggest distance component (x or y) between the two given tiles.
* Also known as L-Infinity-Norm.
* @param t0 the start tile
* @param t1 the end tile
* @return the distance
*/
uint DistanceMax(TileIndex t0, TileIndex t1)
{
const uint dx = Delta(TileX(t0), TileX(t1));
const uint dy = Delta(TileY(t0), TileY(t1));
return max(dx, dy);
}
/*!
* Gets the biggest distance component (x or y) between the two given tiles
* plus the Manhattan distance, i.e. two times the biggest distance component
* and once the smallest component.
* @param t0 the start tile
* @param t1 the end tile
* @return the distance
*/
uint DistanceMaxPlusManhattan(TileIndex t0, TileIndex t1)
{
const uint dx = Delta(TileX(t0), TileX(t1));
const uint dy = Delta(TileY(t0), TileY(t1));
return dx > dy ? 2 * dx + dy : 2 * dy + dx;
}
/*!
* Param the minimum distance to an edge
* @param tile the tile to get the distance from
* @return the distance from the edge in tiles
*/
uint DistanceFromEdge(TileIndex tile)
{
const uint xl = TileX(tile);
const uint yl = TileY(tile);
const uint xh = MapSizeX() - 1 - xl;
const uint yh = MapSizeY() - 1 - yl;
const uint minl = min(xl, yl);
const uint minh = min(xh, yh);
return min(minl, minh);
}
/*!
* Function performing a search around a center tile and going outward, thus in circle.
* Although it really is a square search...
* Every tile will be tested by means of the callback function proc,
* which will determine if yes or no the given tile meets criteria of search.
* @param tile to start the search from. Upon completion, it will return the tile matching the search
* @param size: number of tiles per side of the desired search area
* @param proc: callback testing function pointer.
* @param user_data to be passed to the callback function. Depends on the implementation
* @return result of the search
* @pre proc != NULL
* @pre size > 0
*/
bool CircularTileSearch(TileIndex *tile, uint size, TestTileOnSearchProc proc, void *user_data)
{
assert(proc != NULL);
assert(size > 0);
if (size % 2 == 1) {
/* If the length of the side is uneven, the center has to be checked
* separately, as the pattern of uneven sides requires to go around the center */
if (proc(*tile, user_data)) return true;
/* If tile test is not successful, get one tile down and left,
* ready for a test in first circle around center tile */
*tile = TILE_ADD(*tile, TileOffsByDir(DIR_W));
return CircularTileSearch(tile, size / 2, 1, 1, proc, user_data);
} else {
return CircularTileSearch(tile, size / 2, 0, 0, proc, user_data);
}
}
/*!
* Generalized circular search allowing for rectangles and a hole.
* Function performing a search around a center rectangle and going outward.
* The center rectangle is left out from the search. To do a rectangular search
* without a hole, set either h or w to zero.
* Every tile will be tested by means of the callback function proc,
* which will determine if yes or no the given tile meets criteria of search.
* @param tile to start the search from. Upon completion, it will return the tile matching the search
* @param radius: How many tiles to search outwards. Note: This is a radius and thus different
* from the size parameter of the other CircularTileSearch function, which is a diameter.
* @param proc: callback testing function pointer.
* @param user_data to be passed to the callback function. Depends on the implementation
* @return result of the search
* @pre proc != NULL
* @pre radius > 0
*/
bool CircularTileSearch(TileIndex *tile, uint radius, uint w, uint h, TestTileOnSearchProc proc, void *user_data)
{
assert(proc != NULL);
assert(radius > 0);
uint x = TileX(*tile) + w + 1;
uint y = TileY(*tile);
uint extent[DIAGDIR_END] = { w, h, w, h };
for (uint n = 0; n < radius; n++) {
for (DiagDirection dir = DIAGDIR_NE; dir < DIAGDIR_END; dir++) {
for (uint j = extent[dir] + n * 2 + 1; j != 0; j--) {
if (x <= MapMaxX() && y <= MapMaxY() && ///< Is the tile within the map?
proc(TileXY(x, y), user_data)) { ///< Is the callback successful?
*tile = TileXY(x, y);
return true; ///< then stop the search
}
/* Step to the next 'neighbour' in the circular line */
x += _tileoffs_by_diagdir[dir].x;
y += _tileoffs_by_diagdir[dir].y;
}
}
/* Jump to next circle to test */
x += _tileoffs_by_dir[DIR_W].x;
y += _tileoffs_by_dir[DIR_W].y;
}
*tile = INVALID_TILE;
return false;
}
| 10,004
|
C++
|
.cpp
| 284
| 33.105634
| 113
| 0.672661
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,148
|
roadveh_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/roadveh_gui.cpp
|
/* $Id$ */
/** @file roadveh_gui.cpp GUI for road vehicles. */
#include "stdafx.h"
#include "roadveh.h"
#include "window_gui.h"
#include "gfx_func.h"
#include "vehicle_gui.h"
#include "strings_func.h"
#include "vehicle_func.h"
#include "string_func.h"
#include "table/sprites.h"
#include "table/strings.h"
void DrawRoadVehDetails(const Vehicle *v, int x, int y)
{
uint y_offset = RoadVehHasArticPart(v) ? 15 : 0;
StringID str;
Money feeder_share = 0;
SetDParam(0, v->engine_type);
SetDParam(1, v->build_year);
SetDParam(2, v->value);
DrawString(x, y + y_offset, STR_9011_BUILT_VALUE, TC_FROMSTRING);
if (RoadVehHasArticPart(v)) {
AcceptedCargo max_cargo;
StringID subtype_text[NUM_CARGO];
char capacity[512];
memset(max_cargo, 0, sizeof(max_cargo));
memset(subtype_text, 0, sizeof(subtype_text));
for (const Vehicle *u = v; u != NULL; u = u->Next()) {
max_cargo[u->cargo_type] += u->cargo_cap;
if (u->cargo_cap > 0) {
StringID text = GetCargoSubtypeText(u);
if (text != STR_EMPTY) subtype_text[u->cargo_type] = text;
}
}
GetString(capacity, STR_ARTICULATED_RV_CAPACITY, lastof(capacity));
bool first = true;
for (CargoID i = 0; i < NUM_CARGO; i++) {
if (max_cargo[i] > 0) {
char buffer[128];
SetDParam(0, i);
SetDParam(1, max_cargo[i]);
GetString(buffer, STR_BARE_CARGO, lastof(buffer));
if (!first) strecat(capacity, ", ", lastof(capacity));
strecat(capacity, buffer, lastof(capacity));
if (subtype_text[i] != 0) {
GetString(buffer, subtype_text[i], lastof(buffer));
strecat(capacity, buffer, lastof(capacity));
}
first = false;
}
}
SetDParamStr(0, capacity);
DrawStringTruncated(x, y + 10 + y_offset, STR_JUST_RAW_STRING, TC_BLUE, 380 - x);
for (const Vehicle *u = v; u != NULL; u = u->Next()) {
if (u->cargo_cap == 0) continue;
str = STR_8812_EMPTY;
if (!u->cargo.Empty()) {
SetDParam(0, u->cargo_type);
SetDParam(1, u->cargo.Count());
SetDParam(2, u->cargo.Source());
str = STR_8813_FROM;
feeder_share += u->cargo.FeederShare();
}
DrawString(x, y + 21 + y_offset, str, TC_FROMSTRING);
y_offset += 11;
}
y_offset -= 11;
} else {
SetDParam(0, v->cargo_type);
SetDParam(1, v->cargo_cap);
SetDParam(2, GetCargoSubtypeText(v));
DrawString(x, y + 10 + y_offset, STR_9012_CAPACITY, TC_FROMSTRING);
str = STR_8812_EMPTY;
if (!v->cargo.Empty()) {
SetDParam(0, v->cargo_type);
SetDParam(1, v->cargo.Count());
SetDParam(2, v->cargo.Source());
str = STR_8813_FROM;
feeder_share += v->cargo.FeederShare();
}
DrawString(x, y + 21 + y_offset, str, TC_FROMSTRING);
}
/* Draw Transfer credits text */
SetDParam(0, feeder_share);
DrawString(x, y + 33 + y_offset, STR_FEEDER_CARGO_VALUE, TC_FROMSTRING);
}
static inline int RoadVehLengthToPixels(int length)
{
return (length * 28) / 8;
}
void DrawRoadVehImage(const Vehicle *v, int x, int y, VehicleID selection, int count)
{
/* Road vehicle lengths are measured in eighths of the standard length, so
* count is the number of standard vehicles that should be drawn. If it is
* 0, we draw enough vehicles for 10 standard vehicle lengths. */
int max_length = (count == 0) ? 80 : count * 8;
/* Width of highlight box */
int highlight_w = 0;
for (int dx = 0; v != NULL && dx < max_length ; v = v->Next()) {
int width = v->u.road.cached_veh_length;
if (dx + width > 0 && dx <= max_length) {
SpriteID pal = (v->vehstatus & VS_CRASHED) ? PALETTE_CRASH : GetVehiclePalette(v);
DrawSprite(v->GetImage(DIR_W), pal, x + 14 + RoadVehLengthToPixels(dx), y + 6);
if (v->index == selection) {
/* Set the highlight position */
highlight_w = RoadVehLengthToPixels(width);
} else if (_cursor.vehchain && highlight_w != 0) {
highlight_w += RoadVehLengthToPixels(width);
}
}
dx += width;
}
if (highlight_w != 0) {
DrawFrameRect(x - 1, y - 1, x - 1 + highlight_w, y + 12, COLOUR_WHITE, FR_BORDERONLY);
}
}
void CcBuildRoadVeh(bool success, TileIndex tile, uint32 p1, uint32 p2)
{
const Vehicle *v;
if (!success) return;
v = GetVehicle(_new_vehicle_id);
if (v->tile == _backup_orders_tile) {
_backup_orders_tile = 0;
RestoreVehicleOrders(v);
}
ShowVehicleViewWindow(v);
}
| 4,261
|
C++
|
.cpp
| 127
| 30.377953
| 88
| 0.662277
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,149
|
build_vehicle_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/build_vehicle_gui.cpp
|
/* $Id$ */
/** @file build_vehicle_gui.cpp GUI for building vehicles. */
#include "train.h"
#include "roadveh.h"
#include "ship.h"
#include "aircraft.h"
#include "articulated_vehicles.h"
#include "textbuf_gui.h"
#include "command_func.h"
#include "company_func.h"
#include "vehicle_gui.h"
#include "newgrf_engine.h"
#include "group.h"
#include "strings_func.h"
#include "window_func.h"
#include "date_func.h"
#include "vehicle_func.h"
#include "gfx_func.h"
#include "widgets/dropdown_func.h"
#include "window_gui.h"
#include "engine_gui.h"
#include "settings_type.h"
#include "table/sprites.h"
#include "table/strings.h"
enum BuildVehicleWidgets {
BUILD_VEHICLE_WIDGET_CLOSEBOX = 0,
BUILD_VEHICLE_WIDGET_CAPTION,
BUILD_VEHICLE_WIDGET_SORT_ASSENDING_DESCENDING,
BUILD_VEHICLE_WIDGET_SORT_DROPDOWN,
BUILD_VEHICLE_WIDGET_LIST,
BUILD_VEHICLE_WIDGET_SCROLLBAR,
BUILD_VEHICLE_WIDGET_PANEL,
BUILD_VEHICLE_WIDGET_BUILD,
BUILD_VEHICLE_WIDGET_RENAME,
BUILD_VEHICLE_WIDGET_RESIZE,
BUILD_VEHICLE_WIDGET_END
};
static const Widget _build_vehicle_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW },
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_GREY, 11, 239, 0, 13, 0x0, STR_018C_WINDOW_TITLE_DRAG_THIS },
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 0, 80, 14, 25, STR_SORT_BY, STR_SORT_ORDER_TIP},
{ WWT_DROPDOWN, RESIZE_RIGHT, COLOUR_GREY, 81, 239, 14, 25, 0x0, STR_SORT_CRITERIA_TIP},
{ WWT_MATRIX, RESIZE_RB, COLOUR_GREY, 0, 227, 26, 39, 0x101, STR_NULL },
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_GREY, 228, 239, 26, 39, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST },
{ WWT_PANEL, RESIZE_RTB, COLOUR_GREY, 0, 239, 40, 161, 0x0, STR_NULL },
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 0, 114, 162, 173, 0x0, STR_NULL },
{ WWT_PUSHTXTBTN, RESIZE_RTB, COLOUR_GREY, 115, 227, 162, 173, 0x0, STR_NULL },
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_GREY, 228, 239, 162, 173, 0x0, STR_RESIZE_BUTTON },
{ WIDGETS_END},
};
static bool _internal_sort_order; // descending/ascending
static byte _last_sort_criteria[] = {0, 0, 0, 0};
static bool _last_sort_order[] = {false, false, false, false};
static int CDECL EngineNumberSorter(const void *a, const void *b)
{
const EngineID va = *(const EngineID*)a;
const EngineID vb = *(const EngineID*)b;
int r = ListPositionOfEngine(va) - ListPositionOfEngine(vb);
return _internal_sort_order ? -r : r;
}
static int CDECL EngineIntroDateSorter(const void *a, const void *b)
{
const int va = GetEngine(*(const EngineID*)a)->intro_date;
const int vb = GetEngine(*(const EngineID*)b)->intro_date;
const int r = va - vb;
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
return _internal_sort_order ? -r : r;
}
static int CDECL EngineNameSorter(const void *a, const void *b)
{
static EngineID last_engine[2] = { INVALID_ENGINE, INVALID_ENGINE };
static char last_name[2][64] = { "\0", "\0" };
const EngineID va = *(const EngineID*)a;
const EngineID vb = *(const EngineID*)b;
if (va != last_engine[0]) {
last_engine[0] = va;
SetDParam(0, va);
GetString(last_name[0], STR_ENGINE_NAME, lastof(last_name[0]));
}
if (vb != last_engine[1]) {
last_engine[1] = vb;
SetDParam(0, vb);
GetString(last_name[1], STR_ENGINE_NAME, lastof(last_name[1]));
}
int r = strcmp(last_name[0], last_name[1]); // sort by name
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
return _internal_sort_order ? -r : r;
}
static int CDECL EngineReliabilitySorter(const void *a, const void *b)
{
const int va = GetEngine(*(const EngineID*)a)->reliability;
const int vb = GetEngine(*(const EngineID*)b)->reliability;
const int r = va - vb;
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
return _internal_sort_order ? -r : r;
}
static int CDECL EngineCostSorter(const void *a, const void *b)
{
Money va = GetEngine(*(const EngineID*)a)->GetCost();
Money vb = GetEngine(*(const EngineID*)b)->GetCost();
int r = ClampToI32(va - vb);
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
return _internal_sort_order ? -r : r;
}
static int CDECL EngineSpeedSorter(const void *a, const void *b)
{
int va = GetEngine(*(const EngineID*)a)->GetDisplayMaxSpeed();
int vb = GetEngine(*(const EngineID*)b)->GetDisplayMaxSpeed();
int r = va - vb;
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
return _internal_sort_order ? -r : r;
}
static int CDECL EnginePowerSorter(const void *a, const void *b)
{
int va = GetEngine(*(const EngineID*)a)->GetPower();
int vb = GetEngine(*(const EngineID*)b)->GetPower();
int r = va - vb;
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
return _internal_sort_order ? -r : r;
}
static int CDECL EngineRunningCostSorter(const void *a, const void *b)
{
Money va = GetEngine(*(const EngineID*)a)->GetRunningCost();
Money vb = GetEngine(*(const EngineID*)b)->GetRunningCost();
int r = ClampToI32(va - vb);
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
return _internal_sort_order ? -r : r;
}
/* Train sorting functions */
static int CDECL TrainEnginePowerVsRunningCostSorter(const void *a, const void *b)
{
const Engine *e_a = GetEngine(*(const EngineID*)a);
const Engine *e_b = GetEngine(*(const EngineID*)b);
/* Here we are using a few tricks to get the right sort.
* We want power/running cost, but since we usually got higher running cost than power and we store the result in an int,
* we will actually calculate cunning cost/power (to make it more than 1).
* Because of this, the return value have to be reversed as well and we return b - a instead of a - b.
* Another thing is that both power and running costs should be doubled for multiheaded engines.
* Since it would be multipling with 2 in both numerator and denumerator, it will even themselves out and we skip checking for multiheaded. */
Money va = (e_a->GetRunningCost()) / max(1U, (uint)e_a->GetPower());
Money vb = (e_b->GetRunningCost()) / max(1U, (uint)e_b->GetPower());
int r = ClampToI32(vb - va);
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
return _internal_sort_order ? -r : r;
}
static int CDECL TrainEngineCapacitySorter(const void *a, const void *b)
{
const RailVehicleInfo *rvi_a = RailVehInfo(*(const EngineID*)a);
const RailVehicleInfo *rvi_b = RailVehInfo(*(const EngineID*)b);
int va = GetTotalCapacityOfArticulatedParts(*(const EngineID*)a, VEH_TRAIN) * (rvi_a->railveh_type == RAILVEH_MULTIHEAD ? 2 : 1);
int vb = GetTotalCapacityOfArticulatedParts(*(const EngineID*)b, VEH_TRAIN) * (rvi_b->railveh_type == RAILVEH_MULTIHEAD ? 2 : 1);
int r = va - vb;
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
return _internal_sort_order ? -r : r;
}
static int CDECL TrainEnginesThenWagonsSorter(const void *a, const void *b)
{
EngineID va = *(const EngineID*)a;
EngineID vb = *(const EngineID*)b;
int val_a = (RailVehInfo(va)->railveh_type == RAILVEH_WAGON ? 1 : 0);
int val_b = (RailVehInfo(vb)->railveh_type == RAILVEH_WAGON ? 1 : 0);
int r = val_a - val_b;
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
return _internal_sort_order ? -r : r;
}
/* Road vehicle sorting functions */
static int CDECL RoadVehEngineCapacitySorter(const void *a, const void *b)
{
int va = GetTotalCapacityOfArticulatedParts(*(const EngineID*)a, VEH_ROAD);
int vb = GetTotalCapacityOfArticulatedParts(*(const EngineID*)b, VEH_ROAD);
int r = va - vb;
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
return _internal_sort_order ? -r : r;
}
/* Ship vehicle sorting functions */
static int CDECL ShipEngineCapacitySorter(const void *a, const void *b)
{
const Engine *e_a = GetEngine(*(const EngineID*)a);
const Engine *e_b = GetEngine(*(const EngineID*)b);
int va = e_a->GetDisplayDefaultCapacity();
int vb = e_b->GetDisplayDefaultCapacity();
int r = va - vb;
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
return _internal_sort_order ? -r : r;
}
/* Aircraft sorting functions */
static int CDECL AircraftEngineCargoSorter(const void *a, const void *b)
{
const Engine *e_a = GetEngine(*(const EngineID*)a);
const Engine *e_b = GetEngine(*(const EngineID*)b);
int va = e_a->GetDisplayDefaultCapacity();
int vb = e_b->GetDisplayDefaultCapacity();
int r = va - vb;
if (r == 0) {
/* The planes has the same passenger capacity. Check mail capacity instead */
va = AircraftVehInfo(*(const EngineID*)a)->mail_capacity;
vb = AircraftVehInfo(*(const EngineID*)b)->mail_capacity;
r = va - vb;
if (r == 0) {
/* Use EngineID to sort instead since we want consistent sorting */
return EngineNumberSorter(a, b);
}
}
return _internal_sort_order ? -r : r;
}
static EngList_SortTypeFunction * const _sorter[][10] = {{
/* Trains */
&EngineNumberSorter,
&EngineCostSorter,
&EngineSpeedSorter,
&EnginePowerSorter,
&EngineIntroDateSorter,
&EngineNameSorter,
&EngineRunningCostSorter,
&TrainEnginePowerVsRunningCostSorter,
&EngineReliabilitySorter,
&TrainEngineCapacitySorter,
}, {
/* Road vehicles */
&EngineNumberSorter,
&EngineCostSorter,
&EngineSpeedSorter,
&EngineIntroDateSorter,
&EngineNameSorter,
&EngineRunningCostSorter,
&EngineReliabilitySorter,
&RoadVehEngineCapacitySorter,
}, {
/* Ships */
&EngineNumberSorter,
&EngineCostSorter,
&EngineSpeedSorter,
&EngineIntroDateSorter,
&EngineNameSorter,
&EngineRunningCostSorter,
&EngineReliabilitySorter,
&ShipEngineCapacitySorter,
}, {
/* Aircraft */
&EngineNumberSorter,
&EngineCostSorter,
&EngineSpeedSorter,
&EngineIntroDateSorter,
&EngineNameSorter,
&EngineRunningCostSorter,
&EngineReliabilitySorter,
&AircraftEngineCargoSorter,
}};
static const StringID _sort_listing[][11] = {{
/* Trains */
STR_ENGINE_SORT_ENGINE_ID,
STR_ENGINE_SORT_COST,
STR_SORT_BY_MAX_SPEED,
STR_ENGINE_SORT_POWER,
STR_ENGINE_SORT_INTRO_DATE,
STR_SORT_BY_DROPDOWN_NAME,
STR_ENGINE_SORT_RUNNING_COST,
STR_ENGINE_SORT_POWER_VS_RUNNING_COST,
STR_SORT_BY_RELIABILITY,
STR_ENGINE_SORT_CARGO_CAPACITY,
INVALID_STRING_ID
}, {
/* Road vehicles */
STR_ENGINE_SORT_ENGINE_ID,
STR_ENGINE_SORT_COST,
STR_SORT_BY_MAX_SPEED,
STR_ENGINE_SORT_INTRO_DATE,
STR_SORT_BY_DROPDOWN_NAME,
STR_ENGINE_SORT_RUNNING_COST,
STR_SORT_BY_RELIABILITY,
STR_ENGINE_SORT_CARGO_CAPACITY,
INVALID_STRING_ID
}, {
/* Ships */
STR_ENGINE_SORT_ENGINE_ID,
STR_ENGINE_SORT_COST,
STR_SORT_BY_MAX_SPEED,
STR_ENGINE_SORT_INTRO_DATE,
STR_SORT_BY_DROPDOWN_NAME,
STR_ENGINE_SORT_RUNNING_COST,
STR_SORT_BY_RELIABILITY,
STR_ENGINE_SORT_CARGO_CAPACITY,
INVALID_STRING_ID
}, {
/* Aircraft */
STR_ENGINE_SORT_ENGINE_ID,
STR_ENGINE_SORT_COST,
STR_SORT_BY_MAX_SPEED,
STR_ENGINE_SORT_INTRO_DATE,
STR_SORT_BY_DROPDOWN_NAME,
STR_ENGINE_SORT_RUNNING_COST,
STR_SORT_BY_RELIABILITY,
STR_ENGINE_SORT_CARGO_CAPACITY,
INVALID_STRING_ID
}};
static int DrawCargoCapacityInfo(int x, int y, EngineID engine, VehicleType type, bool refittable)
{
uint16 *cap = GetCapacityOfArticulatedParts(engine, type);
for (uint c = 0; c < NUM_CARGO; c++) {
if (cap[c] == 0) continue;
SetDParam(0, c);
SetDParam(1, cap[c]);
SetDParam(2, refittable ? STR_9842_REFITTABLE : STR_EMPTY);
DrawString(x, y, STR_PURCHASE_INFO_CAPACITY, TC_FROMSTRING);
y += 10;
/* Only show as refittable once */
refittable = false;
}
return y;
}
/* Draw rail wagon specific details */
static int DrawRailWagonPurchaseInfo(int x, int y, EngineID engine_number, const RailVehicleInfo *rvi)
{
const Engine *e = GetEngine(engine_number);
/* Purchase cost */
SetDParam(0, e->GetCost());
DrawString(x, y, STR_PURCHASE_INFO_COST, TC_FROMSTRING);
y += 10;
/* Wagon weight - (including cargo) */
uint weight = e->GetDisplayWeight();
SetDParam(0, weight);
uint cargo_weight = (e->CanCarryCargo() ? GetCargo(e->GetDefaultCargoType())->weight * e->GetDisplayDefaultCapacity() >> 4 : 0);
SetDParam(1, cargo_weight + weight);
DrawString(x, y, STR_PURCHASE_INFO_WEIGHT_CWEIGHT, TC_FROMSTRING);
y += 10;
/* Wagon speed limit, displayed if above zero */
if (_settings_game.vehicle.wagon_speed_limits) {
uint max_speed = e->GetDisplayMaxSpeed();
if (max_speed > 0) {
SetDParam(0, max_speed);
DrawString(x, y, STR_PURCHASE_INFO_SPEED, TC_FROMSTRING);
y += 10;
}
}
/* Running cost */
if (rvi->running_cost_class != 0xFF) {
SetDParam(0, e->GetRunningCost());
DrawString(x, y, STR_PURCHASE_INFO_RUNNINGCOST, TC_FROMSTRING);
y += 10;
}
return y;
}
/* Draw locomotive specific details */
static int DrawRailEnginePurchaseInfo(int x, int y, EngineID engine_number, const RailVehicleInfo *rvi)
{
const Engine *e = GetEngine(engine_number);
/* Purchase Cost - Engine weight */
SetDParam(0, e->GetCost());
SetDParam(1, e->GetDisplayWeight());
DrawString(x, y, STR_PURCHASE_INFO_COST_WEIGHT, TC_FROMSTRING);
y += 10;
/* Max speed - Engine power */
SetDParam(0, e->GetDisplayMaxSpeed());
SetDParam(1, e->GetPower());
DrawString(x, y, STR_PURCHASE_INFO_SPEED_POWER, TC_FROMSTRING);
y += 10;
/* Max tractive effort - not applicable if old acceleration or maglev */
if (_settings_game.vehicle.train_acceleration_model != TAM_ORIGINAL && rvi->railtype != RAILTYPE_MAGLEV) {
SetDParam(0, e->GetDisplayMaxTractiveEffort());
DrawString(x, y, STR_PURCHASE_INFO_MAX_TE, TC_FROMSTRING);
y += 10;
}
/* Running cost */
if (rvi->running_cost_class != 0xFF) {
SetDParam(0, e->GetRunningCost());
DrawString(x, y, STR_PURCHASE_INFO_RUNNINGCOST, TC_FROMSTRING);
y += 10;
}
/* Powered wagons power - Powered wagons extra weight */
if (rvi->pow_wag_power != 0) {
SetDParam(0, rvi->pow_wag_power);
SetDParam(1, rvi->pow_wag_weight);
DrawString(x, y, STR_PURCHASE_INFO_PWAGPOWER_PWAGWEIGHT, TC_FROMSTRING);
y += 10;
};
return y;
}
/* Draw road vehicle specific details */
static int DrawRoadVehPurchaseInfo(int x, int y, EngineID engine_number)
{
const Engine *e = GetEngine(engine_number);
/* Purchase cost - Max speed */
SetDParam(0, e->GetCost());
SetDParam(1, e->GetDisplayMaxSpeed());
DrawString(x, y, STR_PURCHASE_INFO_COST_SPEED, TC_FROMSTRING);
y += 10;
/* Running cost */
SetDParam(0, e->GetRunningCost());
DrawString(x, y, STR_PURCHASE_INFO_RUNNINGCOST, TC_FROMSTRING);
y += 10;
return y;
}
/* Draw ship specific details */
static int DrawShipPurchaseInfo(int x, int y, EngineID engine_number, const ShipVehicleInfo *svi, bool refittable)
{
const Engine *e = GetEngine(engine_number);
/* Purchase cost - Max speed */
SetDParam(0, e->GetCost());
SetDParam(1, e->GetDisplayMaxSpeed());
DrawString(x, y, STR_PURCHASE_INFO_COST_SPEED, TC_FROMSTRING);
y += 10;
/* Cargo type + capacity */
SetDParam(0, e->GetDefaultCargoType());
SetDParam(1, e->GetDisplayDefaultCapacity());
SetDParam(2, refittable ? STR_9842_REFITTABLE : STR_EMPTY);
DrawString(x, y, STR_PURCHASE_INFO_CAPACITY, TC_FROMSTRING);
y += 10;
/* Running cost */
SetDParam(0, e->GetRunningCost());
DrawString(x, y, STR_PURCHASE_INFO_RUNNINGCOST, TC_FROMSTRING);
y += 10;
return y;
}
/* Draw aircraft specific details */
static int DrawAircraftPurchaseInfo(int x, int y, EngineID engine_number, const AircraftVehicleInfo *avi, bool refittable)
{
const Engine *e = GetEngine(engine_number);
CargoID cargo = e->GetDefaultCargoType();
/* Purchase cost - Max speed */
SetDParam(0, e->GetCost());
SetDParam(1, e->GetDisplayMaxSpeed());
DrawString(x, y, STR_PURCHASE_INFO_COST_SPEED, TC_FROMSTRING);
y += 10;
/* Cargo capacity */
if (cargo == CT_INVALID || cargo == CT_PASSENGERS) {
SetDParam(0, e->GetDisplayDefaultCapacity());
SetDParam(1, avi->mail_capacity);
DrawString(x, y, STR_PURCHASE_INFO_AIRCRAFT_CAPACITY, TC_FROMSTRING);
} else {
/* Note, if the default capacity is selected by the refit capacity
* callback, then the capacity shown is likely to be incorrect. */
SetDParam(0, cargo);
SetDParam(1, e->GetDisplayDefaultCapacity());
SetDParam(2, refittable ? STR_9842_REFITTABLE : STR_EMPTY);
DrawString(x, y, STR_PURCHASE_INFO_CAPACITY, TC_FROMSTRING);
}
y += 10;
/* Running cost */
SetDParam(0, e->GetRunningCost());
DrawString(x, y, STR_PURCHASE_INFO_RUNNINGCOST, TC_FROMSTRING);
y += 10;
return y;
}
/**
* Draw the purchase info details of a vehicle at a given location.
* @param x,y location where to draw the info
* @param w how wide are the text allowed to be (size of widget/window to Draw in)
* @param engine_number the engine of which to draw the info of
* @return y after drawing all the text
*/
int DrawVehiclePurchaseInfo(int x, int y, uint w, EngineID engine_number)
{
const Engine *e = GetEngine(engine_number);
YearMonthDay ymd;
ConvertDateToYMD(e->intro_date, &ymd);
bool refittable = IsArticulatedVehicleRefittable(engine_number);
switch (e->type) {
default: NOT_REACHED();
case VEH_TRAIN: {
const RailVehicleInfo *rvi = RailVehInfo(engine_number);
if (rvi->railveh_type == RAILVEH_WAGON) {
y = DrawRailWagonPurchaseInfo(x, y, engine_number, rvi);
} else {
y = DrawRailEnginePurchaseInfo(x, y, engine_number, rvi);
}
/* Cargo type + capacity, or N/A */
int new_y = DrawCargoCapacityInfo(x, y, engine_number, VEH_TRAIN, refittable);
if (new_y == y) {
SetDParam(0, CT_INVALID);
SetDParam(2, STR_EMPTY);
DrawString(x, y, STR_PURCHASE_INFO_CAPACITY, TC_FROMSTRING);
y += 10;
} else {
y = new_y;
}
break;
}
case VEH_ROAD: {
y = DrawRoadVehPurchaseInfo(x, y, engine_number);
/* Cargo type + capacity, or N/A */
int new_y = DrawCargoCapacityInfo(x, y, engine_number, VEH_ROAD, refittable);
if (new_y == y) {
SetDParam(0, CT_INVALID);
SetDParam(2, STR_EMPTY);
DrawString(x, y, STR_PURCHASE_INFO_CAPACITY, TC_FROMSTRING);
y += 10;
} else {
y = new_y;
}
break;
}
case VEH_SHIP:
y = DrawShipPurchaseInfo(x, y, engine_number, ShipVehInfo(engine_number), refittable);
break;
case VEH_AIRCRAFT:
y = DrawAircraftPurchaseInfo(x, y, engine_number, AircraftVehInfo(engine_number), refittable);
break;
}
/* Draw details, that applies to all types except rail wagons */
if (e->type != VEH_TRAIN || RailVehInfo(engine_number)->railveh_type != RAILVEH_WAGON) {
/* Design date - Life length */
SetDParam(0, ymd.year);
SetDParam(1, e->lifelength);
DrawString(x, y, STR_PURCHASE_INFO_DESIGNED_LIFE, TC_FROMSTRING);
y += 10;
/* Reliability */
SetDParam(0, e->reliability * 100 >> 16);
DrawString(x, y, STR_PURCHASE_INFO_RELIABILITY, TC_FROMSTRING);
y += 10;
}
/* Additional text from NewGRF */
y += ShowAdditionalText(x, y, w, engine_number);
if (refittable) y += ShowRefitOptionsList(x, y, w, engine_number);
return y;
}
static void DrawVehicleEngine(VehicleType type, int x, int y, EngineID engine, SpriteID pal)
{
switch (type) {
case VEH_TRAIN: DrawTrainEngine( x, y, engine, pal); break;
case VEH_ROAD: DrawRoadVehEngine( x, y, engine, pal); break;
case VEH_SHIP: DrawShipEngine( x, y, engine, pal); break;
case VEH_AIRCRAFT: DrawAircraftEngine(x, y, engine, pal); break;
default: NOT_REACHED();
}
}
/** Engine drawing loop
* @param type Type of vehicle (VEH_*)
* @param x,y Where should the list start
* @param eng_list What engines to draw
* @param min where to start in the list
* @param max where in the list to end
* @param selected_id what engine to highlight as selected, if any
* @param count_location Offset to print the engine count (used by autoreplace). 0 means it's off
*/
void DrawEngineList(VehicleType type, int x, int r, int y, const GUIEngineList *eng_list, uint16 min, uint16 max, EngineID selected_id, int count_location, GroupID selected_group)
{
byte step_size = GetVehicleListHeight(type);
byte x_offset = 0;
byte y_offset = 0;
assert(max <= eng_list->Length());
switch (type) {
case VEH_TRAIN:
x++; // train and road vehicles use the same offset, except trains are one more pixel to the right
/* Fallthough */
case VEH_ROAD:
x += 26;
x_offset = 30;
y += 2;
y_offset = 4;
break;
case VEH_SHIP:
x += 35;
x_offset = 40;
y += 7;
y_offset = 3;
break;
case VEH_AIRCRAFT:
x += 27;
x_offset = 33;
y += 7;
y_offset = 3;
break;
default: NOT_REACHED();
}
uint maxw = r - x - x_offset;
for (; min < max; min++, y += step_size) {
const EngineID engine = (*eng_list)[min];
/* Note: num_engines is only used in the autoreplace GUI, so it is correct to use _local_company here. */
const uint num_engines = GetGroupNumEngines(_local_company, selected_group, engine);
SetDParam(0, engine);
DrawStringTruncated(x + x_offset, y, STR_ENGINE_NAME, engine == selected_id ? TC_WHITE : TC_BLACK, maxw);
DrawVehicleEngine(type, x, y + y_offset, engine, (count_location != 0 && num_engines == 0) ? PALETTE_CRASH : GetEnginePalette(engine, _local_company));
if (count_location != 0) {
SetDParam(0, num_engines);
DrawStringRightAligned(count_location, y + (GetVehicleListHeight(type) == 14 ? 3 : 8), STR_TINY_BLACK, TC_FROMSTRING);
}
}
}
struct BuildVehicleWindow : Window {
VehicleType vehicle_type;
union {
RailTypeByte railtype;
AirportFTAClass::Flags flags;
RoadTypes roadtypes;
} filter;
bool descending_sort_order;
byte sort_criteria;
bool regenerate_list;
bool listview_mode;
EngineID sel_engine;
EngineID rename_engine;
GUIEngineList eng_list;
BuildVehicleWindow(const WindowDesc *desc, TileIndex tile, VehicleType type) : Window(desc, tile == INVALID_TILE ? (int)type : tile)
{
this->vehicle_type = type;
int vlh = GetVehicleListHeight(this->vehicle_type);
ResizeWindow(this, 0, vlh - 14);
this->resize.step_height = vlh;
this->vscroll.cap = 1;
this->widget[BUILD_VEHICLE_WIDGET_LIST].data = 0x101;
this->resize.width = this->width;
this->resize.height = this->height;
this->owner = (tile != INVALID_TILE) ? GetTileOwner(tile) : _local_company;
this->sel_engine = INVALID_ENGINE;
this->regenerate_list = false;
this->sort_criteria = _last_sort_criteria[type];
this->descending_sort_order = _last_sort_order[type];
switch (type) {
default: NOT_REACHED();
case VEH_TRAIN:
this->filter.railtype = (tile == INVALID_TILE) ? RAILTYPE_END : GetRailType(tile);
break;
case VEH_ROAD:
this->filter.roadtypes = (tile == INVALID_TILE) ? ROADTYPES_ALL : GetRoadTypes(tile);
case VEH_SHIP:
break;
case VEH_AIRCRAFT:
this->filter.flags =
tile == INVALID_TILE ? AirportFTAClass::ALL : GetStationByTile(tile)->Airport()->flags;
break;
}
this->SetupWindowStrings(type);
this->listview_mode = (this->window_number <= VEH_END);
/* If we are just viewing the list of vehicles, we do not need the Build button.
* So we just hide it, and enlarge the Rename buton by the now vacant place. */
if (this->listview_mode) {
this->HideWidget(BUILD_VEHICLE_WIDGET_BUILD);
this->widget[BUILD_VEHICLE_WIDGET_RENAME].left = this->widget[BUILD_VEHICLE_WIDGET_BUILD].left;
} else {
/* Both are visible, adjust the size of each */
ResizeButtons(this, BUILD_VEHICLE_WIDGET_BUILD, BUILD_VEHICLE_WIDGET_RENAME);
}
this->GenerateBuildList(); // generate the list, since we need it in the next line
/* Select the first engine in the list as default when opening the window */
if (this->eng_list.Length() > 0) this->sel_engine = this->eng_list[0];
this->FindWindowPlacementAndResize(desc);
}
/* Setup widget strings to fit the different types of vehicles */
void SetupWindowStrings(VehicleType type)
{
switch (type) {
default: NOT_REACHED();
case VEH_TRAIN:
this->widget[BUILD_VEHICLE_WIDGET_CAPTION].data = this->listview_mode ? STR_AVAILABLE_TRAINS : STR_JUST_STRING;
this->widget[BUILD_VEHICLE_WIDGET_LIST].tooltips = STR_8843_TRAIN_VEHICLE_SELECTION;
this->widget[BUILD_VEHICLE_WIDGET_BUILD].data = STR_881F_BUILD_VEHICLE;
this->widget[BUILD_VEHICLE_WIDGET_BUILD].tooltips = STR_8844_BUILD_THE_HIGHLIGHTED_TRAIN;
this->widget[BUILD_VEHICLE_WIDGET_RENAME].data = STR_8820_RENAME;
this->widget[BUILD_VEHICLE_WIDGET_RENAME].tooltips = STR_8845_RENAME_TRAIN_VEHICLE_TYPE;
break;
case VEH_ROAD:
this->widget[BUILD_VEHICLE_WIDGET_CAPTION].data = this->listview_mode ? STR_AVAILABLE_ROAD_VEHICLES : STR_9006_NEW_ROAD_VEHICLES;
this->widget[BUILD_VEHICLE_WIDGET_LIST].tooltips = STR_9026_ROAD_VEHICLE_SELECTION;
this->widget[BUILD_VEHICLE_WIDGET_BUILD].data = STR_9007_BUILD_VEHICLE;
this->widget[BUILD_VEHICLE_WIDGET_BUILD].tooltips = STR_9027_BUILD_THE_HIGHLIGHTED_ROAD;
this->widget[BUILD_VEHICLE_WIDGET_RENAME].data = STR_9034_RENAME;
this->widget[BUILD_VEHICLE_WIDGET_RENAME].tooltips = STR_9035_RENAME_ROAD_VEHICLE_TYPE;
break;
case VEH_SHIP:
this->widget[BUILD_VEHICLE_WIDGET_CAPTION].data = this->listview_mode ? STR_AVAILABLE_SHIPS : STR_9808_NEW_SHIPS;
this->widget[BUILD_VEHICLE_WIDGET_LIST].tooltips = STR_9825_SHIP_SELECTION_LIST_CLICK;
this->widget[BUILD_VEHICLE_WIDGET_BUILD].data = STR_9809_BUILD_SHIP;
this->widget[BUILD_VEHICLE_WIDGET_BUILD].tooltips = STR_9826_BUILD_THE_HIGHLIGHTED_SHIP;
this->widget[BUILD_VEHICLE_WIDGET_RENAME].data = STR_9836_RENAME;
this->widget[BUILD_VEHICLE_WIDGET_RENAME].tooltips = STR_9837_RENAME_SHIP_TYPE;
break;
case VEH_AIRCRAFT:
this->widget[BUILD_VEHICLE_WIDGET_CAPTION].data = this->listview_mode ? STR_AVAILABLE_AIRCRAFT : STR_A005_NEW_AIRCRAFT;
this->widget[BUILD_VEHICLE_WIDGET_LIST].tooltips = STR_A025_AIRCRAFT_SELECTION_LIST;
this->widget[BUILD_VEHICLE_WIDGET_BUILD].data = STR_A006_BUILD_AIRCRAFT;
this->widget[BUILD_VEHICLE_WIDGET_BUILD].tooltips = STR_A026_BUILD_THE_HIGHLIGHTED_AIRCRAFT;
this->widget[BUILD_VEHICLE_WIDGET_RENAME].data = STR_A037_RENAME;
this->widget[BUILD_VEHICLE_WIDGET_RENAME].tooltips = STR_A038_RENAME_AIRCRAFT_TYPE;
break;
}
}
/* Figure out what train EngineIDs to put in the list */
void GenerateBuildTrainList()
{
EngineID sel_id = INVALID_ENGINE;
int num_engines = 0;
int num_wagons = 0;
this->filter.railtype = (this->listview_mode) ? RAILTYPE_END : GetRailType(this->window_number);
this->eng_list.Clear();
/* Make list of all available train engines and wagons.
* Also check to see if the previously selected engine is still available,
* and if not, reset selection to INVALID_ENGINE. This could be the case
* when engines become obsolete and are removed */
const Engine *e;
FOR_ALL_ENGINES_OF_TYPE(e, VEH_TRAIN) {
EngineID eid = e->index;
const RailVehicleInfo *rvi = &e->u.rail;
if (this->filter.railtype != RAILTYPE_END && !HasPowerOnRail(rvi->railtype, this->filter.railtype)) continue;
if (!IsEngineBuildable(eid, VEH_TRAIN, _local_company)) continue;
*this->eng_list.Append() = eid;
if (rvi->railveh_type != RAILVEH_WAGON) {
num_engines++;
} else {
num_wagons++;
}
if (eid == this->sel_engine) sel_id = eid;
}
this->sel_engine = sel_id;
/* make engines first, and then wagons, sorted by ListPositionOfEngine() */
_internal_sort_order = false;
EngList_Sort(&this->eng_list, TrainEnginesThenWagonsSorter);
/* and then sort engines */
_internal_sort_order = this->descending_sort_order;
EngList_SortPartial(&this->eng_list, _sorter[0][this->sort_criteria], 0, num_engines);
/* and finally sort wagons */
EngList_SortPartial(&this->eng_list, _sorter[0][this->sort_criteria], num_engines, num_wagons);
}
/* Figure out what road vehicle EngineIDs to put in the list */
void GenerateBuildRoadVehList()
{
EngineID sel_id = INVALID_ENGINE;
this->eng_list.Clear();
const Engine *e;
FOR_ALL_ENGINES_OF_TYPE(e, VEH_ROAD) {
EngineID eid = e->index;
if (!IsEngineBuildable(eid, VEH_ROAD, _local_company)) continue;
if (!HasBit(this->filter.roadtypes, HasBit(EngInfo(eid)->misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD)) continue;
*this->eng_list.Append() = eid;
if (eid == this->sel_engine) sel_id = eid;
}
this->sel_engine = sel_id;
}
/* Figure out what ship EngineIDs to put in the list */
void GenerateBuildShipList()
{
EngineID sel_id = INVALID_ENGINE;
this->eng_list.Clear();
const Engine *e;
FOR_ALL_ENGINES_OF_TYPE(e, VEH_SHIP) {
EngineID eid = e->index;
if (!IsEngineBuildable(eid, VEH_SHIP, _local_company)) continue;
*this->eng_list.Append() = eid;
if (eid == this->sel_engine) sel_id = eid;
}
this->sel_engine = sel_id;
}
/* Figure out what aircraft EngineIDs to put in the list */
void GenerateBuildAircraftList()
{
EngineID sel_id = INVALID_ENGINE;
this->eng_list.Clear();
const Station *st = this->listview_mode ? NULL : GetStationByTile(this->window_number);
/* Make list of all available planes.
* Also check to see if the previously selected plane is still available,
* and if not, reset selection to INVALID_ENGINE. This could be the case
* when planes become obsolete and are removed */
const Engine *e;
FOR_ALL_ENGINES_OF_TYPE(e, VEH_AIRCRAFT) {
EngineID eid = e->index;
if (!IsEngineBuildable(eid, VEH_AIRCRAFT, _local_company)) continue;
/* First VEH_END window_numbers are fake to allow a window open for all different types at once */
if (!this->listview_mode && !CanVehicleUseStation(eid, st)) continue;
*this->eng_list.Append() = eid;
if (eid == this->sel_engine) sel_id = eid;
}
this->sel_engine = sel_id;
}
/* Generate the list of vehicles */
void GenerateBuildList()
{
switch (this->vehicle_type) {
default: NOT_REACHED();
case VEH_TRAIN:
this->GenerateBuildTrainList();
return; // trains should not reach the last sorting
case VEH_ROAD:
this->GenerateBuildRoadVehList();
break;
case VEH_SHIP:
this->GenerateBuildShipList();
break;
case VEH_AIRCRAFT:
this->GenerateBuildAircraftList();
break;
}
_internal_sort_order = this->descending_sort_order;
EngList_Sort(&this->eng_list, _sorter[this->vehicle_type][this->sort_criteria]);
}
void OnClick(Point pt, int widget)
{
switch (widget) {
case BUILD_VEHICLE_WIDGET_SORT_ASSENDING_DESCENDING:
this->descending_sort_order ^= true;
_last_sort_order[this->vehicle_type] = this->descending_sort_order;
this->regenerate_list = true;
this->SetDirty();
break;
case BUILD_VEHICLE_WIDGET_LIST: {
uint i = (pt.y - this->widget[BUILD_VEHICLE_WIDGET_LIST].top) / GetVehicleListHeight(this->vehicle_type) + this->vscroll.pos;
size_t num_items = this->eng_list.Length();
this->sel_engine = (i < num_items) ? this->eng_list[i] : INVALID_ENGINE;
this->SetDirty();
break;
}
case BUILD_VEHICLE_WIDGET_SORT_DROPDOWN: // Select sorting criteria dropdown menu
ShowDropDownMenu(this, _sort_listing[this->vehicle_type], this->sort_criteria, BUILD_VEHICLE_WIDGET_SORT_DROPDOWN, 0, 0);
break;
case BUILD_VEHICLE_WIDGET_BUILD: {
EngineID sel_eng = this->sel_engine;
if (sel_eng != INVALID_ENGINE) {
switch (this->vehicle_type) {
default: NOT_REACHED();
case VEH_TRAIN:
DoCommandP(this->window_number, sel_eng, 0,
CMD_BUILD_RAIL_VEHICLE | CMD_MSG(STR_882B_CAN_T_BUILD_RAILROAD_VEHICLE),
(RailVehInfo(sel_eng)->railveh_type == RAILVEH_WAGON) ? CcBuildWagon : CcBuildLoco);
break;
case VEH_ROAD:
DoCommandP(this->window_number, sel_eng, 0, CMD_BUILD_ROAD_VEH | CMD_MSG(STR_9009_CAN_T_BUILD_ROAD_VEHICLE), CcBuildRoadVeh);
break;
case VEH_SHIP:
DoCommandP(this->window_number, sel_eng, 0, CMD_BUILD_SHIP | CMD_MSG(STR_980D_CAN_T_BUILD_SHIP), CcBuildShip);
break;
case VEH_AIRCRAFT:
DoCommandP(this->window_number, sel_eng, 0, CMD_BUILD_AIRCRAFT | CMD_MSG(STR_A008_CAN_T_BUILD_AIRCRAFT), CcBuildAircraft);
break;
}
}
break;
}
case BUILD_VEHICLE_WIDGET_RENAME: {
EngineID sel_eng = this->sel_engine;
if (sel_eng != INVALID_ENGINE) {
StringID str = STR_NULL;
this->rename_engine = sel_eng;
switch (this->vehicle_type) {
default: NOT_REACHED();
case VEH_TRAIN: str = STR_886A_RENAME_TRAIN_VEHICLE_TYPE; break;
case VEH_ROAD: str = STR_9036_RENAME_ROAD_VEHICLE_TYPE; break;
case VEH_SHIP: str = STR_9838_RENAME_SHIP_TYPE; break;
case VEH_AIRCRAFT: str = STR_A039_RENAME_AIRCRAFT_TYPE; break;
}
SetDParam(0, sel_eng);
ShowQueryString(STR_ENGINE_NAME, str, MAX_LENGTH_ENGINE_NAME_BYTES, MAX_LENGTH_ENGINE_NAME_PIXELS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT);
}
break;
}
}
}
virtual void OnInvalidateData(int data)
{
this->regenerate_list = true;
}
virtual void OnPaint()
{
if (this->regenerate_list) {
this->regenerate_list = false;
this->GenerateBuildList();
}
uint max = min(this->vscroll.pos + this->vscroll.cap, this->eng_list.Length());
SetVScrollCount(this, this->eng_list.Length());
if (this->vehicle_type == VEH_TRAIN) {
if (this->filter.railtype == RAILTYPE_END) {
SetDParam(0, STR_ALL_AVAIL_RAIL_VEHICLES);
} else {
const RailtypeInfo *rti = GetRailTypeInfo(this->filter.railtype);
SetDParam(0, rti->strings.build_caption);
}
}
/* Set text of sort by dropdown */
this->widget[BUILD_VEHICLE_WIDGET_SORT_DROPDOWN].data = _sort_listing[this->vehicle_type][this->sort_criteria];
this->DrawWidgets();
DrawEngineList(this->vehicle_type, this->widget[BUILD_VEHICLE_WIDGET_LIST].left + 2, this->widget[BUILD_VEHICLE_WIDGET_LIST].right, this->widget[BUILD_VEHICLE_WIDGET_LIST].top + 1, &this->eng_list, this->vscroll.pos, max, this->sel_engine, 0, DEFAULT_GROUP);
if (this->sel_engine != INVALID_ENGINE) {
const Widget *wi = &this->widget[BUILD_VEHICLE_WIDGET_PANEL];
int text_end = DrawVehiclePurchaseInfo(2, wi->top + 1, wi->right - wi->left - 2, this->sel_engine);
if (text_end > wi->bottom) {
this->SetDirty();
ResizeWindowForWidget(this, BUILD_VEHICLE_WIDGET_PANEL, 0, text_end - wi->bottom);
this->SetDirty();
}
}
this->DrawSortButtonState(BUILD_VEHICLE_WIDGET_SORT_ASSENDING_DESCENDING, this->descending_sort_order ? SBS_DOWN : SBS_UP);
}
virtual void OnDoubleClick(Point pt, int widget)
{
if (widget == BUILD_VEHICLE_WIDGET_LIST) {
/* When double clicking, we want to buy a vehicle */
this->OnClick(pt, BUILD_VEHICLE_WIDGET_BUILD);
}
}
virtual void OnQueryTextFinished(char *str)
{
if (str == NULL) return;
StringID err_str = STR_NULL;
switch (this->vehicle_type) {
default: NOT_REACHED();
case VEH_TRAIN: err_str = STR_886B_CAN_T_RENAME_TRAIN_VEHICLE; break;
case VEH_ROAD: err_str = STR_9037_CAN_T_RENAME_ROAD_VEHICLE; break;
case VEH_SHIP: err_str = STR_9839_CAN_T_RENAME_SHIP_TYPE; break;
case VEH_AIRCRAFT: err_str = STR_A03A_CAN_T_RENAME_AIRCRAFT_TYPE; break;
}
DoCommandP(0, this->rename_engine, 0, CMD_RENAME_ENGINE | CMD_MSG(err_str), NULL, str);
}
virtual void OnDropdownSelect(int widget, int index)
{
if (this->sort_criteria != index) {
this->sort_criteria = index;
_last_sort_criteria[this->vehicle_type] = this->sort_criteria;
this->regenerate_list = true;
}
this->SetDirty();
}
virtual void OnResize(Point new_size, Point delta)
{
if (delta.x != 0 && !this->listview_mode) {
ResizeButtons(this, BUILD_VEHICLE_WIDGET_BUILD, BUILD_VEHICLE_WIDGET_RENAME);
}
if (delta.y == 0) return;
this->vscroll.cap += delta.y / (int)GetVehicleListHeight(this->vehicle_type);
this->widget[BUILD_VEHICLE_WIDGET_LIST].data = (this->vscroll.cap << 8) + 1;
}
};
static const WindowDesc _build_vehicle_desc(
WDP_AUTO, WDP_AUTO, 240, 174, 240, 256,
WC_BUILD_VEHICLE, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_RESIZABLE | WDF_CONSTRUCTION,
_build_vehicle_widgets
);
void ShowBuildVehicleWindow(TileIndex tile, VehicleType type)
{
/* We want to be able to open both Available Train as Available Ships,
* so if tile == INVALID_TILE (Available XXX Window), use 'type' as unique number.
* As it always is a low value, it won't collide with any real tile
* number. */
uint num = (tile == INVALID_TILE) ? (int)type : tile;
assert(IsCompanyBuildableVehicleType(type));
DeleteWindowById(WC_BUILD_VEHICLE, num);
new BuildVehicleWindow(&_build_vehicle_desc, tile, type);
}
| 37,290
|
C++
|
.cpp
| 947
| 36.457233
| 260
| 0.703734
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,150
|
ship_cmd.cpp
|
EnergeticBark_OpenTTD-3DS/src/ship_cmd.cpp
|
/* $Id$ */
/** @file ship_cmd.cpp Handling of ships. */
#include "stdafx.h"
#include "ship.h"
#include "landscape.h"
#include "timetable.h"
#include "command_func.h"
#include "station_map.h"
#include "news_func.h"
#include "company_func.h"
#include "npf.h"
#include "depot_base.h"
#include "vehicle_gui.h"
#include "newgrf_engine.h"
#include "yapf/yapf.h"
#include "newgrf_sound.h"
#include "spritecache.h"
#include "strings_func.h"
#include "functions.h"
#include "window_func.h"
#include "date_func.h"
#include "vehicle_func.h"
#include "sound_func.h"
#include "variables.h"
#include "autoreplace_gui.h"
#include "gfx_func.h"
#include "effectvehicle_func.h"
#include "settings_type.h"
#include "ai/ai.hpp"
#include "pathfind.h"
#include "table/strings.h"
#include "table/sprites.h"
static const uint16 _ship_sprites[] = {0x0E5D, 0x0E55, 0x0E65, 0x0E6D};
static const TrackBits _ship_sometracks[4] = {
TRACK_BIT_X | TRACK_BIT_LOWER | TRACK_BIT_LEFT, // 0x19, // DIAGDIR_NE
TRACK_BIT_Y | TRACK_BIT_UPPER | TRACK_BIT_LEFT, // 0x16, // DIAGDIR_SE
TRACK_BIT_X | TRACK_BIT_UPPER | TRACK_BIT_RIGHT, // 0x25, // DIAGDIR_SW
TRACK_BIT_Y | TRACK_BIT_LOWER | TRACK_BIT_RIGHT, // 0x2A, // DIAGDIR_NW
};
static inline TrackBits GetTileShipTrackStatus(TileIndex tile)
{
return TrackStatusToTrackBits(GetTileTrackStatus(tile, TRANSPORT_WATER, 0));
}
static SpriteID GetShipIcon(EngineID engine)
{
uint8 spritenum = ShipVehInfo(engine)->image_index;
if (is_custom_sprite(spritenum)) {
SpriteID sprite = GetCustomVehicleIcon(engine, DIR_W);
if (sprite != 0) return sprite;
spritenum = GetEngine(engine)->image_index;
}
return 6 + _ship_sprites[spritenum];
}
void DrawShipEngine(int x, int y, EngineID engine, SpriteID pal)
{
DrawSprite(GetShipIcon(engine), pal, x, y);
}
/** Get the size of the sprite of a ship sprite heading west (used for lists)
* @param engine The engine to get the sprite from
* @param width The width of the sprite
* @param height The height of the sprite
*/
void GetShipSpriteSize(EngineID engine, uint &width, uint &height)
{
const Sprite *spr = GetSprite(GetShipIcon(engine), ST_NORMAL);
width = spr->width;
height = spr->height;
}
SpriteID Ship::GetImage(Direction direction) const
{
uint8 spritenum = this->spritenum;
if (is_custom_sprite(spritenum)) {
SpriteID sprite = GetCustomVehicleSprite(this, direction);
if (sprite != 0) return sprite;
spritenum = GetEngine(this->engine_type)->image_index;
}
return _ship_sprites[spritenum] + direction;
}
static const Depot *FindClosestShipDepot(const Vehicle *v)
{
if (_settings_game.pf.pathfinder_for_ships == VPF_NPF) { // NPF is used
Trackdir trackdir = GetVehicleTrackdir(v);
NPFFoundTargetData ftd = NPFRouteToDepotTrialError(v->tile, trackdir, false, TRANSPORT_WATER, 0, v->owner, INVALID_RAILTYPES);
if (ftd.best_bird_dist == 0) return GetDepotByTile(ftd.node.tile); // Found target
return NULL; // Did not find target
}
/* OPF or YAPF - find the closest depot */
const Depot *depot;
const Depot *best_depot = NULL;
uint best_dist = UINT_MAX;
FOR_ALL_DEPOTS(depot) {
TileIndex tile = depot->xy;
if (IsShipDepotTile(tile) && IsTileOwner(tile, v->owner)) {
uint dist = DistanceManhattan(tile, v->tile);
if (dist < best_dist) {
best_dist = dist;
best_depot = depot;
}
}
}
return best_depot;
}
static void CheckIfShipNeedsService(Vehicle *v)
{
if (_settings_game.vehicle.servint_ships == 0 || !v->NeedsAutomaticServicing()) return;
if (v->IsInDepot()) {
VehicleServiceInDepot(v);
return;
}
const Depot *depot = FindClosestShipDepot(v);
if (depot == NULL || DistanceManhattan(v->tile, depot->xy) > 12) {
if (v->current_order.IsType(OT_GOTO_DEPOT)) {
v->current_order.MakeDummy();
InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
}
return;
}
v->current_order.MakeGoToDepot(depot->index, ODTFB_SERVICE);
v->dest_tile = depot->xy;
InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
}
Money Ship::GetRunningCost() const
{
return GetVehicleProperty(this, 0x0F, ShipVehInfo(this->engine_type)->running_cost) * _price.ship_running;
}
void Ship::OnNewDay()
{
if ((++this->day_counter & 7) == 0)
DecreaseVehicleValue(this);
CheckVehicleBreakdown(this);
AgeVehicle(this);
CheckIfShipNeedsService(this);
CheckOrders(this);
if (this->running_ticks == 0) return;
CommandCost cost(EXPENSES_SHIP_RUN, this->GetRunningCost() * this->running_ticks / (DAYS_IN_YEAR * DAY_TICKS));
this->profit_this_year -= cost.GetCost();
this->running_ticks = 0;
SubtractMoneyFromCompanyFract(this->owner, cost);
InvalidateWindow(WC_VEHICLE_DETAILS, this->index);
/* we need this for the profit */
InvalidateWindowClasses(WC_SHIPS_LIST);
}
static void HandleBrokenShip(Vehicle *v)
{
if (v->breakdown_ctr != 1) {
v->breakdown_ctr = 1;
v->cur_speed = 0;
if (v->breakdowns_since_last_service != 255)
v->breakdowns_since_last_service++;
InvalidateWindow(WC_VEHICLE_VIEW, v->index);
InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
if (!PlayVehicleSound(v, VSE_BREAKDOWN)) {
SndPlayVehicleFx((_settings_game.game_creation.landscape != LT_TOYLAND) ?
SND_10_TRAIN_BREAKDOWN : SND_3A_COMEDY_BREAKDOWN_2, v);
}
if (!(v->vehstatus & VS_HIDDEN)) {
Vehicle *u = CreateEffectVehicleRel(v, 4, 4, 5, EV_BREAKDOWN_SMOKE);
if (u != NULL) u->u.effect.animation_state = v->breakdown_delay * 2;
}
}
if (!(v->tick_counter & 1)) {
if (!--v->breakdown_delay) {
v->breakdown_ctr = 0;
InvalidateWindow(WC_VEHICLE_VIEW, v->index);
}
}
}
void Ship::MarkDirty()
{
this->cur_image = this->GetImage(this->direction);
MarkSingleVehicleDirty(this);
}
static void PlayShipSound(const Vehicle *v)
{
if (!PlayVehicleSound(v, VSE_START)) {
SndPlayVehicleFx(ShipVehInfo(v->engine_type)->sfx, v);
}
}
void Ship::PlayLeaveStationSound() const
{
PlayShipSound(this);
}
TileIndex Ship::GetOrderStationLocation(StationID station)
{
if (station == this->last_station_visited) this->last_station_visited = INVALID_STATION;
const Station *st = GetStation(station);
if (st->dock_tile != INVALID_TILE) {
return TILE_ADD(st->dock_tile, ToTileIndexDiff(GetDockOffset(st->dock_tile)));
} else {
this->cur_order_index++;
return 0;
}
}
void Ship::UpdateDeltaXY(Direction direction)
{
#define MKIT(a, b, c, d) ((a & 0xFF) << 24) | ((b & 0xFF) << 16) | ((c & 0xFF) << 8) | ((d & 0xFF) << 0)
static const uint32 _delta_xy_table[8] = {
MKIT( 6, 6, -3, -3),
MKIT( 6, 32, -3, -16),
MKIT( 6, 6, -3, -3),
MKIT(32, 6, -16, -3),
MKIT( 6, 6, -3, -3),
MKIT( 6, 32, -3, -16),
MKIT( 6, 6, -3, -3),
MKIT(32, 6, -16, -3),
};
#undef MKIT
uint32 x = _delta_xy_table[direction];
this->x_offs = GB(x, 0, 8);
this->y_offs = GB(x, 8, 8);
this->x_extent = GB(x, 16, 8);
this->y_extent = GB(x, 24, 8);
this->z_extent = 6;
}
void RecalcShipStuff(Vehicle *v)
{
v->UpdateDeltaXY(v->direction);
v->cur_image = v->GetImage(v->direction);
v->MarkDirty();
InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
}
static const TileIndexDiffC _ship_leave_depot_offs[] = {
{-1, 0},
{ 0, -1}
};
static void CheckShipLeaveDepot(Vehicle *v)
{
if (!v->IsInDepot()) return;
TileIndex tile = v->tile;
Axis axis = GetShipDepotAxis(tile);
/* Check first (north) side */
if (_ship_sometracks[axis] & GetTileShipTrackStatus(TILE_ADD(tile, ToTileIndexDiff(_ship_leave_depot_offs[axis])))) {
v->direction = ReverseDir(AxisToDirection(axis));
/* Check second (south) side */
} else if (_ship_sometracks[axis + 2] & GetTileShipTrackStatus(TILE_ADD(tile, -2 * ToTileIndexDiff(_ship_leave_depot_offs[axis])))) {
v->direction = AxisToDirection(axis);
} else {
return;
}
v->u.ship.state = AxisToTrackBits(axis);
v->vehstatus &= ~VS_HIDDEN;
v->cur_speed = 0;
RecalcShipStuff(v);
PlayShipSound(v);
VehicleServiceInDepot(v);
InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
InvalidateWindowClasses(WC_SHIPS_LIST);
}
static bool ShipAccelerate(Vehicle *v)
{
uint spd;
byte t;
spd = min(v->cur_speed + 1, GetVehicleProperty(v, 0x0B, v->max_speed));
/* updates statusbar only if speed have changed to save CPU time */
if (spd != v->cur_speed) {
v->cur_speed = spd;
if (_settings_client.gui.vehicle_speed)
InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
}
/* Decrease somewhat when turning */
if (!(v->direction & 1)) spd = spd * 3 / 4;
if (spd == 0) return false;
if ((byte)++spd == 0) return true;
v->progress = (t = v->progress) - (byte)spd;
return (t < v->progress);
}
static void ShipArrivesAt(const Vehicle *v, Station *st)
{
/* Check if station was ever visited before */
if (!(st->had_vehicle_of_type & HVOT_SHIP)) {
st->had_vehicle_of_type |= HVOT_SHIP;
SetDParam(0, st->index);
AddNewsItem(
STR_9833_CITIZENS_CELEBRATE_FIRST,
(v->owner == _local_company) ? NS_ARRIVAL_COMPANY : NS_ARRIVAL_OTHER,
v->index,
st->index
);
AI::NewEvent(v->owner, new AIEventStationFirstVehicle(st->index, v->index));
}
}
struct PathFindShip {
TileIndex skiptile;
TileIndex dest_coords;
uint best_bird_dist;
uint best_length;
};
static bool ShipTrackFollower(TileIndex tile, PathFindShip *pfs, int track, uint length)
{
/* Found dest? */
if (tile == pfs->dest_coords) {
pfs->best_bird_dist = 0;
pfs->best_length = minu(pfs->best_length, length);
return true;
}
/* Skip this tile in the calculation */
if (tile != pfs->skiptile) {
pfs->best_bird_dist = minu(pfs->best_bird_dist, DistanceMaxPlusManhattan(pfs->dest_coords, tile));
}
return false;
}
static const byte _ship_search_directions[6][4] = {
{ 0, 9, 2, 9 },
{ 9, 1, 9, 3 },
{ 9, 0, 3, 9 },
{ 1, 9, 9, 2 },
{ 3, 2, 9, 9 },
{ 9, 9, 1, 0 },
};
static const byte _pick_shiptrack_table[6] = {1, 3, 2, 2, 0, 0};
static uint FindShipTrack(Vehicle *v, TileIndex tile, DiagDirection dir, TrackBits bits, TileIndex skiptile, Track *track)
{
PathFindShip pfs;
Track i, best_track;
uint best_bird_dist = 0;
uint best_length = 0;
uint r;
byte ship_dir = v->direction & 3;
pfs.dest_coords = v->dest_tile;
pfs.skiptile = skiptile;
best_track = INVALID_TRACK;
do {
i = RemoveFirstTrack(&bits);
pfs.best_bird_dist = UINT_MAX;
pfs.best_length = UINT_MAX;
FollowTrack(tile, PATHFIND_FLAGS_SHIP_MODE | PATHFIND_FLAGS_DISABLE_TILE_HASH, TRANSPORT_WATER, 0, (DiagDirection)_ship_search_directions[i][dir], (TPFEnumProc*)ShipTrackFollower, NULL, &pfs);
if (best_track != INVALID_TRACK) {
if (pfs.best_bird_dist != 0) {
/* neither reached the destination, pick the one with the smallest bird dist */
if (pfs.best_bird_dist > best_bird_dist) goto bad;
if (pfs.best_bird_dist < best_bird_dist) goto good;
} else {
if (pfs.best_length > best_length) goto bad;
if (pfs.best_length < best_length) goto good;
}
/* if we reach this position, there's two paths of equal value so far.
* pick one randomly. */
r = GB(Random(), 0, 8);
if (_pick_shiptrack_table[i] == ship_dir) r += 80;
if (_pick_shiptrack_table[best_track] == ship_dir) r -= 80;
if (r <= 127) goto bad;
}
good:;
best_track = i;
best_bird_dist = pfs.best_bird_dist;
best_length = pfs.best_length;
bad:;
} while (bits != 0);
*track = best_track;
return best_bird_dist;
}
static inline NPFFoundTargetData PerfNPFRouteToStationOrTile(TileIndex tile, Trackdir trackdir, bool ignore_start_tile, NPFFindStationOrTileData *target, TransportType type, Owner owner, RailTypes railtypes)
{
void *perf = NpfBeginInterval();
NPFFoundTargetData ret = NPFRouteToStationOrTile(tile, trackdir, ignore_start_tile, target, type, 0, owner, railtypes);
int t = NpfEndInterval(perf);
DEBUG(yapf, 4, "[NPFW] %d us - %d rounds - %d open - %d closed -- ", t, 0, _aystar_stats_open_size, _aystar_stats_closed_size);
return ret;
}
/** returns the track to choose on the next tile, or -1 when it's better to
* reverse. The tile given is the tile we are about to enter, enterdir is the
* direction in which we are entering the tile */
static Track ChooseShipTrack(Vehicle *v, TileIndex tile, DiagDirection enterdir, TrackBits tracks)
{
assert(IsValidDiagDirection(enterdir));
switch (_settings_game.pf.pathfinder_for_ships) {
case VPF_YAPF: { // YAPF
Trackdir trackdir = YapfChooseShipTrack(v, tile, enterdir, tracks);
if (trackdir != INVALID_TRACKDIR) return TrackdirToTrack(trackdir);
} break;
case VPF_NPF: { // NPF
NPFFindStationOrTileData fstd;
Trackdir trackdir = GetVehicleTrackdir(v);
assert(trackdir != INVALID_TRACKDIR); // Check that we are not in a depot
NPFFillWithOrderData(&fstd, v);
NPFFoundTargetData ftd = PerfNPFRouteToStationOrTile(tile - TileOffsByDiagDir(enterdir), trackdir, true, &fstd, TRANSPORT_WATER, v->owner, INVALID_RAILTYPES);
/* If ftd.best_bird_dist is 0, we found our target and ftd.best_trackdir contains
* the direction we need to take to get there, if ftd.best_bird_dist is not 0,
* we did not find our target, but ftd.best_trackdir contains the direction leading
* to the tile closest to our target. */
if (ftd.best_trackdir != 0xff) return TrackdirToTrack(ftd.best_trackdir); // TODO: Wrapper function?
} break;
default:
case VPF_OPF: { // OPF
TileIndex tile2 = TILE_ADD(tile, -TileOffsByDiagDir(enterdir));
Track track;
/* Let's find out how far it would be if we would reverse first */
TrackBits b = GetTileShipTrackStatus(tile2) & _ship_sometracks[ReverseDiagDir(enterdir)] & v->u.ship.state;
uint distr = UINT_MAX; // distance if we reversed
if (b != 0) {
distr = FindShipTrack(v, tile2, ReverseDiagDir(enterdir), b, tile, &track);
if (distr != UINT_MAX) distr++; // penalty for reversing
}
/* And if we would not reverse? */
uint dist = FindShipTrack(v, tile, enterdir, tracks, 0, &track);
if (dist <= distr) return track;
} break;
}
return INVALID_TRACK; // We could better reverse
}
static const Direction _new_vehicle_direction_table[] = {
DIR_N , DIR_NW, DIR_W , INVALID_DIR,
DIR_NE, DIR_N , DIR_SW, INVALID_DIR,
DIR_E , DIR_SE, DIR_S
};
static Direction ShipGetNewDirectionFromTiles(TileIndex new_tile, TileIndex old_tile)
{
uint offs = (TileY(new_tile) - TileY(old_tile) + 1) * 4 +
TileX(new_tile) - TileX(old_tile) + 1;
assert(offs < 11 && offs != 3 && offs != 7);
return _new_vehicle_direction_table[offs];
}
static Direction ShipGetNewDirection(Vehicle *v, int x, int y)
{
uint offs = (y - v->y_pos + 1) * 4 + (x - v->x_pos + 1);
assert(offs < 11 && offs != 3 && offs != 7);
return _new_vehicle_direction_table[offs];
}
static inline TrackBits GetAvailShipTracks(TileIndex tile, int dir)
{
return GetTileShipTrackStatus(tile) & _ship_sometracks[dir];
}
static const byte _ship_subcoord[4][6][3] = {
{
{15, 8, 1},
{ 0, 0, 0},
{ 0, 0, 0},
{15, 8, 2},
{15, 7, 0},
{ 0, 0, 0},
},
{
{ 0, 0, 0},
{ 8, 0, 3},
{ 7, 0, 2},
{ 0, 0, 0},
{ 8, 0, 4},
{ 0, 0, 0},
},
{
{ 0, 8, 5},
{ 0, 0, 0},
{ 0, 7, 6},
{ 0, 0, 0},
{ 0, 0, 0},
{ 0, 8, 4},
},
{
{ 0, 0, 0},
{ 8, 15, 7},
{ 0, 0, 0},
{ 8, 15, 6},
{ 0, 0, 0},
{ 7, 15, 0},
}
};
static void ShipController(Vehicle *v)
{
uint32 r;
const byte *b;
Direction dir;
Track track;
TrackBits tracks;
v->tick_counter++;
v->current_order_time++;
if (v->breakdown_ctr != 0) {
if (v->breakdown_ctr <= 2) {
HandleBrokenShip(v);
return;
}
if (!v->current_order.IsType(OT_LOADING)) v->breakdown_ctr--;
}
if (v->vehstatus & VS_STOPPED) return;
ProcessOrders(v);
v->HandleLoading();
if (v->current_order.IsType(OT_LOADING)) return;
CheckShipLeaveDepot(v);
if (!ShipAccelerate(v)) return;
GetNewVehiclePosResult gp = GetNewVehiclePos(v);
if (v->u.ship.state != TRACK_BIT_WORMHOLE) {
/* Not on a bridge */
if (gp.old_tile == gp.new_tile) {
/* Staying in tile */
if (v->IsInDepot()) {
gp.x = v->x_pos;
gp.y = v->y_pos;
} else {
/* Not inside depot */
r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
if (HasBit(r, VETS_CANNOT_ENTER)) goto reverse_direction;
/* A leave station order only needs one tick to get processed, so we can
* always skip ahead. */
if (v->current_order.IsType(OT_LEAVESTATION)) {
v->current_order.Free();
InvalidateWindowWidget(WC_VEHICLE_VIEW, v->index, VVW_WIDGET_START_STOP_VEH);
} else if (v->dest_tile != 0) {
/* We have a target, let's see if we reached it... */
if (v->current_order.IsType(OT_GOTO_STATION) &&
GetStation(v->current_order.GetDestination())->IsBuoy() &&
DistanceManhattan(v->dest_tile, gp.new_tile) <= 3) {
/* We got within 3 tiles of our target buoy, so let's skip to our
* next order */
UpdateVehicleTimetable(v, true);
v->cur_order_index++;
v->current_order.MakeDummy();
InvalidateVehicleOrder(v, 0);
} else {
/* Non-buoy orders really need to reach the tile */
if (v->dest_tile == gp.new_tile) {
if (v->current_order.IsType(OT_GOTO_DEPOT)) {
if ((gp.x & 0xF) == 8 && (gp.y & 0xF) == 8) {
VehicleEnterDepot(v);
return;
}
} else if (v->current_order.IsType(OT_GOTO_STATION)) {
v->last_station_visited = v->current_order.GetDestination();
/* Process station in the orderlist. */
Station *st = GetStation(v->current_order.GetDestination());
if (st->facilities & FACIL_DOCK) { // ugly, ugly workaround for problem with ships able to drop off cargo at wrong stations
ShipArrivesAt(v, st);
v->BeginLoading();
} else { // leave stations without docks right aways
v->current_order.MakeLeaveStation();
v->cur_order_index++;
InvalidateVehicleOrder(v, 0);
}
}
}
}
}
}
} else {
DiagDirection diagdir;
/* New tile */
if (TileX(gp.new_tile) >= MapMaxX() || TileY(gp.new_tile) >= MapMaxY()) {
goto reverse_direction;
}
dir = ShipGetNewDirectionFromTiles(gp.new_tile, gp.old_tile);
assert(dir == DIR_NE || dir == DIR_SE || dir == DIR_SW || dir == DIR_NW);
diagdir = DirToDiagDir(dir);
tracks = GetAvailShipTracks(gp.new_tile, diagdir);
if (tracks == TRACK_BIT_NONE) goto reverse_direction;
/* Choose a direction, and continue if we find one */
track = ChooseShipTrack(v, gp.new_tile, diagdir, tracks);
if (track == INVALID_TRACK) goto reverse_direction;
b = _ship_subcoord[diagdir][track];
gp.x = (gp.x & ~0xF) | b[0];
gp.y = (gp.y & ~0xF) | b[1];
/* Call the landscape function and tell it that the vehicle entered the tile */
r = VehicleEnterTile(v, gp.new_tile, gp.x, gp.y);
if (HasBit(r, VETS_CANNOT_ENTER)) goto reverse_direction;
if (!HasBit(r, VETS_ENTERED_WORMHOLE)) {
v->tile = gp.new_tile;
v->u.ship.state = TrackToTrackBits(track);
}
v->direction = (Direction)b[2];
}
} else {
/* On a bridge */
if (!IsTileType(gp.new_tile, MP_TUNNELBRIDGE) || !HasBit(VehicleEnterTile(v, gp.new_tile, gp.x, gp.y), VETS_ENTERED_WORMHOLE)) {
v->x_pos = gp.x;
v->y_pos = gp.y;
VehicleMove(v, !(v->vehstatus & VS_HIDDEN));
return;
}
}
/* update image of ship, as well as delta XY */
dir = ShipGetNewDirection(v, gp.x, gp.y);
v->x_pos = gp.x;
v->y_pos = gp.y;
v->z_pos = GetSlopeZ(gp.x, gp.y);
getout:
v->UpdateDeltaXY(dir);
v->cur_image = v->GetImage(dir);
VehicleMove(v, true);
return;
reverse_direction:
dir = ReverseDir(v->direction);
v->direction = dir;
goto getout;
}
static void AgeShipCargo(Vehicle *v)
{
if (_age_cargo_skip_counter != 0) return;
v->cargo.AgeCargo();
}
void Ship::Tick()
{
if (!(this->vehstatus & VS_STOPPED)) this->running_ticks++;
AgeShipCargo(this);
ShipController(this);
}
/** 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
*/
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_SHIP_NOT_AVAILABLE);
const Engine *e = GetEngine(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_00E1_TOO_MANY_VEHICLES_IN_GAME);
if (flags & DC_EXEC) {
int x;
int y;
const ShipVehicleInfo *svi = ShipVehInfo(p1);
Vehicle *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->running_ticks = 0;
v->UpdateDeltaXY(v->direction);
v->vehstatus = VS_HIDDEN | VS_STOPPED | VS_DEFPAL;
v->spritenum = svi->image_index;
v->cargo_type = e->GetDefaultCargoType();
v->cargo_subtype = 0;
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->lifelength * DAYS_IN_LEAP_YEAR;
_new_vehicle_id = v->index;
v->name = NULL;
v->u.ship.state = TRACK_BIT_DEPOT;
v->service_interval = _settings_game.vehicle.servint_ships;
v->date_of_last_service = _date;
v->build_year = _cur_year;
v->cur_image = 0x0E5E;
v->random_bits = VehicleRandomBits();
v->vehicle_flags = 0;
if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) SetBit(v->vehicle_flags, VF_BUILT_AS_PROTOTYPE);
v->cargo_cap = GetVehicleProperty(v, 0x0D, svi->capacity);
VehicleMove(v, false);
InvalidateWindowData(WC_VEHICLE_DEPOT, v->tile);
InvalidateWindowClassesData(WC_SHIPS_LIST, 0);
InvalidateWindow(WC_COMPANY, v->owner);
if (IsLocalCompany())
InvalidateAutoreplaceWindow(v->engine_type, v->group_id); // updates the replace Ship window
GetCompany(_current_company)->num_engines[p1]++;
}
return value;
}
/** Sell a ship.
* @param tile unused
* @param flags type of operation
* @param p1 vehicle ID to be sold
* @param p2 unused
*/
CommandCost CmdSellShip(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Vehicle *v;
if (!IsValidVehicleID(p1)) return CMD_ERROR;
v = GetVehicle(p1);
if (v->type != VEH_SHIP || !CheckOwnership(v->owner)) return CMD_ERROR;
if (HASBITS(v->vehstatus, VS_CRASHED)) return_cmd_error(STR_CAN_T_SELL_DESTROYED_VEHICLE);
if (!v->IsStoppedInDepot()) {
return_cmd_error(STR_980B_SHIP_MUST_BE_STOPPED_IN);
}
CommandCost ret(EXPENSES_NEW_VEHICLES, -v->value);
if (flags & DC_EXEC) {
delete v;
}
return ret;
}
bool Ship::FindClosestDepot(TileIndex *location, DestinationID *destination, bool *reverse)
{
const Depot *depot = FindClosestShipDepot(this);
if (depot == NULL) return false;
if (location != NULL) *location = depot->xy;
if (destination != NULL) *destination = depot->index;
return true;
}
/** Send a ship to the depot.
* @param tile unused
* @param flags type of operation
* @param p1 vehicle ID to send to the depot
* @param p2 various bitmasked elements
* - p2 bit 0-3 - DEPOT_ flags (see vehicle.h)
* - p2 bit 8-10 - VLW flag (for mass goto depot)
*/
CommandCost CmdSendShipToDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
if (p2 & DEPOT_MASS_SEND) {
/* Mass goto depot requested */
if (!ValidVLWFlags(p2 & VLW_MASK)) return CMD_ERROR;
return SendAllVehiclesToDepot(VEH_SHIP, flags, p2 & DEPOT_SERVICE, _current_company, (p2 & VLW_MASK), p1);
}
if (!IsValidVehicleID(p1)) return CMD_ERROR;
Vehicle *v = GetVehicle(p1);
if (v->type != VEH_SHIP) return CMD_ERROR;
return v->SendToDepot(flags, (DepotCommand)(p2 & DEPOT_COMMAND_MASK));
}
/** Refits a ship to the specified cargo type.
* @param tile unused
* @param flags type of operation
* @param p1 vehicle ID of the ship to refit
* @param p2 various bitstuffed elements
* - p2 = (bit 0-7) - the new cargo type to refit to (p2 & 0xFF)
* - p2 = (bit 8-15) - the new cargo subtype to refit to
* - p2 = (bit 16) - refit only this vehicle (ignored)
* @return cost of refit or error
*/
CommandCost CmdRefitShip(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text)
{
Vehicle *v;
CommandCost cost(EXPENSES_SHIP_RUN);
CargoID new_cid = GB(p2, 0, 8); // gets the cargo number
byte new_subtype = GB(p2, 8, 8);
uint16 capacity = CALLBACK_FAILED;
if (!IsValidVehicleID(p1)) return CMD_ERROR;
v = GetVehicle(p1);
if (v->type != VEH_SHIP || !CheckOwnership(v->owner)) return CMD_ERROR;
if (!v->IsStoppedInDepot()) return_cmd_error(STR_980B_SHIP_MUST_BE_STOPPED_IN);
if (v->vehstatus & VS_CRASHED) return_cmd_error(STR_CAN_T_REFIT_DESTROYED_VEHICLE);
/* Check cargo */
if (!ShipVehInfo(v->engine_type)->refittable) return CMD_ERROR;
if (new_cid >= NUM_CARGO || !CanRefitTo(v->engine_type, new_cid)) return CMD_ERROR;
/* Check the refit capacity callback */
if (HasBit(EngInfo(v->engine_type)->callbackmask, CBM_VEHICLE_REFIT_CAPACITY)) {
/* Back up the existing cargo type */
CargoID temp_cid = v->cargo_type;
byte temp_subtype = v->cargo_subtype;
v->cargo_type = new_cid;
v->cargo_subtype = new_subtype;
capacity = GetVehicleCallback(CBID_VEHICLE_REFIT_CAPACITY, 0, 0, v->engine_type, v);
/* Restore the cargo type */
v->cargo_type = temp_cid;
v->cargo_subtype = temp_subtype;
}
if (capacity == CALLBACK_FAILED) {
capacity = GetVehicleProperty(v, 0x0D, ShipVehInfo(v->engine_type)->capacity);
}
_returned_refit_capacity = capacity;
if (new_cid != v->cargo_type) {
cost = GetRefitCost(v->engine_type);
}
if (flags & DC_EXEC) {
v->cargo_cap = capacity;
v->cargo.Truncate((v->cargo_type == new_cid) ? capacity : 0);
v->cargo_type = new_cid;
v->cargo_subtype = new_subtype;
v->colourmap = PAL_NONE; // invalidate vehicle colour map
InvalidateWindow(WC_VEHICLE_DETAILS, v->index);
InvalidateWindow(WC_VEHICLE_DEPOT, v->tile);
InvalidateWindowClassesData(WC_SHIPS_LIST, 0);
}
return cost;
}
| 26,704
|
C++
|
.cpp
| 768
| 31.925781
| 207
| 0.686743
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,152
|
road_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/road_gui.cpp
|
/* $Id$ */
/** @file road_gui.cpp GUI for building roads. */
#include "stdafx.h"
#include "openttd.h"
#include "gui.h"
#include "window_gui.h"
#include "station_gui.h"
#include "terraform_gui.h"
#include "viewport_func.h"
#include "gfx_func.h"
#include "command_func.h"
#include "road_type.h"
#include "road_cmd.h"
#include "road_map.h"
#include "station_func.h"
#include "functions.h"
#include "window_func.h"
#include "vehicle_func.h"
#include "sound_func.h"
#include "company_func.h"
#include "tunnelbridge.h"
#include "tilehighlight_func.h"
#include "company_base.h"
#include "settings_type.h"
#include "table/sprites.h"
#include "table/strings.h"
static void ShowRVStationPicker(Window *parent, RoadStopType rs);
static void ShowRoadDepotPicker(Window *parent);
static bool _remove_button_clicked;
static bool _one_way_button_clicked;
/**
* Define the values of the RoadFlags
* @see CmdBuildLongRoad
*/
enum RoadFlags {
RF_NONE = 0x00,
RF_START_HALFROAD_Y = 0x01, // The start tile in Y-dir should have only a half road
RF_END_HALFROAD_Y = 0x02, // The end tile in Y-dir should have only a half road
RF_DIR_Y = 0x04, // The direction is Y-dir
RF_DIR_X = RF_NONE, // Dummy; Dir X is set when RF_DIR_Y is not set
RF_START_HALFROAD_X = 0x08, // The start tile in X-dir should have only a half road
RF_END_HALFROAD_X = 0x10, // The end tile in X-dir should have only a half road
};
DECLARE_ENUM_AS_BIT_SET(RoadFlags);
static RoadFlags _place_road_flag;
static RoadType _cur_roadtype;
static DiagDirection _road_depot_orientation;
static DiagDirection _road_station_picker_orientation;
void CcPlaySound1D(bool success, TileIndex tile, uint32 p1, uint32 p2)
{
if (success) SndPlayTileFx(SND_1F_SPLAT, tile);
}
/**
* Set the initial flags for the road constuction.
* The flags are:
* @li The direction is the X-dir
* @li The first tile has a partitial RoadBit (true or false)
*
* @param tile The start tile
*/
static void PlaceRoad_X_Dir(TileIndex tile)
{
_place_road_flag = RF_DIR_X;
if (_tile_fract_coords.x >= 8) _place_road_flag |= RF_START_HALFROAD_X;
VpStartPlaceSizing(tile, VPM_FIX_Y, DDSP_PLACE_ROAD_X_DIR);
}
/**
* Set the initial flags for the road constuction.
* The flags are:
* @li The direction is the Y-dir
* @li The first tile has a partitial RoadBit (true or false)
*
* @param tile The start tile
*/
static void PlaceRoad_Y_Dir(TileIndex tile)
{
_place_road_flag = RF_DIR_Y;
if (_tile_fract_coords.y >= 8) _place_road_flag |= RF_START_HALFROAD_Y;
VpStartPlaceSizing(tile, VPM_FIX_X, DDSP_PLACE_ROAD_Y_DIR);
}
/**
* Set the initial flags for the road constuction.
* The flags are:
* @li The direction is not set.
* @li The first tile has a partitial RoadBit (true or false)
*
* @param tile The start tile
*/
static void PlaceRoad_AutoRoad(TileIndex tile)
{
_place_road_flag = RF_NONE;
if (_tile_fract_coords.x >= 8) _place_road_flag |= RF_START_HALFROAD_X;
if (_tile_fract_coords.y >= 8) _place_road_flag |= RF_START_HALFROAD_Y;
VpStartPlaceSizing(tile, VPM_X_OR_Y, DDSP_PLACE_AUTOROAD);
}
static void PlaceRoad_Bridge(TileIndex tile)
{
VpStartPlaceSizing(tile, VPM_X_OR_Y, DDSP_BUILD_BRIDGE);
}
void CcBuildRoadTunnel(bool success, TileIndex tile, uint32 p1, uint32 p2)
{
if (success) {
SndPlayTileFx(SND_20_SPLAT_2, tile);
if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
} else {
SetRedErrorSquare(_build_tunnel_endtile);
}
}
/** Structure holding information per roadtype for several functions */
struct RoadTypeInfo {
StringID err_build_road; ///< Building a normal piece of road
StringID err_remove_road; ///< Removing a normal piece of road
StringID err_depot; ///< Building a depot
StringID err_build_station[2]; ///< Building a bus or truck station
StringID err_remove_station[2]; ///< Removing of a bus or truck station
StringID picker_title[2]; ///< Title for the station picker for bus or truck stations
StringID picker_tooltip[2]; ///< Tooltip for the station picker for bus or truck stations
SpriteID cursor_nesw; ///< Cursor for building NE and SW bits
SpriteID cursor_nwse; ///< Cursor for building NW and SE bits
SpriteID cursor_autoroad; ///< Cursor for building autoroad
};
/** What errors/cursors must be shown for several types of roads */
static const RoadTypeInfo _road_type_infos[] = {
{
STR_1804_CAN_T_BUILD_ROAD_HERE,
STR_1805_CAN_T_REMOVE_ROAD_FROM,
STR_1807_CAN_T_BUILD_ROAD_VEHICLE,
{ STR_1808_CAN_T_BUILD_BUS_STATION, STR_1809_CAN_T_BUILD_TRUCK_STATION },
{ STR_CAN_T_REMOVE_BUS_STATION, STR_CAN_T_REMOVE_TRUCK_STATION },
{ STR_3042_BUS_STATION_ORIENTATION, STR_3043_TRUCK_STATION_ORIENT },
{ STR_3051_SELECT_BUS_STATION_ORIENTATION, STR_3052_SELECT_TRUCK_LOADING_BAY },
SPR_CURSOR_ROAD_NESW,
SPR_CURSOR_ROAD_NWSE,
SPR_CURSOR_AUTOROAD,
},
{
STR_CAN_T_BUILD_TRAMWAY_HERE,
STR_CAN_T_REMOVE_TRAMWAY_FROM,
STR_CAN_T_BUILD_TRAM_VEHICLE,
{ STR_CAN_T_BUILD_PASSENGER_TRAM_STATION, STR_CAN_T_BUILD_CARGO_TRAM_STATION },
{ STR_CAN_T_REMOVE_PASSENGER_TRAM_STATION, STR_CAN_T_REMOVE_CARGO_TRAM_STATION },
{ STR_PASSENGER_TRAM_STATION_ORIENTATION, STR_CARGO_TRAM_STATION_ORIENT },
{ STR_SELECT_PASSENGER_TRAM_STATION_ORIENTATION, STR_SELECT_CARGO_TRAM_STATION_ORIENTATION },
SPR_CURSOR_TRAMWAY_NESW,
SPR_CURSOR_TRAMWAY_NWSE,
SPR_CURSOR_AUTOTRAM,
},
};
static void PlaceRoad_Tunnel(TileIndex tile)
{
DoCommandP(tile, 0x200 | RoadTypeToRoadTypes(_cur_roadtype), 0, CMD_BUILD_TUNNEL | CMD_MSG(STR_5016_CAN_T_BUILD_TUNNEL_HERE), CcBuildRoadTunnel);
}
static void BuildRoadOutsideStation(TileIndex tile, DiagDirection direction)
{
tile += TileOffsByDiagDir(direction);
/* if there is a roadpiece just outside of the station entrance, build a connecting route */
if (IsNormalRoadTile(tile)) {
if (GetRoadBits(tile, _cur_roadtype) != ROAD_NONE) {
DoCommandP(tile, _cur_roadtype << 4 | DiagDirToRoadBits(ReverseDiagDir(direction)), 0, CMD_BUILD_ROAD);
}
}
}
void CcRoadDepot(bool success, TileIndex tile, uint32 p1, uint32 p2)
{
if (success) {
DiagDirection dir = (DiagDirection)GB(p1, 0, 2);
SndPlayTileFx(SND_1F_SPLAT, tile);
if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
BuildRoadOutsideStation(tile, dir);
/* For a drive-through road stop build connecting road for other entrance */
if (HasBit(p2, 1)) BuildRoadOutsideStation(tile, ReverseDiagDir(dir));
}
}
static void PlaceRoad_Depot(TileIndex tile)
{
DoCommandP(tile, _cur_roadtype << 2 | _road_depot_orientation, 0, CMD_BUILD_ROAD_DEPOT | CMD_MSG(_road_type_infos[_cur_roadtype].err_depot), CcRoadDepot);
}
static void PlaceRoadStop(TileIndex tile, uint32 p2, uint32 cmd)
{
uint32 p1 = _road_station_picker_orientation;
SB(p2, 16, 16, INVALID_STATION); // no station to join
if (p1 >= DIAGDIR_END) {
SetBit(p2, 1); // It's a drive-through stop
p1 -= DIAGDIR_END; // Adjust picker result to actual direction
}
CommandContainer cmdcont = { tile, p1, p2, cmd, CcRoadDepot, "" };
ShowSelectStationIfNeeded(cmdcont, 1, 1);
}
static void PlaceRoad_BusStation(TileIndex tile)
{
if (_remove_button_clicked) {
DoCommandP(tile, 0, ROADSTOP_BUS, CMD_REMOVE_ROAD_STOP | CMD_MSG(_road_type_infos[_cur_roadtype].err_remove_station[ROADSTOP_BUS]), CcPlaySound1D);
} else {
PlaceRoadStop(tile, (_ctrl_pressed << 5) | RoadTypeToRoadTypes(_cur_roadtype) << 2 | ROADSTOP_BUS, CMD_BUILD_ROAD_STOP | CMD_MSG(_road_type_infos[_cur_roadtype].err_build_station[ROADSTOP_BUS]));
}
}
static void PlaceRoad_TruckStation(TileIndex tile)
{
if (_remove_button_clicked) {
DoCommandP(tile, 0, ROADSTOP_TRUCK, CMD_REMOVE_ROAD_STOP | CMD_MSG(_road_type_infos[_cur_roadtype].err_remove_station[ROADSTOP_TRUCK]), CcPlaySound1D);
} else {
PlaceRoadStop(tile, (_ctrl_pressed << 5) | RoadTypeToRoadTypes(_cur_roadtype) << 2 | ROADSTOP_TRUCK, CMD_BUILD_ROAD_STOP | CMD_MSG(_road_type_infos[_cur_roadtype].err_build_station[ROADSTOP_TRUCK]));
}
}
/** Enum referring to the widgets of the build road toolbar */
enum RoadToolbarWidgets {
RTW_CLOSEBOX = 0,
RTW_CAPTION,
RTW_STICKY,
RTW_ROAD_X,
RTW_ROAD_Y,
RTW_AUTOROAD,
RTW_DEMOLISH,
RTW_DEPOT,
RTW_BUS_STATION,
RTW_TRUCK_STATION,
RTW_ONE_WAY,
RTW_BUILD_BRIDGE,
RTW_BUILD_TUNNEL,
RTW_REMOVE,
};
typedef void OnButtonClick(Window *w);
/** Toogles state of the Remove button of Build road toolbar
* @param w window the button belongs to
*/
static void ToggleRoadButton_Remove(Window *w)
{
w->ToggleWidgetLoweredState(RTW_REMOVE);
w->InvalidateWidget(RTW_REMOVE);
_remove_button_clicked = w->IsWidgetLowered(RTW_REMOVE);
SetSelectionRed(_remove_button_clicked);
}
/** Updates the Remove button because of Ctrl state change
* @param w window the button belongs to
* @return true iff the remove buton was changed
*/
static bool RoadToolbar_CtrlChanged(Window *w)
{
if (w->IsWidgetDisabled(RTW_REMOVE)) return false;
/* allow ctrl to switch remove mode only for these widgets */
for (uint i = RTW_ROAD_X; i <= RTW_AUTOROAD; i++) {
if (w->IsWidgetLowered(i)) {
ToggleRoadButton_Remove(w);
return true;
}
}
return false;
}
/**
* Function that handles the click on the
* X road placement button.
*
* @param w The current window
*/
static void BuildRoadClick_X_Dir(Window *w)
{
HandlePlacePushButton(w, RTW_ROAD_X, _road_type_infos[_cur_roadtype].cursor_nwse, VHM_RECT, PlaceRoad_X_Dir);
}
/**
* Function that handles the click on the
* Y road placement button.
*
* @param w The current window
*/
static void BuildRoadClick_Y_Dir(Window *w)
{
HandlePlacePushButton(w, RTW_ROAD_Y, _road_type_infos[_cur_roadtype].cursor_nesw, VHM_RECT, PlaceRoad_Y_Dir);
}
/**
* Function that handles the click on the
* autoroad placement button.
*
* @param w The current window
*/
static void BuildRoadClick_AutoRoad(Window *w)
{
HandlePlacePushButton(w, RTW_AUTOROAD, _road_type_infos[_cur_roadtype].cursor_autoroad, VHM_RECT, PlaceRoad_AutoRoad);
}
static void BuildRoadClick_Demolish(Window *w)
{
HandlePlacePushButton(w, RTW_DEMOLISH, ANIMCURSOR_DEMOLISH, VHM_RECT, PlaceProc_DemolishArea);
}
static void BuildRoadClick_Depot(Window *w)
{
if (_game_mode == GM_EDITOR || !CanBuildVehicleInfrastructure(VEH_ROAD)) return;
if (HandlePlacePushButton(w, RTW_DEPOT, SPR_CURSOR_ROAD_DEPOT, VHM_RECT, PlaceRoad_Depot)) ShowRoadDepotPicker(w);
}
static void BuildRoadClick_BusStation(Window *w)
{
if (_game_mode == GM_EDITOR || !CanBuildVehicleInfrastructure(VEH_ROAD)) return;
if (HandlePlacePushButton(w, RTW_BUS_STATION, SPR_CURSOR_BUS_STATION, VHM_RECT, PlaceRoad_BusStation)) ShowRVStationPicker(w, ROADSTOP_BUS);
}
static void BuildRoadClick_TruckStation(Window *w)
{
if (_game_mode == GM_EDITOR || !CanBuildVehicleInfrastructure(VEH_ROAD)) return;
if (HandlePlacePushButton(w, RTW_TRUCK_STATION, SPR_CURSOR_TRUCK_STATION, VHM_RECT, PlaceRoad_TruckStation)) ShowRVStationPicker(w, ROADSTOP_TRUCK);
}
/**
* Function that handles the click on the
* one way road button.
*
* @param w The current window
*/
static void BuildRoadClick_OneWay(Window *w)
{
if (w->IsWidgetDisabled(RTW_ONE_WAY)) return;
w->SetDirty();
w->ToggleWidgetLoweredState(RTW_ONE_WAY);
SetSelectionRed(false);
}
static void BuildRoadClick_Bridge(Window *w)
{
HandlePlacePushButton(w, RTW_BUILD_BRIDGE, SPR_CURSOR_BRIDGE, VHM_RECT, PlaceRoad_Bridge);
}
static void BuildRoadClick_Tunnel(Window *w)
{
HandlePlacePushButton(w, RTW_BUILD_TUNNEL, SPR_CURSOR_ROAD_TUNNEL, VHM_SPECIAL, PlaceRoad_Tunnel);
}
static void BuildRoadClick_Remove(Window *w)
{
if (w->IsWidgetDisabled(RTW_REMOVE)) return;
DeleteWindowById(WC_SELECT_STATION, 0);
ToggleRoadButton_Remove(w);
SndPlayFx(SND_15_BEEP);
}
/** Array with the handlers of the button-clicks for the road-toolbar */
static OnButtonClick * const _build_road_button_proc[] = {
BuildRoadClick_X_Dir,
BuildRoadClick_Y_Dir,
BuildRoadClick_AutoRoad,
BuildRoadClick_Demolish,
BuildRoadClick_Depot,
BuildRoadClick_BusStation,
BuildRoadClick_TruckStation,
BuildRoadClick_OneWay,
BuildRoadClick_Bridge,
BuildRoadClick_Tunnel,
BuildRoadClick_Remove
};
/** Array with the keycode of the button-clicks for the road-toolbar */
static const uint16 _road_keycodes[] = {
'1',
'2',
'3',
'4',
'5',
'6',
'7',
'8',
'B',
'T',
'R',
};
struct BuildRoadToolbarWindow : Window {
BuildRoadToolbarWindow(const WindowDesc *desc, WindowNumber window_number) : Window(desc, window_number)
{
this->SetWidgetsDisabledState(true,
RTW_REMOVE,
RTW_ONE_WAY,
WIDGET_LIST_END);
this->FindWindowPlacementAndResize(desc);
if (_settings_client.gui.link_terraform_toolbar) ShowTerraformToolbar(this);
}
~BuildRoadToolbarWindow()
{
if (_settings_client.gui.link_terraform_toolbar) DeleteWindowById(WC_SCEN_LAND_GEN, 0, false);
}
/**
* Update the remove button lowered state of the road toolbar
*
* @param clicked_widget The widget which the client clicked just now
*/
void UpdateOptionWidgetStatus(RoadToolbarWidgets clicked_widget)
{
/* The remove and the one way button state is driven
* by the other buttons so they don't act on themselfs.
* Both are only valid if they are able to apply as options. */
switch (clicked_widget) {
case RTW_REMOVE:
this->RaiseWidget(RTW_ONE_WAY);
this->InvalidateWidget(RTW_ONE_WAY);
break;
case RTW_ONE_WAY:
this->RaiseWidget(RTW_REMOVE);
this->InvalidateWidget(RTW_REMOVE);
break;
case RTW_BUS_STATION:
case RTW_TRUCK_STATION:
this->DisableWidget(RTW_ONE_WAY);
this->SetWidgetDisabledState(RTW_REMOVE, !this->IsWidgetLowered(clicked_widget));
break;
case RTW_ROAD_X:
case RTW_ROAD_Y:
case RTW_AUTOROAD:
this->SetWidgetsDisabledState(!this->IsWidgetLowered(clicked_widget),
RTW_REMOVE,
RTW_ONE_WAY,
WIDGET_LIST_END);
break;
default:
/* When any other buttons than road/station, raise and
* disable the removal button */
this->SetWidgetsDisabledState(true,
RTW_REMOVE,
RTW_ONE_WAY,
WIDGET_LIST_END);
this->SetWidgetsLoweredState (false,
RTW_REMOVE,
RTW_ONE_WAY,
WIDGET_LIST_END);
break;
}
}
virtual void OnPaint()
{
this->SetWidgetsDisabledState(!CanBuildVehicleInfrastructure(VEH_ROAD),
RTW_DEPOT,
RTW_BUS_STATION,
RTW_TRUCK_STATION,
WIDGET_LIST_END);
this->DrawWidgets();
}
virtual void OnClick(Point pt, int widget)
{
if (widget >= RTW_ROAD_X) {
_remove_button_clicked = false;
_one_way_button_clicked = false;
_build_road_button_proc[widget - RTW_ROAD_X](this);
}
this->UpdateOptionWidgetStatus((RoadToolbarWidgets)widget);
if (_ctrl_pressed) RoadToolbar_CtrlChanged(this);
}
virtual EventState OnKeyPress(uint16 key, uint16 keycode)
{
EventState state = ES_NOT_HANDLED;
for (uint i = 0; i != lengthof(_road_keycodes); i++) {
if (keycode == _road_keycodes[i]) {
_remove_button_clicked = false;
_one_way_button_clicked = false;
_build_road_button_proc[i](this);
this->UpdateOptionWidgetStatus((RoadToolbarWidgets)(i + RTW_ROAD_X));
if (_ctrl_pressed) RoadToolbar_CtrlChanged(this);
state = ES_HANDLED;
break;
}
}
MarkTileDirty(_thd.pos.x, _thd.pos.y); // redraw tile selection
return state;
}
virtual void OnPlaceObject(Point pt, TileIndex tile)
{
_remove_button_clicked = this->IsWidgetLowered(RTW_REMOVE);
_one_way_button_clicked = this->IsWidgetLowered(RTW_ONE_WAY);
_place_proc(tile);
}
virtual void OnPlaceObjectAbort()
{
this->RaiseButtons();
this->SetWidgetsDisabledState(true,
RTW_REMOVE,
RTW_ONE_WAY,
WIDGET_LIST_END);
this->InvalidateWidget(RTW_REMOVE);
this->InvalidateWidget(RTW_ONE_WAY);
DeleteWindowById(WC_BUS_STATION, 0);
DeleteWindowById(WC_TRUCK_STATION, 0);
DeleteWindowById(WC_BUILD_DEPOT, 0);
DeleteWindowById(WC_SELECT_STATION, 0);
DeleteWindowById(WC_BUILD_BRIDGE, 0);
}
virtual void OnPlaceDrag(ViewportPlaceMethod select_method, ViewportDragDropSelectionProcess select_proc, Point pt)
{
/* Here we update the end tile flags
* of the road placement actions.
* At first we reset the end halfroad
* bits and if needed we set them again. */
switch (select_proc) {
case DDSP_PLACE_ROAD_X_DIR:
_place_road_flag &= ~RF_END_HALFROAD_X;
if (pt.x & 8) _place_road_flag |= RF_END_HALFROAD_X;
break;
case DDSP_PLACE_ROAD_Y_DIR:
_place_road_flag &= ~RF_END_HALFROAD_Y;
if (pt.y & 8) _place_road_flag |= RF_END_HALFROAD_Y;
break;
case DDSP_PLACE_AUTOROAD:
_place_road_flag &= ~(RF_END_HALFROAD_Y | RF_END_HALFROAD_X);
if (pt.y & 8) _place_road_flag |= RF_END_HALFROAD_Y;
if (pt.x & 8) _place_road_flag |= RF_END_HALFROAD_X;
/* For autoroad we need to update the
* direction of the road */
if (_thd.size.x > _thd.size.y || (_thd.size.x == _thd.size.y &&
( (_tile_fract_coords.x < _tile_fract_coords.y && (_tile_fract_coords.x + _tile_fract_coords.y) < 16) ||
(_tile_fract_coords.x > _tile_fract_coords.y && (_tile_fract_coords.x + _tile_fract_coords.y) > 16) ))) {
/* Set dir = X */
_place_road_flag &= ~RF_DIR_Y;
} else {
/* Set dir = Y */
_place_road_flag |= RF_DIR_Y;
}
break;
default:
break;
}
VpSelectTilesWithMethod(pt.x, pt.y, select_method);
}
virtual void OnPlaceMouseUp(ViewportPlaceMethod select_method, ViewportDragDropSelectionProcess select_proc, Point pt, TileIndex start_tile, TileIndex end_tile)
{
if (pt.x != -1) {
switch (select_proc) {
default: NOT_REACHED();
case DDSP_BUILD_BRIDGE:
if (!_settings_client.gui.persistent_buildingtools) ResetObjectToPlace();
ShowBuildBridgeWindow(start_tile, end_tile, TRANSPORT_ROAD, RoadTypeToRoadTypes(_cur_roadtype));
break;
case DDSP_DEMOLISH_AREA:
GUIPlaceProcDragXY(select_proc, start_tile, end_tile);
break;
case DDSP_PLACE_ROAD_X_DIR:
case DDSP_PLACE_ROAD_Y_DIR:
case DDSP_PLACE_AUTOROAD:
/* Flag description:
* Use the first three bits (0x07) if dir == Y
* else use the last 2 bits (X dir has
* not the 3rd bit set) */
_place_road_flag = (RoadFlags)((_place_road_flag & RF_DIR_Y) ? (_place_road_flag & 0x07) : (_place_road_flag >> 3));
DoCommandP(end_tile, start_tile, _place_road_flag | (_cur_roadtype << 3) | (_one_way_button_clicked << 5),
(_ctrl_pressed || _remove_button_clicked) ?
CMD_REMOVE_LONG_ROAD | CMD_MSG(_road_type_infos[_cur_roadtype].err_remove_road) :
CMD_BUILD_LONG_ROAD | CMD_MSG(_road_type_infos[_cur_roadtype].err_build_road), CcPlaySound1D);
break;
}
}
}
virtual void OnPlacePresize(Point pt, TileIndex tile)
{
DoCommand(tile, 0x200 | RoadTypeToRoadTypes(_cur_roadtype), 0, DC_AUTO, CMD_BUILD_TUNNEL);
VpSetPresizeRange(tile, _build_tunnel_endtile == 0 ? tile : _build_tunnel_endtile);
}
virtual EventState OnCTRLStateChange()
{
if (RoadToolbar_CtrlChanged(this)) return ES_HANDLED;
return ES_NOT_HANDLED;
}
};
/** Widget definition of the build road toolbar */
static const Widget _build_road_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // RTW_CLOSEBOX
{ WWT_CAPTION, RESIZE_NONE, COLOUR_DARK_GREEN, 11, 250, 0, 13, STR_1802_ROAD_CONSTRUCTION, STR_018C_WINDOW_TITLE_DRAG_THIS}, // RTW_CAPTION
{ WWT_STICKYBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 251, 262, 0, 13, 0x0, STR_STICKY_BUTTON}, // RTW_STICKY
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 21, 14, 35, SPR_IMG_ROAD_X_DIR, STR_180B_BUILD_ROAD_SECTION}, // RTW_ROAD_X
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 22, 43, 14, 35, SPR_IMG_ROAD_Y_DIR, STR_180B_BUILD_ROAD_SECTION}, // RTW_ROAD_Y
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 44, 65, 14, 35, SPR_IMG_AUTOROAD, STR_BUILD_AUTOROAD_TIP}, // RTW_AUTOROAD
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 66, 87, 14, 35, SPR_IMG_DYNAMITE, STR_018D_DEMOLISH_BUILDINGS_ETC}, // RTW_DEMOLISH
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 88, 109, 14, 35, SPR_IMG_ROAD_DEPOT, STR_180C_BUILD_ROAD_VEHICLE_DEPOT}, // RTW_DEPOT
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 110, 131, 14, 35, SPR_IMG_BUS_STATION, STR_180D_BUILD_BUS_STATION}, // RTW_BUS_STATION
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 132, 153, 14, 35, SPR_IMG_TRUCK_BAY, STR_180E_BUILD_TRUCK_LOADING_BAY}, // RTW_TRUCK_STATION
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 154, 175, 14, 35, SPR_IMG_ROAD_ONE_WAY, STR_TOGGLE_ONE_WAY_ROAD}, // RTW_ONE_WAY
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 176, 218, 14, 35, SPR_IMG_BRIDGE, STR_180F_BUILD_ROAD_BRIDGE}, // RTW_BUILD_BRIDGE
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 219, 240, 14, 35, SPR_IMG_ROAD_TUNNEL, STR_1810_BUILD_ROAD_TUNNEL}, // RTW_BUILD_TUNNEL
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 241, 262, 14, 35, SPR_IMG_REMOVE, STR_1811_TOGGLE_BUILD_REMOVE_FOR}, // RTW_REMOVE
{ WIDGETS_END},
};
static const WindowDesc _build_road_desc(
WDP_ALIGN_TBR, 22, 263, 36, 263, 36,
WC_BUILD_TOOLBAR, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON | WDF_CONSTRUCTION,
_build_road_widgets
);
/** Widget definition of the build tram toolbar */
static const Widget _build_tramway_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // RTW_CLOSEBOX
{ WWT_CAPTION, RESIZE_NONE, COLOUR_DARK_GREEN, 11, 228, 0, 13, STR_WHITE_TRAMWAY_CONSTRUCTION, STR_018C_WINDOW_TITLE_DRAG_THIS}, // RTW_CAPTION
{ WWT_STICKYBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 229, 240, 0, 13, 0x0, STR_STICKY_BUTTON}, // RTW_STICKY
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 21, 14, 35, SPR_IMG_TRAMWAY_X_DIR, STR_BUILD_TRAMWAY_SECTION}, // RTW_ROAD_X
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 22, 43, 14, 35, SPR_IMG_TRAMWAY_Y_DIR, STR_BUILD_TRAMWAY_SECTION}, // RTW_ROAD_Y
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 44, 65, 14, 35, SPR_IMG_AUTOTRAM, STR_BUILD_AUTOTRAM_TIP}, // RTW_AUTOROAD
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 66, 87, 14, 35, SPR_IMG_DYNAMITE, STR_018D_DEMOLISH_BUILDINGS_ETC}, // RTW_DEMOLISH
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 88, 109, 14, 35, SPR_IMG_ROAD_DEPOT, STR_BUILD_TRAM_VEHICLE_DEPOT}, // RTW_DEPOT
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 110, 131, 14, 35, SPR_IMG_BUS_STATION, STR_BUILD_PASSENGER_TRAM_STATION}, // RTW_BUS_STATION
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 132, 153, 14, 35, SPR_IMG_TRUCK_BAY, STR_BUILD_CARGO_TRAM_STATION}, // RTW_TRUCK_STATION
{ WWT_EMPTY, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 0, 0, 0, 0x0, STR_NULL}, // RTW_ONE_WAY
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 154, 196, 14, 35, SPR_IMG_BRIDGE, STR_BUILD_TRAMWAY_BRIDGE}, // RTW_BUILD_BRIDGE
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 197, 218, 14, 35, SPR_IMG_ROAD_TUNNEL, STR_BUILD_TRAMWAY_TUNNEL}, // RTW_BUILD_TUNNEL
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 219, 240, 14, 35, SPR_IMG_REMOVE, STR_TOGGLE_BUILD_REMOVE_FOR_TRAMWAYS}, // RTW_REMOVE
{ WIDGETS_END},
};
static const WindowDesc _build_tramway_desc(
WDP_ALIGN_TBR, 22, 241, 36, 241, 36,
WC_BUILD_TOOLBAR, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON | WDF_CONSTRUCTION,
_build_tramway_widgets
);
void ShowBuildRoadToolbar(RoadType roadtype)
{
if (!IsValidCompanyID(_local_company)) return;
_cur_roadtype = roadtype;
DeleteWindowByClass(WC_BUILD_TOOLBAR);
AllocateWindowDescFront<BuildRoadToolbarWindow>(roadtype == ROADTYPE_ROAD ? &_build_road_desc : &_build_tramway_desc, TRANSPORT_ROAD);
}
/** Widget definition of the build road toolbar in the scenario editor */
static const Widget _build_road_scen_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // RTW_CLOSEBOX
{ WWT_CAPTION, RESIZE_NONE, COLOUR_DARK_GREEN, 11, 184, 0, 13, STR_1802_ROAD_CONSTRUCTION, STR_018C_WINDOW_TITLE_DRAG_THIS}, // RTW_CAPTION
{ WWT_STICKYBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 185, 196, 0, 13, 0x0, STR_STICKY_BUTTON}, // RTW_STICKY
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 21, 14, 35, SPR_IMG_ROAD_X_DIR, STR_180B_BUILD_ROAD_SECTION}, // RTW_ROAD_X
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 22, 43, 14, 35, SPR_IMG_ROAD_Y_DIR, STR_180B_BUILD_ROAD_SECTION}, // RTW_ROAD_Y
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 44, 65, 14, 35, SPR_IMG_AUTOROAD, STR_BUILD_AUTOROAD_TIP}, // RTW_AUTOROAD
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 66, 87, 14, 35, SPR_IMG_DYNAMITE, STR_018D_DEMOLISH_BUILDINGS_ETC}, // RTW_DEMOLISH
{ WWT_EMPTY, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 0, 0, 0, 0x0, STR_NULL}, // RTW_DEPOT
{ WWT_EMPTY, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 0, 0, 0, 0x0, STR_NULL}, // RTW_BUS_STATION
{ WWT_EMPTY, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 0, 0, 0, 0x0, STR_NULL}, // RTW_TRUCK_STATION
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 88, 109, 14, 35, SPR_IMG_ROAD_ONE_WAY, STR_TOGGLE_ONE_WAY_ROAD}, // RTW_ONE_WAY
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 110, 152, 14, 35, SPR_IMG_BRIDGE, STR_180F_BUILD_ROAD_BRIDGE}, // RTW_BUILD_BRIDGE
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 153, 174, 14, 35, SPR_IMG_ROAD_TUNNEL, STR_1810_BUILD_ROAD_TUNNEL}, // RTW_BUILD_TUNNEL
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 175, 196, 14, 35, SPR_IMG_REMOVE, STR_1811_TOGGLE_BUILD_REMOVE_FOR}, // RTW_REMOVE
{ WIDGETS_END},
};
static const WindowDesc _build_road_scen_desc(
WDP_AUTO, WDP_AUTO, 197, 36, 197, 36,
WC_SCEN_BUILD_TOOLBAR, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON | WDF_CONSTRUCTION,
_build_road_scen_widgets
);
void ShowBuildRoadScenToolbar()
{
_cur_roadtype = ROADTYPE_ROAD;
AllocateWindowDescFront<BuildRoadToolbarWindow>(&_build_road_scen_desc, 0);
}
struct BuildRoadDepotWindow : public PickerWindowBase {
private:
/** Enum referring to the widgets of the build road depot window */
enum BuildRoadDepotWidgets {
BRDW_CLOSEBOX = 0,
BRDW_CAPTION,
BRDW_BACKGROUND,
BRDW_DEPOT_NE,
BRDW_DEPOT_SE,
BRDW_DEPOT_SW,
BRDW_DEPOT_NW,
};
public:
BuildRoadDepotWindow(const WindowDesc *desc, Window *parent) : PickerWindowBase(desc, parent)
{
this->LowerWidget(_road_depot_orientation + BRDW_DEPOT_NE);
if ( _cur_roadtype == ROADTYPE_TRAM) {
this->widget[BRDW_CAPTION].data = STR_TRAM_DEPOT_ORIENTATION;
for (int i = BRDW_DEPOT_NE; i <= BRDW_DEPOT_NW; i++) this->widget[i].tooltips = STR_SELECT_TRAM_VEHICLE_DEPOT;
}
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
this->DrawWidgets();
DrawRoadDepotSprite(70, 17, DIAGDIR_NE, _cur_roadtype);
DrawRoadDepotSprite(70, 69, DIAGDIR_SE, _cur_roadtype);
DrawRoadDepotSprite( 2, 69, DIAGDIR_SW, _cur_roadtype);
DrawRoadDepotSprite( 2, 17, DIAGDIR_NW, _cur_roadtype);
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case BRDW_DEPOT_NW:
case BRDW_DEPOT_NE:
case BRDW_DEPOT_SW:
case BRDW_DEPOT_SE:
this->RaiseWidget(_road_depot_orientation + BRDW_DEPOT_NE);
_road_depot_orientation = (DiagDirection)(widget - BRDW_DEPOT_NE);
this->LowerWidget(_road_depot_orientation + BRDW_DEPOT_NE);
SndPlayFx(SND_15_BEEP);
this->SetDirty();
break;
default:
break;
}
}
};
/** Widget definition of the build road depot window */
static const Widget _build_road_depot_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // BRDW_CLOSEBOX
{ WWT_CAPTION, RESIZE_NONE, COLOUR_DARK_GREEN, 11, 139, 0, 13, STR_1806_ROAD_DEPOT_ORIENTATION, STR_018C_WINDOW_TITLE_DRAG_THIS}, // BRDW_CAPTION
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 139, 14, 121, 0x0, STR_NULL}, // BRDW_BACKGROUND
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 71, 136, 17, 66, 0x0, STR_1813_SELECT_ROAD_VEHICLE_DEPOT}, // BRDW_DEPOT_NE
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 71, 136, 69, 118, 0x0, STR_1813_SELECT_ROAD_VEHICLE_DEPOT}, // BRDW_DEPOT_SE
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 3, 68, 69, 118, 0x0, STR_1813_SELECT_ROAD_VEHICLE_DEPOT}, // BRDW_DEPOT_SW
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 3, 68, 17, 66, 0x0, STR_1813_SELECT_ROAD_VEHICLE_DEPOT}, // BRDW_DEPOT_NW
{ WIDGETS_END},
};
static const WindowDesc _build_road_depot_desc(
WDP_AUTO, WDP_AUTO, 140, 122, 140, 122,
WC_BUILD_DEPOT, WC_BUILD_TOOLBAR,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_CONSTRUCTION,
_build_road_depot_widgets
);
static void ShowRoadDepotPicker(Window *parent)
{
new BuildRoadDepotWindow(&_build_road_depot_desc, parent);
}
struct BuildRoadStationWindow : public PickerWindowBase {
private:
/** Enum referring to the widgets of the build road station window */
enum BuildRoadStationWidgets {
BRSW_CLOSEBOX = 0,
BRSW_CAPTION,
BRSW_BACKGROUND,
BRSW_STATION_NE,
BRSW_STATION_SE,
BRSW_STATION_SW,
BRSW_STATION_NW,
BRSW_STATION_X,
BRSW_STATION_Y,
BRSW_LT_OFF,
BRSW_LT_ON,
BRSW_INFO,
};
public:
BuildRoadStationWindow(const WindowDesc *desc, Window *parent, RoadStopType rs) : PickerWindowBase(desc, parent)
{
/* Trams don't have non-drivethrough stations */
if (_cur_roadtype == ROADTYPE_TRAM && _road_station_picker_orientation < DIAGDIR_END) {
_road_station_picker_orientation = DIAGDIR_END;
}
this->SetWidgetsDisabledState(_cur_roadtype == ROADTYPE_TRAM,
BRSW_STATION_NE,
BRSW_STATION_SE,
BRSW_STATION_SW,
BRSW_STATION_NW,
WIDGET_LIST_END);
this->window_class = (rs == ROADSTOP_BUS) ? WC_BUS_STATION : WC_TRUCK_STATION;
this->widget[BRSW_CAPTION].data = _road_type_infos[_cur_roadtype].picker_title[rs];
for (uint i = BRSW_STATION_NE; i < BRSW_LT_OFF; i++) this->widget[i].tooltips = _road_type_infos[_cur_roadtype].picker_tooltip[rs];
this->LowerWidget(_road_station_picker_orientation + BRSW_STATION_NE);
this->LowerWidget(_settings_client.gui.station_show_coverage + BRSW_LT_OFF);
this->FindWindowPlacementAndResize(desc);
}
virtual ~BuildRoadStationWindow()
{
DeleteWindowById(WC_SELECT_STATION, 0);
}
virtual void OnPaint()
{
this->DrawWidgets();
if (_settings_client.gui.station_show_coverage) {
int rad = _settings_game.station.modified_catchment ? CA_TRUCK /* = CA_BUS */ : CA_UNMODIFIED;
SetTileSelectBigSize(-rad, -rad, 2 * rad, 2 * rad);
} else {
SetTileSelectSize(1, 1);
}
StationType st = (this->window_class == WC_BUS_STATION) ? STATION_BUS : STATION_TRUCK;
StationPickerDrawSprite(103, 35, st, INVALID_RAILTYPE, ROADTYPE_ROAD, 0);
StationPickerDrawSprite(103, 85, st, INVALID_RAILTYPE, ROADTYPE_ROAD, 1);
StationPickerDrawSprite( 35, 85, st, INVALID_RAILTYPE, ROADTYPE_ROAD, 2);
StationPickerDrawSprite( 35, 35, st, INVALID_RAILTYPE, ROADTYPE_ROAD, 3);
StationPickerDrawSprite(171, 35, st, INVALID_RAILTYPE, _cur_roadtype, 4);
StationPickerDrawSprite(171, 85, st, INVALID_RAILTYPE, _cur_roadtype, 5);
int text_end = DrawStationCoverageAreaText(2, 146,
(this->window_class == WC_BUS_STATION) ? SCT_PASSENGERS_ONLY : SCT_NON_PASSENGERS_ONLY,
3, false);
text_end = DrawStationCoverageAreaText(2, text_end + 4,
(this->window_class == WC_BUS_STATION) ? SCT_PASSENGERS_ONLY : SCT_NON_PASSENGERS_ONLY,
3, true) + 4;
if (text_end > this->widget[BRSW_BACKGROUND].bottom) {
this->SetDirty();
ResizeWindowForWidget(this, BRSW_BACKGROUND, 0, text_end - this->widget[BRSW_BACKGROUND].bottom);
this->SetDirty();
}
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case BRSW_STATION_NE:
case BRSW_STATION_SE:
case BRSW_STATION_SW:
case BRSW_STATION_NW:
case BRSW_STATION_X:
case BRSW_STATION_Y:
this->RaiseWidget(_road_station_picker_orientation + BRSW_STATION_NE);
_road_station_picker_orientation = (DiagDirection)(widget - BRSW_STATION_NE);
this->LowerWidget(_road_station_picker_orientation + BRSW_STATION_NE);
SndPlayFx(SND_15_BEEP);
this->SetDirty();
DeleteWindowById(WC_SELECT_STATION, 0);
break;
case BRSW_LT_OFF:
case BRSW_LT_ON:
this->RaiseWidget(_settings_client.gui.station_show_coverage + BRSW_LT_OFF);
_settings_client.gui.station_show_coverage = (widget != BRSW_LT_OFF);
this->LowerWidget(_settings_client.gui.station_show_coverage + BRSW_LT_OFF);
SndPlayFx(SND_15_BEEP);
this->SetDirty();
break;
default:
break;
}
}
virtual void OnTick()
{
CheckRedrawStationCoverage(this);
}
};
/** Widget definition of the build raod station window */
static const Widget _rv_station_picker_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // BRSW_CLOSEBOX
{ WWT_CAPTION, RESIZE_NONE, COLOUR_DARK_GREEN, 11, 206, 0, 13, STR_NULL, STR_018C_WINDOW_TITLE_DRAG_THIS}, // BRSW_CAPTION
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 206, 14, 176, 0x0, STR_NULL}, // BRSW_BACKGROUND
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 71, 136, 17, 66, 0x0, STR_NULL}, // BRSW_STATION_NE
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 71, 136, 69, 118, 0x0, STR_NULL}, // BRSW_STATION_SE
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 3, 68, 69, 118, 0x0, STR_NULL}, // BRSW_STATION_SW
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 3, 68, 17, 66, 0x0, STR_NULL}, // BRSW_STATION_NW
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 139, 204, 17, 66, 0x0, STR_NULL}, // BRSW_STATION_X
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 139, 204, 69, 118, 0x0, STR_NULL}, // BRSW_STATION_Y
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 10, 69, 133, 144, STR_02DB_OFF, STR_3065_DON_T_HIGHLIGHT_COVERAGE}, // BRSW_LT_OFF
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 70, 129, 133, 144, STR_02DA_ON, STR_3064_HIGHLIGHT_COVERAGE_AREA}, // BRSW_LT_ON
{ WWT_LABEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 139, 120, 133, STR_3066_COVERAGE_AREA_HIGHLIGHT, STR_NULL}, // BRSW_INFO
{ WIDGETS_END},
};
static const WindowDesc _rv_station_picker_desc(
WDP_AUTO, WDP_AUTO, 207, 177, 207, 177,
WC_BUS_STATION, WC_BUILD_TOOLBAR,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_CONSTRUCTION,
_rv_station_picker_widgets
);
static void ShowRVStationPicker(Window *parent, RoadStopType rs)
{
new BuildRoadStationWindow(&_rv_station_picker_desc, parent, rs);
}
void InitializeRoadGui()
{
_road_depot_orientation = DIAGDIR_NW;
_road_station_picker_orientation = DIAGDIR_NW;
}
| 37,061
|
C++
|
.cpp
| 831
| 42.027677
| 201
| 0.666602
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,153
|
debug.cpp
|
EnergeticBark_OpenTTD-3DS/src/debug.cpp
|
/* $Id$ */
/** @file debug.cpp Handling of printing debug messages. */
#include "stdafx.h"
#include <stdio.h>
#include <stdarg.h>
#include "console_func.h"
#include "debug.h"
#include "string_func.h"
#include "network/core/core.h"
#include "fileio_func.h"
#if defined(ENABLE_NETWORK)
SOCKET _debug_socket = INVALID_SOCKET;
#endif /* ENABLE_NETWORK */
int _debug_ai_level;
int _debug_driver_level;
int _debug_grf_level;
int _debug_map_level;
int _debug_misc_level;
int _debug_ms_level;
int _debug_net_level;
int _debug_sprite_level;
int _debug_oldloader_level;
int _debug_ntp_level;
int _debug_npf_level;
int _debug_yapf_level;
int _debug_freetype_level;
int _debug_sl_level;
int _debug_station_level;
int _debug_gamelog_level;
int _debug_desync_level;
struct DebugLevel {
const char *name;
int *level;
};
#define DEBUG_LEVEL(x) { #x, &_debug_##x##_level }
static const DebugLevel debug_level[] = {
DEBUG_LEVEL(ai),
DEBUG_LEVEL(driver),
DEBUG_LEVEL(grf),
DEBUG_LEVEL(map),
DEBUG_LEVEL(misc),
DEBUG_LEVEL(ms),
DEBUG_LEVEL(net),
DEBUG_LEVEL(sprite),
DEBUG_LEVEL(oldloader),
DEBUG_LEVEL(ntp),
DEBUG_LEVEL(npf),
DEBUG_LEVEL(yapf),
DEBUG_LEVEL(freetype),
DEBUG_LEVEL(sl),
DEBUG_LEVEL(station),
DEBUG_LEVEL(gamelog),
DEBUG_LEVEL(desync),
};
#undef DEBUG_LEVEL
#if !defined(NO_DEBUG_MESSAGES)
static void debug_print(const char *dbg, const char *buf)
{
#if defined(ENABLE_NETWORK)
if (_debug_socket != INVALID_SOCKET) {
char buf2[1024 + 32];
snprintf(buf2, lengthof(buf2), "dbg: [%s] %s\n", dbg, buf);
send(_debug_socket, buf2, (int)strlen(buf2), 0);
} else
#endif /* ENABLE_NETWORK */
if (strcmp(dbg, "desync") != 0) {
#if defined(WINCE)
/* We need to do OTTD2FS twice, but as it uses a static buffer, we need to store one temporary */
TCHAR tbuf[512];
_sntprintf(tbuf, sizeof(tbuf), _T("%s"), OTTD2FS(dbg));
NKDbgPrintfW(_T("dbg: [%s] %s\n"), tbuf, OTTD2FS(buf));
#else
fprintf(stderr, "dbg: [%s] %s\n", dbg, buf);
#endif
IConsoleDebug(dbg, buf);
} else {
static FILE *f = FioFOpenFile("commands-out.log", "wb", AUTOSAVE_DIR);
if (f == NULL) return;
fprintf(f, "%s", buf);
fflush(f);
}
}
void CDECL debug(const char *dbg, ...)
{
va_list va;
va_start(va, dbg);
const char *s;
char buf[1024];
s = va_arg(va, const char*);
vsnprintf(buf, lengthof(buf), s, va);
va_end(va);
debug_print(dbg, buf);
}
#endif /* NO_DEBUG_MESSAGES */
void SetDebugString(const char *s)
{
int v;
char *end;
const char *t;
/* global debugging level? */
if (*s >= '0' && *s <= '9') {
const DebugLevel *i;
v = strtoul(s, &end, 0);
s = end;
for (i = debug_level; i != endof(debug_level); ++i) *i->level = v;
}
/* individual levels */
for (;;) {
const DebugLevel *i;
int *p;
/* skip delimiters */
while (*s == ' ' || *s == ',' || *s == '\t') s++;
if (*s == '\0') break;
t = s;
while (*s >= 'a' && *s <= 'z') s++;
/* check debugging levels */
p = NULL;
for (i = debug_level; i != endof(debug_level); ++i)
if (s == t + strlen(i->name) && strncmp(t, i->name, s - t) == 0) {
p = i->level;
break;
}
if (*s == '=') s++;
v = strtoul(s, &end, 0);
s = end;
if (p != NULL) {
*p = v;
} else {
ShowInfoF("Unknown debug level '%.*s'", s - t, t);
return;
}
}
}
/** Print out the current debug-level
* Just return a string with the values of all the debug categorites
* @return string with debug-levels
*/
const char *GetDebugString()
{
const DebugLevel *i;
static char dbgstr[150];
char dbgval[20];
memset(dbgstr, 0, sizeof(dbgstr));
i = debug_level;
snprintf(dbgstr, sizeof(dbgstr), "%s=%d", i->name, *i->level);
for (i++; i != endof(debug_level); i++) {
snprintf(dbgval, sizeof(dbgval), ", %s=%d", i->name, *i->level);
strecat(dbgstr, dbgval, lastof(dbgstr));
}
return dbgstr;
}
| 3,805
|
C++
|
.cpp
| 151
| 23.039735
| 99
| 0.650124
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,154
|
openttd.cpp
|
EnergeticBark_OpenTTD-3DS/src/openttd.cpp
|
/* $Id$ */
/** @file openttd.cpp Functions related to starting OpenTTD. */
#include "stdafx.h"
#define VARDEF
#include "variables.h"
#undef VARDEF
#include "openttd.h"
#include "blitter/factory.hpp"
#include "sound/sound_driver.hpp"
#include "music/music_driver.hpp"
#include "video/video_driver.hpp"
#include "fontcache.h"
#include "gfxinit.h"
#include "gui.h"
#include "mixer.h"
#include "sound_func.h"
#include "window_func.h"
#include "saveload/saveload.h"
#include "landscape.h"
#include "company_func.h"
#include "command_func.h"
#include "news_func.h"
#include "fileio_func.h"
#include "fios.h"
#include "aircraft.h"
#include "console_func.h"
#include "screenshot.h"
#include "network/network.h"
#include "network/network_func.h"
#include "signs_base.h"
#include "ai/ai.hpp"
#include "ai/ai_config.hpp"
#include "settings_func.h"
#include "genworld.h"
#include "group.h"
#include "strings_func.h"
#include "date_func.h"
#include "vehicle_func.h"
#include "gamelog.h"
#include "cheat_type.h"
#include "animated_tile_func.h"
#include "functions.h"
#include "elrail_func.h"
#include "rev.h"
#include "highscore.h"
#include "newgrf_commons.h"
#include "town.h"
#include "industry.h"
#include <stdarg.h>
#include "table/strings.h"
StringID _switch_mode_errorstr;
void CallLandscapeTick();
void IncreaseDate();
void DoPaletteAnimations();
void MusicLoop();
void ResetMusic();
void ProcessAsyncSaveFinish();
void CallWindowTickEvent();
extern void SetDifficultyLevel(int mode, DifficultySettings *gm_opt);
extern Company *DoStartupNewCompany(bool is_ai);
extern void ShowOSErrorBox(const char *buf, bool system);
extern void InitializeRailGUI();
/**
* Error handling for fatal user errors.
* @param s the string to print.
* @note Does NEVER return.
*/
void CDECL usererror(const char *s, ...)
{
va_list va;
char buf[512];
// 3DS DEBUGGING
#ifdef N3DS
FILE *file = fopen("ottd_fatal_user.txt","w");
fputs(s, file);
fclose(file);
#endif
va_start(va, s);
vsnprintf(buf, lengthof(buf), s, va);
va_end(va);
ShowOSErrorBox(buf, false);
if (_video_driver != NULL) _video_driver->Stop();
exit(1);
}
/**
* Error handling for fatal non-user errors.
* @param s the string to print.
* @note Does NEVER return.
*/
void CDECL error(const char *s, ...)
{
va_list va;
char buf[512];
// 3DS DEBUGGING
#ifdef N3DS
FILE *file = fopen("ottd_fatal.txt","w");
fputs(s, file);
fclose(file);
#endif
va_start(va, s);
vsnprintf(buf, lengthof(buf), s, va);
va_end(va);
ShowOSErrorBox(buf, true);
if (_video_driver != NULL) _video_driver->Stop();
assert(0);
exit(1);
}
/**
* Shows some information on the console/a popup box depending on the OS.
* @param str the text to show.
*/
void CDECL ShowInfoF(const char *str, ...)
{
va_list va;
char buf[1024];
va_start(va, str);
vsnprintf(buf, lengthof(buf), str, va);
va_end(va);
ShowInfo(buf);
}
/**
* Show the help message when someone passed a wrong parameter.
*/
static void ShowHelp()
{
char buf[8192];
char *p = buf;
p += seprintf(p, lastof(buf), "OpenTTD %s\n", _openttd_revision);
p = strecpy(p,
"\n"
"\n"
"Command line options:\n"
" -v drv = Set video driver (see below)\n"
" -s drv = Set sound driver (see below) (param bufsize,hz)\n"
" -m drv = Set music driver (see below)\n"
" -b drv = Set the blitter to use (see below)\n"
" -a ai = Force use of specific AI (see below)\n"
" -r res = Set resolution (for instance 800x600)\n"
" -h = Display this help text\n"
" -t year = Set starting year\n"
" -d [[fac=]lvl[,...]]= Debug mode\n"
" -e = Start Editor\n"
" -g [savegame] = Start new/save game immediately\n"
" -G seed = Set random seed\n"
#if defined(ENABLE_NETWORK)
" -n [ip:port#company]= Start networkgame\n"
" -D [ip][:port] = Start dedicated server\n"
" -l ip[:port] = Redirect DEBUG()\n"
#if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
" -f = Fork into the background (dedicated only)\n"
#endif
#endif /* ENABLE_NETWORK */
" -i palette = Force to use the DOS (0) or Windows (1) palette\n"
" (defines default setting when adding newgrfs)\n"
" Default value (2) lets OpenTTD use the palette\n"
" specified in graphics set file (see below)\n"
" -I graphics_set = Force the graphics set (see below)\n"
" -c config_file = Use 'config_file' instead of 'openttd.cfg'\n"
" -x = Do not automatically save to config file on exit\n"
"\n",
lastof(buf)
);
/* List the graphics packs */
p = GetGraphicsSetsList(p, lastof(buf));
/* List the drivers */
p = VideoDriverFactoryBase::GetDriversInfo(p, lastof(buf));
/* List the blitters */
p = BlitterFactoryBase::GetBlittersInfo(p, lastof(buf));
/* We need to initialize the AI, so it finds the AIs */
AI::Initialize();
p = AI::GetConsoleList(p, lastof(buf));
AI::Uninitialize(true);
/* ShowInfo put output to stderr, but version information should go
* to stdout; this is the only exception */
#if !defined(WIN32) && !defined(WIN64)
printf("%s\n", buf);
#else
ShowInfo(buf);
#endif
}
struct MyGetOptData {
char *opt;
int numleft;
char **argv;
const char *options;
const char *cont;
MyGetOptData(int argc, char **argv, const char *options)
{
opt = NULL;
numleft = argc;
this->argv = argv;
this->options = options;
cont = NULL;
}
};
static int MyGetOpt(MyGetOptData *md)
{
const char *s, *r, *t;
s = md->cont;
if (s != NULL)
goto md_continue_here;
for (;;) {
if (--md->numleft < 0) return -1;
s = *md->argv++;
if (*s == '-') {
md_continue_here:;
s++;
if (*s != 0) {
/* Found argument, try to locate it in options. */
if (*s == ':' || (r = strchr(md->options, *s)) == NULL) {
/* ERROR! */
return -2;
}
if (r[1] == ':') {
/* Item wants an argument. Check if the argument follows, or if it comes as a separate arg. */
if (!*(t = s + 1)) {
/* It comes as a separate arg. Check if out of args? */
if (--md->numleft < 0 || *(t = *md->argv) == '-') {
/* Check if item is optional? */
if (r[2] != ':')
return -2;
md->numleft++;
t = NULL;
} else {
md->argv++;
}
}
md->opt = (char*)t;
md->cont = NULL;
return *s;
}
md->opt = NULL;
md->cont = s;
return *s;
}
} else {
/* This is currently not supported. */
return -2;
}
}
}
/**
* Extract the resolution from the given string and store
* it in the 'res' parameter.
* @param res variable to store the resolution in.
* @param s the string to decompose.
*/
static void ParseResolution(Dimension *res, const char *s)
{
const char *t = strchr(s, 'x');
if (t == NULL) {
ShowInfoF("Invalid resolution '%s'", s);
return;
}
res->width = max(strtoul(s, NULL, 0), 64UL);
res->height = max(strtoul(t + 1, NULL, 0), 64UL);
}
static void InitializeDynamicVariables()
{
/* Dynamic stuff needs to be initialized somewhere... */
_engine_mngr.ResetToDefaultMapping();
_house_mngr.ResetMapping();
_industry_mngr.ResetMapping();
_industile_mngr.ResetMapping();
_Company_pool.AddBlockToPool();
}
/** Unitializes drivers, frees allocated memory, cleans pools, ...
* Generally, prepares the game for shutting down
*/
static void ShutdownGame()
{
/* stop the AI */
AI::Uninitialize(false);
IConsoleFree();
if (_network_available) NetworkShutDown(); // Shut down the network and close any open connections
DriverFactoryBase::ShutdownDrivers();
UnInitWindowSystem();
/* Uninitialize airport state machines */
UnInitializeAirports();
/* Uninitialize variables that are allocated dynamically */
GamelogReset();
_Town_pool.CleanPool();
_Industry_pool.CleanPool();
_Station_pool.CleanPool();
_Vehicle_pool.CleanPool();
_Sign_pool.CleanPool();
_Order_pool.CleanPool();
_Group_pool.CleanPool();
_CargoPacket_pool.CleanPool();
_Engine_pool.CleanPool();
_Company_pool.CleanPool();
free(_config_file);
/* Close all and any open filehandles */
FioCloseAll();
}
static void LoadIntroGame()
{
_game_mode = GM_MENU;
ResetGRFConfig(false);
/* Setup main window */
ResetWindowSystem();
SetupColoursAndInitialWindow();
/* Load the default opening screen savegame */
if (SaveOrLoad("opntitle.dat", SL_LOAD, DATA_DIR) != SL_OK) {
GenerateWorld(GW_EMPTY, 64, 64); // if failed loading, make empty world.
WaitTillGeneratedWorld();
SetLocalCompany(COMPANY_SPECTATOR);
} else {
SetLocalCompany(COMPANY_FIRST);
}
_pause_game = 0;
_cursor.fix_at = false;
CheckForMissingGlyphsInLoadedLanguagePack();
/* Play main theme */
if (_music_driver->IsSongPlaying()) ResetMusic();
}
void MakeNewgameSettingsLive()
{
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
if (_settings_game.ai_config[c] != NULL) {
delete _settings_game.ai_config[c];
}
}
_settings_game = _settings_newgame;
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
_settings_game.ai_config[c] = NULL;
if (_settings_newgame.ai_config[c] != NULL) {
_settings_game.ai_config[c] = new AIConfig(_settings_newgame.ai_config[c]);
}
}
}
byte _savegame_sort_order;
#if defined(UNIX) && !defined(__MORPHOS__)
extern void DedicatedFork();
#endif
int ttd_main(int argc, char *argv[])
{
int i;
const char *optformat;
char *musicdriver = NULL;
char *sounddriver = NULL;
char *videodriver = NULL;
char *blitter = NULL;
char *graphics_set = NULL;
Dimension resolution = {0, 0};
Year startyear = INVALID_YEAR;
uint generation_seed = GENERATE_NEW_SEED;
bool save_config = true;
#if defined(ENABLE_NETWORK)
bool dedicated = false;
bool network = false;
char *network_conn = NULL;
char *debuglog_conn = NULL;
char *dedicated_host = NULL;
uint16 dedicated_port = 0;
#endif /* ENABLE_NETWORK */
_game_mode = GM_MENU;
_switch_mode = SM_MENU;
_switch_mode_errorstr = INVALID_STRING_ID;
_dedicated_forks = false;
_config_file = NULL;
/* The last param of the following function means this:
* a letter means: it accepts that param (e.g.: -h)
* a ':' behind it means: it need a param (e.g.: -m<driver>)
* a '::' behind it means: it can optional have a param (e.g.: -d<debug>) */
optformat = "m:s:v:b:hD::n::ei::I:t:d::r:g::G:c:xl:"
#if !defined(__MORPHOS__) && !defined(__AMIGA__) && !defined(WIN32)
"f"
#endif
;
MyGetOptData mgo(argc - 1, argv + 1, optformat);
while ((i = MyGetOpt(&mgo)) != -1) {
switch (i) {
case 'I': free(graphics_set); graphics_set = strdup(mgo.opt); break;
case 'm': free(musicdriver); musicdriver = strdup(mgo.opt); break;
case 's': free(sounddriver); sounddriver = strdup(mgo.opt); break;
case 'v': free(videodriver); videodriver = strdup(mgo.opt); break;
case 'b': free(blitter); blitter = strdup(mgo.opt); break;
#if defined(ENABLE_NETWORK)
case 'D':
free(musicdriver);
free(sounddriver);
free(videodriver);
free(blitter);
musicdriver = strdup("null");
sounddriver = strdup("null");
videodriver = strdup("dedicated");
blitter = strdup("null");
dedicated = true;
SetDebugString("net=6");
if (mgo.opt != NULL) {
/* Use the existing method for parsing (openttd -n).
* However, we do ignore the #company part. */
const char *temp = NULL;
const char *port = NULL;
ParseConnectionString(&temp, &port, mgo.opt);
if (!StrEmpty(mgo.opt)) dedicated_host = mgo.opt;
if (port != NULL) dedicated_port = atoi(port);
}
break;
case 'f': _dedicated_forks = true; break;
case 'n':
network = true;
network_conn = mgo.opt; // optional IP parameter, NULL if unset
break;
case 'l':
debuglog_conn = mgo.opt;
break;
#endif /* ENABLE_NETWORK */
case 'r': ParseResolution(&resolution, mgo.opt); break;
case 't': startyear = atoi(mgo.opt); break;
case 'd': {
#if defined(WIN32)
CreateConsole();
#endif
if (mgo.opt != NULL) SetDebugString(mgo.opt);
} break;
case 'e': _switch_mode = SM_EDITOR; break;
case 'i':
/* there is an argument, it is not empty, and it is exactly 1 char long */
if (!StrEmpty(mgo.opt) && mgo.opt[1] == '\0') {
_use_palette = (PaletteType)(mgo.opt[0] - '0');
if (_use_palette <= MAX_PAL) break;
}
usererror("Valid value for '-i' is 0, 1 or 2");
case 'g':
if (mgo.opt != NULL) {
strecpy(_file_to_saveload.name, mgo.opt, lastof(_file_to_saveload.name));
_switch_mode = SM_LOAD;
_file_to_saveload.mode = SL_LOAD;
/* if the file doesn't exist or it is not a valid savegame, let the saveload code show an error */
const char *t = strrchr(_file_to_saveload.name, '.');
if (t != NULL) {
FiosType ft = FiosGetSavegameListCallback(SLD_LOAD_GAME, _file_to_saveload.name, t, NULL, NULL);
if (ft != FIOS_TYPE_INVALID) SetFiosType(ft);
}
break;
}
_switch_mode = SM_NEWGAME;
/* Give a random map if no seed has been given */
if (generation_seed == GENERATE_NEW_SEED) {
generation_seed = InteractiveRandom();
}
break;
case 'G': generation_seed = atoi(mgo.opt); break;
case 'c': _config_file = strdup(mgo.opt); break;
case 'x': save_config = false; break;
case -2:
case 'h':
/* The next two functions are needed to list the graphics sets.
* We can't do them earlier because then we can't show it on
* the debug console as that hasn't been configured yet. */
DeterminePaths(argv[0]);
FindGraphicsSets();
ShowHelp();
return 0;
}
}
#if defined(WINCE) && defined(_DEBUG)
/* Switch on debug lvl 4 for WinCE if Debug release, as you can't give params, and you most likely do want this information */
SetDebugString("4");
#endif
DeterminePaths(argv[0]);
FindGraphicsSets();
#if defined(UNIX) && !defined(__MORPHOS__)
/* We must fork here, or we'll end up without some resources we need (like sockets) */
if (_dedicated_forks)
DedicatedFork();
#endif
AI::Initialize();
LoadFromConfig();
AI::Uninitialize(true);
CheckConfig();
LoadFromHighScore();
if (resolution.width != 0) { _cur_resolution = resolution; }
if (startyear != INVALID_YEAR) _settings_newgame.game_creation.starting_year = startyear;
if (generation_seed != GENERATE_NEW_SEED) _settings_newgame.game_creation.generation_seed = generation_seed;
/* The width and height must be at least 1 pixel, this
* way all internal drawing routines work correctly. */
if (_cur_resolution.width <= 0) _cur_resolution.width = 1;
if (_cur_resolution.height <= 0) _cur_resolution.height = 1;
#if defined(ENABLE_NETWORK)
if (dedicated_host) snprintf(_settings_client.network.server_bind_ip, sizeof(_settings_client.network.server_bind_ip), "%s", dedicated_host);
if (dedicated_port) _settings_client.network.server_port = dedicated_port;
if (_dedicated_forks && !dedicated) _dedicated_forks = false;
#endif /* ENABLE_NETWORK */
/* enumerate language files */
InitializeLanguagePacks();
/* initialize screenshot formats */
InitializeScreenshotFormats();
/* initialize airport state machines */
InitializeAirports();
/* initialize all variables that are allocated dynamically */
InitializeDynamicVariables();
/* Sample catalogue */
DEBUG(misc, 1, "Loading sound effects...");
MxInitialize(11025);
SoundInitialize("sample.cat");
/* Initialize FreeType */
InitFreeType();
/* This must be done early, since functions use the InvalidateWindow* calls */
InitWindowSystem();
if (graphics_set == NULL) graphics_set = _ini_graphics_set;
if (!SetGraphicsSet(graphics_set)) {
StrEmpty(graphics_set) ?
usererror("Failed to find a graphics set. Please acquire a graphics set for OpenTTD.") :
usererror("Failed to select requested graphics set '%s'", graphics_set);
}
/* Initialize game palette */
GfxInitPalettes();
DEBUG(misc, 1, "Loading blitter...");
if (blitter == NULL) blitter = _ini_blitter;
if (BlitterFactoryBase::SelectBlitter(blitter) == NULL)
StrEmpty(blitter) ?
usererror("Failed to autoprobe blitter") :
usererror("Failed to select requested blitter '%s'; does it exist?", blitter);
DEBUG(driver, 1, "Loading drivers...");
if (sounddriver == NULL) sounddriver = _ini_sounddriver;
_sound_driver = (SoundDriver*)SoundDriverFactoryBase::SelectDriver(sounddriver, Driver::DT_SOUND);
if (_sound_driver == NULL) {
StrEmpty(sounddriver) ?
usererror("Failed to autoprobe sound driver") :
usererror("Failed to select requested sound driver '%s'", sounddriver);
}
if (musicdriver == NULL) musicdriver = _ini_musicdriver;
_music_driver = (MusicDriver*)MusicDriverFactoryBase::SelectDriver(musicdriver, Driver::DT_MUSIC);
if (_music_driver == NULL) {
StrEmpty(musicdriver) ?
usererror("Failed to autoprobe music driver") :
usererror("Failed to select requested music driver '%s'", musicdriver);
}
if (videodriver == NULL) videodriver = _ini_videodriver;
_video_driver = (VideoDriver*)VideoDriverFactoryBase::SelectDriver(videodriver, Driver::DT_VIDEO);
if (_video_driver == NULL) {
StrEmpty(videodriver) ?
usererror("Failed to autoprobe video driver") :
usererror("Failed to select requested video driver '%s'", videodriver);
}
_savegame_sort_order = SORT_BY_DATE | SORT_DESCENDING;
/* Initialize the zoom level of the screen to normal */
_screen.zoom = ZOOM_LVL_NORMAL;
/* restore saved music volume */
_music_driver->SetVolume(msf.music_vol);
NetworkStartUp(); // initialize network-core
#if defined(ENABLE_NETWORK)
if (debuglog_conn != NULL && _network_available) {
const char *not_used = NULL;
const char *port = NULL;
uint16 rport;
rport = NETWORK_DEFAULT_DEBUGLOG_PORT;
ParseConnectionString(¬_used, &port, debuglog_conn);
if (port != NULL) rport = atoi(port);
NetworkStartDebugLog(NetworkAddress(debuglog_conn, rport));
}
#endif /* ENABLE_NETWORK */
ScanNewGRFFiles();
ResetGRFConfig(false);
/* Make sure _settings is filled with _settings_newgame if we switch to a game directly */
if (_switch_mode != SM_NONE) MakeNewgameSettingsLive();
/* initialize the ingame console */
IConsoleInit();
_cursor.in_window = true;
InitializeGUI();
IConsoleCmdExec("exec scripts/autoexec.scr 0");
GenerateWorld(GW_EMPTY, 64, 64); // Make the viewport initialization happy
WaitTillGeneratedWorld();
CheckForMissingGlyphsInLoadedLanguagePack();
#ifdef ENABLE_NETWORK
if (network && _network_available) {
if (network_conn != NULL) {
const char *port = NULL;
const char *company = NULL;
uint16 rport;
rport = NETWORK_DEFAULT_PORT;
_network_playas = COMPANY_NEW_COMPANY;
ParseConnectionString(&company, &port, network_conn);
if (company != NULL) {
_network_playas = (CompanyID)atoi(company);
if (_network_playas != COMPANY_SPECTATOR) {
_network_playas--;
if (_network_playas >= MAX_COMPANIES) return false;
}
}
if (port != NULL) rport = atoi(port);
LoadIntroGame();
_switch_mode = SM_NONE;
NetworkClientConnectGame(NetworkAddress(network_conn, rport));
}
}
#endif /* ENABLE_NETWORK */
_video_driver->MainLoop();
WaitTillSaved();
/* only save config if we have to */
if (save_config) {
SaveToConfig();
SaveToHighScore();
}
/* Reset windowing system, stop drivers, free used memory, ... */
ShutdownGame();
return 0;
}
void HandleExitGameRequest()
{
if (_game_mode == GM_MENU) { // do not ask to quit on the main screen
_exit_game = true;
} else if (_settings_client.gui.autosave_on_exit) {
DoExitSave();
_exit_game = true;
} else {
AskExitGame();
}
}
static void ShowScreenshotResult(bool b)
{
if (b) {
extern char _screenshot_name[];
SetDParamStr(0, _screenshot_name);
ShowErrorMessage(INVALID_STRING_ID, STR_031B_SCREENSHOT_SUCCESSFULLY, 0, 0);
} else {
ShowErrorMessage(INVALID_STRING_ID, STR_031C_SCREENSHOT_FAILED, 0, 0);
}
}
static void MakeNewGameDone()
{
SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
/* In a dedicated server, the server does not play */
if (BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth() == 0) {
SetLocalCompany(COMPANY_SPECTATOR);
IConsoleCmdExec("exec scripts/game_start.scr 0");
return;
}
/* Create a single company */
DoStartupNewCompany(false);
IConsoleCmdExec("exec scripts/game_start.scr 0");
SetLocalCompany(COMPANY_FIRST);
_current_company = _local_company;
DoCommandP(0, (_settings_client.gui.autorenew << 15 ) | (_settings_client.gui.autorenew_months << 16) | 4, _settings_client.gui.autorenew_money, CMD_SET_AUTOREPLACE);
InitializeRailGUI();
#ifdef ENABLE_NETWORK
/* We are the server, we start a new company (not dedicated),
* so set the default password *if* needed. */
if (_network_server && !StrEmpty(_settings_client.network.default_company_pass)) {
char *password = _settings_client.network.default_company_pass;
NetworkChangeCompanyPassword(1, &password);
}
#endif /* ENABLE_NETWORK */
MarkWholeScreenDirty();
}
static void MakeNewGame(bool from_heightmap)
{
_game_mode = GM_NORMAL;
ResetGRFConfig(true);
_engine_mngr.ResetToDefaultMapping();
_house_mngr.ResetMapping();
_industile_mngr.ResetMapping();
_industry_mngr.ResetMapping();
GenerateWorldSetCallback(&MakeNewGameDone);
GenerateWorld(from_heightmap ? GW_HEIGHTMAP : GW_NEWGAME, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
}
static void MakeNewEditorWorldDone()
{
SetLocalCompany(OWNER_NONE);
}
static void MakeNewEditorWorld()
{
_game_mode = GM_EDITOR;
ResetGRFConfig(true);
GenerateWorldSetCallback(&MakeNewEditorWorldDone);
GenerateWorld(GW_EMPTY, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
}
void StartupCompanies();
void StartupDisasters();
extern void StartupEconomy();
/**
* Start Scenario starts a new game based on a scenario.
* Eg 'New Game' --> select a preset scenario
* This starts a scenario based on your current difficulty settings
*/
static void StartScenario()
{
_game_mode = GM_NORMAL;
/* invalid type */
if (_file_to_saveload.mode == SL_INVALID) {
DEBUG(sl, 0, "Savegame is obsolete or invalid format: '%s'", _file_to_saveload.name);
SetDParamStr(0, GetSaveLoadErrorString());
ShowErrorMessage(INVALID_STRING_ID, STR_JUST_RAW_STRING, 0, 0);
_game_mode = GM_MENU;
return;
}
/* Reinitialize windows */
ResetWindowSystem();
SetupColoursAndInitialWindow();
ResetGRFConfig(true);
/* Load game */
if (SaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode, SCENARIO_DIR) != SL_OK) {
LoadIntroGame();
SetDParamStr(0, GetSaveLoadErrorString());
ShowErrorMessage(INVALID_STRING_ID, STR_JUST_RAW_STRING, 0, 0);
}
_settings_game.difficulty = _settings_newgame.difficulty;
/* Inititalize data */
StartupEconomy();
StartupCompanies();
StartupEngines();
StartupDisasters();
SetLocalCompany(COMPANY_FIRST);
_current_company = _local_company;
DoCommandP(0, (_settings_client.gui.autorenew << 15 ) | (_settings_client.gui.autorenew_months << 16) | 4, _settings_client.gui.autorenew_money, CMD_SET_AUTOREPLACE);
MarkWholeScreenDirty();
}
/** Load the specified savegame but on error do different things.
* If loading fails due to corrupt savegame, bad version, etc. go back to
* a previous correct state. In the menu for example load the intro game again.
* @param filename file to be loaded
* @param mode mode of loading, either SL_LOAD or SL_OLD_LOAD
* @param newgm switch to this mode of loading fails due to some unknown error
* @param subdir default directory to look for filename, set to 0 if not needed
*/
bool SafeSaveOrLoad(const char *filename, int mode, GameMode newgm, Subdirectory subdir)
{
GameMode ogm = _game_mode;
_game_mode = newgm;
assert(mode == SL_LOAD || mode == SL_OLD_LOAD);
switch (SaveOrLoad(filename, mode, subdir)) {
case SL_OK: return true;
case SL_REINIT:
switch (ogm) {
default:
case GM_MENU: LoadIntroGame(); break;
case GM_EDITOR: MakeNewEditorWorld(); break;
}
return false;
default:
_game_mode = ogm;
return false;
}
}
void SwitchToMode(SwitchMode new_mode)
{
#ifdef ENABLE_NETWORK
/* If we are saving something, the network stays in his current state */
if (new_mode != SM_SAVE) {
/* If the network is active, make it not-active */
if (_networking) {
if (_network_server && (new_mode == SM_LOAD || new_mode == SM_NEWGAME)) {
NetworkReboot();
} else {
NetworkDisconnect();
}
}
/* If we are a server, we restart the server */
if (_is_network_server) {
/* But not if we are going to the menu */
if (new_mode != SM_MENU) {
/* check if we should reload the config */
if (_settings_client.network.reload_cfg) {
LoadFromConfig();
MakeNewgameSettingsLive();
ResetGRFConfig(false);
}
NetworkServerStart();
} else {
/* This client no longer wants to be a network-server */
_is_network_server = false;
}
}
}
#endif /* ENABLE_NETWORK */
/* Make sure all AI controllers are gone at quiting game */
if (new_mode != SM_SAVE) AI::KillAll();
switch (new_mode) {
case SM_EDITOR: // Switch to scenario editor
MakeNewEditorWorld();
break;
case SM_NEWGAME: // New Game --> 'Random game'
#ifdef ENABLE_NETWORK
if (_network_server) {
snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "Random Map");
}
#endif /* ENABLE_NETWORK */
MakeNewGame(false);
break;
case SM_START_SCENARIO: // New Game --> Choose one of the preset scenarios
#ifdef ENABLE_NETWORK
if (_network_server) {
snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Loaded scenario)", _file_to_saveload.title);
}
#endif /* ENABLE_NETWORK */
StartScenario();
break;
case SM_LOAD: { // Load game, Play Scenario
ResetGRFConfig(true);
ResetWindowSystem();
if (!SafeSaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_NORMAL, NO_DIRECTORY)) {
LoadIntroGame();
SetDParamStr(0, GetSaveLoadErrorString());
ShowErrorMessage(INVALID_STRING_ID, STR_JUST_RAW_STRING, 0, 0);
} else {
if (_saveload_mode == SLD_LOAD_SCENARIO) {
StartupEngines();
}
/* Update the local company for a loaded game. It is either always
* company #1 (eg 0) or in the case of a dedicated server a spectator */
SetLocalCompany(_network_dedicated ? COMPANY_SPECTATOR : COMPANY_FIRST);
/* Execute the game-start script */
IConsoleCmdExec("exec scripts/game_start.scr 0");
/* Decrease pause counter (was increased from opening load dialog) */
DoCommandP(0, 0, 0, CMD_PAUSE);
#ifdef ENABLE_NETWORK
if (_network_server) {
snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Loaded game)", _file_to_saveload.title);
}
#endif /* ENABLE_NETWORK */
}
break;
}
case SM_START_HEIGHTMAP: // Load a heightmap and start a new game from it
#ifdef ENABLE_NETWORK
if (_network_server) {
snprintf(_network_game_info.map_name, lengthof(_network_game_info.map_name), "%s (Heightmap)", _file_to_saveload.title);
}
#endif /* ENABLE_NETWORK */
MakeNewGame(true);
break;
case SM_LOAD_HEIGHTMAP: // Load heightmap from scenario editor
SetLocalCompany(OWNER_NONE);
GenerateWorld(GW_HEIGHTMAP, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
MarkWholeScreenDirty();
break;
case SM_LOAD_SCENARIO: { // Load scenario from scenario editor
if (SafeSaveOrLoad(_file_to_saveload.name, _file_to_saveload.mode, GM_EDITOR, NO_DIRECTORY)) {
SetLocalCompany(OWNER_NONE);
_settings_newgame.game_creation.starting_year = _cur_year;
} else {
SetDParamStr(0, GetSaveLoadErrorString());
ShowErrorMessage(INVALID_STRING_ID, STR_JUST_RAW_STRING, 0, 0);
}
break;
}
case SM_MENU: // Switch to game intro menu
LoadIntroGame();
break;
case SM_SAVE: // Save game
/* Make network saved games on pause compatible to singleplayer */
if (_networking && _pause_game == 1) _pause_game = 2;
if (SaveOrLoad(_file_to_saveload.name, SL_SAVE, NO_DIRECTORY) != SL_OK) {
SetDParamStr(0, GetSaveLoadErrorString());
ShowErrorMessage(INVALID_STRING_ID, STR_JUST_RAW_STRING, 0, 0);
} else {
DeleteWindowById(WC_SAVELOAD, 0);
}
if (_networking && _pause_game == 2) _pause_game = 1;
break;
case SM_GENRANDLAND: // Generate random land within scenario editor
SetLocalCompany(OWNER_NONE);
GenerateWorld(GW_RANDOM, 1 << _settings_game.game_creation.map_x, 1 << _settings_game.game_creation.map_y);
/* XXX: set date */
MarkWholeScreenDirty();
break;
default: NOT_REACHED();
}
if (_switch_mode_errorstr != INVALID_STRING_ID) {
ShowErrorMessage(INVALID_STRING_ID, _switch_mode_errorstr, 0, 0);
}
}
/**
* State controlling game loop.
* The state must not be changed from anywhere but here.
* That check is enforced in DoCommand.
*/
void StateGameLoop()
{
/* dont execute the state loop during pause */
if (_pause_game) {
CallWindowTickEvent();
return;
}
if (IsGeneratingWorld()) return;
ClearStorageChanges(false);
if (_game_mode == GM_EDITOR) {
RunTileLoop();
CallVehicleTicks();
CallLandscapeTick();
ClearStorageChanges(true);
CallWindowTickEvent();
NewsLoop();
} else {
if (_debug_desync_level > 1) {
Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v != v->First()) continue;
switch (v->type) {
case VEH_ROAD: {
extern byte GetRoadVehLength(const Vehicle *v);
if (GetRoadVehLength(v) != v->u.road.cached_veh_length) {
DEBUG(desync, 2, "cache mismatch: vehicle %i, company %i, unit number %i\n", v->index, (int)v->owner, v->unitnumber);
}
} break;
case VEH_TRAIN: {
uint length = 0;
for (Vehicle *u = v; u != NULL; u = u->Next()) length++;
VehicleRail *wagons = MallocT<VehicleRail>(length);
length = 0;
for (Vehicle *u = v; u != NULL; u = u->Next()) wagons[length++] = u->u.rail;
TrainConsistChanged(v, true);
length = 0;
for (Vehicle *u = v; u != NULL; u = u->Next()) {
if (memcmp(&wagons[length], &u->u.rail, sizeof(VehicleRail)) != 0) {
DEBUG(desync, 2, "cache mismatch: vehicle %i, company %i, unit number %i, wagon %i\n", v->index, (int)v->owner, v->unitnumber, length);
}
length++;
}
free(wagons);
} break;
case VEH_AIRCRAFT: {
uint speed = v->u.air.cached_max_speed;
UpdateAircraftCache(v);
if (speed != v->u.air.cached_max_speed) {
DEBUG(desync, 2, "cache mismatch: vehicle %i, company %i, unit number %i\n", v->index, (int)v->owner, v->unitnumber);
}
} break;
default:
break;
}
}
}
/* All these actions has to be done from OWNER_NONE
* for multiplayer compatibility */
CompanyID old_company = _current_company;
_current_company = OWNER_NONE;
AnimateAnimatedTiles();
IncreaseDate();
RunTileLoop();
CallVehicleTicks();
CallLandscapeTick();
ClearStorageChanges(true);
AI::GameLoop();
CallWindowTickEvent();
NewsLoop();
_current_company = old_company;
}
}
/** Create an autosave. The default name is "autosave#.sav". However with
* the setting 'keep_all_autosave' the name defaults to company-name + date */
static void DoAutosave()
{
char buf[MAX_PATH];
#if defined(PSP)
/* Autosaving in networking is too time expensive for the PSP */
if (_networking) return;
#endif /* PSP */
if (_settings_client.gui.keep_all_autosave) {
GenerateDefaultSaveName(buf, lastof(buf));
strecat(buf, ".sav", lastof(buf));
} else {
/* generate a savegame name and number according to _settings_client.gui.max_num_autosaves */
snprintf(buf, sizeof(buf), "autosave%d.sav", _autosave_ctr);
if (++_autosave_ctr >= _settings_client.gui.max_num_autosaves) _autosave_ctr = 0;
}
DEBUG(sl, 2, "Autosaving to '%s'", buf);
if (SaveOrLoad(buf, SL_SAVE, AUTOSAVE_DIR) != SL_OK) {
ShowErrorMessage(INVALID_STRING_ID, STR_AUTOSAVE_FAILED, 0, 0);
}
}
void GameLoop()
{
ProcessAsyncSaveFinish();
/* autosave game? */
if (_do_autosave) {
_do_autosave = false;
DoAutosave();
RedrawAutosave();
}
/* make a screenshot? */
if (IsScreenshotRequested()) ShowScreenshotResult(MakeScreenshot());
/* switch game mode? */
if (_switch_mode != SM_NONE) {
SwitchToMode(_switch_mode);
_switch_mode = SM_NONE;
}
IncreaseSpriteLRU();
InteractiveRandom();
extern int _caret_timer;
_caret_timer += 3;
_palette_animation_counter += 8;
CursorTick();
#ifdef ENABLE_NETWORK
/* Check for UDP stuff */
if (_network_available) NetworkUDPGameLoop();
if (_networking && !IsGeneratingWorld()) {
/* Multiplayer */
NetworkGameLoop();
} else {
if (_network_reconnect > 0 && --_network_reconnect == 0) {
/* This means that we want to reconnect to the last host
* We do this here, because it means that the network is really closed */
_network_playas = COMPANY_SPECTATOR;
NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port));
}
/* Singleplayer */
StateGameLoop();
}
#else
StateGameLoop();
#endif /* ENABLE_NETWORK */
if (!_pause_game && HasBit(_display_opt, DO_FULL_ANIMATION)) DoPaletteAnimations();
if (!_pause_game || _cheats.build_in_pause.value) MoveAllTextEffects();
InputLoop();
_sound_driver->MainLoop();
MusicLoop();
}
| 33,434
|
C++
|
.cpp
| 1,011
| 30.14639
| 167
| 0.688834
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,156
|
transparency_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/transparency_gui.cpp
|
/* $Id$ */
/** @file transparency_gui.cpp The transparency GUI. */
#include "stdafx.h"
#include "openttd.h"
#include "window_gui.h"
#include "transparency.h"
#include "sound_func.h"
#include "table/sprites.h"
#include "table/strings.h"
TransparencyOptionBits _transparency_opt;
TransparencyOptionBits _transparency_lock;
TransparencyOptionBits _invisibility_opt;
class TransparenciesWindow : public Window
{
enum TransparencyToolbarWidgets{
TTW_WIDGET_SIGNS = 3, ///< Make signs background transparent
TTW_WIDGET_TREES, ///< Make trees transparent
TTW_WIDGET_HOUSES, ///< Make houses transparent
TTW_WIDGET_INDUSTRIES, ///< Make Industries transparent
TTW_WIDGET_BUILDINGS, ///< Make company buildings and structures transparent
TTW_WIDGET_BRIDGES, ///< Make bridges transparent
TTW_WIDGET_STRUCTURES, ///< Make unmovable structures transparent
TTW_WIDGET_CATENARY, ///< Make catenary transparent
TTW_WIDGET_LOADING, ///< Make loading indicators transparent
TTW_WIDGET_END, ///< End of toggle buttons
/* Panel with buttons for invisibility */
TTW_BUTTONS = 12, ///< Panel with 'invisibility' buttons
};
public:
TransparenciesWindow(const WindowDesc *desc, int window_number) : Window(desc, window_number)
{
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
/* must be sure that the widgets show the transparency variable changes
* also when we use shortcuts */
for (uint i = TTW_WIDGET_SIGNS; i < TTW_WIDGET_END; i++) {
this->SetWidgetLoweredState(i, IsTransparencySet((TransparencyOption)(i - TTW_WIDGET_SIGNS)));
}
this->DrawWidgets();
for (uint i = TO_SIGNS; i < TO_END; i++) {
if (HasBit(_transparency_lock, i)) DrawSprite(SPR_LOCK, PAL_NONE, this->widget[TTW_WIDGET_SIGNS + i].left + 1, this->widget[TTW_WIDGET_SIGNS + i].top + 1);
}
/* Do not draw button for invisible loading indicators */
for (uint i = TTW_WIDGET_SIGNS; i <= TTW_WIDGET_CATENARY; i++) {
const Widget *wi = &this->widget[i];
DrawFrameRect(wi->left + 1, 38, wi->right - 1, 46, COLOUR_PALE_GREEN, HasBit(_invisibility_opt, i - TTW_WIDGET_SIGNS) ? FR_LOWERED : FR_NONE);
}
}
virtual void OnClick(Point pt, int widget)
{
if (widget >= TTW_WIDGET_SIGNS && widget < TTW_WIDGET_END) {
if (_ctrl_pressed) {
/* toggle the bit of the transparencies lock variable */
ToggleTransparencyLock((TransparencyOption)(widget - TTW_WIDGET_SIGNS));
this->SetDirty();
} else {
/* toggle the bit of the transparencies variable and play a sound */
ToggleTransparency((TransparencyOption)(widget - TTW_WIDGET_SIGNS));
SndPlayFx(SND_15_BEEP);
MarkWholeScreenDirty();
}
} else if (widget == TTW_BUTTONS) {
uint x = pt.x / 22;
if (x > TTW_WIDGET_BRIDGES - TTW_WIDGET_SIGNS) x--;
if (x > TTW_WIDGET_CATENARY - TTW_WIDGET_SIGNS) return;
ToggleInvisibility((TransparencyOption)x);
SndPlayFx(SND_15_BEEP);
/* Redraw whole screen only if transparency is set */
if (IsTransparencySet((TransparencyOption)x)) {
MarkWholeScreenDirty();
} else {
this->InvalidateWidget(TTW_BUTTONS);
}
}
}
};
static const Widget _transparency_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_DARK_GREEN, 11, 206, 0, 13, STR_TRANSPARENCY_TOOLB, STR_018C_WINDOW_TITLE_DRAG_THIS},
{WWT_STICKYBOX, RESIZE_NONE, COLOUR_DARK_GREEN, 207, 218, 0, 13, STR_NULL, STR_STICKY_BUTTON},
/* transparency widgets:
* transparent signs, trees, houses, industries, company's buildings, bridges, unmovable structures, catenary and loading indicators */
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 21, 14, 35, SPR_IMG_SIGN, STR_TRANSPARENT_SIGNS_DESC},
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 22, 43, 14, 35, SPR_IMG_PLANTTREES, STR_TRANSPARENT_TREES_DESC},
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 44, 65, 14, 35, SPR_IMG_TOWN, STR_TRANSPARENT_HOUSES_DESC},
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 66, 87, 14, 35, SPR_IMG_INDUSTRY, STR_TRANSPARENT_INDUSTRIES_DESC},
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 88, 109, 14, 35, SPR_IMG_COMPANY_LIST, STR_TRANSPARENT_BUILDINGS_DESC},
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 110, 152, 14, 35, SPR_IMG_BRIDGE, STR_TRANSPARENT_BRIDGES_DESC},
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 153, 174, 14, 35, SPR_IMG_TRANSMITTER, STR_TRANSPARENT_STRUCTURES_DESC},
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 175, 196, 14, 35, SPR_BUILD_X_ELRAIL, STR_TRANSPARENT_CATENARY_DESC},
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_DARK_GREEN, 197, 218, 14, 35, SPR_IMG_TRAINLIST, STR_TRANSPARENT_LOADING_DESC},
{ WWT_PANEL, RESIZE_NONE, COLOUR_DARK_GREEN, 0, 218, 36, 48, 0x0, STR_TRANSPARENT_INVISIBLE_DESC},
{ WIDGETS_END},
};
static const WindowDesc _transparency_desc(
WDP_ALIGN_TBR, 94, 219, 49, 219, 49,
WC_TRANSPARENCY_TOOLBAR, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON,
_transparency_widgets
);
void ShowTransparencyToolbar(void)
{
AllocateWindowDescFront<TransparenciesWindow>(&_transparency_desc, 0);
}
| 5,339
|
C++
|
.cpp
| 106
| 47.726415
| 158
| 0.695569
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,157
|
genworld.cpp
|
EnergeticBark_OpenTTD-3DS/src/genworld.cpp
|
/* $Id$ */
/** @file genworld.cpp Functions to generate a map. */
#include "stdafx.h"
#include "openttd.h"
#include "landscape.h"
#include "company_func.h"
#include "variables.h"
#include "thread.h"
#include "command_func.h"
#include "genworld.h"
#include "gfxinit.h"
#include "window_func.h"
#include "network/network.h"
#include "heightmap.h"
#include "viewport_func.h"
#include "gfx_func.h"
#include "date_func.h"
#include "core/random_func.hpp"
#include "engine_func.h"
#include "newgrf_storage.h"
#include "water.h"
#include "blitter/factory.hpp"
#include "tilehighlight_func.h"
#include "saveload/saveload.h"
#include "void_map.h"
#include "settings_type.h"
#include "town.h"
#include "table/sprites.h"
void GenerateClearTile();
void GenerateIndustries();
void GenerateUnmovables();
void GenerateTrees();
void StartupEconomy();
void StartupCompanies();
void StartupDisasters();
void InitializeGame(uint size_x, uint size_y, bool reset_date);
/* Please only use this variable in genworld.h and genworld.c and
* nowhere else. For speed improvements we need it to be global, but
* in no way the meaning of it is to use it anywhere else besides
* in the genworld.h and genworld.c! -- TrueLight */
gw_info _gw;
/**
* Set the status of the Paint flag.
* If it is true, the thread will hold with any futher generating till
* the drawing of the screen is done. This is handled by
* SetGeneratingWorldProgress(), so calling that function will stall
* from time to time.
*/
void SetGeneratingWorldPaintStatus(bool status)
{
_gw.wait_for_draw = status;
}
/**
* Returns true if the thread wants the main program to do a (full) paint.
* If this returns false, please do not update the screen. Because we are
* writing in a thread, it can cause damaged data (reading and writing the
* same tile at the same time).
*/
bool IsGeneratingWorldReadyForPaint()
{
/* If we are in quit_thread mode, ignore this and always return false. This
* forces the screen to not be drawn, and the GUI not to wait for a draw. */
if (!_gw.active || _gw.quit_thread || !_gw.threaded) return false;
return _gw.wait_for_draw;
}
/**
* Tells if the world generation is done in a thread or not.
*/
bool IsGenerateWorldThreaded()
{
return _gw.threaded && !_gw.quit_thread;
}
/**
* Clean up the 'mess' of generation. That is show windows again, reset
* thread variables and delete the progress window.
*/
static void CleanupGeneration()
{
_generating_world = false;
if (_cursor.sprite == SPR_CURSOR_ZZZ) SetMouseCursor(SPR_CURSOR_MOUSE, PAL_NONE);
/* Show all vital windows again, because we have hidden them */
if (_gw.threaded && _game_mode != GM_MENU) ShowVitalWindows();
_gw.active = false;
_gw.proc = NULL;
_gw.abortp = NULL;
_gw.threaded = false;
DeleteWindowById(WC_GENERATE_PROGRESS_WINDOW, 0);
MarkWholeScreenDirty();
}
/**
* The internal, real, generate function.
*/
static void _GenerateWorld(void *arg)
{
try {
_generating_world = true;
if (_network_dedicated) DEBUG(net, 0, "Generating map, please wait...");
/* Set the Random() seed to generation_seed so we produce the same map with the same seed */
if (_settings_game.game_creation.generation_seed == GENERATE_NEW_SEED) _settings_game.game_creation.generation_seed = _settings_newgame.game_creation.generation_seed = InteractiveRandom();
_random.SetSeed(_settings_game.game_creation.generation_seed);
SetGeneratingWorldProgress(GWP_MAP_INIT, 2);
SetObjectToPlace(SPR_CURSOR_ZZZ, PAL_NONE, VHM_NONE, WC_MAIN_WINDOW, 0);
IncreaseGeneratingWorldProgress(GWP_MAP_INIT);
/* Must start economy early because of the costs. */
StartupEconomy();
/* Don't generate landscape items when in the scenario editor. */
if (_gw.mode == GW_EMPTY) {
SetGeneratingWorldProgress(GWP_UNMOVABLE, 1);
/* Make sure the tiles at the north border are void tiles if needed. */
if (_settings_game.construction.freeform_edges) {
for (uint row = 0; row < MapSizeY(); row++) MakeVoid(TileXY(0, row));
for (uint col = 0; col < MapSizeX(); col++) MakeVoid(TileXY(col, 0));
}
/* Make the map the height of the setting */
if (_game_mode != GM_MENU) FlatEmptyWorld(_settings_game.game_creation.se_flat_world_height);
ConvertGroundTilesIntoWaterTiles();
IncreaseGeneratingWorldProgress(GWP_UNMOVABLE);
} else {
GenerateLandscape(_gw.mode);
GenerateClearTile();
/* only generate towns, tree and industries in newgame mode. */
if (_game_mode != GM_EDITOR) {
if (!GenerateTowns(_settings_game.economy.town_layout)) {
HandleGeneratingWorldAbortion();
return;
}
GenerateIndustries();
GenerateUnmovables();
GenerateTrees();
}
}
ClearStorageChanges(true);
/* These are probably pointless when inside the scenario editor. */
SetGeneratingWorldProgress(GWP_GAME_INIT, 3);
StartupCompanies();
IncreaseGeneratingWorldProgress(GWP_GAME_INIT);
StartupEngines();
IncreaseGeneratingWorldProgress(GWP_GAME_INIT);
StartupDisasters();
_generating_world = false;
/* No need to run the tile loop in the scenario editor. */
if (_gw.mode != GW_EMPTY) {
uint i;
SetGeneratingWorldProgress(GWP_RUNTILELOOP, 0x500);
for (i = 0; i < 0x500; i++) {
RunTileLoop();
IncreaseGeneratingWorldProgress(GWP_RUNTILELOOP);
}
}
ResetObjectToPlace();
_local_company = _gw.lc;
SetGeneratingWorldProgress(GWP_GAME_START, 1);
/* Call any callback */
if (_gw.proc != NULL) _gw.proc();
IncreaseGeneratingWorldProgress(GWP_GAME_START);
CleanupGeneration();
if (_network_dedicated) DEBUG(net, 0, "Map generated, starting game");
DEBUG(desync, 1, "new_map: %i\n", _settings_game.game_creation.generation_seed);
if (_settings_client.gui.pause_on_newgame && _game_mode == GM_NORMAL) DoCommandP(0, 1, 0, CMD_PAUSE);
if (_debug_desync_level > 0) {
char name[MAX_PATH];
snprintf(name, lengthof(name), "dmp_cmds_%08x_%08x.sav", _settings_game.game_creation.generation_seed, _date);
SaveOrLoad(name, SL_SAVE, AUTOSAVE_DIR);
}
} catch (...) {
_generating_world = false;
throw;
}
}
/**
* Set here the function, if any, that you want to be called when landscape
* generation is done.
*/
void GenerateWorldSetCallback(gw_done_proc *proc)
{
_gw.proc = proc;
}
/**
* Set here the function, if any, that you want to be called when landscape
* generation is aborted.
*/
void GenerateWorldSetAbortCallback(gw_abort_proc *proc)
{
_gw.abortp = proc;
}
/**
* This will wait for the thread to finish up his work. It will not continue
* till the work is done.
*/
void WaitTillGeneratedWorld()
{
if (_gw.thread == NULL) return;
_gw.quit_thread = true;
_gw.thread->Join();
delete _gw.thread;
_gw.thread = NULL;
_gw.threaded = false;
}
/**
* Initializes the abortion process
*/
void AbortGeneratingWorld()
{
_gw.abort = true;
}
/**
* Is the generation being aborted?
*/
bool IsGeneratingWorldAborted()
{
return _gw.abort;
}
/**
* Really handle the abortion, i.e. clean up some of the mess
*/
void HandleGeneratingWorldAbortion()
{
/* Clean up - in SE create an empty map, otherwise, go to intro menu */
_switch_mode = (_game_mode == GM_EDITOR) ? SM_EDITOR : SM_MENU;
if (_gw.abortp != NULL) _gw.abortp();
CleanupGeneration();
if (_gw.thread != NULL) _gw.thread->Exit();
extern void SwitchToMode(SwitchMode new_mode);
SwitchToMode(_switch_mode);
}
/**
* Generate a world.
* @param mode The mode of world generation (see GenerateWorldModes).
* @param size_x The X-size of the map.
* @param size_y The Y-size of the map.
*/
void GenerateWorld(GenerateWorldMode mode, uint size_x, uint size_y)
{
if (_gw.active) return;
_gw.mode = mode;
_gw.size_x = size_x;
_gw.size_y = size_y;
_gw.active = true;
_gw.abort = false;
_gw.abortp = NULL;
_gw.lc = _local_company;
_gw.wait_for_draw = false;
_gw.quit_thread = false;
_gw.threaded = true;
/* This disables some commands and stuff */
SetLocalCompany(COMPANY_SPECTATOR);
/* Make sure everything is done via OWNER_NONE */
_current_company = OWNER_NONE;
/* Set the date before loading sprites as some newgrfs check it */
SetDate(ConvertYMDToDate(_settings_game.game_creation.starting_year, 0, 1));
/* Load the right landscape stuff */
GfxLoadSprites();
LoadStringWidthTable();
InitializeGame(_gw.size_x, _gw.size_y, false);
PrepareGenerateWorldProgress();
/* Re-init the windowing system */
ResetWindowSystem();
/* Create toolbars */
SetupColoursAndInitialWindow();
if (_gw.thread != NULL) {
_gw.thread->Join();
delete _gw.thread;
_gw.thread = NULL;
}
if (BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth() == 0 ||
!ThreadObject::New(&_GenerateWorld, NULL, &_gw.thread)) {
DEBUG(misc, 1, "Cannot create genworld thread, reverting to single-threaded mode");
_gw.threaded = false;
_GenerateWorld(NULL);
return;
}
/* Remove any open window */
DeleteAllNonVitalWindows();
/* Hide vital windows, because we don't allow to use them */
HideVitalWindows();
/* Don't show the dialog if we don't have a thread */
ShowGenerateWorldProgress();
/* Centre the view on the map */
if (FindWindowById(WC_MAIN_WINDOW, 0) != NULL) {
ScrollMainWindowToTile(TileXY(MapSizeX() / 2, MapSizeY() / 2), true);
}
}
| 9,266
|
C++
|
.cpp
| 282
| 30.524823
| 190
| 0.721003
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,159
|
music.cpp
|
EnergeticBark_OpenTTD-3DS/src/music.cpp
|
/* $Id$ */
/** @file music.cpp The songs that OpenTTD knows. */
#include "stdafx.h"
#include "music.h"
const SongSpecs _origin_songs_specs[] = {
{"gm_tt00.gm", "Tycoon DELUXE Theme"},
{"gm_tt02.gm", "Easy Driver"},
{"gm_tt03.gm", "Little Red Diesel"},
{"gm_tt17.gm", "Cruise Control"},
{"gm_tt07.gm", "Don't Walk!"},
{"gm_tt09.gm", "Fell Apart On Me"},
{"gm_tt04.gm", "City Groove"},
{"gm_tt19.gm", "Funk Central"},
{"gm_tt06.gm", "Stoke It"},
{"gm_tt12.gm", "Road Hog"},
{"gm_tt05.gm", "Aliens Ate My Railway"},
{"gm_tt01.gm", "Snarl Up"},
{"gm_tt18.gm", "Stroll On"},
{"gm_tt10.gm", "Can't Get There From Here"},
{"gm_tt08.gm", "Sawyer's Tune"},
{"gm_tt13.gm", "Hold That Train!"},
{"gm_tt21.gm", "Movin' On"},
{"gm_tt15.gm", "Goss Groove"},
{"gm_tt16.gm", "Small Town"},
{"gm_tt14.gm", "Broomer's Oil Rag"},
{"gm_tt20.gm", "Jammit"},
{"gm_tt11.gm", "Hard Drivin'"},
};
assert_compile(NUM_SONGS_AVAILABLE == lengthof(_origin_songs_specs));
| 968
|
C++
|
.cpp
| 29
| 31.482759
| 69
| 0.608556
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,160
|
win32.cpp
|
EnergeticBark_OpenTTD-3DS/src/win32.cpp
|
/* $Id$ */
/** @file win32.cpp Implementation of MS Windows system calls */
#include "stdafx.h"
#include "openttd.h"
#include "debug.h"
#include "saveload/saveload.h"
#include "gfx_func.h"
#include "textbuf_gui.h"
#include "fileio_func.h"
#include "fios.h"
#include "rev.h"
#include <windows.h>
#include <winnt.h>
#include <wininet.h>
#include <fcntl.h>
#include <shlobj.h> /* SHGetFolderPath */
#include "variables.h"
#include "win32.h"
#include "core/alloc_func.hpp"
#include "functions.h"
#include "core/random_func.hpp"
#include "core/bitmath_func.hpp"
#include "string_func.h"
#include "gamelog.h"
#include <ctype.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#if defined(_MSC_VER) && !defined(WINCE)
#include <dbghelp.h>
#include "strings_func.h"
#endif
static bool _has_console;
static bool cursor_visible = true;
bool MyShowCursor(bool show)
{
if (cursor_visible == show) return show;
cursor_visible = show;
ShowCursor(show);
return !show;
}
/** Helper function needed by dynamically loading libraries
* XXX: Hurray for MS only having an ANSI GetProcAddress function
* on normal windows and no Wide version except for in Windows Mobile/CE */
bool LoadLibraryList(Function proc[], const char *dll)
{
while (*dll != '\0') {
HMODULE lib;
lib = LoadLibrary(MB_TO_WIDE(dll));
if (lib == NULL) return false;
for (;;) {
FARPROC p;
while (*dll++ != '\0') { /* Nothing */ }
if (*dll == '\0') break;
#if defined(WINCE)
p = GetProcAddress(lib, MB_TO_WIDE(dll));
#else
p = GetProcAddress(lib, dll);
#endif
if (p == NULL) return false;
*proc++ = (Function)p;
}
dll++;
}
return true;
}
#ifdef _MSC_VER
static const char *_exception_string = NULL;
void SetExceptionString(const char *s, ...)
{
va_list va;
char buf[512];
va_start(va, s);
vsnprintf(buf, lengthof(buf), s, va);
va_end(va);
_exception_string = strdup(buf);
}
#endif
void ShowOSErrorBox(const char *buf, bool system)
{
MyShowCursor(true);
MessageBox(GetActiveWindow(), MB_TO_WIDE(buf), _T("Error!"), MB_ICONSTOP);
/* if exception tracker is enabled, we crash here to let the exception handler handle it. */
#if defined(WIN32_EXCEPTION_TRACKER) && !defined(_DEBUG)
if (system) {
_exception_string = buf;
*(byte*)0 = 0;
}
#endif
}
#if defined(_MSC_VER) && !defined(WINCE)
static void *_safe_esp;
static char *_crash_msg;
static bool _expanded;
static bool _did_emerg_save;
static int _ident;
struct DebugFileInfo {
uint32 size;
uint32 crc32;
SYSTEMTIME file_time;
};
static uint32 *_crc_table;
static void MakeCRCTable(uint32 *table)
{
uint32 crc, poly = 0xEDB88320L;
int i;
int j;
_crc_table = table;
for (i = 0; i != 256; i++) {
crc = i;
for (j = 8; j != 0; j--) {
crc = (crc & 1 ? (crc >> 1) ^ poly : crc >> 1);
}
table[i] = crc;
}
}
static uint32 CalcCRC(byte *data, uint size, uint32 crc)
{
for (; size > 0; size--) {
crc = ((crc >> 8) & 0x00FFFFFF) ^ _crc_table[(crc ^ *data++) & 0xFF];
}
return crc;
}
static void GetFileInfo(DebugFileInfo *dfi, const TCHAR *filename)
{
HANDLE file;
memset(dfi, 0, sizeof(*dfi));
file = CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, 0);
if (file != INVALID_HANDLE_VALUE) {
byte buffer[1024];
DWORD numread;
uint32 filesize = 0;
FILETIME write_time;
uint32 crc = (uint32)-1;
for (;;) {
if (ReadFile(file, buffer, sizeof(buffer), &numread, NULL) == 0 || numread == 0)
break;
filesize += numread;
crc = CalcCRC(buffer, numread, crc);
}
dfi->size = filesize;
dfi->crc32 = crc ^ (uint32)-1;
if (GetFileTime(file, NULL, NULL, &write_time)) {
FileTimeToSystemTime(&write_time, &dfi->file_time);
}
CloseHandle(file);
}
}
static char *PrintModuleInfo(char *output, const char *last, HMODULE mod)
{
TCHAR buffer[MAX_PATH];
DebugFileInfo dfi;
GetModuleFileName(mod, buffer, MAX_PATH);
GetFileInfo(&dfi, buffer);
output += seprintf(output, last, " %-20s handle: %p size: %d crc: %.8X date: %d-%.2d-%.2d %.2d:%.2d:%.2d\r\n",
WIDE_TO_MB(buffer),
mod,
dfi.size,
dfi.crc32,
dfi.file_time.wYear,
dfi.file_time.wMonth,
dfi.file_time.wDay,
dfi.file_time.wHour,
dfi.file_time.wMinute,
dfi.file_time.wSecond
);
return output;
}
static char *PrintModuleList(char *output, const char *last)
{
BOOL (WINAPI *EnumProcessModules)(HANDLE, HMODULE*, DWORD, LPDWORD);
if (LoadLibraryList((Function*)&EnumProcessModules, "psapi.dll\0EnumProcessModules\0\0")) {
HMODULE modules[100];
DWORD needed;
BOOL res;
HANDLE proc = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId());
if (proc != NULL) {
res = EnumProcessModules(proc, modules, sizeof(modules), &needed);
CloseHandle(proc);
if (res) {
size_t count = min(needed / sizeof(HMODULE), lengthof(modules));
for (size_t i = 0; i != count; i++) output = PrintModuleInfo(output, last, modules[i]);
return output;
}
}
}
output = PrintModuleInfo(output, last, NULL);
return output;
}
static const TCHAR _crash_desc[] =
_T("A serious fault condition occured in the game. The game will shut down.\n")
_T("Please send the crash information and the crash.dmp file (if any) to the developers.\n")
_T("This will greatly help debugging. The correct place to do this is http://bugs.openttd.org. ")
_T("The information contained in the report is displayed below.\n")
_T("Press \"Emergency save\" to attempt saving the game.");
static const TCHAR _save_succeeded[] =
_T("Emergency save succeeded.\n")
_T("Be aware that critical parts of the internal game state may have become ")
_T("corrupted. The saved game is not guaranteed to work.");
static const TCHAR _emergency_crash[] =
_T("A serious fault condition occured in the game. The game will shut down.\n")
_T("As you loaded an emergency savegame no crash information will be generated.\n");
static bool EmergencySave()
{
GamelogStartAction(GLAT_EMERGENCY);
GamelogEmergency();
GamelogStopAction();
SaveOrLoad("crash.sav", SL_SAVE, BASE_DIR);
return true;
}
/* Disable the crash-save submit code as it's not used */
#if 0
struct WinInetProcs {
HINTERNET (WINAPI *InternetOpen)(LPCTSTR, DWORD, LPCTSTR, LPCTSTR, DWORD);
HINTERNET (WINAPI *InternetConnect)(HINTERNET, LPCTSTR, INTERNET_PORT, LPCTSTR, LPCTSTR, DWORD, DWORD, DWORD);
HINTERNET (WINAPI *HttpOpenRequest)(HINTERNET, LPCTSTR, LPCTSTR, LPCTSTR, LPCTSTR, LPCTSTR *, DWORD, DWORD);
BOOL (WINAPI *HttpSendRequest)(HINTERNET, LPCTSTR, DWORD, LPVOID, DWORD);
BOOL (WINAPI *InternetCloseHandle)(HINTERNET);
BOOL (WINAPI *HttpQueryInfo)(HINTERNET, DWORD, LPVOID, LPDWORD, LPDWORD);
};
#define M(x) x "\0"
#if defined(UNICODE)
# define W(x) x "W"
#else
# define W(x) x "A"
#endif
static const char wininet_files[] =
M("wininet.dll")
M(W("InternetOpen"))
M(W("InternetConnect"))
M(W("HttpOpenRequest"))
M(W("HttpSendRequest"))
M("InternetCloseHandle")
M(W("HttpQueryInfo"))
M("");
#undef W
#undef M
static WinInetProcs _wininet;
static const TCHAR *SubmitCrashReport(HWND wnd, void *msg, size_t msglen, const TCHAR *arg)
{
HINTERNET inet, conn, http;
const TCHAR *err = NULL;
DWORD code, len;
static TCHAR buf[100];
TCHAR buff[100];
if (_wininet.InternetOpen == NULL && !LoadLibraryList((Function*)&_wininet, wininet_files)) return _T("can't load wininet.dll");
inet = _wininet.InternetOpen(_T("OTTD"), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0 );
if (inet == NULL) { err = _T("internetopen failed"); goto error1; }
conn = _wininet.InternetConnect(inet, _T("www.openttd.org"), INTERNET_DEFAULT_HTTP_PORT, _T(""), _T(""), INTERNET_SERVICE_HTTP, 0, 0);
if (conn == NULL) { err = _T("internetconnect failed"); goto error2; }
_sntprintf(buff, lengthof(buff), _T("/crash.php?file=%s&ident=%d"), arg, _ident);
http = _wininet.HttpOpenRequest(conn, _T("POST"), buff, NULL, NULL, NULL, INTERNET_FLAG_NO_CACHE_WRITE , 0);
if (http == NULL) { err = _T("httpopenrequest failed"); goto error3; }
if (!_wininet.HttpSendRequest(http, _T("Content-type: application/binary"), -1, msg, (DWORD)msglen)) { err = _T("httpsendrequest failed"); goto error4; }
len = sizeof(code);
if (!_wininet.HttpQueryInfo(http, HTTP_QUERY_STATUS_CODE | HTTP_QUERY_FLAG_NUMBER, &code, &len, 0)) { err = _T("httpqueryinfo failed"); goto error4; }
if (code != 200) {
int l = _sntprintf(buf, lengthof(buf), _T("Server said: %d "), code);
len = sizeof(buf) - l;
_wininet.HttpQueryInfo(http, HTTP_QUERY_STATUS_TEXT, buf + l, &len, 0);
err = buf;
}
error4:
_wininet.InternetCloseHandle(http);
error3:
_wininet.InternetCloseHandle(conn);
error2:
_wininet.InternetCloseHandle(inet);
error1:
return err;
}
static void SubmitFile(HWND wnd, const TCHAR *file)
{
HANDLE h;
unsigned long size;
unsigned long read;
void *mem;
h = CreateFile(file, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
if (h == NULL) return;
size = GetFileSize(h, NULL);
if (size > 500000) goto error1;
mem = MallocT<byte>(size);
if (mem == NULL) goto error1;
if (!ReadFile(h, mem, size, &read, NULL) || read != size) goto error2;
SubmitCrashReport(wnd, mem, size, file);
error2:
free(mem);
error1:
CloseHandle(h);
}
#endif /* Disabled crash-submit procedures */
static const TCHAR * const _expand_texts[] = {_T("S&how report >>"), _T("&Hide report <<") };
static void SetWndSize(HWND wnd, int mode)
{
RECT r, r2;
int offs;
GetWindowRect(wnd, &r);
SetDlgItemText(wnd, 15, _expand_texts[mode == 1]);
if (mode >= 0) {
GetWindowRect(GetDlgItem(wnd, 11), &r2);
offs = r2.bottom - r2.top + 10;
if (!mode) offs = -offs;
SetWindowPos(wnd, HWND_TOPMOST, 0, 0,
r.right - r.left, r.bottom - r.top + offs, SWP_NOMOVE | SWP_NOZORDER);
} else {
SetWindowPos(wnd, HWND_TOPMOST,
(GetSystemMetrics(SM_CXSCREEN) - (r.right - r.left)) / 2,
(GetSystemMetrics(SM_CYSCREEN) - (r.bottom - r.top)) / 2,
0, 0, SWP_NOSIZE);
}
}
static bool DoEmergencySave(HWND wnd)
{
bool b = false;
EnableWindow(GetDlgItem(wnd, 13), FALSE);
_did_emerg_save = true;
__try {
b = EmergencySave();
} __except (1) {}
return b;
}
static INT_PTR CALLBACK CrashDialogFunc(HWND wnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg) {
case WM_INITDIALOG: {
#if defined(UNICODE)
/* We need to put the crash-log in a seperate buffer because the default
* buffer in MB_TO_WIDE is not large enough (512 chars) */
wchar_t crash_msgW[8096];
#endif
SetDlgItemText(wnd, 10, _crash_desc);
SetDlgItemText(wnd, 11, MB_TO_WIDE_BUFFER(_crash_msg, crash_msgW, lengthof(crash_msgW)));
SendDlgItemMessage(wnd, 11, WM_SETFONT, (WPARAM)GetStockObject(ANSI_FIXED_FONT), FALSE);
SetWndSize(wnd, -1);
} return TRUE;
case WM_COMMAND:
switch (wParam) {
case 12: // Close
ExitProcess(0);
case 13: // Emergency save
if (DoEmergencySave(wnd)) {
MessageBox(wnd, _save_succeeded, _T("Save successful"), MB_ICONINFORMATION);
} else {
MessageBox(wnd, _T("Save failed"), _T("Save failed"), MB_ICONINFORMATION);
}
break;
/* Disable the crash-save submit code as it's not used */
#if 0
case 14: { // Submit crash report
const TCHAR *s;
SetCursor(LoadCursor(NULL, IDC_WAIT));
s = SubmitCrashReport(wnd, _crash_msg, strlen(_crash_msg), _T(""));
if (s != NULL) {
MessageBox(wnd, s, _T("Error"), MB_ICONSTOP);
break;
}
/* try to submit emergency savegame */
if (_did_emerg_save || DoEmergencySave(wnd)) SubmitFile(wnd, _T("crash.sav"));
/* try to submit the autosaved game */
if (_opt.autosave) {
TCHAR buf[40];
_sntprintf(buf, lengthof(buf), _T("autosave%d.sav"), (_autosave_ctr - 1) & 3);
SubmitFile(wnd, buf);
}
EnableWindow(GetDlgItem(wnd, 14), FALSE);
SetCursor(LoadCursor(NULL, IDC_ARROW));
MessageBox(wnd, _T("Crash report submitted. Thank you."), _T("Crash Report"), MB_ICONINFORMATION);
} break;
#endif /* Disabled crash-submit procedures */
case 15: // Expand window to show crash-message
_expanded ^= 1;
SetWndSize(wnd, _expanded);
break;
}
return TRUE;
case WM_CLOSE: ExitProcess(0);
}
return FALSE;
}
static void Handler2()
{
ShowCursor(TRUE);
ShowWindow(GetActiveWindow(), FALSE);
DialogBox(GetModuleHandle(NULL), MAKEINTRESOURCE(100), NULL, CrashDialogFunc);
}
extern bool CloseConsoleLogIfActive();
static HANDLE _file_crash_log;
static void GamelogPrintCrashLogProc(const char *s)
{
DWORD num_written;
WriteFile(_file_crash_log, s, (DWORD)strlen(s), &num_written, NULL);
WriteFile(_file_crash_log, "\r\n", (DWORD)strlen("\r\n"), &num_written, NULL);
}
/** Amount of output for the execption handler. */
static const int EXCEPTION_OUTPUT_SIZE = 8192;
static LONG WINAPI ExceptionHandler(EXCEPTION_POINTERS *ep)
{
char *output;
static bool had_exception = false;
if (had_exception) ExitProcess(0);
if (GamelogTestEmergency()) {
MessageBox(NULL, _emergency_crash, _T("Fatal Application Failure"), MB_ICONERROR);
ExitProcess(0);
}
had_exception = true;
_ident = GetTickCount(); // something pretty unique
MakeCRCTable(AllocaM(uint32, 256));
_crash_msg = output = (char*)LocalAlloc(LMEM_FIXED, EXCEPTION_OUTPUT_SIZE);
const char *last = output + EXCEPTION_OUTPUT_SIZE - 1;
{
SYSTEMTIME time;
GetLocalTime(&time);
output += seprintf(output, last,
"*** OpenTTD Crash Report ***\r\n"
"Date: %d-%.2d-%.2d %.2d:%.2d:%.2d\r\n"
"Build: %s (%d) built on " __DATE__ " " __TIME__ "\r\n",
time.wYear,
time.wMonth,
time.wDay,
time.wHour,
time.wMinute,
time.wSecond,
_openttd_revision,
_openttd_revision_modified
);
}
if (_exception_string)
output += seprintf(output, last, "Reason: %s\r\n", _exception_string);
output += seprintf(output, last, "Language: %s\r\n", _dynlang.curr_file);
#ifdef _M_AMD64
output += seprintf(output, last, "Exception %.8X at %.16IX\r\n"
"Registers:\r\n"
"RAX: %.16llX RBX: %.16llX RCX: %.16llX RDX: %.16llX\r\n"
"RSI: %.16llX RDI: %.16llX RBP: %.16llX RSP: %.16llX\r\n"
"R8: %.16llX R9: %.16llX R10: %.16llX R11: %.16llX\r\n"
"R12: %.16llX R13: %.16llX R14: %.16llX R15: %.16llX\r\n"
"RIP: %.16llX EFLAGS: %.8X\r\n"
"\r\nBytes at CS:RIP:\r\n",
ep->ExceptionRecord->ExceptionCode,
ep->ExceptionRecord->ExceptionAddress,
ep->ContextRecord->Rax,
ep->ContextRecord->Rbx,
ep->ContextRecord->Rcx,
ep->ContextRecord->Rdx,
ep->ContextRecord->Rsi,
ep->ContextRecord->Rdi,
ep->ContextRecord->Rbp,
ep->ContextRecord->Rsp,
ep->ContextRecord->R8,
ep->ContextRecord->R9,
ep->ContextRecord->R10,
ep->ContextRecord->R11,
ep->ContextRecord->R12,
ep->ContextRecord->R13,
ep->ContextRecord->R14,
ep->ContextRecord->R15,
ep->ContextRecord->Rip,
ep->ContextRecord->EFlags
);
#else
output += seprintf(output, last, "Exception %.8X at %.8p\r\n"
"Registers:\r\n"
" EAX: %.8X EBX: %.8X ECX: %.8X EDX: %.8X\r\n"
" ESI: %.8X EDI: %.8X EBP: %.8X ESP: %.8X\r\n"
" EIP: %.8X EFLAGS: %.8X\r\n"
"\r\nBytes at CS:EIP:\r\n",
ep->ExceptionRecord->ExceptionCode,
ep->ExceptionRecord->ExceptionAddress,
ep->ContextRecord->Eax,
ep->ContextRecord->Ebx,
ep->ContextRecord->Ecx,
ep->ContextRecord->Edx,
ep->ContextRecord->Esi,
ep->ContextRecord->Edi,
ep->ContextRecord->Ebp,
ep->ContextRecord->Esp,
ep->ContextRecord->Eip,
ep->ContextRecord->EFlags
);
#endif
{
#ifdef _M_AMD64
byte *b = (byte*)ep->ContextRecord->Rip;
#else
byte *b = (byte*)ep->ContextRecord->Eip;
#endif
int i;
for (i = 0; i != 24; i++) {
if (IsBadReadPtr(b, 1)) {
output += seprintf(output, last, " ??"); // OCR: WAS: , 0);
} else {
output += seprintf(output, last, " %.2X", *b);
}
b++;
}
output += seprintf(output, last,
"\r\n"
"\r\nStack trace: \r\n"
);
}
{
int i, j;
#ifdef _M_AMD64
uint32 *b = (uint32*)ep->ContextRecord->Rsp;
#else
uint32 *b = (uint32*)ep->ContextRecord->Esp;
#endif
for (j = 0; j != 24; j++) {
for (i = 0; i != 8; i++) {
if (IsBadReadPtr(b, sizeof(uint32))) {
output += seprintf(output, last, " ????????"); // OCR: WAS - , 0);
} else {
output += seprintf(output, last, " %.8X", *b);
}
b++;
}
output += seprintf(output, last, "\r\n");
}
}
output += seprintf(output, last, "\r\nModule information:\r\n");
output = PrintModuleList(output, last);
{
_OSVERSIONINFOA os;
os.dwOSVersionInfoSize = sizeof(os);
GetVersionExA(&os);
output += seprintf(output, last, "\r\nSystem information:\r\n"
" Windows version %d.%d %d %s\r\n\r\n",
os.dwMajorVersion, os.dwMinorVersion, os.dwBuildNumber, os.szCSDVersion);
}
_file_crash_log = CreateFile(_T("crash.log"), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0);
if (_file_crash_log != INVALID_HANDLE_VALUE) {
DWORD num_written;
WriteFile(_file_crash_log, _crash_msg, output - _crash_msg, &num_written, NULL);
}
#if !defined(_DEBUG)
HMODULE dbghelp = LoadLibrary(_T("dbghelp.dll"));
if (dbghelp != NULL) {
typedef BOOL (WINAPI *MiniDumpWriteDump_t)(HANDLE, DWORD, HANDLE,
MINIDUMP_TYPE,
CONST PMINIDUMP_EXCEPTION_INFORMATION,
CONST PMINIDUMP_USER_STREAM_INFORMATION,
CONST PMINIDUMP_CALLBACK_INFORMATION);
MiniDumpWriteDump_t funcMiniDumpWriteDump = (MiniDumpWriteDump_t)GetProcAddress(dbghelp, "MiniDumpWriteDump");
if (funcMiniDumpWriteDump != NULL) {
HANDLE file = CreateFile(_T("crash.dmp"), GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, 0, 0);
HANDLE proc = GetCurrentProcess();
DWORD procid = GetCurrentProcessId();
MINIDUMP_EXCEPTION_INFORMATION mdei;
MINIDUMP_USER_STREAM userstream;
MINIDUMP_USER_STREAM_INFORMATION musi;
char msg[] = "****** Built on " __DATE__ " " __TIME__ ". ******";
userstream.Type = LastReservedStream + 1;
userstream.Buffer = msg;
userstream.BufferSize = sizeof(msg);
musi.UserStreamCount = 1;
musi.UserStreamArray = &userstream;
mdei.ThreadId = GetCurrentThreadId();
mdei.ExceptionPointers = ep;
mdei.ClientPointers = false;
funcMiniDumpWriteDump(proc, procid, file, MiniDumpWithDataSegs, &mdei, &musi, NULL);
}
FreeLibrary(dbghelp);
}
#endif
if (_file_crash_log != INVALID_HANDLE_VALUE) {
GamelogPrint(&GamelogPrintCrashLogProc);
CloseHandle(_file_crash_log);
}
/* Close any possible log files */
CloseConsoleLogIfActive();
if (_safe_esp) {
#ifdef _M_AMD64
ep->ContextRecord->Rip = (DWORD64)Handler2;
ep->ContextRecord->Rsp = (DWORD64)_safe_esp;
#else
ep->ContextRecord->Eip = (DWORD)Handler2;
ep->ContextRecord->Esp = (DWORD)_safe_esp;
#endif
return EXCEPTION_CONTINUE_EXECUTION;
}
return EXCEPTION_EXECUTE_HANDLER;
}
#ifdef _M_AMD64
extern "C" void *_get_safe_esp();
#endif
static void Win32InitializeExceptions()
{
#ifdef _M_AMD64
_safe_esp = _get_safe_esp();
#else
_asm {
mov _safe_esp, esp
}
#endif
SetUnhandledExceptionFilter(ExceptionHandler);
}
#endif /* _MSC_VER */
/* Code below for windows version of opendir/readdir/closedir copied and
* modified from Jan Wassenberg's GPL implementation posted over at
* http://www.gamedev.net/community/forums/topic.asp?topic_id=364584&whichpage=1� */
/* suballocator - satisfies most requests with a reusable static instance.
* this avoids hundreds of alloc/free which would fragment the heap.
* To guarantee concurrency, we fall back to malloc if the instance is
* already in use (it's important to avoid suprises since this is such a
* low-level routine). */
static DIR _global_dir;
static LONG _global_dir_is_in_use = false;
static inline DIR *dir_calloc()
{
DIR *d;
if (InterlockedExchange(&_global_dir_is_in_use, true) == (LONG)true) {
d = CallocT<DIR>(1);
} else {
d = &_global_dir;
memset(d, 0, sizeof(*d));
}
return d;
}
static inline void dir_free(DIR *d)
{
if (d == &_global_dir) {
_global_dir_is_in_use = (LONG)false;
} else {
free(d);
}
}
DIR *opendir(const TCHAR *path)
{
DIR *d;
UINT sem = SetErrorMode(SEM_FAILCRITICALERRORS); // disable 'no-disk' message box
DWORD fa = GetFileAttributes(path);
if ((fa != INVALID_FILE_ATTRIBUTES) && (fa & FILE_ATTRIBUTE_DIRECTORY)) {
d = dir_calloc();
if (d != NULL) {
TCHAR search_path[MAX_PATH];
bool slash = path[_tcslen(path) - 1] == '\\';
/* build search path for FindFirstFile, try not to append additional slashes
* as it throws Win9x off its groove for root directories */
_sntprintf(search_path, lengthof(search_path), _T("%s%s*"), path, slash ? _T("") : _T("\\"));
*lastof(search_path) = '\0';
d->hFind = FindFirstFile(search_path, &d->fd);
if (d->hFind != INVALID_HANDLE_VALUE ||
GetLastError() == ERROR_NO_MORE_FILES) { // the directory is empty
d->ent.dir = d;
d->at_first_entry = true;
} else {
dir_free(d);
d = NULL;
}
} else {
errno = ENOMEM;
}
} else {
/* path not found or not a directory */
d = NULL;
errno = ENOENT;
}
SetErrorMode(sem); // restore previous setting
return d;
}
struct dirent *readdir(DIR *d)
{
DWORD prev_err = GetLastError(); // avoid polluting last error
if (d->at_first_entry) {
/* the directory was empty when opened */
if (d->hFind == INVALID_HANDLE_VALUE) return NULL;
d->at_first_entry = false;
} else if (!FindNextFile(d->hFind, &d->fd)) { // determine cause and bail
if (GetLastError() == ERROR_NO_MORE_FILES) SetLastError(prev_err);
return NULL;
}
/* This entry has passed all checks; return information about it.
* (note: d_name is a pointer; see struct dirent definition) */
d->ent.d_name = d->fd.cFileName;
return &d->ent;
}
int closedir(DIR *d)
{
FindClose(d->hFind);
dir_free(d);
return 0;
}
bool FiosIsRoot(const char *file)
{
return file[3] == '\0'; // C:\...
}
void FiosGetDrives()
{
#if defined(WINCE)
/* WinCE only knows one drive: / */
FiosItem *fios = _fios_items.Append();
fios->type = FIOS_TYPE_DRIVE;
fios->mtime = 0;
snprintf(fios->name, lengthof(fios->name), PATHSEP "");
strecpy(fios->title, fios->name, lastof(fios->title));
#else
TCHAR drives[256];
const TCHAR *s;
GetLogicalDriveStrings(lengthof(drives), drives);
for (s = drives; *s != '\0';) {
FiosItem *fios = _fios_items.Append();
fios->type = FIOS_TYPE_DRIVE;
fios->mtime = 0;
snprintf(fios->name, lengthof(fios->name), "%c:", s[0] & 0xFF);
strecpy(fios->title, fios->name, lastof(fios->title));
while (*s++ != '\0') { /* Nothing */ }
}
#endif
}
bool FiosIsValidFile(const char *path, const struct dirent *ent, struct stat *sb)
{
/* hectonanoseconds between Windows and POSIX epoch */
static const int64 posix_epoch_hns = 0x019DB1DED53E8000LL;
const WIN32_FIND_DATA *fd = &ent->dir->fd;
sb->st_size = ((uint64) fd->nFileSizeHigh << 32) + fd->nFileSizeLow;
/* UTC FILETIME to seconds-since-1970 UTC
* we just have to subtract POSIX epoch and scale down to units of seconds.
* http://www.gamedev.net/community/forums/topic.asp?topic_id=294070&whichpage=1�
* XXX - not entirely correct, since filetimes on FAT aren't UTC but local,
* this won't entirely be correct, but we use the time only for comparsion. */
sb->st_mtime = (time_t)((*(uint64*)&fd->ftLastWriteTime - posix_epoch_hns) / 1E7);
sb->st_mode = (fd->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)? S_IFDIR : S_IFREG;
return true;
}
bool FiosIsHiddenFile(const struct dirent *ent)
{
return (ent->dir->fd.dwFileAttributes & (FILE_ATTRIBUTE_HIDDEN | FILE_ATTRIBUTE_SYSTEM)) != 0;
}
bool FiosGetDiskFreeSpace(const char *path, uint64 *tot)
{
UINT sem = SetErrorMode(SEM_FAILCRITICALERRORS); // disable 'no-disk' message box
bool retval = false;
TCHAR root[4];
DWORD spc, bps, nfc, tnc;
_sntprintf(root, lengthof(root), _T("%c:") _T(PATHSEP), path[0]);
if (tot != NULL && GetDiskFreeSpace(root, &spc, &bps, &nfc, &tnc)) {
*tot = ((spc * bps) * (uint64)nfc);
retval = true;
}
SetErrorMode(sem); // reset previous setting
return retval;
}
static int ParseCommandLine(char *line, char **argv, int max_argc)
{
int n = 0;
do {
/* skip whitespace */
while (*line == ' ' || *line == '\t') line++;
/* end? */
if (*line == '\0') break;
/* special handling when quoted */
if (*line == '"') {
argv[n++] = ++line;
while (*line != '"') {
if (*line == '\0') return n;
line++;
}
} else {
argv[n++] = line;
while (*line != ' ' && *line != '\t') {
if (*line == '\0') return n;
line++;
}
}
*line++ = '\0';
} while (n != max_argc);
return n;
}
void CreateConsole()
{
#if defined(WINCE)
/* WinCE doesn't support console stuff */
#else
HANDLE hand;
CONSOLE_SCREEN_BUFFER_INFO coninfo;
if (_has_console) return;
_has_console = true;
AllocConsole();
hand = GetStdHandle(STD_OUTPUT_HANDLE);
GetConsoleScreenBufferInfo(hand, &coninfo);
coninfo.dwSize.Y = 500;
SetConsoleScreenBufferSize(hand, coninfo.dwSize);
/* redirect unbuffered STDIN, STDOUT, STDERR to the console */
#if !defined(__CYGWIN__)
*stdout = *_fdopen( _open_osfhandle((intptr_t)hand, _O_TEXT), "w" );
*stdin = *_fdopen(_open_osfhandle((intptr_t)GetStdHandle(STD_INPUT_HANDLE), _O_TEXT), "r" );
*stderr = *_fdopen(_open_osfhandle((intptr_t)GetStdHandle(STD_ERROR_HANDLE), _O_TEXT), "w" );
#else
/* open_osfhandle is not in cygwin */
*stdout = *fdopen(1, "w" );
*stdin = *fdopen(0, "r" );
*stderr = *fdopen(2, "w" );
#endif
setvbuf(stdin, NULL, _IONBF, 0);
setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, NULL, _IONBF, 0);
#endif
}
void ShowInfo(const char *str)
{
if (_has_console) {
fprintf(stderr, "%s\n", str);
} else {
bool old;
#if defined(UNICODE)
/* We need to put the text in a seperate buffer because the default
* buffer in MB_TO_WIDE might not be large enough (512 chars) */
wchar_t help_msgW[8192];
#endif
ReleaseCapture();
_left_button_clicked = _left_button_down = false;
old = MyShowCursor(true);
if (MessageBox(GetActiveWindow(), MB_TO_WIDE_BUFFER(str, help_msgW, lengthof(help_msgW)), _T("OpenTTD"), MB_ICONINFORMATION | MB_OKCANCEL) == IDCANCEL) {
CreateConsole();
}
MyShowCursor(old);
}
}
#if defined(WINCE)
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
#else
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
#endif
{
int argc;
char *argv[64]; // max 64 command line arguments
char *cmdline;
#if !defined(UNICODE)
_codepage = GetACP(); // get system codepage as some kind of a default
#endif /* UNICODE */
#if defined(UNICODE)
#if !defined(WINCE)
/* Check if a win9x user started the win32 version */
if (HasBit(GetVersion(), 31)) usererror("This version of OpenTTD doesn't run on windows 95/98/ME.\nPlease download the win9x binary and try again.");
#endif
/* For UNICODE we need to convert the commandline to char* _AND_
* save it because argv[] points into this buffer and thus needs to
* be available between subsequent calls to FS2OTTD() */
char cmdlinebuf[MAX_PATH];
#endif /* UNICODE */
cmdline = WIDE_TO_MB_BUFFER(GetCommandLine(), cmdlinebuf, lengthof(cmdlinebuf));
#if defined(_DEBUG)
CreateConsole();
#endif
#if !defined(WINCE)
_set_error_mode(_OUT_TO_MSGBOX); // force assertion output to messagebox
#endif
/* setup random seed to something quite random */
SetRandomSeed(GetTickCount());
argc = ParseCommandLine(cmdline, argv, lengthof(argv));
#if defined(WIN32_EXCEPTION_TRACKER)
Win32InitializeExceptions();
#endif
#if defined(WIN32_EXCEPTION_TRACKER_DEBUG)
_try {
LONG WINAPI ExceptionHandler(EXCEPTION_POINTERS *ep);
#endif
ttd_main(argc, argv);
#if defined(WIN32_EXCEPTION_TRACKER_DEBUG)
} _except (ExceptionHandler(_exception_info())) {}
#endif
return 0;
}
#if defined(WINCE)
void GetCurrentDirectoryW(int length, wchar_t *path)
{
/* Get the name of this module */
GetModuleFileName(NULL, path, length);
/* Remove the executable name, this we call CurrentDir */
wchar_t *pDest = wcsrchr(path, '\\');
if (pDest != NULL) {
int result = pDest - path + 1;
path[result] = '\0';
}
}
#endif
char *getcwd(char *buf, size_t size)
{
#if defined(WINCE)
TCHAR path[MAX_PATH];
GetModuleFileName(NULL, path, MAX_PATH);
convert_from_fs(path, buf, size);
/* GetModuleFileName returns dir with file, so remove everything behind latest '\\' */
char *p = strrchr(buf, '\\');
if (p != NULL) *p = '\0';
#elif defined(UNICODE)
TCHAR path[MAX_PATH];
GetCurrentDirectory(MAX_PATH - 1, path);
convert_from_fs(path, buf, size);
#else
GetCurrentDirectory(size, buf);
#endif
return buf;
}
void DetermineBasePaths(const char *exe)
{
char tmp[MAX_PATH];
TCHAR path[MAX_PATH];
#ifdef WITH_PERSONAL_DIR
SHGetFolderPath(NULL, CSIDL_PERSONAL, NULL, SHGFP_TYPE_CURRENT, path);
strecpy(tmp, WIDE_TO_MB_BUFFER(path, tmp, lengthof(tmp)), lastof(tmp));
AppendPathSeparator(tmp, MAX_PATH);
ttd_strlcat(tmp, PERSONAL_DIR, MAX_PATH);
AppendPathSeparator(tmp, MAX_PATH);
_searchpaths[SP_PERSONAL_DIR] = strdup(tmp);
SHGetFolderPath(NULL, CSIDL_COMMON_DOCUMENTS, NULL, SHGFP_TYPE_CURRENT, path);
strecpy(tmp, WIDE_TO_MB_BUFFER(path, tmp, lengthof(tmp)), lastof(tmp));
AppendPathSeparator(tmp, MAX_PATH);
ttd_strlcat(tmp, PERSONAL_DIR, MAX_PATH);
AppendPathSeparator(tmp, MAX_PATH);
_searchpaths[SP_SHARED_DIR] = strdup(tmp);
#else
_searchpaths[SP_PERSONAL_DIR] = NULL;
_searchpaths[SP_SHARED_DIR] = NULL;
#endif
/* Get the path to working directory of OpenTTD */
getcwd(tmp, lengthof(tmp));
AppendPathSeparator(tmp, MAX_PATH);
_searchpaths[SP_WORKING_DIR] = strdup(tmp);
if (!GetModuleFileName(NULL, path, lengthof(path))) {
DEBUG(misc, 0, "GetModuleFileName failed (%d)\n", GetLastError());
_searchpaths[SP_BINARY_DIR] = NULL;
} else {
TCHAR exec_dir[MAX_PATH];
_tcsncpy(path, MB_TO_WIDE_BUFFER(exe, path, lengthof(path)), lengthof(path));
if (!GetFullPathName(path, lengthof(exec_dir), exec_dir, NULL)) {
DEBUG(misc, 0, "GetFullPathName failed (%d)\n", GetLastError());
_searchpaths[SP_BINARY_DIR] = NULL;
} else {
strecpy(tmp, WIDE_TO_MB_BUFFER(exec_dir, tmp, lengthof(tmp)), lastof(tmp));
char *s = strrchr(tmp, PATHSEPCHAR);
*(s + 1) = '\0';
_searchpaths[SP_BINARY_DIR] = strdup(tmp);
}
}
_searchpaths[SP_INSTALLATION_DIR] = NULL;
_searchpaths[SP_APPLICATION_BUNDLE_DIR] = NULL;
}
/**
* Insert a chunk of text from the clipboard onto the textbuffer. Get TEXT clipboard
* and append this up to the maximum length (either absolute or screenlength). If maxlength
* is zero, we don't care about the screenlength but only about the physical length of the string
* @param tb Textbuf type to be changed
* @return true on successful change of Textbuf, or false otherwise
*/
bool InsertTextBufferClipboard(Textbuf *tb)
{
HGLOBAL cbuf;
char utf8_buf[512];
const char *ptr;
WChar c;
uint16 width, length;
if (IsClipboardFormatAvailable(CF_UNICODETEXT)) {
OpenClipboard(NULL);
cbuf = GetClipboardData(CF_UNICODETEXT);
ptr = (const char*)GlobalLock(cbuf);
const char *ret = convert_from_fs((wchar_t*)ptr, utf8_buf, lengthof(utf8_buf));
GlobalUnlock(cbuf);
CloseClipboard();
if (*ret == '\0') return false;
#if !defined(UNICODE)
} else if (IsClipboardFormatAvailable(CF_TEXT)) {
OpenClipboard(NULL);
cbuf = GetClipboardData(CF_TEXT);
ptr = (const char*)GlobalLock(cbuf);
strecpy(utf8_buf, FS2OTTD(ptr), lastof(utf8_buf));
GlobalUnlock(cbuf);
CloseClipboard();
#endif /* UNICODE */
} else {
return false;
}
width = length = 0;
for (ptr = utf8_buf; (c = Utf8Consume(&ptr)) != '\0';) {
if (!IsPrintable(c)) break;
byte len = Utf8CharLen(c);
if (tb->size + length + len > tb->maxsize) break;
byte charwidth = GetCharacterWidth(FS_NORMAL, c);
if (tb->maxwidth != 0 && width + tb->width + charwidth > tb->maxwidth) break;
width += charwidth;
length += len;
}
if (length == 0) return false;
memmove(tb->buf + tb->caretpos + length, tb->buf + tb->caretpos, tb->size - tb->caretpos);
memcpy(tb->buf + tb->caretpos, utf8_buf, length);
tb->width += width;
tb->caretxoffs += width;
tb->size += length;
tb->caretpos += length;
assert(tb->size <= tb->maxsize);
tb->buf[tb->size - 1] = '\0'; // terminating zero
return true;
}
void CSleep(int milliseconds)
{
Sleep(milliseconds);
}
/** Utility function to get the current timestamp in milliseconds
* Useful for profiling */
int64 GetTS()
{
static double freq;
__int64 value;
if (!freq) {
QueryPerformanceFrequency((LARGE_INTEGER*)&value);
freq = (double)1000000 / value;
}
QueryPerformanceCounter((LARGE_INTEGER*)&value);
return (__int64)(value * freq);
}
/**
* Convert to OpenTTD's encoding from that of the local environment.
* When the project is built in UNICODE, the system codepage is irrelevant and
* the input string is wide. In ANSI mode, the string is in the
* local codepage which we'll convert to wide-char, and then to UTF-8.
* OpenTTD internal encoding is UTF8.
* The returned value's contents can only be guaranteed until the next call to
* this function. So if the value is needed for anything else, use convert_from_fs
* @param name pointer to a valid string that will be converted (local, or wide)
* @return pointer to the converted string; if failed string is of zero-length
* @see the current code-page comes from video\win32_v.cpp, event-notification
* WM_INPUTLANGCHANGE */
const char *FS2OTTD(const TCHAR *name)
{
static char utf8_buf[512];
#if defined(UNICODE)
return convert_from_fs(name, utf8_buf, lengthof(utf8_buf));
#else
char *s = utf8_buf;
for (; *name != '\0'; name++) {
wchar_t w;
int len = MultiByteToWideChar(_codepage, 0, name, 1, &w, 1);
if (len != 1) {
DEBUG(misc, 0, "[utf8] M2W error converting '%c'. Errno %d", *name, GetLastError());
continue;
}
if (s + Utf8CharLen(w) >= lastof(utf8_buf)) break;
s += Utf8Encode(s, w);
}
*s = '\0';
return utf8_buf;
#endif /* UNICODE */
}
/**
* Convert from OpenTTD's encoding to that of the local environment.
* When the project is built in UNICODE the system codepage is irrelevant and
* the converted string is wide. In ANSI mode, the UTF8 string is converted
* to multi-byte.
* OpenTTD internal encoding is UTF8.
* The returned value's contents can only be guaranteed until the next call to
* this function. So if the value is needed for anything else, use convert_from_fs
* @param name pointer to a valid string that will be converted (UTF8)
* @return pointer to the converted string; if failed string is of zero-length
* @see the current code-page comes from video\win32_v.cpp, event-notification
* WM_INPUTLANGCHANGE */
const TCHAR *OTTD2FS(const char *name)
{
static TCHAR system_buf[512];
#if defined(UNICODE)
return convert_to_fs(name, system_buf, lengthof(system_buf));
#else
char *s = system_buf;
for (WChar c; (c = Utf8Consume(&name)) != '\0';) {
if (s >= lastof(system_buf)) break;
char mb;
int len = WideCharToMultiByte(_codepage, 0, (wchar_t*)&c, 1, &mb, 1, NULL, NULL);
if (len != 1) {
DEBUG(misc, 0, "[utf8] W2M error converting '0x%X'. Errno %d", c, GetLastError());
continue;
}
*s++ = mb;
}
*s = '\0';
return system_buf;
#endif /* UNICODE */
}
/** Convert to OpenTTD's encoding from that of the environment in
* UNICODE. OpenTTD encoding is UTF8, local is wide
* @param name pointer to a valid string that will be converted
* @param utf8_buf pointer to a valid buffer that will receive the converted string
* @param buflen length in characters of the receiving buffer
* @return pointer to utf8_buf. If conversion fails the string is of zero-length */
char *convert_from_fs(const wchar_t *name, char *utf8_buf, size_t buflen)
{
int len = WideCharToMultiByte(CP_UTF8, 0, name, -1, utf8_buf, (int)buflen, NULL, NULL);
if (len == 0) {
DEBUG(misc, 0, "[utf8] W2M error converting wide-string. Errno %d", GetLastError());
utf8_buf[0] = '\0';
}
return utf8_buf;
}
/** Convert from OpenTTD's encoding to that of the environment in
* UNICODE. OpenTTD encoding is UTF8, local is wide
* @param name pointer to a valid string that will be converted
* @param utf16_buf pointer to a valid wide-char buffer that will receive the
* converted string
* @param buflen length in wide characters of the receiving buffer
* @return pointer to utf16_buf. If conversion fails the string is of zero-length */
wchar_t *convert_to_fs(const char *name, wchar_t *utf16_buf, size_t buflen)
{
int len = MultiByteToWideChar(CP_UTF8, 0, name, -1, utf16_buf, (int)buflen);
if (len == 0) {
DEBUG(misc, 0, "[utf8] M2W error converting '%s'. Errno %d", name, GetLastError());
utf16_buf[0] = '\0';
}
return utf16_buf;
}
/** Our very own SHGetFolderPath function for support of windows operating
* systems that don't have this function (eg Win9x, etc.). We try using the
* native function, and if that doesn't exist we will try a more crude approach
* of environment variables and hope for the best */
HRESULT OTTDSHGetFolderPath(HWND hwnd, int csidl, HANDLE hToken, DWORD dwFlags, LPTSTR pszPath)
{
static HRESULT (WINAPI *SHGetFolderPath)(HWND, int, HANDLE, DWORD, LPTSTR) = NULL;
static bool first_time = true;
/* We only try to load the library one time; if it fails, it fails */
if (first_time) {
#if defined(UNICODE)
# define W(x) x "W"
#else
# define W(x) x "A"
#endif
if (!LoadLibraryList((Function*)&SHGetFolderPath, "SHFolder.dll\0" W("SHGetFolderPath") "\0\0")) {
DEBUG(misc, 0, "Unable to load " W("SHGetFolderPath") "from SHFolder.dll");
}
#undef W
first_time = false;
}
if (SHGetFolderPath != NULL) return SHGetFolderPath(hwnd, csidl, hToken, dwFlags, pszPath);
/* SHGetFolderPath doesn't exist, try a more conservative approach,
* eg environment variables. This is only included for legacy modes
* MSDN says: that 'pszPath' is a "Pointer to a null-terminated string of
* length MAX_PATH which will receive the path" so let's assume that
* Windows 95 with Internet Explorer 5.0, Windows 98 with Internet Explorer 5.0,
* Windows 98 Second Edition (SE), Windows NT 4.0 with Internet Explorer 5.0,
* Windows NT 4.0 with Service Pack 4 (SP4) */
{
DWORD ret;
switch (csidl) {
case CSIDL_FONTS: // Get the system font path, eg %WINDIR%\Fonts
ret = GetEnvironmentVariable(_T("WINDIR"), pszPath, MAX_PATH);
if (ret == 0) break;
_tcsncat(pszPath, _T("\\Fonts"), MAX_PATH);
return (HRESULT)0;
break;
/* XXX - other types to go here when needed... */
}
}
return E_INVALIDARG;
}
/** Determine the current user's locale. */
const char *GetCurrentLocale(const char *)
{
char lang[9], country[9];
if (GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_SISO639LANGNAME, lang, lengthof(lang)) == 0 ||
GetLocaleInfoA(LOCALE_USER_DEFAULT, LOCALE_SISO3166CTRYNAME, country, lengthof(country)) == 0) {
/* Unable to retrieve the locale. */
return NULL;
}
/* Format it as 'en_us'. */
static char retbuf[6] = {lang[0], lang[1], '_', country[0], country[1], 0};
return retbuf;
}
| 38,815
|
C++
|
.cpp
| 1,163
| 30.871023
| 155
| 0.694958
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,161
|
vehicle_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/vehicle_gui.cpp
|
/* $Id$ */
/** @file vehicle_gui.cpp The base GUI for all vehicles. */
#include "stdafx.h"
#include "openttd.h"
#include "debug.h"
#include "company_func.h"
#include "gui.h"
#include "window_gui.h"
#include "textbuf_gui.h"
#include "command_func.h"
#include "vehicle_gui.h"
#include "vehicle_gui_base.h"
#include "viewport_func.h"
#include "gfx_func.h"
#include "newgrf_engine.h"
#include "newgrf_text.h"
#include "station_map.h"
#include "roadveh.h"
#include "depot_base.h"
#include "group_gui.h"
#include "strings_func.h"
#include "window_func.h"
#include "vehicle_func.h"
#include "autoreplace_gui.h"
#include "string_func.h"
#include "widgets/dropdown_func.h"
#include "timetable.h"
#include "vehiclelist.h"
#include "settings_type.h"
#include "articulated_vehicles.h"
#include "table/sprites.h"
#include "table/strings.h"
Sorting _sorting;
static GUIVehicleList::SortFunction VehicleNumberSorter;
static GUIVehicleList::SortFunction VehicleNameSorter;
static GUIVehicleList::SortFunction VehicleAgeSorter;
static GUIVehicleList::SortFunction VehicleProfitThisYearSorter;
static GUIVehicleList::SortFunction VehicleProfitLastYearSorter;
static GUIVehicleList::SortFunction VehicleCargoSorter;
static GUIVehicleList::SortFunction VehicleReliabilitySorter;
static GUIVehicleList::SortFunction VehicleMaxSpeedSorter;
static GUIVehicleList::SortFunction VehicleModelSorter;
static GUIVehicleList::SortFunction VehicleValueSorter;
static GUIVehicleList::SortFunction VehicleLengthSorter;
static GUIVehicleList::SortFunction VehicleTimeToLiveSorter;
GUIVehicleList::SortFunction * const BaseVehicleListWindow::vehicle_sorter_funcs[] = {
&VehicleNumberSorter,
&VehicleNameSorter,
&VehicleAgeSorter,
&VehicleProfitThisYearSorter,
&VehicleProfitLastYearSorter,
&VehicleCargoSorter,
&VehicleReliabilitySorter,
&VehicleMaxSpeedSorter,
&VehicleModelSorter,
&VehicleValueSorter,
&VehicleLengthSorter,
&VehicleTimeToLiveSorter,
};
const StringID BaseVehicleListWindow::vehicle_sorter_names[] = {
STR_SORT_BY_NUMBER,
STR_SORT_BY_DROPDOWN_NAME,
STR_SORT_BY_AGE,
STR_SORT_BY_PROFIT_THIS_YEAR,
STR_SORT_BY_PROFIT_LAST_YEAR,
STR_SORT_BY_TOTAL_CAPACITY_PER_CARGOTYPE,
STR_SORT_BY_RELIABILITY,
STR_SORT_BY_MAX_SPEED,
STR_SORT_BY_MODEL,
STR_SORT_BY_VALUE,
STR_SORT_BY_LENGTH,
STR_SORT_BY_LIFE_TIME,
INVALID_STRING_ID
};
void BaseVehicleListWindow::BuildVehicleList(Owner owner, uint16 index, uint16 window_type)
{
if (!this->vehicles.NeedRebuild()) return;
DEBUG(misc, 3, "Building vehicle list for company %d at station %d", owner, index);
GenerateVehicleSortList(&this->vehicles, this->vehicle_type, owner, index, window_type);
this->vehicles.RebuildDone();
}
/* cached values for VehicleNameSorter to spare many GetString() calls */
static const Vehicle *_last_vehicle[2] = { NULL, NULL };
void BaseVehicleListWindow::SortVehicleList()
{
if (this->vehicles.Sort()) return;
/* invalidate cached values for name sorter - vehicle names could change */
_last_vehicle[0] = _last_vehicle[1] = NULL;
}
void DepotSortList(VehicleList *list)
{
if (list->Length() < 2) return;
QSortT(list->Begin(), list->Length(), &VehicleNumberSorter);
}
/** draw the vehicle profit button in the vehicle list window. */
void DrawVehicleProfitButton(const Vehicle *v, int x, int y)
{
SpriteID pal;
/* draw profit-based coloured icons */
if (v->age <= DAYS_IN_YEAR * 2) {
pal = PALETTE_TO_GREY;
} else if (v->GetDisplayProfitLastYear() < 0) {
pal = PALETTE_TO_RED;
} else if (v->GetDisplayProfitLastYear() < 10000) {
pal = PALETTE_TO_YELLOW;
} else {
pal = PALETTE_TO_GREEN;
}
DrawSprite(SPR_BLOT, pal, x, y);
}
struct RefitOption {
CargoID cargo;
byte subtype;
uint16 value;
EngineID engine;
};
struct RefitList {
uint num_lines;
RefitOption *items;
};
static RefitList *BuildRefitList(const Vehicle *v)
{
uint max_lines = 256;
RefitOption *refit = CallocT<RefitOption>(max_lines);
RefitList *list = CallocT<RefitList>(1);
Vehicle *u = (Vehicle*)v;
uint num_lines = 0;
uint i;
do {
uint32 cmask = EngInfo(u->engine_type)->refit_mask;
byte callbackmask = EngInfo(u->engine_type)->callbackmask;
/* Skip this engine if it has no capacity */
if (u->cargo_cap == 0) continue;
/* Loop through all cargos in the refit mask */
for (CargoID cid = 0; cid < NUM_CARGO && num_lines < max_lines; cid++) {
/* Skip cargo type if it's not listed */
if (!HasBit(cmask, cid)) continue;
/* Check the vehicle's callback mask for cargo suffixes */
if (HasBit(callbackmask, CBM_VEHICLE_CARGO_SUFFIX)) {
/* Make a note of the original cargo type. It has to be
* changed to test the cargo & subtype... */
CargoID temp_cargo = u->cargo_type;
byte temp_subtype = u->cargo_subtype;
byte refit_cyc;
u->cargo_type = cid;
for (refit_cyc = 0; refit_cyc < 16 && num_lines < max_lines; refit_cyc++) {
bool duplicate = false;
uint16 callback;
u->cargo_subtype = refit_cyc;
callback = GetVehicleCallback(CBID_VEHICLE_CARGO_SUFFIX, 0, 0, u->engine_type, u);
if (callback == 0xFF) callback = CALLBACK_FAILED;
if (refit_cyc != 0 && callback == CALLBACK_FAILED) break;
/* Check if this cargo and subtype combination are listed */
for (i = 0; i < num_lines && !duplicate; i++) {
if (refit[i].cargo == cid && refit[i].value == callback) duplicate = true;
}
if (duplicate) continue;
refit[num_lines].cargo = cid;
refit[num_lines].subtype = refit_cyc;
refit[num_lines].value = callback;
refit[num_lines].engine = u->engine_type;
num_lines++;
}
/* Reset the vehicle's cargo type */
u->cargo_type = temp_cargo;
u->cargo_subtype = temp_subtype;
} else {
/* No cargo suffix callback -- use no subtype */
bool duplicate = false;
for (i = 0; i < num_lines && !duplicate; i++) {
if (refit[i].cargo == cid && refit[i].value == CALLBACK_FAILED) duplicate = true;
}
if (!duplicate) {
refit[num_lines].cargo = cid;
refit[num_lines].subtype = 0;
refit[num_lines].value = CALLBACK_FAILED;
refit[num_lines].engine = INVALID_ENGINE;
num_lines++;
}
}
}
} while ((v->type == VEH_TRAIN || v->type == VEH_ROAD) && (u = u->Next()) != NULL && num_lines < max_lines);
list->num_lines = num_lines;
list->items = refit;
return list;
}
/** Draw the list of available refit options for a consist.
* Draw the list and highlight the selected refit option (if any)
* @param *list first vehicle in consist to get the refit-options of
* @param sel selected refit cargo-type in the window
* @param pos position of the selected item in caller widow
* @param rows number of rows(capacity) in caller window
* @param delta step height in caller window
* @return the refit option that is hightlighted, NULL if none
*/
static RefitOption *DrawVehicleRefitWindow(const RefitList *list, int sel, uint pos, uint rows, uint delta)
{
RefitOption *refit = list->items;
RefitOption *selected = NULL;
uint num_lines = list->num_lines;
uint y = 31;
uint i;
/* Draw the list, and find the selected cargo (by its position in list) */
for (i = 0; i < num_lines; i++) {
TextColour colour = TC_BLACK;
if (sel == 0) {
selected = &refit[i];
colour = TC_WHITE;
}
if (i >= pos && i < pos + rows) {
/* Draw the cargo name */
int last_x = DrawString(2, y, GetCargo(refit[i].cargo)->name, colour);
/* If the callback succeeded, draw the cargo suffix */
if (refit[i].value != CALLBACK_FAILED) {
DrawString(last_x + 1, y, GetGRFStringID(GetEngineGRFID(refit[i].engine), 0xD000 + refit[i].value), colour);
}
y += delta;
}
sel--;
}
return selected;
}
struct RefitWindow : public Window {
int sel;
RefitOption *cargo;
RefitList *list;
uint length;
VehicleOrderID order;
RefitWindow(const WindowDesc *desc, const Vehicle *v, VehicleOrderID order) : Window(desc, v->index)
{
this->owner = v->owner;
this->vscroll.cap = 8;
this->resize.step_height = 14;
this->order = order;
this->sel = -1;
this->list = BuildRefitList(v);
if (v->type == VEH_TRAIN) this->length = CountVehiclesInChain(v);
SetVScrollCount(this, this->list->num_lines);
switch (v->type) {
case VEH_TRAIN:
this->widget[3].tooltips = STR_RAIL_SELECT_TYPE_OF_CARGO_FOR;
this->widget[6].data = STR_RAIL_REFIT_VEHICLE;
this->widget[6].tooltips = STR_RAIL_REFIT_TO_CARRY_HIGHLIGHTED;
break;
case VEH_ROAD:
this->widget[3].tooltips = STR_ROAD_SELECT_TYPE_OF_CARGO_FOR;
this->widget[6].data = STR_REFIT_ROAD_VEHICLE;
this->widget[6].tooltips = STR_REFIT_ROAD_VEHICLE_TO_CARRY_HIGHLIGHTED;
break;
case VEH_SHIP:
this->widget[3].tooltips = STR_983D_SELECT_TYPE_OF_CARGO_FOR;
this->widget[6].data = STR_983C_REFIT_SHIP;
this->widget[6].tooltips = STR_983E_REFIT_SHIP_TO_CARRY_HIGHLIGHTED;
break;
case VEH_AIRCRAFT:
this->widget[3].tooltips = STR_A03E_SELECT_TYPE_OF_CARGO_FOR;
this->widget[6].data = STR_A03D_REFIT_AIRCRAFT;
this->widget[6].tooltips = STR_A03F_REFIT_AIRCRAFT_TO_CARRY;
break;
default: NOT_REACHED();
}
this->FindWindowPlacementAndResize(desc);
}
~RefitWindow()
{
free(this->list->items);
free(this->list);
}
virtual void OnPaint()
{
Vehicle *v = GetVehicle(this->window_number);
if (v->type == VEH_TRAIN) {
uint length = CountVehiclesInChain(v);
if (length != this->length) {
/* Consist length has changed, so rebuild the refit list */
free(this->list->items);
free(this->list);
this->list = BuildRefitList(v);
this->length = length;
}
}
SetVScrollCount(this, this->list->num_lines);
SetDParam(0, v->index);
this->DrawWidgets();
this->cargo = DrawVehicleRefitWindow(this->list, this->sel, this->vscroll.pos, this->vscroll.cap, this->resize.step_height);
if (this->cargo != NULL) {
CommandCost cost;
cost = DoCommand(v->tile, v->index, this->cargo->cargo | this->cargo->subtype << 8,
DC_QUERY_COST, GetCmdRefitVeh(v->type));
if (CmdSucceeded(cost)) {
SetDParam(0, this->cargo->cargo);
SetDParam(1, _returned_refit_capacity);
SetDParam(2, cost.GetCost());
DrawString(2, this->widget[5].top + 1, STR_9840_NEW_CAPACITY_COST_OF_REFIT, TC_FROMSTRING);
}
}
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case 3: { // listbox
int y = pt.y - this->widget[3].top;
if (y >= 0) {
this->sel = (y / (int)this->resize.step_height) + this->vscroll.pos;
this->SetDirty();
}
break;
}
case 6: // refit button
if (this->cargo != NULL) {
const Vehicle *v = GetVehicle(this->window_number);
if (this->order == INVALID_VEH_ORDER_ID) {
int command = 0;
switch (v->type) {
default: NOT_REACHED();
case VEH_TRAIN: command = CMD_REFIT_RAIL_VEHICLE | CMD_MSG(STR_RAIL_CAN_T_REFIT_VEHICLE); break;
case VEH_ROAD: command = CMD_REFIT_ROAD_VEH | CMD_MSG(STR_REFIT_ROAD_VEHICLE_CAN_T); break;
case VEH_SHIP: command = CMD_REFIT_SHIP | CMD_MSG(STR_9841_CAN_T_REFIT_SHIP); break;
case VEH_AIRCRAFT: command = CMD_REFIT_AIRCRAFT | CMD_MSG(STR_A042_CAN_T_REFIT_AIRCRAFT); break;
}
if (DoCommandP(v->tile, v->index, this->cargo->cargo | this->cargo->subtype << 8, command)) delete this;
} else {
if (DoCommandP(v->tile, v->index, this->cargo->cargo | this->cargo->subtype << 8 | this->order << 16, CMD_ORDER_REFIT)) delete this;
}
}
break;
}
}
virtual void OnResize(Point new_size, Point delta)
{
this->vscroll.cap += delta.y / (int)this->resize.step_height;
this->widget[3].data = (this->vscroll.cap << 8) + 1;
}
};
static const Widget _vehicle_refit_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 11, 239, 0, 13, STR_983B_REFIT, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 0, 239, 14, 27, STR_983F_SELECT_CARGO_TYPE_TO_CARRY, STR_983D_SELECT_TYPE_OF_CARGO_FOR},
{ WWT_MATRIX, RESIZE_BOTTOM, COLOUR_GREY, 0, 227, 28, 139, 0x801, STR_EMPTY},
{ WWT_SCROLLBAR, RESIZE_BOTTOM, COLOUR_GREY, 228, 239, 28, 139, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST},
{ WWT_PANEL, RESIZE_TB, COLOUR_GREY, 0, 239, 140, 161, 0x0, STR_NULL},
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 0, 227, 162, 173, 0x0, STR_NULL},
{ WWT_RESIZEBOX, RESIZE_TB, COLOUR_GREY, 228, 239, 162, 173, 0x0, STR_RESIZE_BUTTON},
{ WIDGETS_END},
};
static const WindowDesc _vehicle_refit_desc(
WDP_AUTO, WDP_AUTO, 240, 174, 240, 174,
WC_VEHICLE_REFIT, WC_VEHICLE_VIEW,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_RESIZABLE | WDF_CONSTRUCTION,
_vehicle_refit_widgets
);
/** Show the refit window for a vehicle
* @param *v The vehicle to show the refit window for
* @param order of the vehicle ( ? )
*/
void ShowVehicleRefitWindow(const Vehicle *v, VehicleOrderID order, Window *parent)
{
DeleteWindowById(WC_VEHICLE_REFIT, v->index);
RefitWindow *w = new RefitWindow(&_vehicle_refit_desc, v, order);
w->parent = parent;
}
/** Display additional text from NewGRF in the purchase information window */
uint ShowAdditionalText(int x, int y, uint w, EngineID engine)
{
uint16 callback = GetVehicleCallback(CBID_VEHICLE_ADDITIONAL_TEXT, 0, 0, engine, NULL);
if (callback == CALLBACK_FAILED) return 0;
/* STR_02BD is used to start the string with {BLACK} */
SetDParam(0, GetGRFStringID(GetEngineGRFID(engine), 0xD000 + callback));
PrepareTextRefStackUsage(0);
uint result = DrawStringMultiLine(x, y, STR_02BD, w);
StopTextRefStackUsage();
return result;
}
/** Display list of cargo types of the engine, for the purchase information window */
uint ShowRefitOptionsList(int x, int y, uint w, EngineID engine)
{
/* List of cargo types of this engine */
uint32 cmask = GetUnionOfArticulatedRefitMasks(engine, GetEngine(engine)->type, false);
/* List of cargo types available in this climate */
uint32 lmask = _cargo_mask;
char string[512];
char *b = string;
/* Draw nothing if the engine is not refittable */
if (CountBits(cmask) <= 1) return 0;
b = InlineString(b, STR_PURCHASE_INFO_REFITTABLE_TO);
if (cmask == lmask) {
/* Engine can be refitted to all types in this climate */
b = InlineString(b, STR_PURCHASE_INFO_ALL_TYPES);
} else {
/* Check if we are able to refit to more cargo types and unable to. If
* so, invert the cargo types to list those that we can't refit to. */
if (CountBits(cmask ^ lmask) < CountBits(cmask)) {
cmask ^= lmask;
b = InlineString(b, STR_PURCHASE_INFO_ALL_BUT);
}
bool first = true;
/* Add each cargo type to the list */
for (CargoID cid = 0; cid < NUM_CARGO; cid++) {
if (!HasBit(cmask, cid)) continue;
if (b >= lastof(string) - (2 + 2 * 4)) break; // ", " and two calls to Utf8Encode()
if (!first) b = strecpy(b, ", ", lastof(string));
first = false;
b = InlineString(b, GetCargo(cid)->name);
}
}
/* Terminate and display the completed string */
*b = '\0';
/* Make sure we detect any buffer overflow */
assert(b < endof(string));
SetDParamStr(0, string);
return DrawStringMultiLine(x, y, STR_JUST_RAW_STRING, w);
}
/** Get the cargo subtype text from NewGRF for the vehicle details window. */
StringID GetCargoSubtypeText(const Vehicle *v)
{
if (HasBit(EngInfo(v->engine_type)->callbackmask, CBM_VEHICLE_CARGO_SUFFIX)) {
uint16 cb = GetVehicleCallback(CBID_VEHICLE_CARGO_SUFFIX, 0, 0, v->engine_type, v);
if (cb != CALLBACK_FAILED) {
return GetGRFStringID(GetEngineGRFID(v->engine_type), 0xD000 + cb);
}
}
return STR_EMPTY;
}
/** Sort vehicles by their number */
static int CDECL VehicleNumberSorter(const Vehicle * const *a, const Vehicle * const *b)
{
return (*a)->unitnumber - (*b)->unitnumber;
}
/** Sort vehicles by their name */
static int CDECL VehicleNameSorter(const Vehicle * const *a, const Vehicle * const *b)
{
static char last_name[2][64];
if (*a != _last_vehicle[0]) {
_last_vehicle[0] = *a;
SetDParam(0, (*a)->index);
GetString(last_name[0], STR_VEHICLE_NAME, lastof(last_name[0]));
}
if (*b != _last_vehicle[1]) {
_last_vehicle[1] = *b;
SetDParam(0, (*b)->index);
GetString(last_name[1], STR_VEHICLE_NAME, lastof(last_name[1]));
}
int r = strcmp(last_name[0], last_name[1]);
return (r != 0) ? r : VehicleNumberSorter(a, b);
}
/** Sort vehicles by their age */
static int CDECL VehicleAgeSorter(const Vehicle * const *a, const Vehicle * const *b)
{
int r = (*a)->age - (*b)->age;
return (r != 0) ? r : VehicleNumberSorter(a, b);
}
/** Sort vehicles by this year profit */
static int CDECL VehicleProfitThisYearSorter(const Vehicle * const *a, const Vehicle * const *b)
{
int r = ClampToI32((*a)->GetDisplayProfitThisYear() - (*b)->GetDisplayProfitThisYear());
return (r != 0) ? r : VehicleNumberSorter(a, b);
}
/** Sort vehicles by last year profit */
static int CDECL VehicleProfitLastYearSorter(const Vehicle * const *a, const Vehicle * const *b)
{
int r = ClampToI32((*a)->GetDisplayProfitLastYear() - (*b)->GetDisplayProfitLastYear());
return (r != 0) ? r : VehicleNumberSorter(a, b);
}
/** Sort vehicles by their cargo */
static int CDECL VehicleCargoSorter(const Vehicle * const *a, const Vehicle * const *b)
{
const Vehicle *v;
AcceptedCargo diff;
memset(diff, 0, sizeof(diff));
/* Append the cargo of the connected weagons */
for (v = *a; v != NULL; v = v->Next()) diff[v->cargo_type] += v->cargo_cap;
for (v = *b; v != NULL; v = v->Next()) diff[v->cargo_type] -= v->cargo_cap;
int r = 0;
for (CargoID i = 0; i < NUM_CARGO; i++) {
r = diff[i];
if (r != 0) break;
}
return (r != 0) ? r : VehicleNumberSorter(a, b);
}
/** Sort vehicles by their reliability */
static int CDECL VehicleReliabilitySorter(const Vehicle * const *a, const Vehicle * const *b)
{
int r = (*a)->reliability - (*b)->reliability;
return (r != 0) ? r : VehicleNumberSorter(a, b);
}
/** Sort vehicles by their max speed */
static int CDECL VehicleMaxSpeedSorter(const Vehicle * const *a, const Vehicle * const *b)
{
int r = 0;
if ((*a)->type == VEH_TRAIN && (*b)->type == VEH_TRAIN) {
r = (*a)->u.rail.cached_max_speed - (*b)->u.rail.cached_max_speed;
} else {
r = (*a)->max_speed - (*b)->max_speed;
}
return (r != 0) ? r : VehicleNumberSorter(a, b);
}
/** Sort vehicles by model */
static int CDECL VehicleModelSorter(const Vehicle * const *a, const Vehicle * const *b)
{
int r = (*a)->engine_type - (*b)->engine_type;
return (r != 0) ? r : VehicleNumberSorter(a, b);
}
/** Sort vehciles by their value */
static int CDECL VehicleValueSorter(const Vehicle * const *a, const Vehicle * const *b)
{
const Vehicle *u;
Money diff = 0;
for (u = *a; u != NULL; u = u->Next()) diff += u->value;
for (u = *b; u != NULL; u = u->Next()) diff -= u->value;
int r = ClampToI32(diff);
return (r != 0) ? r : VehicleNumberSorter(a, b);
}
/** Sort vehicles by their length */
static int CDECL VehicleLengthSorter(const Vehicle * const *a, const Vehicle * const *b)
{
int r = 0;
switch ((*a)->type) {
case VEH_TRAIN:
r = (*a)->u.rail.cached_total_length - (*b)->u.rail.cached_total_length;
break;
case VEH_ROAD: {
const Vehicle *u;
for (u = *a; u != NULL; u = u->Next()) r += u->u.road.cached_veh_length;
for (u = *b; u != NULL; u = u->Next()) r -= u->u.road.cached_veh_length;
} break;
default: NOT_REACHED();
}
return (r != 0) ? r : VehicleNumberSorter(a, b);
}
/** Sort vehicles by the time they can still live */
static int CDECL VehicleTimeToLiveSorter(const Vehicle * const *a, const Vehicle * const *b)
{
int r = ClampToI32(((*a)->max_age - (*a)->age) - ((*b)->max_age - (*b)->age));
return (r != 0) ? r : VehicleNumberSorter(a, b);
}
void InitializeGUI()
{
MemSetT(&_sorting, 0);
}
/**
* Assign a vehicle window a new vehicle
* @param window_class WindowClass to search for
* @param from_index the old vehicle ID
* @param to_index the new vehicle ID
*/
static inline void ChangeVehicleWindow(WindowClass window_class, VehicleID from_index, VehicleID to_index)
{
Window *w = FindWindowById(window_class, from_index);
if (w != NULL) {
w->window_number = to_index;
if (w->viewport != NULL) w->viewport->follow_vehicle = to_index;
if (to_index != INVALID_VEHICLE) InvalidateThisWindowData(w, 0);
}
}
/**
* Report a change in vehicle IDs (due to autoreplace) to affected vehicle windows.
* @param from_index the old vehicle ID
* @param to_index the new vehicle ID
*/
void ChangeVehicleViewWindow(VehicleID from_index, VehicleID to_index)
{
ChangeVehicleWindow(WC_VEHICLE_VIEW, from_index, to_index);
ChangeVehicleWindow(WC_VEHICLE_ORDERS, from_index, to_index);
ChangeVehicleWindow(WC_VEHICLE_REFIT, from_index, to_index);
ChangeVehicleWindow(WC_VEHICLE_DETAILS, from_index, to_index);
ChangeVehicleWindow(WC_VEHICLE_TIMETABLE, from_index, to_index);
}
enum VehicleListWindowWidgets {
VLW_WIDGET_CLOSEBOX = 0,
VLW_WIDGET_CAPTION,
VLW_WIDGET_STICKY,
VLW_WIDGET_SORT_ORDER,
VLW_WIDGET_SORT_BY_PULLDOWN,
VLW_WIDGET_EMPTY_TOP_RIGHT,
VLW_WIDGET_LIST,
VLW_WIDGET_SCROLLBAR,
VLW_WIDGET_OTHER_COMPANY_FILLER,
VLW_WIDGET_AVAILABLE_VEHICLES,
VLW_WIDGET_MANAGE_VEHICLES_DROPDOWN,
VLW_WIDGET_STOP_ALL,
VLW_WIDGET_START_ALL,
VLW_WIDGET_EMPTY_BOTTOM_RIGHT,
VLW_WIDGET_RESIZE,
};
static const Widget _vehicle_list_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_GREY, 11, 247, 0, 13, 0x0, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_STICKYBOX, RESIZE_LR, COLOUR_GREY, 248, 259, 0, 13, 0x0, STR_STICKY_BUTTON},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 0, 80, 14, 25, STR_SORT_BY, STR_SORT_ORDER_TIP},
{ WWT_DROPDOWN, RESIZE_NONE, COLOUR_GREY, 81, 247, 14, 25, 0x0, STR_SORT_CRITERIA_TIP},
{ WWT_PANEL, RESIZE_RIGHT, COLOUR_GREY, 248, 259, 14, 25, 0x0, STR_NULL},
{ WWT_MATRIX, RESIZE_RB, COLOUR_GREY, 0, 247, 26, 181, 0x0, STR_NULL},
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_GREY, 248, 259, 26, 181, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST},
/* Widget to be shown for other companies hiding the following 6 widgets */
{ WWT_PANEL, RESIZE_RTB, COLOUR_GREY, 0, 247, 182, 193, 0x0, STR_NULL},
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 0, 105, 182, 193, 0x0, STR_AVAILABLE_ENGINES_TIP},
{ WWT_DROPDOWN, RESIZE_TB, COLOUR_GREY, 106, 223, 182, 193, STR_MANAGE_LIST, STR_MANAGE_LIST_TIP},
{ WWT_PUSHIMGBTN, RESIZE_TB, COLOUR_GREY, 224, 235, 182, 193, SPR_FLAG_VEH_STOPPED, STR_MASS_STOP_LIST_TIP},
{ WWT_PUSHIMGBTN, RESIZE_TB, COLOUR_GREY, 236, 247, 182, 193, SPR_FLAG_VEH_RUNNING, STR_MASS_START_LIST_TIP},
{ WWT_PANEL, RESIZE_RTB, COLOUR_GREY, 248, 247, 182, 193, 0x0, STR_NULL},
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_GREY, 248, 259, 182, 193, 0x0, STR_RESIZE_BUTTON},
{ WIDGETS_END},
};
static void DrawSmallOrderList(const Vehicle *v, int x, int y)
{
const Order *order;
int sel, i = 0;
sel = v->cur_order_index;
FOR_VEHICLE_ORDERS(v, order) {
if (sel == 0) DrawString(x - 6, y, STR_SMALL_RIGHT_ARROW, TC_BLACK);
sel--;
if (order->IsType(OT_GOTO_STATION)) {
if (v->type == VEH_SHIP && GetStation(order->GetDestination())->IsBuoy()) continue;
SetDParam(0, order->GetDestination());
DrawString(x, y, STR_A036, TC_FROMSTRING);
y += 6;
if (++i == 4) break;
}
}
}
static void DrawVehicleImage(const Vehicle *v, int x, int y, VehicleID selection, int count, int skip)
{
switch (v->type) {
case VEH_TRAIN: DrawTrainImage(v, x, y, selection, count, skip); break;
case VEH_ROAD: DrawRoadVehImage(v, x, y, selection, count); break;
case VEH_SHIP: DrawShipImage(v, x, y, selection); break;
case VEH_AIRCRAFT: DrawAircraftImage(v, x, y, selection); break;
default: NOT_REACHED();
}
}
/**
* Draw all the vehicle list items.
* @param x the position from where to draw the items.
* @param selected_vehicle the vehicle that is to be selected
*/
void BaseVehicleListWindow::DrawVehicleListItems(int x, VehicleID selected_vehicle)
{
int y = PLY_WND_PRC__OFFSET_TOP_WIDGET;
uint max = min(this->vscroll.pos + this->vscroll.cap, this->vehicles.Length());
for (uint i = this->vscroll.pos; i < max; ++i) {
const Vehicle *v = this->vehicles[i];
StringID str;
SetDParam(0, v->GetDisplayProfitThisYear());
SetDParam(1, v->GetDisplayProfitLastYear());
DrawVehicleImage(v, x + 19, y + 6, selected_vehicle, this->widget[VLW_WIDGET_LIST].right - this->widget[VLW_WIDGET_LIST].left - 20, 0);
DrawString(x + 19, y + this->resize.step_height - 8, STR_0198_PROFIT_THIS_YEAR_LAST_YEAR, TC_FROMSTRING);
if (v->name != NULL) {
/* The vehicle got a name so we will print it */
SetDParam(0, v->index);
DrawString(x + 19, y, STR_01AB, TC_FROMSTRING);
} else if (v->group_id != DEFAULT_GROUP) {
/* The vehicle has no name, but is member of a group, so print group name */
SetDParam(0, v->group_id);
DrawString(x + 19, y, STR_GROUP_TINY_NAME, TC_BLACK);
}
if (this->resize.step_height == PLY_WND_PRC__SIZE_OF_ROW_BIG) DrawSmallOrderList(v, x + 138, y);
if (v->IsInDepot()) {
str = STR_021F;
} else {
str = (v->age > v->max_age - DAYS_IN_LEAP_YEAR) ? STR_00E3 : STR_00E2;
}
SetDParam(0, v->unitnumber);
DrawString(x, y + 2, str, TC_FROMSTRING);
DrawVehicleProfitButton(v, x, y + 13);
y += this->resize.step_height;
}
}
/**
* Window for the (old) vehicle listing.
*
* bitmask for w->window_number
* 0-7 CompanyID (owner)
* 8-10 window type (use flags in vehicle_gui.h)
* 11-15 vehicle type (using VEH_, but can be compressed to fewer bytes if needed)
* 16-31 StationID or OrderID depending on window type (bit 8-10)
*/
struct VehicleListWindow : public BaseVehicleListWindow {
VehicleListWindow(const WindowDesc *desc, WindowNumber window_number) : BaseVehicleListWindow(desc, window_number)
{
uint16 window_type = this->window_number & VLW_MASK;
CompanyID company = (CompanyID)GB(this->window_number, 0, 8);
this->vehicle_type = (VehicleType)GB(this->window_number, 11, 5);
this->owner = company;
/* Hide the widgets that we will not use in this window
* Some windows contains actions only fit for the owner */
if (company == _local_company) {
this->HideWidget(VLW_WIDGET_OTHER_COMPANY_FILLER);
this->SetWidgetDisabledState(VLW_WIDGET_AVAILABLE_VEHICLES, window_type != VLW_STANDARD);
} else {
this->SetWidgetsHiddenState(true,
VLW_WIDGET_AVAILABLE_VEHICLES,
VLW_WIDGET_MANAGE_VEHICLES_DROPDOWN,
VLW_WIDGET_STOP_ALL,
VLW_WIDGET_START_ALL,
VLW_WIDGET_EMPTY_BOTTOM_RIGHT,
WIDGET_LIST_END);
}
/* Set up the window widgets */
switch (this->vehicle_type) {
case VEH_TRAIN:
this->widget[VLW_WIDGET_LIST].tooltips = STR_883D_TRAINS_CLICK_ON_TRAIN_FOR;
this->widget[VLW_WIDGET_AVAILABLE_VEHICLES].data = STR_AVAILABLE_TRAINS;
break;
case VEH_ROAD:
this->widget[VLW_WIDGET_LIST].tooltips = STR_901A_ROAD_VEHICLES_CLICK_ON;
this->widget[VLW_WIDGET_AVAILABLE_VEHICLES].data = STR_AVAILABLE_ROAD_VEHICLES;
break;
case VEH_SHIP:
this->widget[VLW_WIDGET_LIST].tooltips = STR_9823_SHIPS_CLICK_ON_SHIP_FOR;
this->widget[VLW_WIDGET_AVAILABLE_VEHICLES].data = STR_AVAILABLE_SHIPS;
break;
case VEH_AIRCRAFT:
this->widget[VLW_WIDGET_LIST].tooltips = STR_A01F_AIRCRAFT_CLICK_ON_AIRCRAFT;
this->widget[VLW_WIDGET_AVAILABLE_VEHICLES].data = STR_AVAILABLE_AIRCRAFT;
break;
default: NOT_REACHED();
}
switch (window_type) {
case VLW_SHARED_ORDERS:
this->widget[VLW_WIDGET_CAPTION].data = STR_VEH_WITH_SHARED_ORDERS_LIST;
break;
case VLW_STANDARD: // Company Name - standard widget setup
switch (this->vehicle_type) {
case VEH_TRAIN: this->widget[VLW_WIDGET_CAPTION].data = STR_881B_TRAINS; break;
case VEH_ROAD: this->widget[VLW_WIDGET_CAPTION].data = STR_9001_ROAD_VEHICLES; break;
case VEH_SHIP: this->widget[VLW_WIDGET_CAPTION].data = STR_9805_SHIPS; break;
case VEH_AIRCRAFT: this->widget[VLW_WIDGET_CAPTION].data = STR_A009_AIRCRAFT; break;
default: NOT_REACHED(); break;
}
break;
case VLW_WAYPOINT_LIST:
this->widget[VLW_WIDGET_CAPTION].data = STR_WAYPOINT_VIEWPORT_LIST;
break;
case VLW_STATION_LIST: // Station Name
switch (this->vehicle_type) {
case VEH_TRAIN: this->widget[VLW_WIDGET_CAPTION].data = STR_SCHEDULED_TRAINS; break;
case VEH_ROAD: this->widget[VLW_WIDGET_CAPTION].data = STR_SCHEDULED_ROAD_VEHICLES; break;
case VEH_SHIP: this->widget[VLW_WIDGET_CAPTION].data = STR_SCHEDULED_SHIPS; break;
case VEH_AIRCRAFT: this->widget[VLW_WIDGET_CAPTION].data = STR_SCHEDULED_AIRCRAFT; break;
default: NOT_REACHED(); break;
}
break;
case VLW_DEPOT_LIST:
switch (this->vehicle_type) {
case VEH_TRAIN: this->widget[VLW_WIDGET_CAPTION].data = STR_VEHICLE_LIST_TRAIN_DEPOT; break;
case VEH_ROAD: this->widget[VLW_WIDGET_CAPTION].data = STR_VEHICLE_LIST_ROADVEH_DEPOT; break;
case VEH_SHIP: this->widget[VLW_WIDGET_CAPTION].data = STR_VEHICLE_LIST_SHIP_DEPOT; break;
case VEH_AIRCRAFT: this->widget[VLW_WIDGET_CAPTION].data = STR_VEHICLE_LIST_AIRCRAFT_DEPOT; break;
default: NOT_REACHED(); break;
}
break;
default: NOT_REACHED(); break;
}
switch (this->vehicle_type) {
case VEH_TRAIN:
this->resize.step_width = 1;
/* Fallthrough */
case VEH_ROAD:
this->vscroll.cap = 6;
this->resize.step_height = PLY_WND_PRC__SIZE_OF_ROW_SMALL;
break;
case VEH_SHIP:
case VEH_AIRCRAFT:
this->vscroll.cap = 4;
this->resize.step_height = PLY_WND_PRC__SIZE_OF_ROW_BIG;
break;
default: NOT_REACHED();
}
this->widget[VLW_WIDGET_LIST].data = (this->vscroll.cap << 8) + 1;
/* Set up sorting. Make the window-specific _sorting variable
* point to the correct global _sorting struct so we are freed
* from having conditionals during window operation */
switch (this->vehicle_type) {
case VEH_TRAIN: this->sorting = &_sorting.train; break;
case VEH_ROAD: this->sorting = &_sorting.roadveh; break;
case VEH_SHIP: this->sorting = &_sorting.ship; break;
case VEH_AIRCRAFT: this->sorting = &_sorting.aircraft; break;
default: NOT_REACHED(); break;
}
this->vehicles.SetListing(*this->sorting);
this->vehicles.ForceRebuild();
this->vehicles.NeedResort();
this->FindWindowPlacementAndResize(desc);
if (this->vehicle_type == VEH_TRAIN) ResizeWindow(this, 65, 0);
}
~VehicleListWindow()
{
*this->sorting = this->vehicles.GetListing();
}
virtual void OnPaint()
{
int x = 2;
const Owner owner = this->owner;
const uint16 window_type = this->window_number & VLW_MASK;
const uint16 index = GB(this->window_number, 16, 16);
this->BuildVehicleList(owner, index, window_type);
this->SortVehicleList();
SetVScrollCount(this, this->vehicles.Length());
if (this->vehicles.Length() == 0) HideDropDownMenu(this);
/* draw the widgets */
switch (window_type) {
case VLW_SHARED_ORDERS: // Shared Orders
if (this->vehicles.Length() == 0) {
/* We can't open this window without vehicles using this order
* and we should close the window when deleting the order */
NOT_REACHED();
}
SetDParam(0, this->vscroll.count);
break;
case VLW_STANDARD: // Company Name
SetDParam(0, owner);
SetDParam(1, this->vscroll.count);
break;
case VLW_WAYPOINT_LIST:
SetDParam(0, index);
SetDParam(1, this->vscroll.count);
break;
case VLW_STATION_LIST: // Station Name
SetDParam(0, index);
SetDParam(1, this->vscroll.count);
break;
case VLW_DEPOT_LIST:
switch (this->vehicle_type) {
case VEH_TRAIN: SetDParam(0, STR_8800_TRAIN_DEPOT); break;
case VEH_ROAD: SetDParam(0, STR_9003_ROAD_VEHICLE_DEPOT); break;
case VEH_SHIP: SetDParam(0, STR_9803_SHIP_DEPOT); break;
case VEH_AIRCRAFT: SetDParam(0, STR_A002_AIRCRAFT_HANGAR); break;
default: NOT_REACHED(); break;
}
if (this->vehicle_type == VEH_AIRCRAFT) {
SetDParam(1, index); // Airport name
} else {
SetDParam(1, GetDepot(index)->town_index);
}
SetDParam(2, this->vscroll.count);
break;
default: NOT_REACHED(); break;
}
this->SetWidgetsDisabledState(this->vehicles.Length() == 0,
VLW_WIDGET_MANAGE_VEHICLES_DROPDOWN,
VLW_WIDGET_STOP_ALL,
VLW_WIDGET_START_ALL,
WIDGET_LIST_END);
this->DrawWidgets();
/* draw sorting criteria string */
DrawString(85, 15, this->vehicle_sorter_names[this->vehicles.SortType()], TC_BLACK);
/* draw arrow pointing up/down for ascending/descending sorting */
this->DrawSortButtonState(VLW_WIDGET_SORT_ORDER, this->vehicles.IsDescSortOrder() ? SBS_DOWN : SBS_UP);
this->DrawVehicleListItems(x, INVALID_VEHICLE);
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case VLW_WIDGET_SORT_ORDER: // Flip sorting method ascending/descending
this->vehicles.ToggleSortOrder();
this->SetDirty();
break;
case VLW_WIDGET_SORT_BY_PULLDOWN:// Select sorting criteria dropdown menu
ShowDropDownMenu(this, this->vehicle_sorter_names, this->vehicles.SortType(), VLW_WIDGET_SORT_BY_PULLDOWN, 0, (this->vehicle_type == VEH_TRAIN || this->vehicle_type == VEH_ROAD) ? 0 : (1 << 10));
return;
case VLW_WIDGET_LIST: { // Matrix to show vehicles
uint32 id_v = (pt.y - PLY_WND_PRC__OFFSET_TOP_WIDGET) / this->resize.step_height;
const Vehicle *v;
if (id_v >= this->vscroll.cap) return; // click out of bounds
id_v += this->vscroll.pos;
if (id_v >= this->vehicles.Length()) return; // click out of list bound
v = this->vehicles[id_v];
ShowVehicleViewWindow(v);
} break;
case VLW_WIDGET_AVAILABLE_VEHICLES:
ShowBuildVehicleWindow(INVALID_TILE, this->vehicle_type);
break;
case VLW_WIDGET_MANAGE_VEHICLES_DROPDOWN: {
static StringID action_str[] = {
STR_REPLACE_VEHICLES,
STR_SEND_FOR_SERVICING,
STR_NULL,
INVALID_STRING_ID
};
static const StringID depot_name[] = {
STR_SEND_TRAIN_TO_DEPOT,
STR_SEND_ROAD_VEHICLE_TO_DEPOT,
STR_SEND_SHIP_TO_DEPOT,
STR_SEND_AIRCRAFT_TO_HANGAR
};
/* XXX - Substite string since the dropdown cannot handle dynamic strings */
action_str[2] = depot_name[this->vehicle_type];
ShowDropDownMenu(this, action_str, 0, VLW_WIDGET_MANAGE_VEHICLES_DROPDOWN, 0, (this->window_number & VLW_MASK) == VLW_STANDARD ? 0 : 1);
break;
}
case VLW_WIDGET_STOP_ALL:
case VLW_WIDGET_START_ALL:
DoCommandP(0, GB(this->window_number, 16, 16), (this->window_number & VLW_MASK) | (1 << 6) | (widget == VLW_WIDGET_START_ALL ? (1 << 5) : 0) | this->vehicle_type, CMD_MASS_START_STOP);
break;
}
}
virtual void OnDropdownSelect(int widget, int index)
{
switch (widget) {
case VLW_WIDGET_SORT_BY_PULLDOWN:
this->vehicles.SetSortType(index);
break;
case VLW_WIDGET_MANAGE_VEHICLES_DROPDOWN:
assert(this->vehicles.Length() != 0);
switch (index) {
case 0: // Replace window
ShowReplaceGroupVehicleWindow(DEFAULT_GROUP, this->vehicle_type);
break;
case 1: // Send for servicing
DoCommandP(0, GB(this->window_number, 16, 16) /* StationID or OrderID (depending on VLW) */,
(this->window_number & VLW_MASK) | DEPOT_MASS_SEND | DEPOT_SERVICE,
GetCmdSendToDepot(this->vehicle_type));
break;
case 2: // Send to Depots
DoCommandP(0, GB(this->window_number, 16, 16) /* StationID or OrderID (depending on VLW) */,
(this->window_number & VLW_MASK) | DEPOT_MASS_SEND,
GetCmdSendToDepot(this->vehicle_type));
break;
default: NOT_REACHED();
}
break;
default: NOT_REACHED();
}
this->SetDirty();
}
virtual void OnTick()
{
if (_pause_game != 0) return;
if (this->vehicles.NeedResort()) {
StationID station = ((this->window_number & VLW_MASK) == VLW_STATION_LIST) ? GB(this->window_number, 16, 16) : INVALID_STATION;
DEBUG(misc, 3, "Periodic resort %d list company %d at station %d", this->vehicle_type, this->owner, station);
this->SetDirty();
}
}
virtual void OnResize(Point new_size, Point delta)
{
this->vscroll.cap += delta.y / (int)this->resize.step_height;
this->widget[VLW_WIDGET_LIST].data = (this->vscroll.cap << 8) + 1;
}
virtual void OnInvalidateData(int data)
{
if (HasBit(data, 15) && (this->window_number & VLW_MASK) == VLW_SHARED_ORDERS) {
SB(this->window_number, 16, 16, GB(data, 16, 16));
this->vehicles.ForceRebuild();
return;
}
if (data == 0) {
this->vehicles.ForceRebuild();
} else {
this->vehicles.ForceResort();
}
}
};
static WindowDesc _vehicle_list_desc(
WDP_AUTO, WDP_AUTO, 260, 194, 260, 246,
WC_INVALID, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
_vehicle_list_widgets
);
static void ShowVehicleListWindowLocal(CompanyID company, uint16 VLW_flag, VehicleType vehicle_type, uint16 unique_number)
{
if (!IsValidCompanyID(company)) return;
_vehicle_list_desc.cls = GetWindowClassForVehicleType(vehicle_type);
WindowNumber num = (unique_number << 16) | (vehicle_type << 11) | VLW_flag | company;
AllocateWindowDescFront<VehicleListWindow>(&_vehicle_list_desc, num);
}
void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type)
{
/* If _settings_client.gui.advanced_vehicle_list > 1, display the Advanced list
* if _settings_client.gui.advanced_vehicle_list == 1, display Advanced list only for local company
* if _ctrl_pressed, do the opposite action (Advanced list x Normal list)
*/
if ((_settings_client.gui.advanced_vehicle_list > (uint)(company != _local_company)) != _ctrl_pressed) {
ShowCompanyGroup(company, vehicle_type);
} else {
ShowVehicleListWindowLocal(company, VLW_STANDARD, vehicle_type, 0);
}
}
void ShowVehicleListWindow(const Waypoint *wp)
{
if (wp == NULL) return;
ShowVehicleListWindowLocal(wp->owner, VLW_WAYPOINT_LIST, VEH_TRAIN, wp->index);
}
void ShowVehicleListWindow(const Vehicle *v)
{
ShowVehicleListWindowLocal(v->owner, VLW_SHARED_ORDERS, v->type, v->FirstShared()->index);
}
void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, StationID station)
{
ShowVehicleListWindowLocal(company, VLW_STATION_LIST, vehicle_type, station);
}
void ShowVehicleListWindow(CompanyID company, VehicleType vehicle_type, TileIndex depot_tile)
{
uint16 depot_airport_index;
if (vehicle_type == VEH_AIRCRAFT) {
depot_airport_index = GetStationIndex(depot_tile);
} else {
Depot *depot = GetDepotByTile(depot_tile);
if (depot == NULL) return; // no depot to show
depot_airport_index = depot->index;
}
ShowVehicleListWindowLocal(company, VLW_DEPOT_LIST, vehicle_type, depot_airport_index);
}
/* Unified vehicle GUI - Vehicle Details Window */
/** Constants of vehicle details widget indices */
enum VehicleDetailsWindowWidgets {
VLD_WIDGET_CLOSEBOX = 0,
VLD_WIDGET_CAPTION,
VLD_WIDGET_RENAME_VEHICLE,
VLD_WIDGET_STICKY,
VLD_WIDGET_TOP_DETAILS,
VLD_WIDGET_INCREASE_SERVICING_INTERVAL,
VLD_WIDGET_DECREASE_SERVICING_INTERVAL,
VLD_WIDGET_BOTTOM_RIGHT,
VLD_WIDGET_MIDDLE_DETAILS,
VLD_WIDGET_SCROLLBAR,
VLD_WIDGET_DETAILS_CARGO_CARRIED,
VLD_WIDGET_DETAILS_TRAIN_VEHICLES,
VLD_WIDGET_DETAILS_CAPACITY_OF_EACH,
VLD_WIDGET_DETAILS_TOTAL_CARGO,
VLD_WIDGET_RESIZE,
};
/** Vehicle details widgets. */
static const Widget _vehicle_details_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // VLD_WIDGET_CLOSEBOX
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_GREY, 11, 352, 0, 13, 0x0, STR_018C_WINDOW_TITLE_DRAG_THIS}, // VLD_WIDGET_CAPTION
{ WWT_PUSHTXTBTN, RESIZE_LR, COLOUR_GREY, 353, 392, 0, 13, STR_01AA_NAME, STR_NULL /* filled in later */}, // VLD_WIDGET_RENAME_VEHICLE
{ WWT_STICKYBOX, RESIZE_LR, COLOUR_GREY, 393, 404, 0, 13, STR_NULL, STR_STICKY_BUTTON}, // VLD_WIDGET_STICKY
{ WWT_PANEL, RESIZE_RIGHT, COLOUR_GREY, 0, 404, 14, 55, 0x0, STR_NULL}, // VLD_WIDGET_TOP_DETAILS
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 0, 10, 101, 106, STR_0188, STR_884D_INCREASE_SERVICING_INTERVAL}, // VLD_WIDGET_INCREASE_SERVICING_INTERVAL
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 0, 10, 107, 112, STR_0189, STR_884E_DECREASE_SERVICING_INTERVAL}, // VLD_WIDGET_DECREASE_SERVICING_INTERVAL
{ WWT_PANEL, RESIZE_RTB, COLOUR_GREY, 11, 404, 101, 112, 0x0, STR_NULL}, // VLD_WIDGET_BOTTOM_RIGHT
{ WWT_MATRIX, RESIZE_RB, COLOUR_GREY, 0, 392, 56, 100, 0x701, STR_NULL}, // VLD_WIDGET_MIDDLE_DETAILS
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_GREY, 393, 404, 56, 100, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST}, // VLD_WIDGET_SCROLLBAR
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 0, 95, 113, 124, STR_013C_CARGO, STR_884F_SHOW_DETAILS_OF_CARGO_CARRIED}, // VLD_WIDGET_DETAILS_CARGO_CARRIED
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 96, 194, 113, 124, STR_013D_INFORMATION, STR_8850_SHOW_DETAILS_OF_TRAIN_VEHICLES},// VLD_WIDGET_DETAILS_TRAIN_VEHICLES
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_GREY, 195, 293, 113, 124, STR_013E_CAPACITIES, STR_8851_SHOW_CAPACITIES_OF_EACH}, // VLD_WIDGET_DETAILS_CAPACITY_OF_EACH
{ WWT_PUSHTXTBTN, RESIZE_RTB, COLOUR_GREY, 294, 392, 113, 124, STR_TOTAL_CARGO, STR_SHOW_TOTAL_CARGO}, // VLD_WIDGET_DETAILS_TOTAL_CARGO
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_GREY, 393, 404, 113, 124, 0x0, STR_RESIZE_BUTTON}, // VLD_RESIZE
{ WIDGETS_END},
};
/** Command indices for the _vehicle_command_translation_table. */
enum VehicleStringTranslation {
VST_VEHICLE_AGE_RUNNING_COST_YR,
VST_VEHICLE_MAX_SPEED,
VST_VEHICLE_PROFIT_THIS_YEAR_LAST_YEAR,
VST_VEHICLE_RELIABILITY_BREAKDOWNS,
};
/** Command codes for the shared buttons indexed by VehicleCommandTranslation and vehicle type. */
static const StringID _vehicle_translation_table[][4] = {
{ // VST_VEHICLE_AGE_RUNNING_COST_YR
STR_885D_AGE_RUNNING_COST_YR,
STR_900D_AGE_RUNNING_COST_YR,
STR_9812_AGE_RUNNING_COST_YR,
STR_A00D_AGE_RUNNING_COST_YR,
},
{ // VST_VEHICLE_MAX_SPEED
STR_NULL,
STR_900E_MAX_SPEED,
STR_9813_MAX_SPEED,
STR_A00E_MAX_SPEED,
},
{ // VST_VEHICLE_PROFIT_THIS_YEAR_LAST_YEAR
STR_885F_PROFIT_THIS_YEAR_LAST_YEAR,
STR_900F_PROFIT_THIS_YEAR_LAST_YEAR,
STR_9814_PROFIT_THIS_YEAR_LAST_YEAR,
STR_A00F_PROFIT_THIS_YEAR_LAST_YEAR,
},
{ // VST_VEHICLE_RELIABILITY_BREAKDOWNS
STR_8860_RELIABILITY_BREAKDOWNS,
STR_9010_RELIABILITY_BREAKDOWNS,
STR_9815_RELIABILITY_BREAKDOWNS,
STR_A010_RELIABILITY_BREAKDOWNS,
},
};
extern int GetTrainDetailsWndVScroll(VehicleID veh_id, byte det_tab);
extern void DrawTrainDetails(const Vehicle *v, int x, int y, int vscroll_pos, uint16 vscroll_cap, byte det_tab);
extern void DrawRoadVehDetails(const Vehicle *v, int x, int y);
extern void DrawShipDetails(const Vehicle *v, int x, int y);
extern void DrawAircraftDetails(const Vehicle *v, int x, int y);
struct VehicleDetailsWindow : Window {
int tab;
/** Initialize a newly created vehicle details window */
VehicleDetailsWindow(const WindowDesc *desc, WindowNumber window_number) : Window(desc, window_number)
{
const Vehicle *v = GetVehicle(this->window_number);
switch (v->type) {
case VEH_TRAIN:
ResizeWindow(this, 0, 39);
this->vscroll.cap = 6;
this->height += 12;
this->resize.step_height = 14;
this->resize.height = this->height - 14 * 2; // Minimum of 4 wagons in the display
this->widget[VLD_WIDGET_RENAME_VEHICLE].tooltips = STR_8867_NAME_TRAIN;
this->widget[VLD_WIDGET_CAPTION].data = STR_8802_DETAILS;
break;
case VEH_ROAD: {
this->widget[VLD_WIDGET_CAPTION].data = STR_900C_DETAILS;
this->widget[VLD_WIDGET_RENAME_VEHICLE].tooltips = STR_902E_NAME_ROAD_VEHICLE;
if (!RoadVehHasArticPart(v)) break;
/* Draw the text under the vehicle instead of next to it, minus the
* height already allocated for the cargo of the first vehicle. */
uint height_extension = 15 - 11;
/* Add space for the cargo amount for each part. */
for (const Vehicle *u = v; u != NULL; u = u->Next()) {
if (u->cargo_cap != 0) height_extension += 11;
}
ResizeWindow(this, 0, height_extension);
} break;
case VEH_SHIP:
this->widget[VLD_WIDGET_RENAME_VEHICLE].tooltips = STR_982F_NAME_SHIP;
this->widget[VLD_WIDGET_CAPTION].data = STR_9811_DETAILS;
break;
case VEH_AIRCRAFT:
ResizeWindow(this, 0, 11);
this->widget[VLD_WIDGET_RENAME_VEHICLE].tooltips = STR_A032_NAME_AIRCRAFT;
this->widget[VLD_WIDGET_CAPTION].data = STR_A00C_DETAILS;
break;
default: NOT_REACHED();
}
if (v->type != VEH_TRAIN) {
this->vscroll.cap = 1;
this->widget[VLD_WIDGET_MIDDLE_DETAILS].right += 12;
}
this->widget[VLD_WIDGET_MIDDLE_DETAILS].data = (this->vscroll.cap << 8) + 1;
this->owner = v->owner;
this->tab = 0;
this->FindWindowPlacementAndResize(desc);
}
/** Checks whether service interval is enabled for the vehicle. */
static bool IsVehicleServiceIntervalEnabled(const VehicleType vehicle_type)
{
switch (vehicle_type) {
default: NOT_REACHED();
case VEH_TRAIN: return _settings_game.vehicle.servint_trains != 0; break;
case VEH_ROAD: return _settings_game.vehicle.servint_roadveh != 0; break;
case VEH_SHIP: return _settings_game.vehicle.servint_ships != 0; break;
case VEH_AIRCRAFT: return _settings_game.vehicle.servint_aircraft != 0; break;
}
return false; // kill a compiler warning
}
/**
* Draw the details for the given vehicle at the position (x, y) of the Details windows
*
* @param v current vehicle
* @param x The x coordinate
* @param y The y coordinate
* @param vscroll_pos (train only)
* @param vscroll_cap (train only)
* @param det_tab (train only)
*/
static void DrawVehicleDetails(const Vehicle *v, int x, int y, int vscroll_pos, uint vscroll_cap, byte det_tab)
{
switch (v->type) {
case VEH_TRAIN: DrawTrainDetails(v, x, y, vscroll_pos, vscroll_cap, det_tab); break;
case VEH_ROAD: DrawRoadVehDetails(v, x, y); break;
case VEH_SHIP: DrawShipDetails(v, x, y); break;
case VEH_AIRCRAFT: DrawAircraftDetails(v, x, y); break;
default: NOT_REACHED();
}
}
/** Repaint vehicle details window. */
virtual void OnPaint()
{
const Vehicle *v = GetVehicle(this->window_number);
byte det_tab = this->tab;
this->SetWidgetDisabledState(VLD_WIDGET_RENAME_VEHICLE, v->owner != _local_company);
if (v->type == VEH_TRAIN) {
this->DisableWidget(det_tab + VLD_WIDGET_DETAILS_CARGO_CARRIED);
SetVScrollCount(this, GetTrainDetailsWndVScroll(v->index, det_tab));
}
this->SetWidgetsHiddenState(v->type != VEH_TRAIN,
VLD_WIDGET_SCROLLBAR,
VLD_WIDGET_DETAILS_CARGO_CARRIED,
VLD_WIDGET_DETAILS_TRAIN_VEHICLES,
VLD_WIDGET_DETAILS_CAPACITY_OF_EACH,
VLD_WIDGET_DETAILS_TOTAL_CARGO,
VLD_WIDGET_RESIZE,
WIDGET_LIST_END);
/* Disable service-scroller when interval is set to disabled */
this->SetWidgetsDisabledState(!IsVehicleServiceIntervalEnabled(v->type),
VLD_WIDGET_INCREASE_SERVICING_INTERVAL,
VLD_WIDGET_DECREASE_SERVICING_INTERVAL,
WIDGET_LIST_END);
SetDParam(0, v->index);
this->DrawWidgets();
/* Draw running cost */
SetDParam(1, v->age / DAYS_IN_LEAP_YEAR);
SetDParam(0, (v->age + DAYS_IN_YEAR < v->max_age) ? STR_AGE : STR_AGE_RED);
SetDParam(2, v->max_age / DAYS_IN_LEAP_YEAR);
SetDParam(3, v->GetDisplayRunningCost());
DrawString(2, 15, _vehicle_translation_table[VST_VEHICLE_AGE_RUNNING_COST_YR][v->type], TC_FROMSTRING);
/* Draw max speed */
switch (v->type) {
case VEH_TRAIN:
SetDParam(2, v->GetDisplayMaxSpeed());
SetDParam(1, v->u.rail.cached_power);
SetDParam(0, v->u.rail.cached_weight);
SetDParam(3, v->u.rail.cached_max_te / 1000);
DrawString(2, 25, (_settings_game.vehicle.train_acceleration_model != TAM_ORIGINAL && v->u.rail.railtype != RAILTYPE_MAGLEV) ?
STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED_MAX_TE :
STR_VEHICLE_INFO_WEIGHT_POWER_MAX_SPEED, TC_FROMSTRING);
break;
case VEH_ROAD:
case VEH_SHIP:
case VEH_AIRCRAFT:
SetDParam(0, v->GetDisplayMaxSpeed());
DrawString(2, 25, _vehicle_translation_table[VST_VEHICLE_MAX_SPEED][v->type], TC_FROMSTRING);
break;
default: NOT_REACHED();
}
/* Draw profit */
SetDParam(0, v->GetDisplayProfitThisYear());
SetDParam(1, v->GetDisplayProfitLastYear());
DrawString(2, 35, _vehicle_translation_table[VST_VEHICLE_PROFIT_THIS_YEAR_LAST_YEAR][v->type], TC_FROMSTRING);
/* Draw breakdown & reliability */
SetDParam(0, v->reliability * 100 >> 16);
SetDParam(1, v->breakdowns_since_last_service);
DrawString(2, 45, _vehicle_translation_table[VST_VEHICLE_RELIABILITY_BREAKDOWNS][v->type], TC_FROMSTRING);
/* Draw service interval text */
SetDParam(0, v->service_interval);
SetDParam(1, v->date_of_last_service);
DrawString(13, this->height - (v->type != VEH_TRAIN ? 11 : 23), _settings_game.vehicle.servint_ispercent ? STR_SERVICING_INTERVAL_PERCENT : STR_883C_SERVICING_INTERVAL_DAYS, TC_FROMSTRING);
switch (v->type) {
case VEH_TRAIN:
DrawVehicleDetails(v, 2, 57, this->vscroll.pos, this->vscroll.cap, det_tab);
break;
case VEH_ROAD:
case VEH_SHIP:
case VEH_AIRCRAFT:
DrawVehicleImage(v, 3, 57, INVALID_VEHICLE, 0, 0);
DrawVehicleDetails(v, 75, 57, this->vscroll.pos, this->vscroll.cap, det_tab);
break;
default: NOT_REACHED();
}
}
virtual void OnClick(Point pt, int widget)
{
/** Message strings for renaming vehicles indexed by vehicle type. */
static const StringID _name_vehicle_title[] = {
STR_8865_NAME_TRAIN,
STR_902C_NAME_ROAD_VEHICLE,
STR_9831_NAME_SHIP,
STR_A030_NAME_AIRCRAFT
};
switch (widget) {
case VLD_WIDGET_RENAME_VEHICLE: {// rename
const Vehicle *v = GetVehicle(this->window_number);
SetDParam(0, v->index);
ShowQueryString(STR_VEHICLE_NAME, _name_vehicle_title[v->type], MAX_LENGTH_VEHICLE_NAME_BYTES, MAX_LENGTH_VEHICLE_NAME_PIXELS, this, CS_ALPHANUMERAL, QSF_ENABLE_DEFAULT);
} break;
case VLD_WIDGET_INCREASE_SERVICING_INTERVAL: // increase int
case VLD_WIDGET_DECREASE_SERVICING_INTERVAL: { // decrease int
int mod = _ctrl_pressed ? 5 : 10;
const Vehicle *v = GetVehicle(this->window_number);
mod = (widget == VLD_WIDGET_DECREASE_SERVICING_INTERVAL) ? -mod : mod;
mod = GetServiceIntervalClamped(mod + v->service_interval);
if (mod == v->service_interval) return;
DoCommandP(v->tile, v->index, mod, CMD_CHANGE_SERVICE_INT | CMD_MSG(STR_018A_CAN_T_CHANGE_SERVICING));
} break;
case VLD_WIDGET_DETAILS_CARGO_CARRIED:
case VLD_WIDGET_DETAILS_TRAIN_VEHICLES:
case VLD_WIDGET_DETAILS_CAPACITY_OF_EACH:
case VLD_WIDGET_DETAILS_TOTAL_CARGO:
this->SetWidgetsDisabledState(false,
VLD_WIDGET_DETAILS_CARGO_CARRIED,
VLD_WIDGET_DETAILS_TRAIN_VEHICLES,
VLD_WIDGET_DETAILS_CAPACITY_OF_EACH,
VLD_WIDGET_DETAILS_TOTAL_CARGO,
widget,
WIDGET_LIST_END);
this->tab = widget - VLD_WIDGET_DETAILS_CARGO_CARRIED;
this->SetDirty();
break;
}
}
virtual void OnQueryTextFinished(char *str)
{
/** Message strings for error while renaming indexed by vehicle type. */
static const StringID _name_vehicle_error[] = {
STR_8866_CAN_T_NAME_TRAIN,
STR_902D_CAN_T_NAME_ROAD_VEHICLE,
STR_9832_CAN_T_NAME_SHIP,
STR_A031_CAN_T_NAME_AIRCRAFT
};
if (str == NULL) return;
DoCommandP(0, this->window_number, 0, CMD_RENAME_VEHICLE | CMD_MSG(_name_vehicle_error[GetVehicle(this->window_number)->type]), NULL, str);
}
virtual void OnResize(Point new_size, Point delta)
{
if (delta.x != 0) ResizeButtons(this, VLD_WIDGET_DETAILS_CARGO_CARRIED, VLD_WIDGET_DETAILS_TOTAL_CARGO);
if (delta.y == 0) return;
this->vscroll.cap += delta.y / 14;
this->widget[VLD_WIDGET_MIDDLE_DETAILS].data = (this->vscroll.cap << 8) + 1;
}
};
/** Vehicle details window descriptor. */
static const WindowDesc _vehicle_details_desc(
WDP_AUTO, WDP_AUTO, 405, 113, 405, 113,
WC_VEHICLE_DETAILS, WC_VEHICLE_VIEW,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
_vehicle_details_widgets
);
/** Shows the vehicle details window of the given vehicle. */
static void ShowVehicleDetailsWindow(const Vehicle *v)
{
DeleteWindowById(WC_VEHICLE_ORDERS, v->index, false);
DeleteWindowById(WC_VEHICLE_TIMETABLE, v->index, false);
AllocateWindowDescFront<VehicleDetailsWindow>(&_vehicle_details_desc, v->index);
}
/* Unified vehicle GUI - Vehicle View Window */
/** Vehicle view widgets. */
static const Widget _vehicle_view_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW }, // VVW_WIDGET_CLOSEBOX
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_GREY, 11, 237, 0, 13, 0x0 /* filled later */, STR_018C_WINDOW_TITLE_DRAG_THIS }, // VVW_WIDGET_CAPTION
{ WWT_STICKYBOX, RESIZE_LR, COLOUR_GREY, 238, 249, 0, 13, 0x0, STR_STICKY_BUTTON }, // VVW_WIDGET_STICKY
{ WWT_PANEL, RESIZE_RB, COLOUR_GREY, 0, 231, 14, 103, 0x0, STR_NULL }, // VVW_WIDGET_PANEL
{ WWT_INSET, RESIZE_RB, COLOUR_GREY, 2, 229, 16, 101, 0x0, STR_NULL }, // VVW_WIDGET_VIEWPORT
{ WWT_PUSHBTN, RESIZE_RTB, COLOUR_GREY, 0, 237, 104, 115, 0x0, 0x0 /* filled later */ }, // VVW_WIDGET_START_STOP_VEH
{ WWT_PUSHIMGBTN, RESIZE_LR, COLOUR_GREY, 232, 249, 14, 31, SPR_CENTRE_VIEW_VEHICLE, 0x0 /* filled later */ }, // VVW_WIDGET_CENTER_MAIN_VIEH
{ WWT_PUSHIMGBTN, RESIZE_LR, COLOUR_GREY, 232, 249, 32, 49, 0x0 /* filled later */, 0x0 /* filled later */ }, // VVW_WIDGET_GOTO_DEPOT
{ WWT_PUSHIMGBTN, RESIZE_LR, COLOUR_GREY, 232, 249, 50, 67, SPR_REFIT_VEHICLE, 0x0 /* filled later */ }, // VVW_WIDGET_REFIT_VEH
{ WWT_PUSHIMGBTN, RESIZE_LR, COLOUR_GREY, 232, 249, 68, 85, SPR_SHOW_ORDERS, 0x0 /* filled later */ }, // VVW_WIDGET_SHOW_ORDERS
{ WWT_PUSHIMGBTN, RESIZE_LR, COLOUR_GREY, 232, 249, 86, 103, SPR_SHOW_VEHICLE_DETAILS, 0x0 /* filled later */ }, // VVW_WIDGET_SHOW_DETAILS
{ WWT_PUSHIMGBTN, RESIZE_LR, COLOUR_GREY, 232, 249, 32, 49, 0x0 /* filled later */, 0x0 /* filled later */ }, // VVW_WIDGET_CLONE_VEH
{ WWT_PANEL, RESIZE_LRB, COLOUR_GREY, 232, 249, 104, 103, 0x0, STR_NULL }, // VVW_WIDGET_EMPTY_BOTTOM_RIGHT
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_GREY, 238, 249, 104, 115, 0x0, STR_NULL }, // VVW_WIDGET_RESIZE
{ WWT_PUSHIMGBTN, RESIZE_LR, COLOUR_GREY, 232, 249, 50, 67, SPR_FORCE_VEHICLE_TURN, STR_9020_FORCE_VEHICLE_TO_TURN_AROUND }, // VVW_WIDGET_TURN_AROUND
{ WWT_PUSHIMGBTN, RESIZE_LR, COLOUR_GREY, 232, 249, 50, 67, SPR_IGNORE_SIGNALS, STR_884A_FORCE_TRAIN_TO_PROCEED }, // VVW_WIDGET_FORCE_PROCEED
{ WIDGETS_END},
};
/** Vehicle view window descriptor for all vehicles but trains. */
static const WindowDesc _vehicle_view_desc(
WDP_AUTO, WDP_AUTO, 250, 116, 250, 116,
WC_VEHICLE_VIEW, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
_vehicle_view_widgets
);
/** Vehicle view window descriptor for trains. Only minimum_height and
* default_height are different for train view.
*/
static const WindowDesc _train_view_desc(
WDP_AUTO, WDP_AUTO, 250, 134, 250, 134,
WC_VEHICLE_VIEW, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON | WDF_RESIZABLE,
_vehicle_view_widgets
);
/* Just to make sure, nobody has changed the vehicle type constants, as we are
using them for array indexing in a number of places here. */
assert_compile(VEH_TRAIN == 0);
assert_compile(VEH_ROAD == 1);
assert_compile(VEH_SHIP == 2);
assert_compile(VEH_AIRCRAFT == 3);
/** Zoom levels for vehicle views indexed by vehicle type. */
static const ZoomLevel _vehicle_view_zoom_levels[] = {
ZOOM_LVL_TRAIN,
ZOOM_LVL_ROADVEH,
ZOOM_LVL_SHIP,
ZOOM_LVL_AIRCRAFT,
};
/* Constants for geometry of vehicle view viewport */
static const int VV_VIEWPORT_X = 3;
static const int VV_VIEWPORT_Y = 17;
static const int VV_INITIAL_VIEWPORT_WIDTH = 226;
static const int VV_INITIAL_VIEWPORT_HEIGHT = 84;
static const int VV_INITIAL_VIEWPORT_HEIGHT_TRAIN = 102;
/** Command indices for the _vehicle_command_translation_table. */
enum VehicleCommandTranslation {
VCT_CMD_START_STOP = 0,
VCT_CMD_GOTO_DEPOT,
VCT_CMD_CLONE_VEH,
VCT_CMD_TURN_AROUND,
};
/** Command codes for the shared buttons indexed by VehicleCommandTranslation and vehicle type. */
static const uint32 _vehicle_command_translation_table[][4] = {
{ // VCT_CMD_START_STOP
CMD_START_STOP_VEHICLE | CMD_MSG(STR_883B_CAN_T_STOP_START_TRAIN),
CMD_START_STOP_VEHICLE | CMD_MSG(STR_9015_CAN_T_STOP_START_ROAD_VEHICLE),
CMD_START_STOP_VEHICLE | CMD_MSG(STR_9818_CAN_T_STOP_START_SHIP),
CMD_START_STOP_VEHICLE | CMD_MSG(STR_A016_CAN_T_STOP_START_AIRCRAFT)
},
{ // VCT_CMD_GOTO_DEPOT
/* TrainGotoDepot has a nice randomizer in the pathfinder, which causes desyncs... */
CMD_SEND_TRAIN_TO_DEPOT | CMD_NO_TEST_IF_IN_NETWORK | CMD_MSG(STR_8830_CAN_T_SEND_TRAIN_TO_DEPOT),
CMD_SEND_ROADVEH_TO_DEPOT | CMD_MSG(STR_9018_CAN_T_SEND_VEHICLE_TO_DEPOT),
CMD_SEND_SHIP_TO_DEPOT | CMD_MSG(STR_9819_CAN_T_SEND_SHIP_TO_DEPOT),
CMD_SEND_AIRCRAFT_TO_HANGAR | CMD_MSG(STR_A012_CAN_T_SEND_AIRCRAFT_TO)
},
{ // VCT_CMD_CLONE_VEH
CMD_CLONE_VEHICLE | CMD_MSG(STR_882B_CAN_T_BUILD_RAILROAD_VEHICLE),
CMD_CLONE_VEHICLE | CMD_MSG(STR_9009_CAN_T_BUILD_ROAD_VEHICLE),
CMD_CLONE_VEHICLE | CMD_MSG(STR_980D_CAN_T_BUILD_SHIP),
CMD_CLONE_VEHICLE | CMD_MSG(STR_A008_CAN_T_BUILD_AIRCRAFT)
},
{ // VCT_CMD_TURN_AROUND
CMD_REVERSE_TRAIN_DIRECTION | CMD_MSG(STR_8869_CAN_T_REVERSE_DIRECTION),
CMD_TURN_ROADVEH | CMD_MSG(STR_9033_CAN_T_MAKE_VEHICLE_TURN),
0xffffffff, // invalid for ships
0xffffffff // invalid for aircrafts
},
};
/** Checks whether the vehicle may be refitted at the moment.*/
static bool IsVehicleRefitable(const Vehicle *v)
{
if (!v->IsStoppedInDepot()) return false;
do {
if (IsEngineRefittable(v->engine_type)) return true;
} while ((v->type == VEH_TRAIN || v->type == VEH_ROAD) && (v = v->Next()) != NULL);
return false;
}
struct VehicleViewWindow : Window {
VehicleViewWindow(const WindowDesc *desc, WindowNumber window_number) : Window(desc, window_number)
{
const Vehicle *v = GetVehicle(this->window_number);
this->owner = v->owner;
InitializeWindowViewport(this, VV_VIEWPORT_X, VV_VIEWPORT_Y, VV_INITIAL_VIEWPORT_WIDTH,
(v->type == VEH_TRAIN) ? VV_INITIAL_VIEWPORT_HEIGHT_TRAIN : VV_INITIAL_VIEWPORT_HEIGHT,
this->window_number | (1 << 31), _vehicle_view_zoom_levels[v->type]);
/*
* fill in data and tooltip codes for the widgets and
* move some of the buttons for trains
*/
switch (v->type) {
case VEH_TRAIN:
this->widget[VVW_WIDGET_CAPTION].data = STR_882E;
this->widget[VVW_WIDGET_START_STOP_VEH].tooltips = STR_8846_CURRENT_TRAIN_ACTION_CLICK;
this->widget[VVW_WIDGET_CENTER_MAIN_VIEH].tooltips = STR_8848_CENTER_MAIN_VIEW_ON_TRAIN;
this->widget[VVW_WIDGET_GOTO_DEPOT].data = SPR_SEND_TRAIN_TODEPOT;
this->widget[VVW_WIDGET_GOTO_DEPOT].tooltips = STR_8849_SEND_TRAIN_TO_DEPOT;
this->widget[VVW_WIDGET_REFIT_VEH].tooltips = STR_RAIL_REFIT_VEHICLE_TO_CARRY;
this->widget[VVW_WIDGET_SHOW_ORDERS].tooltips = STR_8847_SHOW_TRAIN_S_ORDERS;
this->widget[VVW_WIDGET_SHOW_DETAILS].tooltips = STR_884C_SHOW_TRAIN_DETAILS;
this->widget[VVW_WIDGET_CLONE_VEH].data = SPR_CLONE_TRAIN;
this->widget[VVW_WIDGET_CLONE_VEH].tooltips = STR_CLONE_TRAIN_INFO;
this->widget[VVW_WIDGET_TURN_AROUND].tooltips = STR_884B_REVERSE_DIRECTION_OF_TRAIN;
/* due to more buttons we must modify the layout a bit for trains */
this->widget[VVW_WIDGET_PANEL].bottom = 121;
this->widget[VVW_WIDGET_VIEWPORT].bottom = 119;
this->widget[VVW_WIDGET_START_STOP_VEH].top = 122;
this->widget[VVW_WIDGET_START_STOP_VEH].bottom = 133;
this->widget[VVW_WIDGET_REFIT_VEH].top = 68;
this->widget[VVW_WIDGET_REFIT_VEH].bottom = 85;
this->widget[VVW_WIDGET_SHOW_ORDERS].top = 86;
this->widget[VVW_WIDGET_SHOW_ORDERS].bottom = 103;
this->widget[VVW_WIDGET_SHOW_DETAILS].top = 104;
this->widget[VVW_WIDGET_SHOW_DETAILS].bottom = 121;
this->widget[VVW_WIDGET_EMPTY_BOTTOM_RIGHT].top = 122;
this->widget[VVW_WIDGET_EMPTY_BOTTOM_RIGHT].bottom = 121;
this->widget[VVW_WIDGET_RESIZE].top = 122;
this->widget[VVW_WIDGET_RESIZE].bottom = 133;
this->widget[VVW_WIDGET_TURN_AROUND].top = 68;
this->widget[VVW_WIDGET_TURN_AROUND].bottom = 85;
break;
case VEH_ROAD:
this->widget[VVW_WIDGET_CAPTION].data = STR_9002;
this->widget[VVW_WIDGET_START_STOP_VEH].tooltips = STR_901C_CURRENT_VEHICLE_ACTION;
this->widget[VVW_WIDGET_CENTER_MAIN_VIEH].tooltips = STR_901E_CENTER_MAIN_VIEW_ON_VEHICLE;
this->widget[VVW_WIDGET_GOTO_DEPOT].data = SPR_SEND_ROADVEH_TODEPOT;
this->widget[VVW_WIDGET_GOTO_DEPOT].tooltips = STR_901F_SEND_VEHICLE_TO_DEPOT;
this->widget[VVW_WIDGET_REFIT_VEH].tooltips = STR_REFIT_ROAD_VEHICLE_TO_CARRY;
this->widget[VVW_WIDGET_SHOW_ORDERS].tooltips = STR_901D_SHOW_VEHICLE_S_ORDERS;
this->widget[VVW_WIDGET_SHOW_DETAILS].tooltips = STR_9021_SHOW_ROAD_VEHICLE_DETAILS;
this->widget[VVW_WIDGET_CLONE_VEH].data = SPR_CLONE_ROADVEH;
this->widget[VVW_WIDGET_CLONE_VEH].tooltips = STR_CLONE_ROAD_VEHICLE_INFO;
this->SetWidgetHiddenState(VVW_WIDGET_FORCE_PROCEED, true);
break;
case VEH_SHIP:
this->widget[VVW_WIDGET_CAPTION].data = STR_980F;
this->widget[VVW_WIDGET_START_STOP_VEH].tooltips = STR_9827_CURRENT_SHIP_ACTION_CLICK;
this->widget[VVW_WIDGET_CENTER_MAIN_VIEH].tooltips = STR_9829_CENTER_MAIN_VIEW_ON_SHIP;
this->widget[VVW_WIDGET_GOTO_DEPOT].data = SPR_SEND_SHIP_TODEPOT;
this->widget[VVW_WIDGET_GOTO_DEPOT].tooltips = STR_982A_SEND_SHIP_TO_DEPOT;
this->widget[VVW_WIDGET_REFIT_VEH].tooltips = STR_983A_REFIT_CARGO_SHIP_TO_CARRY;
this->widget[VVW_WIDGET_SHOW_ORDERS].tooltips = STR_9828_SHOW_SHIP_S_ORDERS;
this->widget[VVW_WIDGET_SHOW_DETAILS].tooltips = STR_982B_SHOW_SHIP_DETAILS;
this->widget[VVW_WIDGET_CLONE_VEH].data = SPR_CLONE_SHIP;
this->widget[VVW_WIDGET_CLONE_VEH].tooltips = STR_CLONE_SHIP_INFO;
this->SetWidgetsHiddenState(true,
VVW_WIDGET_TURN_AROUND,
VVW_WIDGET_FORCE_PROCEED,
WIDGET_LIST_END);
break;
case VEH_AIRCRAFT:
this->widget[VVW_WIDGET_CAPTION].data = STR_A00A;
this->widget[VVW_WIDGET_START_STOP_VEH].tooltips = STR_A027_CURRENT_AIRCRAFT_ACTION;
this->widget[VVW_WIDGET_CENTER_MAIN_VIEH].tooltips = STR_A029_CENTER_MAIN_VIEW_ON_AIRCRAFT;
this->widget[VVW_WIDGET_GOTO_DEPOT].data = SPR_SEND_AIRCRAFT_TODEPOT;
this->widget[VVW_WIDGET_GOTO_DEPOT].tooltips = STR_A02A_SEND_AIRCRAFT_TO_HANGAR;
this->widget[VVW_WIDGET_REFIT_VEH].tooltips = STR_A03B_REFIT_AIRCRAFT_TO_CARRY;
this->widget[VVW_WIDGET_SHOW_ORDERS].tooltips = STR_A028_SHOW_AIRCRAFT_S_ORDERS;
this->widget[VVW_WIDGET_SHOW_DETAILS].tooltips = STR_A02B_SHOW_AIRCRAFT_DETAILS;
this->widget[VVW_WIDGET_CLONE_VEH].data = SPR_CLONE_AIRCRAFT;
this->widget[VVW_WIDGET_CLONE_VEH].tooltips = STR_CLONE_AIRCRAFT_INFO;
this->SetWidgetsHiddenState(true,
VVW_WIDGET_TURN_AROUND,
VVW_WIDGET_FORCE_PROCEED,
WIDGET_LIST_END);
break;
default: NOT_REACHED();
}
this->FindWindowPlacementAndResize(desc);
}
~VehicleViewWindow()
{
DeleteWindowById(WC_VEHICLE_ORDERS, this->window_number, false);
DeleteWindowById(WC_VEHICLE_REFIT, this->window_number, false);
DeleteWindowById(WC_VEHICLE_DETAILS, this->window_number, false);
DeleteWindowById(WC_VEHICLE_TIMETABLE, this->window_number, false);
}
virtual void OnPaint()
{
/** Message strings for heading to depot indexed by vehicle type. */
static const StringID _heading_for_depot_strings[] = {
STR_HEADING_FOR_TRAIN_DEPOT,
STR_HEADING_FOR_ROAD_DEPOT,
STR_HEADING_FOR_SHIP_DEPOT,
STR_HEADING_FOR_HANGAR,
};
/** Message strings for heading to depot and servicing indexed by vehicle type. */
static const StringID _heading_for_depot_service_strings[] = {
STR_HEADING_FOR_TRAIN_DEPOT_SERVICE,
STR_HEADING_FOR_ROAD_DEPOT_SERVICE,
STR_HEADING_FOR_SHIP_DEPOT_SERVICE,
STR_HEADING_FOR_HANGAR_SERVICE,
};
const Vehicle *v = GetVehicle(this->window_number);
StringID str;
bool is_localcompany = v->owner == _local_company;
bool refitable_and_stopped_in_depot = IsVehicleRefitable(v);
this->SetWidgetDisabledState(VVW_WIDGET_GOTO_DEPOT, !is_localcompany);
this->SetWidgetDisabledState(VVW_WIDGET_REFIT_VEH,
!refitable_and_stopped_in_depot || !is_localcompany);
this->SetWidgetDisabledState(VVW_WIDGET_CLONE_VEH, !is_localcompany);
if (v->type == VEH_TRAIN) {
this->SetWidgetDisabledState(VVW_WIDGET_FORCE_PROCEED, !is_localcompany);
this->SetWidgetDisabledState(VVW_WIDGET_TURN_AROUND, !is_localcompany);
}
/* draw widgets & caption */
SetDParam(0, v->index);
this->DrawWidgets();
if (v->vehstatus & VS_CRASHED) {
str = STR_8863_CRASHED;
} else if (v->type != VEH_AIRCRAFT && v->breakdown_ctr == 1) { // check for aircraft necessary?
str = STR_885C_BROKEN_DOWN;
} else if (v->vehstatus & VS_STOPPED) {
if (v->type == VEH_TRAIN) {
if (v->cur_speed == 0) {
if (v->u.rail.cached_power == 0) {
str = STR_TRAIN_NO_POWER;
} else {
str = STR_8861_STOPPED;
}
} else {
SetDParam(0, v->GetDisplaySpeed());
str = STR_TRAIN_STOPPING + _settings_client.gui.vehicle_speed;
}
} else { // no train
str = STR_8861_STOPPED;
}
} else if (v->type == VEH_TRAIN && HasBit(v->u.rail.flags, VRF_TRAIN_STUCK)) {
str = STR_TRAIN_STUCK;
} else { // vehicle is in a "normal" state, show current order
switch (v->current_order.GetType()) {
case OT_GOTO_STATION: {
SetDParam(0, v->current_order.GetDestination());
SetDParam(1, v->GetDisplaySpeed());
str = STR_HEADING_FOR_STATION + _settings_client.gui.vehicle_speed;
} break;
case OT_GOTO_DEPOT: {
if (v->type == VEH_AIRCRAFT) {
/* Aircrafts always go to a station, even if you say depot */
SetDParam(0, v->current_order.GetDestination());
SetDParam(1, v->GetDisplaySpeed());
} else {
Depot *depot = GetDepot(v->current_order.GetDestination());
SetDParam(0, depot->town_index);
SetDParam(1, v->GetDisplaySpeed());
}
if (v->current_order.GetDepotActionType() & ODATFB_HALT) {
str = _heading_for_depot_strings[v->type] + _settings_client.gui.vehicle_speed;
} else {
str = _heading_for_depot_service_strings[v->type] + _settings_client.gui.vehicle_speed;
}
} break;
case OT_LOADING:
str = STR_882F_LOADING_UNLOADING;
break;
case OT_GOTO_WAYPOINT: {
assert(v->type == VEH_TRAIN);
SetDParam(0, v->current_order.GetDestination());
str = STR_HEADING_FOR_WAYPOINT + _settings_client.gui.vehicle_speed;
SetDParam(1, v->GetDisplaySpeed());
break;
}
case OT_LEAVESTATION:
if (v->type != VEH_AIRCRAFT) {
str = STR_LEAVING;
break;
}
/* fall-through if aircraft. Does this even happen? */
default:
if (v->GetNumOrders() == 0) {
str = STR_NO_ORDERS + _settings_client.gui.vehicle_speed;
SetDParam(0, v->GetDisplaySpeed());
} else {
str = STR_EMPTY;
}
break;
}
}
/* draw the flag plus orders */
DrawSprite(v->vehstatus & VS_STOPPED ? SPR_FLAG_VEH_STOPPED : SPR_FLAG_VEH_RUNNING, PAL_NONE, 2, this->widget[VVW_WIDGET_START_STOP_VEH].top + 1);
DrawStringCenteredTruncated(this->widget[VVW_WIDGET_START_STOP_VEH].left + 8, this->widget[VVW_WIDGET_START_STOP_VEH].right, this->widget[VVW_WIDGET_START_STOP_VEH].top + 1, str, TC_FROMSTRING);
this->DrawViewport();
}
virtual void OnClick(Point pt, int widget)
{
const Vehicle *v = GetVehicle(this->window_number);
switch (widget) {
case VVW_WIDGET_START_STOP_VEH: // start stop
DoCommandP(v->tile, v->index, 0,
_vehicle_command_translation_table[VCT_CMD_START_STOP][v->type]);
break;
case VVW_WIDGET_CENTER_MAIN_VIEH: {// center main view
const Window *mainwindow = FindWindowById(WC_MAIN_WINDOW, 0);
/* code to allow the main window to 'follow' the vehicle if the ctrl key is pressed */
if (_ctrl_pressed && mainwindow->viewport->zoom == ZOOM_LVL_NORMAL) {
mainwindow->viewport->follow_vehicle = v->index;
} else {
ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos);
}
} break;
case VVW_WIDGET_GOTO_DEPOT: // goto hangar
DoCommandP(v->tile, v->index, _ctrl_pressed ? DEPOT_SERVICE : 0,
_vehicle_command_translation_table[VCT_CMD_GOTO_DEPOT][v->type]);
break;
case VVW_WIDGET_REFIT_VEH: // refit
ShowVehicleRefitWindow(v, INVALID_VEH_ORDER_ID, this);
break;
case VVW_WIDGET_SHOW_ORDERS: // show orders
if (_ctrl_pressed) {
ShowTimetableWindow(v);
} else {
ShowOrdersWindow(v);
}
break;
case VVW_WIDGET_SHOW_DETAILS: // show details
ShowVehicleDetailsWindow(v);
break;
case VVW_WIDGET_CLONE_VEH: // clone vehicle
DoCommandP(v->tile, v->index, _ctrl_pressed ? 1 : 0,
_vehicle_command_translation_table[VCT_CMD_CLONE_VEH][v->type],
CcCloneVehicle);
break;
case VVW_WIDGET_TURN_AROUND: // turn around
assert(v->type == VEH_TRAIN || v->type == VEH_ROAD);
DoCommandP(v->tile, v->index, 0,
_vehicle_command_translation_table[VCT_CMD_TURN_AROUND][v->type]);
break;
case VVW_WIDGET_FORCE_PROCEED: // force proceed
assert(v->type == VEH_TRAIN);
DoCommandP(v->tile, v->index, 0, CMD_FORCE_TRAIN_PROCEED | CMD_MSG(STR_8862_CAN_T_MAKE_TRAIN_PASS_SIGNAL));
break;
}
}
virtual void OnResize(Point new_size, Point delta)
{
this->viewport->width += delta.x;
this->viewport->height += delta.y;
this->viewport->virtual_width += delta.x;
this->viewport->virtual_height += delta.y;
}
virtual void OnTick()
{
const Vehicle *v = GetVehicle(this->window_number);
bool veh_stopped = v->IsStoppedInDepot();
/* Widget VVW_WIDGET_GOTO_DEPOT must be hidden if the vehicle is already
* stopped in depot.
* Widget VVW_WIDGET_CLONE_VEH should then be shown, since cloning is
* allowed only while in depot and stopped.
* This sytem allows to have two buttons, on top of each other.
* The same system applies to widget VVW_WIDGET_REFIT_VEH and VVW_WIDGET_TURN_AROUND.*/
if (veh_stopped != this->IsWidgetHidden(VVW_WIDGET_GOTO_DEPOT) || veh_stopped == this->IsWidgetHidden(VVW_WIDGET_CLONE_VEH)) {
this->SetWidgetHiddenState( VVW_WIDGET_GOTO_DEPOT, veh_stopped); // send to depot
this->SetWidgetHiddenState(VVW_WIDGET_CLONE_VEH, !veh_stopped); // clone
if (v->type == VEH_ROAD || v->type == VEH_TRAIN) {
this->SetWidgetHiddenState( VVW_WIDGET_REFIT_VEH, !veh_stopped); // refit
this->SetWidgetHiddenState(VVW_WIDGET_TURN_AROUND, veh_stopped); // force turn around
}
this->SetDirty();
}
}
};
/** Shows the vehicle view window of the given vehicle. */
void ShowVehicleViewWindow(const Vehicle *v)
{
AllocateWindowDescFront<VehicleViewWindow>((v->type == VEH_TRAIN) ? &_train_view_desc : &_vehicle_view_desc, v->index);
}
void StopGlobalFollowVehicle(const Vehicle *v)
{
Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
if (w != NULL && w->viewport->follow_vehicle == v->index) {
ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos, true); // lock the main view on the vehicle's last position
w->viewport->follow_vehicle = INVALID_VEHICLE;
}
}
| 73,519
|
C++
|
.cpp
| 1,706
| 39.618992
| 199
| 0.682551
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,167
|
sdl_v.cpp
|
EnergeticBark_OpenTTD-3DS/src/video/sdl_v.cpp
|
/* $Id$ */
/** @file sdl_v.cpp Implementation of the SDL video driver. */
#ifdef WITH_SDL
#include "../stdafx.h"
#include "../openttd.h"
#include "../gfx_func.h"
#include "../sdl.h"
#include "../variables.h"
#include "../rev.h"
#include "../blitter/factory.hpp"
#include "../network/network.h"
#include "../functions.h"
#include "sdl_v.h"
#include <SDL.h>
#ifdef N3DS
#include <3ds.h>
#endif
static FVideoDriver_SDL iFVideoDriver_SDL;
static SDL_Surface *_sdl_screen;
static bool _all_modes;
#ifdef N3DS
static SDL_Joystick *_3ds_joystick;
#endif
#define MAX_DIRTY_RECTS 100
static SDL_Rect _dirty_rects[MAX_DIRTY_RECTS];
static int _num_dirty_rects;
void VideoDriver_SDL::MakeDirty(int left, int top, int width, int height)
{
if (_num_dirty_rects < MAX_DIRTY_RECTS) {
_dirty_rects[_num_dirty_rects].x = left;
_dirty_rects[_num_dirty_rects].y = top;
_dirty_rects[_num_dirty_rects].w = width;
_dirty_rects[_num_dirty_rects].h = height;
}
_num_dirty_rects++;
}
static void UpdatePalette(uint start, uint count)
{
SDL_Color pal[256];
for (uint i = 0; i != count; i++) {
pal[i].r = _cur_palette[start + i].r;
pal[i].g = _cur_palette[start + i].g;
pal[i].b = _cur_palette[start + i].b;
pal[i].unused = 0;
}
SDL_CALL SDL_SetColors(_sdl_screen, pal, start, count);
}
static void InitPalette()
{
UpdatePalette(0, 256);
}
static void CheckPaletteAnim()
{
if (_pal_count_dirty != 0) {
Blitter *blitter = BlitterFactoryBase::GetCurrentBlitter();
switch (blitter->UsePaletteAnimation()) {
case Blitter::PALETTE_ANIMATION_VIDEO_BACKEND:
UpdatePalette(_pal_first_dirty, _pal_count_dirty);
break;
case Blitter::PALETTE_ANIMATION_BLITTER:
blitter->PaletteAnimate(_pal_first_dirty, _pal_count_dirty);
break;
case Blitter::PALETTE_ANIMATION_NONE:
break;
default:
NOT_REACHED();
}
_pal_count_dirty = 0;
}
}
static void DrawSurfaceToScreen()
{
int n = _num_dirty_rects;
if (n == 0) return;
_num_dirty_rects = 0;
if (n > MAX_DIRTY_RECTS) {
SDL_CALL SDL_UpdateRect(_sdl_screen, 0, 0, 0, 0);
} else {
SDL_CALL SDL_UpdateRects(_sdl_screen, n, _dirty_rects);
}
}
static const Dimension _default_resolutions[] = {
{ 640, 480},
{ 800, 600},
{1024, 768},
{1152, 864},
{1280, 800},
{1280, 960},
{1280, 1024},
{1400, 1050},
{1600, 1200},
{1680, 1050},
{1920, 1200}
};
static void GetVideoModes()
{
SDL_Rect **modes = SDL_CALL SDL_ListModes(NULL, SDL_SWSURFACE | SDL_FULLSCREEN);
if (modes == NULL) usererror("sdl: no modes available");
_all_modes = (SDL_CALL SDL_ListModes(NULL, SDL_SWSURFACE | (_fullscreen ? SDL_FULLSCREEN : 0)) == (void*)-1);
if (modes == (void*)-1) {
int n = 0;
for (uint i = 0; i < lengthof(_default_resolutions); i++) {
if (SDL_CALL SDL_VideoModeOK(_default_resolutions[i].width, _default_resolutions[i].height, 8, SDL_FULLSCREEN) != 0) {
_resolutions[n] = _default_resolutions[i];
if (++n == lengthof(_resolutions)) break;
}
}
_num_resolutions = n;
} else {
int n = 0;
for (int i = 0; modes[i]; i++) {
int w = modes[i]->w;
int h = modes[i]->h;
int j;
for (j = 0; j < n; j++) {
if (_resolutions[j].width == w && _resolutions[j].height == h) break;
}
if (j == n) {
_resolutions[j].width = w;
_resolutions[j].height = h;
if (++n == lengthof(_resolutions)) break;
}
}
_num_resolutions = n;
SortResolutions(_num_resolutions);
}
}
static void GetAvailableVideoMode(int *w, int *h)
{
/* All modes available? */
if (_all_modes || _num_resolutions == 0) return;
/* Is the wanted mode among the available modes? */
for (int i = 0; i != _num_resolutions; i++) {
if (*w == _resolutions[i].width && *h == _resolutions[i].height) return;
}
/* Use the closest possible resolution */
int best = 0;
uint delta = abs((_resolutions[0].width - *w) * (_resolutions[0].height - *h));
for (int i = 1; i != _num_resolutions; ++i) {
uint newdelta = abs((_resolutions[i].width - *w) * (_resolutions[i].height - *h));
if (newdelta < delta) {
best = i;
delta = newdelta;
}
}
*w = _resolutions[best].width;
*h = _resolutions[best].height;
}
#ifndef ICON_DIR
#define ICON_DIR "media"
#endif
#ifdef WIN32
/* Let's redefine the LoadBMP macro with because we are dynamically
* loading SDL and need to 'SDL_CALL' all functions */
#undef SDL_LoadBMP
#define SDL_LoadBMP(file) SDL_LoadBMP_RW(SDL_CALL SDL_RWFromFile(file, "rb"), 1)
#endif
static bool CreateMainSurface(int w, int h)
{
SDL_Surface *newscreen, *icon;
char caption[50];
int bpp = BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth();
GetAvailableVideoMode(&w, &h);
DEBUG(driver, 1, "SDL: using mode %dx%dx%d", w, h, bpp);
if (bpp == 0) usererror("Can't use a blitter that blits 0 bpp for normal visuals");
/* Give the application an icon */
icon = SDL_CALL SDL_LoadBMP(ICON_DIR PATHSEP "openttd.32.bmp");
if (icon != NULL) {
/* Get the colourkey, which will be magenta */
uint32 rgbmap = SDL_CALL SDL_MapRGB(icon->format, 255, 0, 255);
SDL_CALL SDL_SetColorKey(icon, SDL_SRCCOLORKEY, rgbmap);
SDL_CALL SDL_WM_SetIcon(icon, NULL);
SDL_CALL SDL_FreeSurface(icon);
}
/* DO NOT CHANGE TO HWSURFACE, IT DOES NOT WORK */
#ifndef N3DS
newscreen = SDL_CALL SDL_SetVideoMode(w, h, bpp, SDL_SWSURFACE | SDL_HWPALETTE | (_fullscreen ? SDL_FULLSCREEN : SDL_RESIZABLE));
#else
// game bottom screen and console top
newscreen = SDL_CALL SDL_SetVideoMode(w, h, bpp, SDL_SWSURFACE | 0 | 0x00200000 | 0x00040000);
#endif
if (newscreen == NULL) {
DEBUG(driver, 0, "SDL: Couldn't allocate a window to draw on");
return false;
}
_screen.width = newscreen->w;
_screen.height = newscreen->h;
_screen.pitch = newscreen->pitch / (bpp / 8);
_sdl_screen = newscreen;
InitPalette();
snprintf(caption, sizeof(caption), "OpenTTD %s", _openttd_revision);
SDL_CALL SDL_WM_SetCaption(caption, caption);
SDL_CALL SDL_ShowCursor(0);
GameSizeChanged();
return true;
}
struct VkMapping {
uint16 vk_from;
byte vk_count;
byte map_to;
};
#define AS(x, z) {x, 0, z}
#define AM(x, y, z, w) {x, y - x, z}
static const VkMapping _vk_mapping[] = {
/* Pageup stuff + up/down */
AM(SDLK_PAGEUP, SDLK_PAGEDOWN, WKC_PAGEUP, WKC_PAGEDOWN),
AS(SDLK_UP, WKC_UP),
AS(SDLK_DOWN, WKC_DOWN),
AS(SDLK_LEFT, WKC_LEFT),
AS(SDLK_RIGHT, WKC_RIGHT),
AS(SDLK_HOME, WKC_HOME),
AS(SDLK_END, WKC_END),
AS(SDLK_INSERT, WKC_INSERT),
AS(SDLK_DELETE, WKC_DELETE),
/* Map letters & digits */
AM(SDLK_a, SDLK_z, 'A', 'Z'),
AM(SDLK_0, SDLK_9, '0', '9'),
AS(SDLK_ESCAPE, WKC_ESC),
AS(SDLK_PAUSE, WKC_PAUSE),
AS(SDLK_BACKSPACE, WKC_BACKSPACE),
AS(SDLK_SPACE, WKC_SPACE),
AS(SDLK_RETURN, WKC_RETURN),
AS(SDLK_TAB, WKC_TAB),
/* Function keys */
AM(SDLK_F1, SDLK_F12, WKC_F1, WKC_F12),
/* Numeric part. */
AM(SDLK_KP0, SDLK_KP9, '0', '9'),
AS(SDLK_KP_DIVIDE, WKC_NUM_DIV),
AS(SDLK_KP_MULTIPLY, WKC_NUM_MUL),
AS(SDLK_KP_MINUS, WKC_NUM_MINUS),
AS(SDLK_KP_PLUS, WKC_NUM_PLUS),
AS(SDLK_KP_ENTER, WKC_NUM_ENTER),
AS(SDLK_KP_PERIOD, WKC_NUM_DECIMAL),
/* Other non-letter keys */
AS(SDLK_SLASH, WKC_SLASH),
AS(SDLK_SEMICOLON, WKC_SEMICOLON),
AS(SDLK_EQUALS, WKC_EQUALS),
AS(SDLK_LEFTBRACKET, WKC_L_BRACKET),
AS(SDLK_BACKSLASH, WKC_BACKSLASH),
AS(SDLK_RIGHTBRACKET, WKC_R_BRACKET),
AS(SDLK_QUOTE, WKC_SINGLEQUOTE),
AS(SDLK_COMMA, WKC_COMMA),
AS(SDLK_MINUS, WKC_MINUS),
AS(SDLK_PERIOD, WKC_PERIOD)
};
static uint32 ConvertSdlKeyIntoMy(SDL_keysym *sym)
{
const VkMapping *map;
uint key = 0;
for (map = _vk_mapping; map != endof(_vk_mapping); ++map) {
if ((uint)(sym->sym - map->vk_from) <= map->vk_count) {
key = sym->sym - map->vk_from + map->map_to;
break;
}
}
/* check scancode for BACKQUOTE key, because we want the key left of "1", not anything else (on non-US keyboards) */
#if defined(WIN32) || defined(__OS2__)
if (sym->scancode == 41) key = WKC_BACKQUOTE;
#elif defined(__APPLE__)
if (sym->scancode == 10) key = WKC_BACKQUOTE;
#elif defined(__MORPHOS__)
if (sym->scancode == 0) key = WKC_BACKQUOTE; // yes, that key is code '0' under MorphOS :)
#elif defined(__BEOS__)
if (sym->scancode == 17) key = WKC_BACKQUOTE;
#elif defined(__SVR4) && defined(__sun)
if (sym->scancode == 60) key = WKC_BACKQUOTE;
if (sym->scancode == 49) key = WKC_BACKSPACE;
#elif defined(__sgi__)
if (sym->scancode == 22) key = WKC_BACKQUOTE;
#else
if (sym->scancode == 49) key = WKC_BACKQUOTE;
#endif
/* META are the command keys on mac */
if (sym->mod & KMOD_META) key |= WKC_META;
if (sym->mod & KMOD_SHIFT) key |= WKC_SHIFT;
if (sym->mod & KMOD_CTRL) key |= WKC_CTRL;
if (sym->mod & KMOD_ALT) key |= WKC_ALT;
return (key << 16) + sym->unicode;
}
static int PollEvent()
{
SDL_Event ev;
if (!SDL_CALL SDL_PollEvent(&ev)) return -2;
switch (ev.type) {
case SDL_MOUSEMOTION:
if (_cursor.fix_at) {
int dx = ev.motion.x - _cursor.pos.x;
int dy = ev.motion.y - _cursor.pos.y;
if (dx != 0 || dy != 0) {
_cursor.delta.x += dx;
_cursor.delta.y += dy;
SDL_CALL SDL_WarpMouse(_cursor.pos.x, _cursor.pos.y);
}
} else {
_cursor.delta.x = ev.motion.x - _cursor.pos.x;
_cursor.delta.y = ev.motion.y - _cursor.pos.y;
_cursor.pos.x = ev.motion.x;
_cursor.pos.y = ev.motion.y;
_cursor.dirty = true;
}
HandleMouseEvents();
break;
case SDL_MOUSEBUTTONDOWN:
if (_rightclick_emulate && SDL_CALL SDL_GetModState() & KMOD_CTRL) {
ev.button.button = SDL_BUTTON_RIGHT;
}
switch (ev.button.button) {
case SDL_BUTTON_LEFT:
_left_button_down = true;
break;
case SDL_BUTTON_RIGHT:
_right_button_down = true;
_right_button_clicked = true;
break;
case SDL_BUTTON_WHEELUP: _cursor.wheel--; break;
case SDL_BUTTON_WHEELDOWN: _cursor.wheel++; break;
default: break;
}
HandleMouseEvents();
break;
case SDL_MOUSEBUTTONUP:
if (_rightclick_emulate) {
_right_button_down = false;
_left_button_down = false;
_left_button_clicked = false;
} else if (ev.button.button == SDL_BUTTON_LEFT) {
_left_button_down = false;
_left_button_clicked = false;
} else if (ev.button.button == SDL_BUTTON_RIGHT) {
_right_button_down = false;
}
HandleMouseEvents();
break;
case SDL_ACTIVEEVENT:
if (!(ev.active.state & SDL_APPMOUSEFOCUS)) break;
if (ev.active.gain) { // mouse entered the window, enable cursor
_cursor.in_window = true;
} else {
UndrawMouseCursor(); // mouse left the window, undraw cursor
_cursor.in_window = false;
}
break;
case SDL_QUIT:
HandleExitGameRequest();
break;
case SDL_KEYDOWN: // Toggle full-screen on ALT + ENTER/F
if ((ev.key.keysym.mod & (KMOD_ALT | KMOD_META)) &&
(ev.key.keysym.sym == SDLK_RETURN || ev.key.keysym.sym == SDLK_f)) {
ToggleFullScreen(!_fullscreen);
} else {
HandleKeypress(ConvertSdlKeyIntoMy(&ev.key.keysym));
}
break;
case SDL_VIDEORESIZE: {
int w = max(ev.resize.w, 64);
int h = max(ev.resize.h, 64);
ChangeResInGame(w, h);
break;
}
}
return -1;
}
const char *VideoDriver_SDL::Start(const char * const *parm)
{
char buf[30];
#ifndef N3DS
const char *s = SdlOpen(SDL_INIT_VIDEO);
#else
const char *s = SdlOpen(SDL_INIT_VIDEO|SDL_INIT_JOYSTICK);
#endif /* N3DS */
if (s != NULL) return s;
SDL_CALL SDL_VideoDriverName(buf, 30);
DEBUG(driver, 1, "SDL: using driver '%s'", buf);
GetVideoModes();
CreateMainSurface(_cur_resolution.width, _cur_resolution.height);
MarkWholeScreenDirty();
SDL_CALL SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY, SDL_DEFAULT_REPEAT_INTERVAL);
SDL_CALL SDL_EnableUNICODE(1);
#ifdef N3DS
printf("**** Starting OpenTTD 0.7.0 ****\n");
printf("Don't worry if you get a \"Game Load Failed\" error.That's just the title screen savegame.\n\n");
// Enable the 3DS's controls to be used as a joystick.
_3ds_joystick = SDL_JoystickOpen(0);
SDL_JoystickEventState(SDL_ENABLE);
#endif /* N3DS */
return NULL;
}
void VideoDriver_SDL::Stop()
{
SdlClose(SDL_INIT_VIDEO);
}
void VideoDriver_SDL::MainLoop()
{
uint32 cur_ticks = SDL_CALL SDL_GetTicks();
uint32 last_cur_ticks = cur_ticks;
uint32 next_tick = cur_ticks + 30;
uint32 pal_tick = 0;
uint32 mod;
int numkeys;
Uint8 *keys;
for (;;) {
uint32 prev_cur_ticks = cur_ticks; // to check for wrapping
InteractiveRandom(); // randomness
while (PollEvent() == -1) {}
if (_exit_game) return;
mod = SDL_CALL SDL_GetModState();
keys = SDL_CALL SDL_GetKeyState(&numkeys);
#if defined(_DEBUG)
if (_shift_pressed)
#else
/* Speedup when pressing tab, except when using ALT+TAB
* to switch to another application */
if (keys[SDLK_TAB] && (mod & KMOD_ALT) == 0)
#endif
{
if (!_networking && _game_mode != GM_MENU) _fast_forward |= 2;
} else if (_fast_forward & 2) {
_fast_forward = 0;
}
cur_ticks = SDL_CALL SDL_GetTicks();
if (cur_ticks >= next_tick || (_fast_forward && !_pause_game) || cur_ticks < prev_cur_ticks) {
_realtime_tick += cur_ticks - last_cur_ticks;
last_cur_ticks = cur_ticks;
next_tick = cur_ticks + 30;
bool old_ctrl_pressed = _ctrl_pressed;
_ctrl_pressed = !!(mod & KMOD_CTRL);
_shift_pressed = !!(mod & KMOD_SHIFT);
/* determine which directional keys are down */
#ifdef N3DS
_dirkeys =
(SDL_JoystickGetButton(_3ds_joystick, 9) ? 1 : 0) |
(SDL_JoystickGetButton(_3ds_joystick, 10) ? 2 : 0) |
(SDL_JoystickGetButton(_3ds_joystick, 11) ? 4 : 0) |
(SDL_JoystickGetButton(_3ds_joystick, 8) ? 8 : 0);
#else
_dirkeys =
(keys[SDLK_LEFT] ? 1 : 0) |
(keys[SDLK_UP] ? 2 : 0) |
(keys[SDLK_RIGHT] ? 4 : 0) |
(keys[SDLK_DOWN] ? 8 : 0);
#endif
if (old_ctrl_pressed != _ctrl_pressed) HandleCtrlChanged();
GameLoop();
_screen.dst_ptr = _sdl_screen->pixels;
UpdateWindows();
if (++pal_tick > 4) {
CheckPaletteAnim();
pal_tick = 1;
}
DrawSurfaceToScreen();
} else {
SDL_CALL SDL_Delay(1);
_screen.dst_ptr = _sdl_screen->pixels;
NetworkDrawChatMessage();
DrawMouseCursor();
DrawSurfaceToScreen();
}
#ifdef N3DS
/*int heap_size = envGetHeapSize();
printf("heap size: %d\n\n", heap_size);*/
#endif
}
}
bool VideoDriver_SDL::ChangeResolution(int w, int h)
{
return CreateMainSurface(w, h);
}
bool VideoDriver_SDL::ToggleFullscreen(bool fullscreen)
{
_fullscreen = fullscreen;
GetVideoModes(); // get the list of available video modes
if (_num_resolutions == 0 || !this->ChangeResolution(_cur_resolution.width, _cur_resolution.height)) {
/* switching resolution failed, put back full_screen to original status */
_fullscreen ^= true;
return false;
}
return true;
}
#endif /* WITH_SDL */
| 14,730
|
C++
|
.cpp
| 479
| 27.91023
| 131
| 0.662522
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,169
|
random_func.cpp
|
EnergeticBark_OpenTTD-3DS/src/core/random_func.cpp
|
/* $Id$ */
/** @file random_func.cpp Implementation of the pseudo random generator. */
#include "../stdafx.h"
#include "random_func.hpp"
#include "bitmath_func.hpp"
Randomizer _random, _interactive_random;
uint32 Randomizer::Next()
{
const uint32 s = this->state[0];
const uint32 t = this->state[1];
this->state[0] = s + ROR(t ^ 0x1234567F, 7) + 1;
return this->state[1] = ROR(s, 3) - 1;
}
uint32 Randomizer::Next(uint16 max)
{
return GB(this->Next(), 0, 16) * max >> 16;
}
void Randomizer::SetSeed(uint32 seed)
{
this->state[0] = seed;
this->state[1] = seed;
}
void SetRandomSeed(uint32 seed)
{
_random.SetSeed(seed);
_interactive_random.SetSeed(seed * 0x1234567);
}
#ifdef RANDOM_DEBUG
#include "../network/network_internal.h"
#include "../company_func.h"
uint32 DoRandom(int line, const char *file)
{
if (_networking && (GetNetworkClientSocket(0)->status != STATUS_INACTIVE || !_network_server)) {
printf("Random [%d/%d] %s:%d\n", _frame_counter, (byte)_current_company, file, line);
}
return _random.Next();
}
uint DoRandomRange(uint max, int line, const char *file)
{
return GB(DoRandom(line, file), 0, 16) * max >> 16;
}
#endif /* RANDOM_DEBUG */
| 1,180
|
C++
|
.cpp
| 42
| 26.452381
| 97
| 0.695382
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
1,539,170
|
alloc_func.cpp
|
EnergeticBark_OpenTTD-3DS/src/core/alloc_func.cpp
|
/* $Id$ */
/** @file alloc_func.cpp Functions to 'handle' memory allocation errors */
#include "../stdafx.h"
#include "alloc_func.hpp"
/**
* Function to exit with an error message after malloc() or calloc() have failed
* @param size number of bytes we tried to allocate
*/
void NORETURN MallocError(size_t size)
{
error("Out of memory. Cannot allocate %i bytes", size);
}
/**
* Function to exit with an error message after realloc() have failed
* @param size number of bytes we tried to allocate
*/
void NORETURN ReallocError(size_t size)
{
error("Out of memory. Cannot reallocate %i bytes", size);
}
| 613
|
C++
|
.cpp
| 20
| 29.05
| 80
| 0.730051
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,171
|
bitmath_func.cpp
|
EnergeticBark_OpenTTD-3DS/src/core/bitmath_func.cpp
|
/* $Id$ */
/** @file bitmath_func.cpp Functions related to bit mathematics. */
#include "../stdafx.h"
#include "bitmath_func.hpp"
const uint8 _ffb_64[64] = {
0, 0, 1, 0, 2, 0, 1, 0,
3, 0, 1, 0, 2, 0, 1, 0,
4, 0, 1, 0, 2, 0, 1, 0,
3, 0, 1, 0, 2, 0, 1, 0,
5, 0, 1, 0, 2, 0, 1, 0,
3, 0, 1, 0, 2, 0, 1, 0,
4, 0, 1, 0, 2, 0, 1, 0,
3, 0, 1, 0, 2, 0, 1, 0,
};
/**
* Search the first set bit in a 32 bit variable.
*
* This algorithm is a static implementation of a log
* conguence search algorithm. It checks the first half
* if there is a bit set search there further. And this
* way further. If no bit is set return 0.
*
* @param x The value to search
* @return The position of the first bit set
*/
uint8 FindFirstBit(uint32 x)
{
if (x == 0) return 0;
/* The macro FIND_FIRST_BIT is better to use when your x is
not more than 128. */
uint8 pos = 0;
if ((x & 0x0000ffff) == 0) { x >>= 16; pos += 16; }
if ((x & 0x000000ff) == 0) { x >>= 8; pos += 8; }
if ((x & 0x0000000f) == 0) { x >>= 4; pos += 4; }
if ((x & 0x00000003) == 0) { x >>= 2; pos += 2; }
if ((x & 0x00000001) == 0) { pos += 1; }
return pos;
}
/**
* Search the last set bit in a 64 bit variable.
*
* This algorithm is a static implementation of a log
* conguence search algorithm. It checks the second half
* if there is a bit set search there further. And this
* way further. If no bit is set return 0.
*
* @param x The value to search
* @return The position of the last bit set
*/
uint8 FindLastBit(uint64 x)
{
if (x == 0) return 0;
uint8 pos = 0;
if ((x & 0xffffffff00000000ULL) != 0) { x >>= 32; pos += 32; }
if ((x & 0x00000000ffff0000ULL) != 0) { x >>= 16; pos += 16; }
if ((x & 0x000000000000ff00ULL) != 0) { x >>= 8; pos += 8; }
if ((x & 0x00000000000000f0ULL) != 0) { x >>= 4; pos += 4; }
if ((x & 0x000000000000000cULL) != 0) { x >>= 2; pos += 2; }
if ((x & 0x0000000000000002ULL) != 0) { pos += 1; }
return pos;
}
| 2,009
|
C++
|
.cpp
| 61
| 30.95082
| 67
| 0.574084
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
1,539,173
|
32bpp_base.cpp
|
EnergeticBark_OpenTTD-3DS/src/blitter/32bpp_base.cpp
|
/* $Id$ */
/** @file 32bpp_base.cpp Implementation of base for 32 bpp blitters. */
#include "../stdafx.h"
#include "../gfx_func.h"
#include "32bpp_base.hpp"
void *Blitter_32bppBase::MoveTo(const void *video, int x, int y)
{
return (uint32 *)video + x + y * _screen.pitch;
}
void Blitter_32bppBase::SetPixel(void *video, int x, int y, uint8 colour)
{
*((uint32 *)video + x + y * _screen.pitch) = LookupColourInPalette(colour);
}
void Blitter_32bppBase::SetPixelIfEmpty(void *video, int x, int y, uint8 colour)
{
uint32 *dst = (uint32 *)video + x + y * _screen.pitch;
if (*dst == 0) *dst = LookupColourInPalette(colour);
}
void Blitter_32bppBase::DrawRect(void *video, int width, int height, uint8 colour)
{
uint32 colour32 = LookupColourInPalette(colour);
do {
uint32 *dst = (uint32 *)video;
for (int i = width; i > 0; i--) {
*dst = colour32;
dst++;
}
video = (uint32 *)video + _screen.pitch;
} while (--height);
}
void Blitter_32bppBase::DrawLine(void *video, int x, int y, int x2, int y2, int screen_width, int screen_height, uint8 colour)
{
int dy;
int dx;
int stepx;
int stepy;
int frac;
dy = (y2 - y) * 2;
if (dy < 0) {
dy = -dy;
stepy = -1;
} else {
stepy = 1;
}
dx = (x2 - x) * 2;
if (dx < 0) {
dx = -dx;
stepx = -1;
} else {
stepx = 1;
}
if (x >= 0 && y >= 0 && x < screen_width && y < screen_height) this->SetPixel(video, x, y, colour);
if (dx > dy) {
frac = dy - (dx / 2);
while (x != x2) {
if (frac >= 0) {
y += stepy;
frac -= dx;
}
x += stepx;
frac += dy;
if (x >= 0 && y >= 0 && x < screen_width && y < screen_height) this->SetPixel(video, x, y, colour);
}
} else {
frac = dx - (dy / 2);
while (y != y2) {
if (frac >= 0) {
x += stepx;
frac -= dy;
}
y += stepy;
frac += dx;
if (x >= 0 && y >= 0 && x < screen_width && y < screen_height) this->SetPixel(video, x, y, colour);
}
}
}
void Blitter_32bppBase::CopyFromBuffer(void *video, const void *src, int width, int height)
{
uint32 *dst = (uint32 *)video;
uint32 *usrc = (uint32 *)src;
for (; height > 0; height--) {
memcpy(dst, usrc, width * sizeof(uint32));
usrc += width;
dst += _screen.pitch;
}
}
void Blitter_32bppBase::CopyToBuffer(const void *video, void *dst, int width, int height)
{
uint32 *udst = (uint32 *)dst;
uint32 *src = (uint32 *)video;
for (; height > 0; height--) {
memcpy(udst, src, width * sizeof(uint32));
src += _screen.pitch;
udst += width;
}
}
void Blitter_32bppBase::CopyImageToBuffer(const void *video, void *dst, int width, int height, int dst_pitch)
{
uint32 *udst = (uint32 *)dst;
uint32 *src = (uint32 *)video;
for (; height > 0; height--) {
memcpy(udst, src, width * sizeof(uint32));
src += _screen.pitch;
udst += dst_pitch;
}
}
void Blitter_32bppBase::ScrollBuffer(void *video, int &left, int &top, int &width, int &height, int scroll_x, int scroll_y)
{
const uint32 *src;
uint32 *dst;
if (scroll_y > 0) {
/* Calculate pointers */
dst = (uint32 *)video + left + (top + height - 1) * _screen.pitch;
src = dst - scroll_y * _screen.pitch;
/* Decrease height and increase top */
top += scroll_y;
height -= scroll_y;
assert(height > 0);
/* Adjust left & width */
if (scroll_x >= 0) {
dst += scroll_x;
left += scroll_x;
width -= scroll_x;
} else {
src -= scroll_x;
width += scroll_x;
}
for (int h = height; h > 0; h--) {
memcpy(dst, src, width * sizeof(uint32));
src -= _screen.pitch;
dst -= _screen.pitch;
}
} else {
/* Calculate pointers */
dst = (uint32 *)video + left + top * _screen.pitch;
src = dst - scroll_y * _screen.pitch;
/* Decrese height. (scroll_y is <=0). */
height += scroll_y;
assert(height > 0);
/* Adjust left & width */
if (scroll_x >= 0) {
dst += scroll_x;
left += scroll_x;
width -= scroll_x;
} else {
src -= scroll_x;
width += scroll_x;
}
/* the y-displacement may be 0 therefore we have to use memmove,
* because source and destination may overlap */
for (int h = height; h > 0; h--) {
memmove(dst, src, width * sizeof(uint32));
src += _screen.pitch;
dst += _screen.pitch;
}
}
}
int Blitter_32bppBase::BufferSize(int width, int height)
{
return width * height * sizeof(uint32);
}
void Blitter_32bppBase::PaletteAnimate(uint start, uint count)
{
/* By default, 32bpp doesn't have palette animation */
}
Blitter::PaletteAnimation Blitter_32bppBase::UsePaletteAnimation()
{
return Blitter::PALETTE_ANIMATION_NONE;
}
| 4,501
|
C++
|
.cpp
| 169
| 23.994083
| 126
| 0.624071
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,179
|
null.cpp
|
EnergeticBark_OpenTTD-3DS/src/blitter/null.cpp
|
/* $Id$ */
/** @file null.cpp A blitter that doesn't blit. */
#include "../stdafx.h"
#include "null.hpp"
static FBlitter_Null iFBlitter_Null;
Sprite *Blitter_Null::Encode(SpriteLoader::Sprite *sprite, Blitter::AllocatorProc *allocator)
{
Sprite *dest_sprite;
dest_sprite = (Sprite *)allocator(sizeof(*dest_sprite));
dest_sprite->height = sprite->height;
dest_sprite->width = sprite->width;
dest_sprite->x_offs = sprite->x_offs;
dest_sprite->y_offs = sprite->y_offs;
return dest_sprite;
}
| 502
|
C++
|
.cpp
| 15
| 31.6
| 93
| 0.725572
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| true
| false
|
1,539,202
|
yapf_road.cpp
|
EnergeticBark_OpenTTD-3DS/src/yapf/yapf_road.cpp
|
/* $Id$ */
/** @file yapf_road.cpp The road pathfinding. */
#include "../stdafx.h"
#include "../depot_base.h"
#include "yapf.hpp"
#include "yapf_node_road.hpp"
template <class Types>
class CYapfCostRoadT
{
public:
typedef typename Types::Tpf Tpf; ///< pathfinder (derived from THIS class)
typedef typename Types::TrackFollower TrackFollower; ///< track follower helper
typedef typename Types::NodeList::Titem Node; ///< this will be our node type
typedef typename Node::Key Key; ///< key to hash tables
protected:
/** to access inherited path finder */
Tpf& Yapf()
{
return *static_cast<Tpf*>(this);
}
int SlopeCost(TileIndex tile, TileIndex next_tile, Trackdir trackdir)
{
/* height of the center of the current tile */
int x1 = TileX(tile) * TILE_SIZE;
int y1 = TileY(tile) * TILE_SIZE;
int z1 = GetSlopeZ(x1 + TILE_SIZE / 2, y1 + TILE_SIZE / 2);
/* height of the center of the next tile */
int x2 = TileX(next_tile) * TILE_SIZE;
int y2 = TileY(next_tile) * TILE_SIZE;
int z2 = GetSlopeZ(x2 + TILE_SIZE / 2, y2 + TILE_SIZE / 2);
if (z2 - z1 > 1) {
/* Slope up */
return Yapf().PfGetSettings().road_slope_penalty;
}
return 0;
}
/** return one tile cost */
FORCEINLINE int OneTileCost(TileIndex tile, Trackdir trackdir)
{
int cost = 0;
/* set base cost */
if (IsDiagonalTrackdir(trackdir)) {
cost += YAPF_TILE_LENGTH;
switch (GetTileType(tile)) {
case MP_ROAD:
/* Increase the cost for level crossings */
if (IsLevelCrossing(tile)) {
cost += Yapf().PfGetSettings().road_crossing_penalty;
}
break;
case MP_STATION:
if (IsDriveThroughStopTile(tile)) {
cost += Yapf().PfGetSettings().road_stop_penalty;
}
break;
default:
break;
}
} else {
/* non-diagonal trackdir */
cost = YAPF_TILE_CORNER_LENGTH + Yapf().PfGetSettings().road_curve_penalty;
}
return cost;
}
public:
/** Called by YAPF to calculate the cost from the origin to the given node.
* Calculates only the cost of given node, adds it to the parent node cost
* and stores the result into Node::m_cost member */
FORCEINLINE bool PfCalcCost(Node& n, const TrackFollower *tf)
{
int segment_cost = 0;
/* start at n.m_key.m_tile / n.m_key.m_td and walk to the end of segment */
TileIndex tile = n.m_key.m_tile;
Trackdir trackdir = n.m_key.m_td;
while (true) {
/* base tile cost depending on distance between edges */
segment_cost += Yapf().OneTileCost(tile, trackdir);
const Vehicle *v = Yapf().GetVehicle();
/* we have reached the vehicle's destination - segment should end here to avoid target skipping */
if (Yapf().PfDetectDestinationTile(tile, trackdir)) break;
/* stop if we have just entered the depot */
if (IsRoadDepotTile(tile) && trackdir == DiagDirToDiagTrackdir(ReverseDiagDir(GetRoadDepotDirection(tile)))) {
/* next time we will reverse and leave the depot */
break;
}
/* if there are no reachable trackdirs on new tile, we have end of road */
TrackFollower F(Yapf().GetVehicle());
if (!F.Follow(tile, trackdir)) break;
/* if there are more trackdirs available & reachable, we are at the end of segment */
if (KillFirstBit(F.m_new_td_bits) != TRACKDIR_BIT_NONE) break;
Trackdir new_td = (Trackdir)FindFirstBit2x64(F.m_new_td_bits);
/* stop if RV is on simple loop with no junctions */
if (F.m_new_tile == n.m_key.m_tile && new_td == n.m_key.m_td) return false;
/* if we skipped some tunnel tiles, add their cost */
segment_cost += F.m_tiles_skipped * YAPF_TILE_LENGTH;
/* add hilly terrain penalty */
segment_cost += Yapf().SlopeCost(tile, F.m_new_tile, trackdir);
/* add min/max speed penalties */
int min_speed = 0;
int max_speed = F.GetSpeedLimit(&min_speed);
if (max_speed < v->max_speed) segment_cost += 1 * (v->max_speed - max_speed);
if (min_speed > v->max_speed) segment_cost += 10 * (min_speed - v->max_speed);
/* move to the next tile */
tile = F.m_new_tile;
trackdir = new_td;
};
/* save end of segment back to the node */
n.m_segment_last_tile = tile;
n.m_segment_last_td = trackdir;
/* save also tile cost */
int parent_cost = (n.m_parent != NULL) ? n.m_parent->m_cost : 0;
n.m_cost = parent_cost + segment_cost;
return true;
}
};
template <class Types>
class CYapfDestinationAnyDepotRoadT
{
public:
typedef typename Types::Tpf Tpf; ///< the pathfinder class (derived from THIS class)
typedef typename Types::TrackFollower TrackFollower;
typedef typename Types::NodeList::Titem Node; ///< this will be our node type
typedef typename Node::Key Key; ///< key to hash tables
/** to access inherited path finder */
Tpf& Yapf()
{
return *static_cast<Tpf*>(this);
}
/** Called by YAPF to detect if node ends in the desired destination */
FORCEINLINE bool PfDetectDestination(Node& n)
{
bool bDest = IsRoadDepotTile(n.m_segment_last_tile);
return bDest;
}
FORCEINLINE bool PfDetectDestinationTile(TileIndex tile, Trackdir trackdir)
{
return IsRoadDepotTile(tile);
}
/** Called by YAPF to calculate cost estimate. Calculates distance to the destination
* adds it to the actual cost from origin and stores the sum to the Node::m_estimate */
FORCEINLINE bool PfCalcEstimate(Node& n)
{
n.m_estimate = n.m_cost;
return true;
}
};
template <class Types>
class CYapfDestinationTileRoadT
{
public:
typedef typename Types::Tpf Tpf; ///< the pathfinder class (derived from THIS class)
typedef typename Types::TrackFollower TrackFollower;
typedef typename Types::NodeList::Titem Node; ///< this will be our node type
typedef typename Node::Key Key; ///< key to hash tables
protected:
TileIndex m_destTile;
TrackdirBits m_destTrackdirs;
public:
void SetDestination(TileIndex tile, TrackdirBits trackdirs)
{
m_destTile = tile;
m_destTrackdirs = trackdirs;
}
protected:
/** to access inherited path finder */
Tpf& Yapf()
{
return *static_cast<Tpf*>(this);
}
public:
/** Called by YAPF to detect if node ends in the desired destination */
FORCEINLINE bool PfDetectDestination(Node& n)
{
bool bDest = (n.m_segment_last_tile == m_destTile) && ((m_destTrackdirs & TrackdirToTrackdirBits(n.m_segment_last_td)) != TRACKDIR_BIT_NONE);
return bDest;
}
FORCEINLINE bool PfDetectDestinationTile(TileIndex tile, Trackdir trackdir)
{
return tile == m_destTile && ((m_destTrackdirs & TrackdirToTrackdirBits(trackdir)) != TRACKDIR_BIT_NONE);
}
/** Called by YAPF to calculate cost estimate. Calculates distance to the destination
* adds it to the actual cost from origin and stores the sum to the Node::m_estimate */
inline bool PfCalcEstimate(Node& n)
{
static int dg_dir_to_x_offs[] = {-1, 0, 1, 0};
static int dg_dir_to_y_offs[] = {0, 1, 0, -1};
if (PfDetectDestination(n)) {
n.m_estimate = n.m_cost;
return true;
}
TileIndex tile = n.m_segment_last_tile;
DiagDirection exitdir = TrackdirToExitdir(n.m_segment_last_td);
int x1 = 2 * TileX(tile) + dg_dir_to_x_offs[(int)exitdir];
int y1 = 2 * TileY(tile) + dg_dir_to_y_offs[(int)exitdir];
int x2 = 2 * TileX(m_destTile);
int y2 = 2 * TileY(m_destTile);
int dx = abs(x1 - x2);
int dy = abs(y1 - y2);
int dmin = min(dx, dy);
int dxy = abs(dx - dy);
int d = dmin * YAPF_TILE_CORNER_LENGTH + (dxy - 1) * (YAPF_TILE_LENGTH / 2);
n.m_estimate = n.m_cost + d;
assert(n.m_estimate >= n.m_parent->m_estimate);
return true;
}
};
template <class Types>
class CYapfFollowRoadT
{
public:
typedef typename Types::Tpf Tpf; ///< the pathfinder class (derived from THIS class)
typedef typename Types::TrackFollower TrackFollower;
typedef typename Types::NodeList::Titem Node; ///< this will be our node type
typedef typename Node::Key Key; ///< key to hash tables
protected:
/** to access inherited path finder */
FORCEINLINE Tpf& Yapf()
{
return *static_cast<Tpf*>(this);
}
public:
/** Called by YAPF to move from the given node to the next tile. For each
* reachable trackdir on the new tile creates new node, initializes it
* and adds it to the open list by calling Yapf().AddNewNode(n) */
inline void PfFollowNode(Node& old_node)
{
TrackFollower F(Yapf().GetVehicle());
if (F.Follow(old_node.m_segment_last_tile, old_node.m_segment_last_td)) {
Yapf().AddMultipleNodes(&old_node, F);
}
}
/** return debug report character to identify the transportation type */
FORCEINLINE char TransportTypeChar() const
{
return 'r';
}
static Trackdir stChooseRoadTrack(const Vehicle *v, TileIndex tile, DiagDirection enterdir)
{
Tpf pf;
return pf.ChooseRoadTrack(v, tile, enterdir);
}
FORCEINLINE Trackdir ChooseRoadTrack(const Vehicle *v, TileIndex tile, DiagDirection enterdir)
{
/* handle special case - when next tile is destination tile */
if (tile == v->dest_tile) {
/* choose diagonal trackdir reachable from enterdir */
return DiagDirToDiagTrackdir(enterdir);
}
/* our source tile will be the next vehicle tile (should be the given one) */
TileIndex src_tile = tile;
/* get available trackdirs on the start tile */
TrackdirBits src_trackdirs = TrackStatusToTrackdirBits(GetTileTrackStatus(tile, TRANSPORT_ROAD, v->u.road.compatible_roadtypes));
/* select reachable trackdirs only */
src_trackdirs &= DiagdirReachesTrackdirs(enterdir);
/* get available trackdirs on the destination tile */
TileIndex dest_tile = v->dest_tile;
TrackdirBits dest_trackdirs = TrackStatusToTrackdirBits(GetTileTrackStatus(dest_tile, TRANSPORT_ROAD, v->u.road.compatible_roadtypes));
/* set origin and destination nodes */
Yapf().SetOrigin(src_tile, src_trackdirs);
Yapf().SetDestination(dest_tile, dest_trackdirs);
/* find the best path */
Yapf().FindPath(v);
/* if path not found - return INVALID_TRACKDIR */
Trackdir next_trackdir = INVALID_TRACKDIR;
Node *pNode = Yapf().GetBestNode();
if (pNode != NULL) {
/* path was found or at least suggested
* walk through the path back to its origin */
while (pNode->m_parent != NULL) {
pNode = pNode->m_parent;
}
/* return trackdir from the best origin node (one of start nodes) */
Node& best_next_node = *pNode;
assert(best_next_node.GetTile() == tile);
next_trackdir = best_next_node.GetTrackdir();
}
return next_trackdir;
}
static uint stDistanceToTile(const Vehicle *v, TileIndex tile)
{
Tpf pf;
return pf.DistanceToTile(v, tile);
}
FORCEINLINE uint DistanceToTile(const Vehicle *v, TileIndex dst_tile)
{
/* handle special case - when current tile is the destination tile */
if (dst_tile == v->tile) {
/* distance is zero in this case */
return 0;
}
if (!SetOriginFromVehiclePos(v)) return UINT_MAX;
/* set destination tile, trackdir
* get available trackdirs on the destination tile */
TrackdirBits dst_td_bits = TrackStatusToTrackdirBits(GetTileTrackStatus(dst_tile, TRANSPORT_ROAD, v->u.road.compatible_roadtypes));
Yapf().SetDestination(dst_tile, dst_td_bits);
/* if path not found - return distance = UINT_MAX */
uint dist = UINT_MAX;
/* find the best path */
if (!Yapf().FindPath(v)) return dist;
Node *pNode = Yapf().GetBestNode();
if (pNode != NULL) {
/* path was found
* get the path cost estimate */
dist = pNode->GetCostEstimate();
}
return dist;
}
/** Return true if the valid origin (tile/trackdir) was set from the current vehicle position. */
FORCEINLINE bool SetOriginFromVehiclePos(const Vehicle *v)
{
/* set origin (tile, trackdir) */
TileIndex src_tile = v->tile;
Trackdir src_td = GetVehicleTrackdir(v);
if ((TrackStatusToTrackdirBits(GetTileTrackStatus(src_tile, TRANSPORT_ROAD, v->u.road.compatible_roadtypes)) & TrackdirToTrackdirBits(src_td)) == 0) {
/* sometimes the roadveh is not on the road (it resides on non-existing track)
* how should we handle that situation? */
return false;
}
Yapf().SetOrigin(src_tile, TrackdirToTrackdirBits(src_td));
return true;
}
static Depot *stFindNearestDepot(const Vehicle *v, TileIndex tile, Trackdir td)
{
Tpf pf;
return pf.FindNearestDepot(v, tile, td);
}
FORCEINLINE Depot *FindNearestDepot(const Vehicle *v, TileIndex tile, Trackdir td)
{
/* set origin and destination nodes */
Yapf().SetOrigin(tile, TrackdirToTrackdirBits(td));
/* find the best path */
bool bFound = Yapf().FindPath(v);
if (!bFound) return;
/* some path found
* get found depot tile */
Node *n = Yapf().GetBestNode();
TileIndex depot_tile = n->m_segment_last_tile;
assert(IsRoadDepotTile(depot_tile));
Depot *ret = GetDepotByTile(depot_tile);
return ret;
}
};
template <class Tpf_, class Tnode_list, template <class Types> class Tdestination>
struct CYapfRoad_TypesT
{
typedef CYapfRoad_TypesT<Tpf_, Tnode_list, Tdestination> Types;
typedef Tpf_ Tpf;
typedef CFollowTrackRoad TrackFollower;
typedef Tnode_list NodeList;
typedef CYapfBaseT<Types> PfBase;
typedef CYapfFollowRoadT<Types> PfFollow;
typedef CYapfOriginTileT<Types> PfOrigin;
typedef Tdestination<Types> PfDestination;
typedef CYapfSegmentCostCacheNoneT<Types> PfCache;
typedef CYapfCostRoadT<Types> PfCost;
};
struct CYapfRoad1 : CYapfT<CYapfRoad_TypesT<CYapfRoad1 , CRoadNodeListTrackDir, CYapfDestinationTileRoadT > > {};
struct CYapfRoad2 : CYapfT<CYapfRoad_TypesT<CYapfRoad2 , CRoadNodeListExitDir , CYapfDestinationTileRoadT > > {};
struct CYapfRoadAnyDepot1 : CYapfT<CYapfRoad_TypesT<CYapfRoadAnyDepot1, CRoadNodeListTrackDir, CYapfDestinationAnyDepotRoadT> > {};
struct CYapfRoadAnyDepot2 : CYapfT<CYapfRoad_TypesT<CYapfRoadAnyDepot2, CRoadNodeListExitDir , CYapfDestinationAnyDepotRoadT> > {};
Trackdir YapfChooseRoadTrack(const Vehicle *v, TileIndex tile, DiagDirection enterdir)
{
/* default is YAPF type 2 */
typedef Trackdir (*PfnChooseRoadTrack)(const Vehicle*, TileIndex, DiagDirection);
PfnChooseRoadTrack pfnChooseRoadTrack = &CYapfRoad2::stChooseRoadTrack; // default: ExitDir, allow 90-deg
/* check if non-default YAPF type should be used */
if (_settings_game.pf.yapf.disable_node_optimization) {
pfnChooseRoadTrack = &CYapfRoad1::stChooseRoadTrack; // Trackdir, allow 90-deg
}
Trackdir td_ret = pfnChooseRoadTrack(v, tile, enterdir);
return td_ret;
}
uint YapfRoadVehDistanceToTile(const Vehicle *v, TileIndex tile)
{
/* default is YAPF type 2 */
typedef uint (*PfnDistanceToTile)(const Vehicle*, TileIndex);
PfnDistanceToTile pfnDistanceToTile = &CYapfRoad2::stDistanceToTile; // default: ExitDir, allow 90-deg
/* check if non-default YAPF type should be used */
if (_settings_game.pf.yapf.disable_node_optimization) {
pfnDistanceToTile = &CYapfRoad1::stDistanceToTile; // Trackdir, allow 90-deg
}
/* measure distance in YAPF units */
uint dist = pfnDistanceToTile(v, tile);
/* convert distance to tiles */
if (dist != UINT_MAX) {
dist = (dist + YAPF_TILE_LENGTH - 1) / YAPF_TILE_LENGTH;
}
return dist;
}
Depot *YapfFindNearestRoadDepot(const Vehicle *v)
{
TileIndex tile = v->tile;
Trackdir trackdir = GetVehicleTrackdir(v);
if ((TrackStatusToTrackdirBits(GetTileTrackStatus(tile, TRANSPORT_ROAD, v->u.road.compatible_roadtypes)) & TrackdirToTrackdirBits(trackdir)) == 0) {
return NULL;
}
/* handle the case when our vehicle is already in the depot tile */
if (IsRoadDepotTile(tile)) {
/* only what we need to return is the Depot* */
return GetDepotByTile(tile);
}
/* default is YAPF type 2 */
typedef Depot *(*PfnFindNearestDepot)(const Vehicle*, TileIndex, Trackdir);
PfnFindNearestDepot pfnFindNearestDepot = &CYapfRoadAnyDepot2::stFindNearestDepot;
/* check if non-default YAPF type should be used */
if (_settings_game.pf.yapf.disable_node_optimization) {
pfnFindNearestDepot = &CYapfRoadAnyDepot1::stFindNearestDepot; // Trackdir, allow 90-deg
}
Depot *ret = pfnFindNearestDepot(v, tile, trackdir);
return ret;
}
| 16,129
|
C++
|
.cpp
| 411
| 36.386861
| 152
| 0.710265
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,204
|
dropdown.cpp
|
EnergeticBark_OpenTTD-3DS/src/widgets/dropdown.cpp
|
/* $Id$ */
/** @file dropdown.cpp Implementation of the dropdown widget. */
#include "../stdafx.h"
#include "../window_gui.h"
#include "../strings_func.h"
#include "../gfx_func.h"
#include "../window_func.h"
#include "../core/math_func.hpp"
#include "dropdown_type.h"
#include "table/strings.h"
void DropDownListItem::Draw(int x, int y, uint width, uint height, bool sel, int bg_colour) const
{
int c1 = _colour_gradient[bg_colour][3];
int c2 = _colour_gradient[bg_colour][7];
GfxFillRect(x + 1, y + 3, x + width - 2, y + 3, c1);
GfxFillRect(x + 1, y + 4, x + width - 2, y + 4, c2);
}
uint DropDownListStringItem::Width() const
{
char buffer[512];
GetString(buffer, this->String(), lastof(buffer));
return GetStringBoundingBox(buffer).width;
}
void DropDownListStringItem::Draw(int x, int y, uint width, uint height, bool sel, int bg_colour) const
{
DrawStringTruncated(x + 2, y, this->String(), sel ? TC_WHITE : TC_BLACK, width);
}
StringID DropDownListParamStringItem::String() const
{
for (uint i = 0; i < lengthof(this->decode_params); i++) SetDParam(i, this->decode_params[i]);
return this->string;
}
uint DropDownListCharStringItem::Width() const
{
return GetStringBoundingBox(this->string).width;
}
void DropDownListCharStringItem::Draw(int x, int y, uint width, uint height, bool sel, int bg_colour) const
{
DoDrawStringTruncated(this->string, x + 2, y, sel ? TC_WHITE : TC_BLACK, width);
}
/**
* Delete all items of a drop down list and the list itself
* @param list List to delete.
*/
static void DeleteDropDownList(DropDownList *list)
{
for (DropDownList::iterator it = list->begin(); it != list->end(); ++it) {
DropDownListItem *item = *it;
delete item;
}
delete list;
}
static const Widget _dropdown_menu_widgets[] = {
{ WWT_PANEL, RESIZE_NONE, COLOUR_END, 0, 0, 0, 0, 0x0, STR_NULL},
{ WWT_SCROLLBAR, RESIZE_NONE, COLOUR_END, 0, 0, 0, 0, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST},
{ WIDGETS_END},
};
struct DropdownWindow : Window {
WindowClass parent_wnd_class;
WindowNumber parent_wnd_num;
byte parent_button;
DropDownList *list;
int selected_index;
byte click_delay;
bool drag_mode;
bool instant_close;
int scrolling;
DropdownWindow(int x, int y, int width, int height, const Widget *widget) : Window(x, y, width, height, WC_DROPDOWN_MENU, widget)
{
this->FindWindowPlacementAndResize(width, height);
}
~DropdownWindow()
{
Window *w2 = FindWindowById(this->parent_wnd_class, this->parent_wnd_num);
if (w2 != NULL) {
w2->RaiseWidget(this->parent_button);
w2->InvalidateWidget(this->parent_button);
}
DeleteDropDownList(this->list);
}
bool GetDropDownItem(int &value)
{
if (GetWidgetFromPos(this, _cursor.pos.x - this->left, _cursor.pos.y - this->top) < 0) return false;
int y = _cursor.pos.y - this->top - 2;
int width = this->widget[0].right - 3;
int pos = this->vscroll.pos;
const DropDownList *list = this->list;
for (DropDownList::const_iterator it = list->begin(); it != list->end(); ++it) {
/* Skip items that are scrolled up */
if (--pos >= 0) continue;
const DropDownListItem *item = *it;
int item_height = item->Height(width);
if (y < item_height) {
if (item->masked || !item->Selectable()) return false;
value = item->result;
return true;
}
y -= item_height;
}
return false;
}
virtual void OnPaint()
{
this->DrawWidgets();
int x = 1;
int y = 2;
int sel = this->selected_index;
int width = this->widget[0].right - 2;
int height = this->widget[0].bottom;
int pos = this->vscroll.pos;
DropDownList *list = this->list;
for (DropDownList::const_iterator it = list->begin(); it != list->end(); ++it) {
const DropDownListItem *item = *it;
int item_height = item->Height(width);
/* Skip items that are scrolled up */
if (--pos >= 0) continue;
if (y + item_height < height) {
if (sel == item->result) GfxFillRect(x + 1, y, x + width - 1, y + item_height - 1, 0);
item->Draw(x, y, width, height, sel == item->result, (TextColour)this->widget[0].colour);
if (item->masked) {
GfxFillRect(x, y, x + width - 1, y + item_height - 1,
_colour_gradient[this->widget[0].colour][5], FILLRECT_CHECKER
);
}
}
y += item_height;
}
};
virtual void OnClick(Point pt, int widget)
{
if (widget != 0) return;
int item;
if (this->GetDropDownItem(item)) {
this->click_delay = 4;
this->selected_index = item;
this->SetDirty();
}
}
virtual void OnTick()
{
if (this->scrolling == -1) {
this->vscroll.pos = max(0, this->vscroll.pos - 1);
this->SetDirty();
} else if (this->scrolling == 1) {
this->vscroll.pos = min(this->vscroll.count - this->vscroll.cap, this->vscroll.pos + 1);
this->SetDirty();
}
this->scrolling = 0;
}
virtual void OnMouseLoop()
{
Window *w2 = FindWindowById(this->parent_wnd_class, this->parent_wnd_num);
if (w2 == NULL) {
delete this;
return;
}
if (this->click_delay != 0 && --this->click_delay == 0) {
w2->OnDropdownSelect(this->parent_button, this->selected_index);
delete this;
return;
}
if (this->drag_mode) {
int item;
if (!_left_button_clicked) {
this->drag_mode = false;
if (!this->GetDropDownItem(item)) {
if (this->instant_close) {
if (GetWidgetFromPos(w2, _cursor.pos.x - w2->left, _cursor.pos.y - w2->top) == this->parent_button) {
/* Send event for selected option if we're still
* on the parent button of the list. */
w2->OnDropdownSelect(this->parent_button, this->selected_index);
}
delete this;
}
return;
}
this->click_delay = 2;
} else {
if (_cursor.pos.y <= this->top + 2) {
/* Cursor is above the list, set scroll up */
this->scrolling = -1;
return;
} else if (_cursor.pos.y >= this->top + this->height - 2) {
/* Cursor is below list, set scroll down */
this->scrolling = 1;
return;
}
if (!this->GetDropDownItem(item)) return;
}
this->selected_index = item;
this->SetDirty();
}
}
};
void ShowDropDownList(Window *w, DropDownList *list, int selected, int button, uint width, bool auto_width, bool instant_close)
{
DeleteWindowById(WC_DROPDOWN_MENU, 0);
w->LowerWidget(button);
w->InvalidateWidget(button);
/* Our parent's button widget is used to determine where to place the drop
* down list window. */
const Widget *wi = &w->widget[button];
/* The preferred position is just below the dropdown calling widget */
int top = w->top + wi->bottom + 1;
if (width == 0) width = wi->right - wi->left + 1;
uint max_item_width = 0;
if (auto_width) {
/* Find the longest item in the list */
for (DropDownList::const_iterator it = list->begin(); it != list->end(); ++it) {
const DropDownListItem *item = *it;
max_item_width = max(max_item_width, item->Width() + 5);
}
}
/* Total length of list */
int list_height = 0;
for (DropDownList::const_iterator it = list->begin(); it != list->end(); ++it) {
DropDownListItem *item = *it;
list_height += item->Height(width);
}
/* Height of window visible */
int height = list_height;
/* Check if the status bar is visible, as we don't want to draw over it */
Window *w3 = FindWindowById(WC_STATUS_BAR, 0);
int screen_bottom = w3 == NULL ? _screen.height : w3->top;
bool scroll = false;
/* Check if the dropdown will fully fit below the widget */
if (top + height + 4 >= screen_bottom) {
w3 = FindWindowById(WC_MAIN_TOOLBAR, 0);
int screen_top = w3 == NULL ? 0 : w3->top + w3->height;
/* If not, check if it will fit above the widget */
if (w->top + wi->top - height > screen_top) {
top = w->top + wi->top - height - 4;
} else {
/* ... and lastly if it won't, enable the scroll bar and fit the
* list in below the widget */
int avg_height = list_height / (int)list->size();
int rows = (screen_bottom - 4 - top) / avg_height;
height = rows * avg_height;
scroll = true;
/* Add space for the scroll bar if we automatically determined
* the width of the list. */
max_item_width += 12;
}
}
if (auto_width) width = max(width, max_item_width);
DropdownWindow *dw = new DropdownWindow(
w->left + wi->left,
top,
width,
height + 4,
_dropdown_menu_widgets);
dw->widget[0].colour = wi->colour;
dw->widget[0].right = width - 1;
dw->widget[0].bottom = height + 3;
dw->SetWidgetHiddenState(1, !scroll);
if (scroll) {
/* We're scrolling, so enable the scroll bar and shrink the list by
* the scrollbar's width */
dw->widget[1].colour = wi->colour;
dw->widget[1].right = dw->widget[0].right;
dw->widget[1].left = dw->widget[1].right - 11;
dw->widget[1].bottom = dw->widget[0].bottom;
dw->widget[0].right -= 12;
/* Capacity is the average number of items visible */
dw->vscroll.cap = height * (uint16)list->size() / list_height;
dw->vscroll.count = (uint16)list->size();
}
dw->desc_flags = WDF_DEF_WIDGET;
dw->flags4 &= ~WF_WHITE_BORDER_MASK;
dw->parent_wnd_class = w->window_class;
dw->parent_wnd_num = w->window_number;
dw->parent_button = button;
dw->list = list;
dw->selected_index = selected;
dw->click_delay = 0;
dw->drag_mode = true;
dw->instant_close = instant_close;
}
void ShowDropDownMenu(Window *w, const StringID *strings, int selected, int button, uint32 disabled_mask, uint32 hidden_mask, uint width)
{
uint result = 0;
DropDownList *list = new DropDownList();
for (uint i = 0; strings[i] != INVALID_STRING_ID; i++) {
if (!HasBit(hidden_mask, i)) {
list->push_back(new DropDownListStringItem(strings[i], result, HasBit(disabled_mask, i)));
}
result++;
}
/* No entries in the list? */
if (list->size() == 0) {
DeleteDropDownList(list);
return;
}
ShowDropDownList(w, list, selected, button, width);
}
/**
* Delete the drop-down menu from window \a pw
* @param pw Parent window of the drop-down menu window
*/
int HideDropDownMenu(Window *pw)
{
Window *w;
FOR_ALL_WINDOWS_FROM_BACK(w) {
if (w->window_class != WC_DROPDOWN_MENU) continue;
DropdownWindow *dw = dynamic_cast<DropdownWindow*>(w);
if (pw->window_class == dw->parent_wnd_class &&
pw->window_number == dw->parent_wnd_num) {
int parent_button = dw->parent_button;
delete dw;
return parent_button;
}
}
return -1;
}
| 10,353
|
C++
|
.cpp
| 314
| 29.914013
| 137
| 0.659209
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,205
|
allegro_s.cpp
|
EnergeticBark_OpenTTD-3DS/src/sound/allegro_s.cpp
|
/* $Id$ */
/** @file allegro_s.cpp Playing sound via Allegro. */
#ifdef WITH_ALLEGRO
#include "../stdafx.h"
#include "../driver.h"
#include "../mixer.h"
#include "../sdl.h"
#include "../debug.h"
#include "allegro_s.h"
#include <allegro.h>
static FSoundDriver_Allegro iFSoundDriver_Allegro;
/** The stream we are writing too */
static AUDIOSTREAM *_stream = NULL;
/** The number of samples in the buffer */
static const int BUFFER_SIZE = 512;
void SoundDriver_Allegro::MainLoop()
{
/* We haven't opened a stream yet */
if (_stream == NULL) return;
void *data = get_audio_stream_buffer(_stream);
/* We don't have to fill the stream yet */
if (data == NULL) return;
/* Mix the samples */
MxMixSamples(data, BUFFER_SIZE);
/* Allegro sound is always unsigned, so we need to correct that */
uint16 *snd = (uint16*)data;
for (int i = 0; i < BUFFER_SIZE * 2; i++) snd[i] ^= 0x8000;
/* Tell we've filled the stream */
free_audio_stream_buffer(_stream);
}
/** There are multiple modules that might be using Allegro and
* Allegro can only be initiated once. */
extern int _allegro_instance_count;
const char *SoundDriver_Allegro::Start(const char * const *parm)
{
if (_allegro_instance_count == 0 && install_allegro(SYSTEM_AUTODETECT, &errno, NULL)) return NULL;
_allegro_instance_count++;
/* Initialise the sound */
if (install_sound(DIGI_AUTODETECT, MIDI_AUTODETECT, NULL) != 0) return NULL;
/* Okay, there's no soundcard */
if (digi_card == DIGI_NONE) {
DEBUG(driver, 0, "allegro: no sound card found");
return NULL;
}
_stream = play_audio_stream(BUFFER_SIZE, 16, true, 11025, 255, 128);
return NULL;
}
void SoundDriver_Allegro::Stop()
{
if (_stream != NULL) {
stop_audio_stream(_stream);
_stream = NULL;
}
remove_sound();
if (--_allegro_instance_count == 0) allegro_exit();
}
#endif /* WITH_ALLEGRO */
| 1,847
|
C++
|
.cpp
| 57
| 30.491228
| 99
| 0.698081
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,206
|
null_s.cpp
|
EnergeticBark_OpenTTD-3DS/src/sound/null_s.cpp
|
/* $Id$ */
/** @file null_s.cpp The sound driver that doesn't produce sound. */
#include "../stdafx.h"
#include "null_s.h"
static FSoundDriver_Null iFSoundDriver_Null;
| 171
|
C++
|
.cpp
| 5
| 32.6
| 68
| 0.711656
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
1,539,207
|
cocoa_s.cpp
|
EnergeticBark_OpenTTD-3DS/src/sound/cocoa_s.cpp
|
/* $Id$ */
/** @file cocoa_s.cpp Sound driver for cocoa. */
/*****************************************************************************
* Cocoa sound driver *
* Known things left to do: *
* - Might need to do endian checking for it to work on both ppc and x86 *
*****************************************************************************/
#ifdef WITH_COCOA
#define MAC_OS_X_VERSION_MIN_REQUIRED MAC_OS_X_VERSION_10_3
#include <AvailabilityMacros.h>
#include <AudioUnit/AudioUnit.h>
/* Name conflict */
#define Rect OTTDRect
#define Point OTTDPoint
#define WindowClass OTTDWindowClass
#include "../stdafx.h"
#include "../debug.h"
#include "../driver.h"
#include "../mixer.h"
#include "../core/endian_type.hpp"
#include "cocoa_s.h"
#undef WindowClass
#undef Point
#undef Rect
static FSoundDriver_Cocoa iFSoundDriver_Cocoa;
static AudioUnit _outputAudioUnit;
/* The CoreAudio callback */
static OSStatus audioCallback(void *inRefCon, AudioUnitRenderActionFlags *inActionFlags, const AudioTimeStamp *inTimeStamp, UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList * ioData)
{
MxMixSamples(ioData->mBuffers[0].mData, ioData->mBuffers[0].mDataByteSize / 4);
return noErr;
}
const char *SoundDriver_Cocoa::Start(const char * const *parm)
{
Component comp;
ComponentDescription desc;
struct AURenderCallbackStruct callback;
AudioStreamBasicDescription requestedDesc;
/* Setup a AudioStreamBasicDescription with the requested format */
requestedDesc.mFormatID = kAudioFormatLinearPCM;
requestedDesc.mFormatFlags = kLinearPCMFormatFlagIsPacked;
requestedDesc.mChannelsPerFrame = 2;
requestedDesc.mSampleRate = GetDriverParamInt(parm, "hz", 11025);
requestedDesc.mBitsPerChannel = 16;
requestedDesc.mFormatFlags |= kLinearPCMFormatFlagIsSignedInteger;
#if TTD_ENDIAN == TTD_BIG_ENDIAN
requestedDesc.mFormatFlags |= kLinearPCMFormatFlagIsBigEndian;
#endif /* TTD_ENDIAN == TTD_BIG_ENDIAN */
requestedDesc.mFramesPerPacket = 1;
requestedDesc.mBytesPerFrame = requestedDesc.mBitsPerChannel * requestedDesc.mChannelsPerFrame / 8;
requestedDesc.mBytesPerPacket = requestedDesc.mBytesPerFrame * requestedDesc.mFramesPerPacket;
/* Locate the default output audio unit */
desc.componentType = kAudioUnitType_Output;
desc.componentSubType = kAudioUnitSubType_HALOutput;
desc.componentManufacturer = kAudioUnitManufacturer_Apple;
desc.componentFlags = 0;
desc.componentFlagsMask = 0;
comp = FindNextComponent (NULL, &desc);
if (comp == NULL) {
return "cocoa_s: Failed to start CoreAudio: FindNextComponent returned NULL";
}
/* Open & initialize the default output audio unit */
if (OpenAComponent(comp, &_outputAudioUnit) != noErr) {
return "cocoa_s: Failed to start CoreAudio: OpenAComponent";
}
if (AudioUnitInitialize(_outputAudioUnit) != noErr) {
return "cocoa_s: Failed to start CoreAudio: AudioUnitInitialize";
}
/* Set the input format of the audio unit. */
if (AudioUnitSetProperty(_outputAudioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &requestedDesc, sizeof(requestedDesc)) != noErr) {
return "cocoa_s: Failed to start CoreAudio: AudioUnitSetProperty (kAudioUnitProperty_StreamFormat)";
}
/* Set the audio callback */
callback.inputProc = audioCallback;
callback.inputProcRefCon = NULL;
if (AudioUnitSetProperty(_outputAudioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &callback, sizeof(callback)) != noErr) {
return "cocoa_s: Failed to start CoreAudio: AudioUnitSetProperty (kAudioUnitProperty_SetRenderCallback)";
}
/* Finally, start processing of the audio unit */
if (AudioOutputUnitStart(_outputAudioUnit) != noErr) {
return "cocoa_s: Failed to start CoreAudio: AudioOutputUnitStart";
}
/* We're running! */
return NULL;
}
void SoundDriver_Cocoa::Stop()
{
struct AURenderCallbackStruct callback;
/* stop processing the audio unit */
if (AudioOutputUnitStop(_outputAudioUnit) != noErr) {
DEBUG(driver, 0, "cocoa_s: Core_CloseAudio: AudioOutputUnitStop failed");
return;
}
/* Remove the input callback */
callback.inputProc = 0;
callback.inputProcRefCon = 0;
if (AudioUnitSetProperty(_outputAudioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &callback, sizeof(callback)) != noErr) {
DEBUG(driver, 0, "cocoa_s: Core_CloseAudio: AudioUnitSetProperty (kAudioUnitProperty_SetRenderCallback) failed");
return;
}
if (CloseComponent(_outputAudioUnit) != noErr) {
DEBUG(driver, 0, "cocoa_s: Core_CloseAudio: CloseComponent failed");
return;
}
}
#endif /* WITH_COCOA */
| 4,678
|
C++
|
.cpp
| 106
| 42.028302
| 192
| 0.738651
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
1,539,208
|
win32_s.cpp
|
EnergeticBark_OpenTTD-3DS/src/sound/win32_s.cpp
|
/* $Id$ */
/** @file win32_s.cpp Handling of sound for Windows. */
#include "../stdafx.h"
#include "../openttd.h"
#include "../driver.h"
#include "../mixer.h"
#include "../core/alloc_func.hpp"
#include "win32_s.h"
#include <windows.h>
#include <mmsystem.h>
static FSoundDriver_Win32 iFSoundDriver_Win32;
static HWAVEOUT _waveout;
static WAVEHDR _wave_hdr[2];
static int _bufsize;
static void PrepareHeader(WAVEHDR *hdr)
{
hdr->dwBufferLength = _bufsize * 4;
hdr->dwFlags = 0;
hdr->lpData = MallocT<char>(_bufsize * 4);
if (waveOutPrepareHeader(_waveout, hdr, sizeof(WAVEHDR)) != MMSYSERR_NOERROR)
usererror("waveOutPrepareHeader failed");
}
static void FillHeaders()
{
WAVEHDR *hdr;
for (hdr = _wave_hdr; hdr != endof(_wave_hdr); hdr++) {
if (!(hdr->dwFlags & WHDR_INQUEUE)) {
MxMixSamples(hdr->lpData, hdr->dwBufferLength / 4);
if (waveOutWrite(_waveout, hdr, sizeof(WAVEHDR)) != MMSYSERR_NOERROR)
usererror("waveOutWrite failed");
}
}
}
static void CALLBACK waveOutProc(HWAVEOUT hwo, UINT uMsg, DWORD_PTR dwInstance,
DWORD dwParam1, DWORD dwParam2)
{
switch (uMsg) {
case WOM_DONE:
if (_waveout != NULL) FillHeaders();
break;
default: break;
}
}
const char *SoundDriver_Win32::Start(const char * const *parm)
{
WAVEFORMATEX wfex;
wfex.wFormatTag = WAVE_FORMAT_PCM;
wfex.nChannels = 2;
wfex.wBitsPerSample = 16;
wfex.nSamplesPerSec = GetDriverParamInt(parm, "hz", 11025);
wfex.nBlockAlign = (wfex.nChannels * wfex.wBitsPerSample) / 8;
wfex.nAvgBytesPerSec = wfex.nSamplesPerSec * wfex.nBlockAlign;
_bufsize = GetDriverParamInt(parm, "bufsize", (GB(GetVersion(), 0, 8) > 5) ? 2048 : 1024);
if (waveOutOpen(&_waveout, WAVE_MAPPER, &wfex, (DWORD_PTR)&waveOutProc, 0, CALLBACK_FUNCTION) != MMSYSERR_NOERROR)
return "waveOutOpen failed";
PrepareHeader(&_wave_hdr[0]);
PrepareHeader(&_wave_hdr[1]);
FillHeaders();
return NULL;
}
void SoundDriver_Win32::Stop()
{
HWAVEOUT waveout = _waveout;
_waveout = NULL;
waveOutReset(waveout);
waveOutUnprepareHeader(waveout, &_wave_hdr[0], sizeof(WAVEHDR));
waveOutUnprepareHeader(waveout, &_wave_hdr[1], sizeof(WAVEHDR));
waveOutClose(waveout);
}
| 2,152
|
C++
|
.cpp
| 69
| 29.15942
| 115
| 0.727888
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,210
|
countedobj.cpp
|
EnergeticBark_OpenTTD-3DS/src/misc/countedobj.cpp
|
/* $Id$ */
/** @file countedobj.cpp Support for reference counted objects. */
#include "../stdafx.h"
#include "countedptr.hpp"
int32 SimpleCountedObject::AddRef()
{
return ++m_ref_cnt;
}
int32 SimpleCountedObject::Release()
{
int32 res = --m_ref_cnt;
assert(res >= 0);
if (res == 0) {
FinalRelease();
delete this;
}
return res;
}
| 345
|
C++
|
.cpp
| 18
| 17.333333
| 66
| 0.689441
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
1,539,211
|
dbg_helpers.cpp
|
EnergeticBark_OpenTTD-3DS/src/misc/dbg_helpers.cpp
|
/* $Id$ */
/** @file dbg_helpers.cpp Helpers for outputting debug information. */
#include "../stdafx.h"
#include "../rail_map.h"
#include "dbg_helpers.h"
/** Trackdir & TrackdirBits short names. */
static const char *trackdir_names[] = {
"NE", "SE", "UE", "LE", "LS", "RS", "rne", "rse",
"SW", "NW", "UW", "LW", "LN", "RN", "rsw", "rnw",
};
/** Return name of given Trackdir. */
CStrA ValueStr(Trackdir td)
{
CStrA out;
out.Format("%d (%s)", td, ItemAtT(td, trackdir_names, "UNK", INVALID_TRACKDIR, "INV"));
return out.Transfer();
}
/** Return composed name of given TrackdirBits. */
CStrA ValueStr(TrackdirBits td_bits)
{
CStrA out;
out.Format("%d (%s)", td_bits, ComposeNameT(td_bits, trackdir_names, "UNK", INVALID_TRACKDIR_BIT, "INV").Data());
return out.Transfer();
}
/** DiagDirection short names. */
static const char *diagdir_names[] = {
"NE", "SE", "SW", "NW",
};
/** Return name of given DiagDirection. */
CStrA ValueStr(DiagDirection dd)
{
CStrA out;
out.Format("%d (%s)", dd, ItemAtT(dd, diagdir_names, "UNK", INVALID_DIAGDIR, "INV"));
return out.Transfer();
}
/** SignalType short names. */
static const char *signal_type_names[] = {
"NORMAL", "ENTRY", "EXIT", "COMBO", "PBS", "NOENTRY",
};
/** Return name of given SignalType. */
CStrA ValueStr(SignalType t)
{
CStrA out;
out.Format("%d (%s)", t, ItemAtT(t, signal_type_names, "UNK"));
return out.Transfer();
}
/** Translate TileIndex into string. */
CStrA TileStr(TileIndex tile)
{
CStrA out;
out.Format("0x%04X (%d, %d)", tile, TileX(tile), TileY(tile));
return out.Transfer();
}
/** Keep track of the last assigned type_id. Used for anti-recursion.
*static*/ size_t& DumpTarget::LastTypeId()
{
static size_t last_type_id = 0;
return last_type_id;
}
/** Return structured name of the current class/structure. */
CStrA DumpTarget::GetCurrentStructName()
{
CStrA out;
if (!m_cur_struct.empty()) {
/* we are inside some named struct, return its name */
out = m_cur_struct.top();
}
return out.Transfer();
}
/**
* Find the given instance in our anti-recursion repository.
* Return true and set name when object was found.
*/
bool DumpTarget::FindKnownName(size_t type_id, const void *ptr, CStrA &name)
{
KNOWN_NAMES::const_iterator it = m_known_names.find(KnownStructKey(type_id, ptr));
if (it != m_known_names.end()) {
/* we have found it */
name = (*it).second;
return true;
}
return false;
}
/** Write some leading spaces into the output. */
void DumpTarget::WriteIndent()
{
int num_spaces = 2 * m_indent;
memset(m_out.GrowSizeNC(num_spaces), ' ', num_spaces);
}
/** Write a line with indent at the beginning and <LF> at the end. */
void DumpTarget::WriteLine(const char *format, ...)
{
WriteIndent();
va_list args;
va_start(args, format);
m_out.AddFormatL(format, args);
va_end(args);
m_out.AppendStr("\n");
}
/** Write 'name = value' with indent and new-line. */
void DumpTarget::WriteValue(const char *name, const char *value_str)
{
WriteIndent();
m_out.AddFormat("%s = %s\n", name, value_str);
}
/** Write name & TileIndex to the output. */
void DumpTarget::WriteTile(const char *name, TileIndex tile)
{
WriteIndent();
m_out.AddFormat("%s = %s\n", name, TileStr(tile).Data());
}
/**
* Open new structure (one level deeper than the current one) 'name = {<LF>'.
*/
void DumpTarget::BeginStruct(size_t type_id, const char *name, const void *ptr)
{
/* make composite name */
CStrA cur_name = GetCurrentStructName().Transfer();
if (cur_name.Size() > 0) {
/* add name delimiter (we use structured names) */
cur_name.AppendStr(".");
}
cur_name.AppendStr(name);
/* put the name onto stack (as current struct name) */
m_cur_struct.push(cur_name);
/* put it also to the map of known structures */
m_known_names.insert(KNOWN_NAMES::value_type(KnownStructKey(type_id, ptr), cur_name));
WriteIndent();
m_out.AddFormat("%s = {\n", name);
m_indent++;
}
/**
* Close structure '}<LF>'.
*/
void DumpTarget::EndStruct()
{
m_indent--;
WriteIndent();
m_out.AddFormat("}\n");
/* remove current struct name from the stack */
m_cur_struct.pop();
}
| 4,100
|
C++
|
.cpp
| 142
| 27.119718
| 114
| 0.682015
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
1,539,212
|
cargopacket_sl.cpp
|
EnergeticBark_OpenTTD-3DS/src/saveload/cargopacket_sl.cpp
|
/* $Id$ */
/** @file cargopacket_sl.cpp Code handling saving and loading of cargo packets */
#include "../stdafx.h"
#include "../cargopacket.h"
#include "saveload.h"
static const SaveLoad _cargopacket_desc[] = {
SLE_VAR(CargoPacket, source, SLE_UINT16),
SLE_VAR(CargoPacket, source_xy, SLE_UINT32),
SLE_VAR(CargoPacket, loaded_at_xy, SLE_UINT32),
SLE_VAR(CargoPacket, count, SLE_UINT16),
SLE_VAR(CargoPacket, days_in_transit, SLE_UINT8),
SLE_VAR(CargoPacket, feeder_share, SLE_INT64),
SLE_VAR(CargoPacket, paid_for, SLE_BOOL),
SLE_END()
};
static void Save_CAPA()
{
CargoPacket *cp;
FOR_ALL_CARGOPACKETS(cp) {
SlSetArrayIndex(cp->index);
SlObject(cp, _cargopacket_desc);
}
}
static void Load_CAPA()
{
int index;
while ((index = SlIterateArray()) != -1) {
CargoPacket *cp = new (index) CargoPacket();
SlObject(cp, _cargopacket_desc);
}
}
extern const ChunkHandler _cargopacket_chunk_handlers[] = {
{ 'CAPA', Save_CAPA, Load_CAPA, CH_ARRAY | CH_LAST},
};
| 1,024
|
C++
|
.cpp
| 34
| 28.147059
| 81
| 0.690816
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,217
|
company_sl.cpp
|
EnergeticBark_OpenTTD-3DS/src/saveload/company_sl.cpp
|
/* $Id$ */
/** @file company_sl.cpp Code handling saving and loading of company data */
#include "../stdafx.h"
#include "../company_base.h"
#include "../company_func.h"
#include "../company_manager_face.h"
#include "saveload.h"
/**
* Converts an old company manager's face format to the new company manager's face format
*
* Meaning of the bits in the old face (some bits are used in several times):
* - 4 and 5: chin
* - 6 to 9: eyebrows
* - 10 to 13: nose
* - 13 to 15: lips (also moustache for males)
* - 16 to 19: hair
* - 20 to 22: eye colour
* - 20 to 27: tie, ear rings etc.
* - 28 to 30: glasses
* - 19, 26 and 27: race (bit 27 set and bit 19 equal to bit 26 = black, otherwise white)
* - 31: gender (0 = male, 1 = female)
*
* @param face the face in the old format
* @return the face in the new format
*/
CompanyManagerFace ConvertFromOldCompanyManagerFace(uint32 face)
{
CompanyManagerFace cmf = 0;
GenderEthnicity ge = GE_WM;
if (HasBit(face, 31)) SetBit(ge, GENDER_FEMALE);
if (HasBit(face, 27) && (HasBit(face, 26) == HasBit(face, 19))) SetBit(ge, ETHNICITY_BLACK);
SetCompanyManagerFaceBits(cmf, CMFV_GEN_ETHN, ge, ge);
SetCompanyManagerFaceBits(cmf, CMFV_HAS_GLASSES, ge, GB(face, 28, 3) <= 1);
SetCompanyManagerFaceBits(cmf, CMFV_EYE_COLOUR, ge, HasBit(ge, ETHNICITY_BLACK) ? 0 : ClampU(GB(face, 20, 3), 5, 7) - 5);
SetCompanyManagerFaceBits(cmf, CMFV_CHIN, ge, ScaleCompanyManagerFaceValue(CMFV_CHIN, ge, GB(face, 4, 2)));
SetCompanyManagerFaceBits(cmf, CMFV_EYEBROWS, ge, ScaleCompanyManagerFaceValue(CMFV_EYEBROWS, ge, GB(face, 6, 4)));
SetCompanyManagerFaceBits(cmf, CMFV_HAIR, ge, ScaleCompanyManagerFaceValue(CMFV_HAIR, ge, GB(face, 16, 4)));
SetCompanyManagerFaceBits(cmf, CMFV_JACKET, ge, ScaleCompanyManagerFaceValue(CMFV_JACKET, ge, GB(face, 20, 2)));
SetCompanyManagerFaceBits(cmf, CMFV_COLLAR, ge, ScaleCompanyManagerFaceValue(CMFV_COLLAR, ge, GB(face, 22, 2)));
SetCompanyManagerFaceBits(cmf, CMFV_GLASSES, ge, GB(face, 28, 1));
uint lips = GB(face, 10, 4);
if (!HasBit(ge, GENDER_FEMALE) && lips < 4) {
SetCompanyManagerFaceBits(cmf, CMFV_HAS_MOUSTACHE, ge, true);
SetCompanyManagerFaceBits(cmf, CMFV_MOUSTACHE, ge, max(lips, 1U) - 1);
} else {
if (!HasBit(ge, GENDER_FEMALE)) {
lips = lips * 15 / 16;
lips -= 3;
if (HasBit(ge, ETHNICITY_BLACK) && lips > 8) lips = 0;
} else {
lips = ScaleCompanyManagerFaceValue(CMFV_LIPS, ge, lips);
}
SetCompanyManagerFaceBits(cmf, CMFV_LIPS, ge, lips);
uint nose = GB(face, 13, 3);
if (ge == GE_WF) {
nose = (nose * 3 >> 3) * 3 >> 2; // There is 'hole' in the nose sprites for females
} else {
nose = ScaleCompanyManagerFaceValue(CMFV_NOSE, ge, nose);
}
SetCompanyManagerFaceBits(cmf, CMFV_NOSE, ge, nose);
}
uint tie_earring = GB(face, 24, 4);
if (!HasBit(ge, GENDER_FEMALE) || tie_earring < 3) { // Not all females have an earring
if (HasBit(ge, GENDER_FEMALE)) SetCompanyManagerFaceBits(cmf, CMFV_HAS_TIE_EARRING, ge, true);
SetCompanyManagerFaceBits(cmf, CMFV_TIE_EARRING, ge, HasBit(ge, GENDER_FEMALE) ? tie_earring : ScaleCompanyManagerFaceValue(CMFV_TIE_EARRING, ge, tie_earring / 2));
}
return cmf;
}
/* Save/load of companies */
static const SaveLoad _company_desc[] = {
SLE_VAR(Company, name_2, SLE_UINT32),
SLE_VAR(Company, name_1, SLE_STRINGID),
SLE_CONDSTR(Company, name, SLE_STR, 0, 84, SL_MAX_VERSION),
SLE_VAR(Company, president_name_1, SLE_UINT16),
SLE_VAR(Company, president_name_2, SLE_UINT32),
SLE_CONDSTR(Company, president_name, SLE_STR, 0, 84, SL_MAX_VERSION),
SLE_VAR(Company, face, SLE_UINT32),
/* money was changed to a 64 bit field in savegame version 1. */
SLE_CONDVAR(Company, money, SLE_VAR_I64 | SLE_FILE_I32, 0, 0),
SLE_CONDVAR(Company, money, SLE_INT64, 1, SL_MAX_VERSION),
SLE_CONDVAR(Company, current_loan, SLE_VAR_I64 | SLE_FILE_I32, 0, 64),
SLE_CONDVAR(Company, current_loan, SLE_INT64, 65, SL_MAX_VERSION),
SLE_VAR(Company, colour, SLE_UINT8),
SLE_VAR(Company, money_fraction, SLE_UINT8),
SLE_CONDVAR(Company, avail_railtypes, SLE_UINT8, 0, 57),
SLE_VAR(Company, block_preview, SLE_UINT8),
SLE_CONDVAR(Company, cargo_types, SLE_FILE_U16 | SLE_VAR_U32, 0, 93),
SLE_CONDVAR(Company, cargo_types, SLE_UINT32, 94, SL_MAX_VERSION),
SLE_CONDVAR(Company, location_of_HQ, SLE_FILE_U16 | SLE_VAR_U32, 0, 5),
SLE_CONDVAR(Company, location_of_HQ, SLE_UINT32, 6, SL_MAX_VERSION),
SLE_CONDVAR(Company, last_build_coordinate, SLE_FILE_U16 | SLE_VAR_U32, 0, 5),
SLE_CONDVAR(Company, last_build_coordinate, SLE_UINT32, 6, SL_MAX_VERSION),
SLE_CONDVAR(Company, inaugurated_year, SLE_FILE_U8 | SLE_VAR_I32, 0, 30),
SLE_CONDVAR(Company, inaugurated_year, SLE_INT32, 31, SL_MAX_VERSION),
SLE_ARR(Company, share_owners, SLE_UINT8, 4),
SLE_VAR(Company, num_valid_stat_ent, SLE_UINT8),
SLE_VAR(Company, quarters_of_bankrupcy, SLE_UINT8),
SLE_CONDVAR(Company, bankrupt_asked, SLE_FILE_U8 | SLE_VAR_U16, 0, 103),
SLE_CONDVAR(Company, bankrupt_asked, SLE_UINT16, 104, SL_MAX_VERSION),
SLE_VAR(Company, bankrupt_timeout, SLE_INT16),
SLE_CONDVAR(Company, bankrupt_value, SLE_VAR_I64 | SLE_FILE_I32, 0, 64),
SLE_CONDVAR(Company, bankrupt_value, SLE_INT64, 65, SL_MAX_VERSION),
/* yearly expenses was changed to 64-bit in savegame version 2. */
SLE_CONDARR(Company, yearly_expenses, SLE_FILE_I32 | SLE_VAR_I64, 3 * 13, 0, 1),
SLE_CONDARR(Company, yearly_expenses, SLE_INT64, 3 * 13, 2, SL_MAX_VERSION),
SLE_CONDVAR(Company, is_ai, SLE_BOOL, 2, SL_MAX_VERSION),
SLE_CONDNULL(1, 107, 111), ///< is_noai
SLE_CONDNULL(1, 4, 99),
/* Engine renewal settings */
SLE_CONDNULL(512, 16, 18),
SLE_CONDREF(Company, engine_renew_list, REF_ENGINE_RENEWS, 19, SL_MAX_VERSION),
SLE_CONDVAR(Company, engine_renew, SLE_BOOL, 16, SL_MAX_VERSION),
SLE_CONDVAR(Company, engine_renew_months, SLE_INT16, 16, SL_MAX_VERSION),
SLE_CONDVAR(Company, engine_renew_money, SLE_UINT32, 16, SL_MAX_VERSION),
SLE_CONDVAR(Company, renew_keep_length, SLE_BOOL, 2, SL_MAX_VERSION), // added with 16.1, but was blank since 2
/* Reserve extra space in savegame here. (currently 63 bytes) */
SLE_CONDNULL(63, 2, SL_MAX_VERSION),
SLE_END()
};
static const SaveLoad _company_economy_desc[] = {
/* these were changed to 64-bit in savegame format 2 */
SLE_CONDVAR(CompanyEconomyEntry, income, SLE_FILE_I32 | SLE_VAR_I64, 0, 1),
SLE_CONDVAR(CompanyEconomyEntry, income, SLE_INT64, 2, SL_MAX_VERSION),
SLE_CONDVAR(CompanyEconomyEntry, expenses, SLE_FILE_I32 | SLE_VAR_I64, 0, 1),
SLE_CONDVAR(CompanyEconomyEntry, expenses, SLE_INT64, 2, SL_MAX_VERSION),
SLE_CONDVAR(CompanyEconomyEntry, company_value, SLE_FILE_I32 | SLE_VAR_I64, 0, 1),
SLE_CONDVAR(CompanyEconomyEntry, company_value, SLE_INT64, 2, SL_MAX_VERSION),
SLE_VAR(CompanyEconomyEntry, delivered_cargo, SLE_INT32),
SLE_VAR(CompanyEconomyEntry, performance_history, SLE_INT32),
SLE_END()
};
/* We do need to read this single value, as the bigger it gets, the more data is stored */
struct CompanyOldAI {
uint8 num_build_rec;
};
static const SaveLoad _company_ai_desc[] = {
SLE_CONDNULL(2, 0, 106),
SLE_CONDNULL(2, 0, 12),
SLE_CONDNULL(4, 13, 106),
SLE_CONDNULL(8, 0, 106),
SLE_CONDVAR(CompanyOldAI, num_build_rec, SLE_UINT8, 0, 106),
SLE_CONDNULL(3, 0, 106),
SLE_CONDNULL(2, 0, 5),
SLE_CONDNULL(4, 6, 106),
SLE_CONDNULL(2, 0, 5),
SLE_CONDNULL(4, 6, 106),
SLE_CONDNULL(2, 0, 106),
SLE_CONDNULL(2, 0, 5),
SLE_CONDNULL(4, 6, 106),
SLE_CONDNULL(2, 0, 5),
SLE_CONDNULL(4, 6, 106),
SLE_CONDNULL(2, 0, 106),
SLE_CONDNULL(2, 0, 68),
SLE_CONDNULL(4, 69, 106),
SLE_CONDNULL(18, 0, 106),
SLE_CONDNULL(20, 0, 106),
SLE_CONDNULL(32, 0, 106),
SLE_CONDNULL(64, 2, 106),
SLE_END()
};
static const SaveLoad _company_ai_build_rec_desc[] = {
SLE_CONDNULL(2, 0, 5),
SLE_CONDNULL(4, 6, 106),
SLE_CONDNULL(2, 0, 5),
SLE_CONDNULL(4, 6, 106),
SLE_CONDNULL(8, 0, 106),
SLE_END()
};
static const SaveLoad _company_livery_desc[] = {
SLE_CONDVAR(Livery, in_use, SLE_BOOL, 34, SL_MAX_VERSION),
SLE_CONDVAR(Livery, colour1, SLE_UINT8, 34, SL_MAX_VERSION),
SLE_CONDVAR(Livery, colour2, SLE_UINT8, 34, SL_MAX_VERSION),
SLE_END()
};
static void SaveLoad_PLYR(Company *c)
{
int i;
SlObject(c, _company_desc);
/* Keep backwards compatible for savegames, so load the old AI block */
if (CheckSavegameVersion(107) && !IsHumanCompany(c->index)) {
CompanyOldAI old_ai;
char nothing;
SlObject(&old_ai, _company_ai_desc);
for (i = 0; i != old_ai.num_build_rec; i++) {
SlObject(¬hing, _company_ai_build_rec_desc);
}
}
/* Write economy */
SlObject(&c->cur_economy, _company_economy_desc);
/* Write old economy entries. */
for (i = 0; i < c->num_valid_stat_ent; i++) {
SlObject(&c->old_economy[i], _company_economy_desc);
}
/* Write each livery entry. */
int num_liveries = CheckSavegameVersion(63) ? LS_END - 4 : (CheckSavegameVersion(85) ? LS_END - 2: LS_END);
for (i = 0; i < num_liveries; i++) {
SlObject(&c->livery[i], _company_livery_desc);
}
if (num_liveries < LS_END) {
/* We want to insert some liveries somewhere in between. This means some have to be moved. */
memmove(&c->livery[LS_FREIGHT_WAGON], &c->livery[LS_PASSENGER_WAGON_MONORAIL], (LS_END - LS_FREIGHT_WAGON) * sizeof(c->livery[0]));
c->livery[LS_PASSENGER_WAGON_MONORAIL] = c->livery[LS_MONORAIL];
c->livery[LS_PASSENGER_WAGON_MAGLEV] = c->livery[LS_MAGLEV];
}
if (num_liveries == LS_END - 4) {
/* Copy bus/truck liveries over to trams */
c->livery[LS_PASSENGER_TRAM] = c->livery[LS_BUS];
c->livery[LS_FREIGHT_TRAM] = c->livery[LS_TRUCK];
}
}
static void Save_PLYR()
{
Company *c;
FOR_ALL_COMPANIES(c) {
SlSetArrayIndex(c->index);
SlAutolength((AutolengthProc*)SaveLoad_PLYR, c);
}
}
static void Load_PLYR()
{
int index;
while ((index = SlIterateArray()) != -1) {
Company *c = new (index) Company();
SaveLoad_PLYR(c);
_company_colours[index] = (Colours)c->colour;
}
}
extern const ChunkHandler _company_chunk_handlers[] = {
{ 'PLYR', Save_PLYR, Load_PLYR, CH_ARRAY | CH_LAST},
};
| 10,829
|
C++
|
.cpp
| 230
| 44.569565
| 166
| 0.649981
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,219
|
economy_sl.cpp
|
EnergeticBark_OpenTTD-3DS/src/saveload/economy_sl.cpp
|
/* $Id$ */
/** @file economy_sl.cpp Code handling saving and loading of economy data */
#include "../stdafx.h"
#include "../economy_func.h"
#include "saveload.h"
/** Prices */
static void SaveLoad_PRIC()
{
int vt = CheckSavegameVersion(65) ? (SLE_FILE_I32 | SLE_VAR_I64) : SLE_INT64;
SlArray(&_price, NUM_PRICES, vt);
SlArray(&_price_frac, NUM_PRICES, SLE_UINT16);
}
/** Cargo payment rates */
static void SaveLoad_CAPR()
{
uint num_cargo = CheckSavegameVersion(55) ? 12 : NUM_CARGO;
int vt = CheckSavegameVersion(65) ? (SLE_FILE_I32 | SLE_VAR_I64) : SLE_INT64;
SlArray(&_cargo_payment_rates, num_cargo, vt);
SlArray(&_cargo_payment_rates_frac, num_cargo, SLE_UINT16);
}
static const SaveLoad _economy_desc[] = {
SLE_CONDVAR(Economy, max_loan, SLE_FILE_I32 | SLE_VAR_I64, 0, 64),
SLE_CONDVAR(Economy, max_loan, SLE_INT64, 65, SL_MAX_VERSION),
SLE_CONDVAR(Economy, max_loan_unround, SLE_FILE_I32 | SLE_VAR_I64, 0, 64),
SLE_CONDVAR(Economy, max_loan_unround, SLE_INT64, 65, SL_MAX_VERSION),
SLE_CONDVAR(Economy, max_loan_unround_fract, SLE_UINT16, 70, SL_MAX_VERSION),
SLE_VAR(Economy, fluct, SLE_INT16),
SLE_VAR(Economy, interest_rate, SLE_UINT8),
SLE_VAR(Economy, infl_amount, SLE_UINT8),
SLE_VAR(Economy, infl_amount_pr, SLE_UINT8),
SLE_CONDVAR(Economy, industry_daily_change_counter, SLE_UINT32, 102, SL_MAX_VERSION),
SLE_END()
};
/** Economy variables */
static void Save_ECMY()
{
SlObject(&_economy, _economy_desc);
}
/** Economy variables */
static void Load_ECMY()
{
SlObject(&_economy, _economy_desc);
StartupIndustryDailyChanges(CheckSavegameVersion(102)); // old savegames will need to be initialized
}
extern const ChunkHandler _economy_chunk_handlers[] = {
{ 'PRIC', SaveLoad_PRIC, SaveLoad_PRIC, CH_RIFF | CH_AUTO_LENGTH},
{ 'CAPR', SaveLoad_CAPR, SaveLoad_CAPR, CH_RIFF | CH_AUTO_LENGTH},
{ 'ECMY', Save_ECMY, Load_ECMY, CH_RIFF | CH_LAST},
};
| 2,144
|
C++
|
.cpp
| 49
| 41.673469
| 102
| 0.631831
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,221
|
animated_tile_sl.cpp
|
EnergeticBark_OpenTTD-3DS/src/saveload/animated_tile_sl.cpp
|
/* $Id$ */
/** @file animated_tile_sl.cpp Code handling saving and loading of animated tiles */
#include "../stdafx.h"
#include "../tile_type.h"
#include "../core/alloc_func.hpp"
#include "saveload.h"
extern TileIndex *_animated_tile_list;
extern uint _animated_tile_count;
extern uint _animated_tile_allocated;
/**
* Save the ANIT chunk.
*/
static void Save_ANIT()
{
SlSetLength(_animated_tile_count * sizeof(*_animated_tile_list));
SlArray(_animated_tile_list, _animated_tile_count, SLE_UINT32);
}
/**
* Load the ANIT chunk; the chunk containing the animated tiles.
*/
static void Load_ANIT()
{
/* Before version 80 we did NOT have a variable length animated tile table */
if (CheckSavegameVersion(80)) {
/* In pre version 6, we has 16bit per tile, now we have 32bit per tile, convert it ;) */
SlArray(_animated_tile_list, 256, CheckSavegameVersion(6) ? (SLE_FILE_U16 | SLE_VAR_U32) : SLE_UINT32);
for (_animated_tile_count = 0; _animated_tile_count < 256; _animated_tile_count++) {
if (_animated_tile_list[_animated_tile_count] == 0) break;
}
return;
}
_animated_tile_count = (uint)SlGetFieldLength() / sizeof(*_animated_tile_list);
/* Determine a nice rounded size for the amount of allocated tiles */
_animated_tile_allocated = 256;
while (_animated_tile_allocated < _animated_tile_count) _animated_tile_allocated *= 2;
_animated_tile_list = ReallocT<TileIndex>(_animated_tile_list, _animated_tile_allocated);
SlArray(_animated_tile_list, _animated_tile_count, SLE_UINT32);
}
/**
* "Definition" imported by the saveload code to be able to load and save
* the animated tile table.
*/
extern const ChunkHandler _animated_tile_chunk_handlers[] = {
{ 'ANIT', Save_ANIT, Load_ANIT, CH_RIFF | CH_LAST},
};
| 1,748
|
C++
|
.cpp
| 45
| 36.888889
| 105
| 0.723404
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
1,539,223
|
afterload.cpp
|
EnergeticBark_OpenTTD-3DS/src/saveload/afterload.cpp
|
/* $Id$ */
/** @file afterload.cpp Code updating data after game load */
#include "../stdafx.h"
#include "../void_map.h"
#include "../signs_base.h"
#include "../window_func.h"
#include "../fios.h"
#include "../train.h"
#include "../string_func.h"
#include "../gamelog.h"
#include "../network/network.h"
#include "../gfxinit.h"
#include "../functions.h"
#include "../industry_map.h"
#include "../town_map.h"
#include "../clear_map.h"
#include "../vehicle_func.h"
#include "../newgrf_station.h"
#include "../yapf/yapf.hpp"
#include "../elrail_func.h"
#include "../signs_func.h"
#include "../aircraft.h"
#include "../unmovable_map.h"
#include "../tree_map.h"
#include "../company_func.h"
#include "../road_cmd.h"
#include "../ai/ai.hpp"
#include "table/strings.h"
#include "saveload_internal.h"
#include <signal.h>
extern StringID _switch_mode_errorstr;
extern Company *DoStartupNewCompany(bool is_ai);
extern void InitializeRailGUI();
/**
* Makes a tile canal or water depending on the surroundings.
*
* Must only be used for converting old savegames. Use WaterClass now.
*
* This as for example docks and shipdepots do not store
* whether the tile used to be canal or 'normal' water.
* @param t the tile to change.
* @param o the owner of the new tile.
* @param include_invalid_water_class Also consider WATER_CLASS_INVALID, i.e. industry tiles on land
*/
void SetWaterClassDependingOnSurroundings(TileIndex t, bool include_invalid_water_class)
{
/* If the slope is not flat, we always assume 'land' (if allowed). Also for one-corner-raised-shores.
* Note: Wrt. autosloping under industry tiles this is the most fool-proof behaviour. */
if (GetTileSlope(t, NULL) != SLOPE_FLAT) {
if (include_invalid_water_class) {
SetWaterClass(t, WATER_CLASS_INVALID);
return;
} else {
NOT_REACHED();
}
}
/* Mark tile dirty in all cases */
MarkTileDirtyByTile(t);
if (TileX(t) == 0 || TileY(t) == 0 || TileX(t) == MapMaxX() - 1 || TileY(t) == MapMaxY() - 1) {
/* tiles at map borders are always WATER_CLASS_SEA */
SetWaterClass(t, WATER_CLASS_SEA);
return;
}
bool has_water = false;
bool has_canal = false;
bool has_river = false;
for (DiagDirection dir = DIAGDIR_BEGIN; dir < DIAGDIR_END; dir++) {
TileIndex neighbour = TileAddByDiagDir(t, dir);
switch (GetTileType(neighbour)) {
case MP_WATER:
/* clear water and shipdepots have already a WaterClass associated */
if (IsCoast(neighbour)) {
has_water = true;
} else if (!IsLock(neighbour)) {
switch (GetWaterClass(neighbour)) {
case WATER_CLASS_SEA: has_water = true; break;
case WATER_CLASS_CANAL: has_canal = true; break;
case WATER_CLASS_RIVER: has_river = true; break;
default: NOT_REACHED();
}
}
break;
case MP_RAILWAY:
/* Shore or flooded halftile */
has_water |= (GetRailGroundType(neighbour) == RAIL_GROUND_WATER);
break;
case MP_TREES:
/* trees on shore */
has_water |= (GetTreeGround(neighbour) == TREE_GROUND_SHORE);
break;
default: break;
}
}
if (!has_water && !has_canal && !has_river && include_invalid_water_class) {
SetWaterClass(t, WATER_CLASS_INVALID);
return;
}
if (has_river && !has_canal) {
SetWaterClass(t, WATER_CLASS_RIVER);
} else if (has_canal || !has_water) {
SetWaterClass(t, WATER_CLASS_CANAL);
} else {
SetWaterClass(t, WATER_CLASS_SEA);
}
}
static void ConvertTownOwner()
{
for (TileIndex tile = 0; tile != MapSize(); tile++) {
switch (GetTileType(tile)) {
case MP_ROAD:
if (GB(_m[tile].m5, 4, 2) == ROAD_TILE_CROSSING && HasBit(_m[tile].m3, 7)) {
_m[tile].m3 = OWNER_TOWN;
}
/* FALLTHROUGH */
case MP_TUNNELBRIDGE:
if (GetTileOwner(tile) & 0x80) SetTileOwner(tile, OWNER_TOWN);
break;
default: break;
}
}
}
/* since savegame version 4.1, exclusive transport rights are stored at towns */
static void UpdateExclusiveRights()
{
Town *t;
FOR_ALL_TOWNS(t) {
t->exclusivity = INVALID_COMPANY;
}
/* FIXME old exclusive rights status is not being imported (stored in s->blocked_months_obsolete)
* could be implemented this way:
* 1.) Go through all stations
* Build an array town_blocked[ town_id ][ company_id ]
* that stores if at least one station in that town is blocked for a company
* 2.) Go through that array, if you find a town that is not blocked for
* one company, but for all others, then give him exclusivity.
*/
}
static const byte convert_currency[] = {
0, 1, 12, 8, 3,
10, 14, 19, 4, 5,
9, 11, 13, 6, 17,
16, 22, 21, 7, 15,
18, 2, 20,
};
/* since savegame version 4.2 the currencies are arranged differently */
static void UpdateCurrencies()
{
_settings_game.locale.currency = convert_currency[_settings_game.locale.currency];
}
/* Up to revision 1413 the invisible tiles at the southern border have not been
* MP_VOID, even though they should have. This is fixed by this function
*/
static void UpdateVoidTiles()
{
uint i;
for (i = 0; i < MapMaxY(); ++i) MakeVoid(i * MapSizeX() + MapMaxX());
for (i = 0; i < MapSizeX(); ++i) MakeVoid(MapSizeX() * MapMaxY() + i);
}
static inline RailType UpdateRailType(RailType rt, RailType min)
{
return rt >= min ? (RailType)(rt + 1): rt;
}
/**
* Initialization of the windows and several kinds of caches.
* This is not done directly in AfterLoadGame because these
* functions require that all saveload conversions have been
* done. As people tend to add savegame conversion stuff after
* the intialization of the windows and caches quite some bugs
* had been made.
* Moving this out of there is both cleaner and less bug-prone.
*
* @return true if everything went according to plan, otherwise false.
*/
static bool InitializeWindowsAndCaches()
{
/* Initialize windows */
ResetWindowSystem();
SetupColoursAndInitialWindow();
ResetViewportAfterLoadGame();
/* Update coordinates of the signs. */
UpdateAllStationVirtCoord();
UpdateAllSignVirtCoords();
UpdateAllTownVirtCoords();
UpdateAllWaypointSigns();
Company *c;
FOR_ALL_COMPANIES(c) {
/* For each company, verify (while loading a scenario) that the inauguration date is the current year and set it
* accordingly if it is not the case. No need to set it on companies that are not been used already,
* thus the MIN_YEAR (which is really nothing more than Zero, initialized value) test */
if (_file_to_saveload.filetype == FT_SCENARIO && c->inaugurated_year != MIN_YEAR) {
c->inaugurated_year = _cur_year;
}
}
SetCachedEngineCounts();
/* Towns have a noise controlled number of airports system
* So each airport's noise value must be added to the town->noise_reached value
* Reset each town's noise_reached value to '0' before. */
UpdateAirportsNoise();
CheckTrainsLengths();
return true;
}
/**
* Signal handler used to give a user a more useful report for crashes during
* the savegame loading process; especially when there's problems with the
* NewGRFs that are required by the savegame.
* @param unused well... unused
*/
void CDECL HandleSavegameLoadCrash(int unused)
{
char buffer[8192];
char *p = buffer;
p += seprintf(p, lastof(buffer),
"Loading your savegame caused OpenTTD to crash.\n"
"This is most likely caused by a missing NewGRF or a NewGRF that has been\n"
"loaded as replacement for a missing NewGRF. OpenTTD cannot easily\n"
"determine whether a replacement NewGRF is of a newer or older version.\n"
"It will load a NewGRF with the same GRF ID as the missing NewGRF. This\n"
"means that if the author makes incompatible NewGRFs with the same GRF ID\n"
"OpenTTD cannot magically do the right thing. In most cases OpenTTD will\n"
"load the savegame and not crash, but this is an exception.\n"
"Please load the savegame with the appropriate NewGRFs. When loading a\n"
"savegame still crashes when all NewGRFs are found you should file a\n"
"bug report. The missing NewGRFs are:\n");
for (GRFConfig *c = _grfconfig; c != NULL; c = c->next) {
if (HasBit(c->flags, GCF_COMPATIBLE)) {
char buf[40];
md5sumToString(buf, lastof(buf), c->md5sum);
p += seprintf(p, lastof(buffer), "NewGRF %08X (%s) not found; checksum %s. Tried another NewGRF with same GRF ID\n", BSWAP32(c->grfid), c->filename, buf);
}
if (c->status == GCS_NOT_FOUND) {
char buf[40];
md5sumToString(buf, lastof(buf), c->md5sum);
p += seprintf(p, lastof(buffer), "NewGRF %08X (%s) not found; checksum %s\n", BSWAP32(c->grfid), c->filename, buf);
}
}
ShowInfo(buffer);
}
/**
* Tries to change owner of this rail tile to a valid owner. In very old versions it could happen that
* a rail track had an invalid owner. When conversion isn't possible, track is removed.
* @param t tile to update
*/
static void FixOwnerOfRailTrack(TileIndex t)
{
assert(!IsValidCompanyID(GetTileOwner(t)) && (IsLevelCrossingTile(t) || IsPlainRailTile(t)));
/* remove leftover rail piece from crossing (from very old savegames) */
Vehicle *v = NULL, *w;
FOR_ALL_VEHICLES(w) {
if (w->type == VEH_TRAIN && w->tile == t) {
v = w;
break;
}
}
if (v != NULL) {
/* when there is a train on crossing (it could happen in TTD), set owner of crossing to train owner */
SetTileOwner(t, v->owner);
return;
}
/* try to find any connected rail */
for (DiagDirection dd = DIAGDIR_BEGIN; dd < DIAGDIR_END; dd++) {
TileIndex tt = t + TileOffsByDiagDir(dd);
if (GetTileTrackStatus(t, TRANSPORT_RAIL, 0, dd) != 0 &&
GetTileTrackStatus(tt, TRANSPORT_RAIL, 0, ReverseDiagDir(dd)) != 0 &&
IsValidCompanyID(GetTileOwner(tt))) {
SetTileOwner(t, GetTileOwner(tt));
return;
}
}
if (IsLevelCrossingTile(t)) {
/* else change the crossing to normal road (road vehicles won't care) */
MakeRoadNormal(t, GetCrossingRoadBits(t), GetRoadTypes(t), GetTownIndex(t),
GetRoadOwner(t, ROADTYPE_ROAD), GetRoadOwner(t, ROADTYPE_TRAM));
return;
}
/* if it's not a crossing, make it clean land */
MakeClear(t, CLEAR_GRASS, 0);
}
bool AfterLoadGame()
{
typedef void (CDECL *SignalHandlerPointer)(int);
SignalHandlerPointer prev_segfault = signal(SIGSEGV, HandleSavegameLoadCrash);
SignalHandlerPointer prev_abort = signal(SIGABRT, HandleSavegameLoadCrash);
TileIndex map_size = MapSize();
Company *c;
if (CheckSavegameVersion(98)) GamelogOldver();
GamelogTestRevision();
GamelogTestMode();
if (CheckSavegameVersion(98)) GamelogGRFAddList(_grfconfig);
/* in very old versions, size of train stations was stored differently */
if (CheckSavegameVersion(2)) {
Station *st;
FOR_ALL_STATIONS(st) {
if (st->train_tile != 0 && st->trainst_h == 0) {
uint n = _savegame_type == SGT_OTTD ? 4 : 3; // OTTD uses 4 bits per dimensions, TTD 3 bits
uint w = GB(st->trainst_w, n, n);
uint h = GB(st->trainst_w, 0, n);
if (GetRailStationAxis(st->train_tile) != AXIS_X) Swap(w, h);
st->trainst_w = w;
st->trainst_h = h;
assert(GetStationIndex(st->train_tile + TileDiffXY(w - 1, h - 1)) == st->index);
}
}
}
/* in version 2.1 of the savegame, town owner was unified. */
if (CheckSavegameVersionOldStyle(2, 1)) ConvertTownOwner();
/* from version 4.1 of the savegame, exclusive rights are stored at towns */
if (CheckSavegameVersionOldStyle(4, 1)) UpdateExclusiveRights();
/* from version 4.2 of the savegame, currencies are in a different order */
if (CheckSavegameVersionOldStyle(4, 2)) UpdateCurrencies();
/* In old version there seems to be a problem that water is owned by
* OWNER_NONE, not OWNER_WATER.. I can't replicate it for the current
* (4.3) version, so I just check when versions are older, and then
* walk through the whole map.. */
if (CheckSavegameVersionOldStyle(4, 3)) {
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_WATER) && GetTileOwner(t) >= MAX_COMPANIES) {
SetTileOwner(t, OWNER_WATER);
}
}
}
if (CheckSavegameVersion(84)) {
FOR_ALL_COMPANIES(c) {
c->name = CopyFromOldName(c->name_1);
if (c->name != NULL) c->name_1 = STR_SV_UNNAMED;
c->president_name = CopyFromOldName(c->president_name_1);
if (c->president_name != NULL) c->president_name_1 = SPECSTR_PRESIDENT_NAME;
}
Station *st;
FOR_ALL_STATIONS(st) {
st->name = CopyFromOldName(st->string_id);
/* generating new name would be too much work for little effect, use the station name fallback */
if (st->name != NULL) st->string_id = STR_SV_STNAME_FALLBACK;
}
Town *t;
FOR_ALL_TOWNS(t) {
t->name = CopyFromOldName(t->townnametype);
if (t->name != NULL) t->townnametype = SPECSTR_TOWNNAME_START + _settings_game.game_creation.town_name;
}
Waypoint *wp;
FOR_ALL_WAYPOINTS(wp) {
wp->name = CopyFromOldName(wp->string);
wp->string = STR_EMPTY;
}
}
/* From this point the old names array is cleared. */
ResetOldNames();
if (CheckSavegameVersion(106)) {
/* no station is determined by 'tile == INVALID_TILE' now (instead of '0') */
Station *st;
FOR_ALL_STATIONS(st) {
if (st->airport_tile == 0) st->airport_tile = INVALID_TILE;
if (st->dock_tile == 0) st->dock_tile = INVALID_TILE;
if (st->train_tile == 0) st->train_tile = INVALID_TILE;
}
/* the same applies to Company::location_of_HQ */
Company *c;
FOR_ALL_COMPANIES(c) {
if (c->location_of_HQ == 0 || (CheckSavegameVersion(4) && c->location_of_HQ == 0xFFFF)) {
c->location_of_HQ = INVALID_TILE;
}
}
}
/* convert road side to my format. */
if (_settings_game.vehicle.road_side) _settings_game.vehicle.road_side = 1;
/* Check if all NewGRFs are present, we are very strict in MP mode */
GRFListCompatibility gcf_res = IsGoodGRFConfigList();
if (_networking && gcf_res != GLC_ALL_GOOD) {
SetSaveLoadError(STR_NETWORK_ERR_CLIENT_NEWGRF_MISMATCH);
/* Restore the signals */
signal(SIGSEGV, prev_segfault);
signal(SIGABRT, prev_abort);
return false;
}
switch (gcf_res) {
case GLC_COMPATIBLE: _switch_mode_errorstr = STR_NEWGRF_COMPATIBLE_LOAD_WARNING; break;
case GLC_NOT_FOUND: _switch_mode_errorstr = STR_NEWGRF_DISABLED_WARNING; _pause_game = -1; break;
default: break;
}
/* Update current year
* must be done before loading sprites as some newgrfs check it */
SetDate(_date);
/* Force dynamic engines off when loading older savegames */
if (CheckSavegameVersion(95)) _settings_game.vehicle.dynamic_engines = 0;
/* Load the sprites */
GfxLoadSprites();
LoadStringWidthTable();
/* Copy temporary data to Engine pool */
CopyTempEngineData();
/* Connect front and rear engines of multiheaded trains and converts
* subtype to the new format */
if (CheckSavegameVersionOldStyle(17, 1)) ConvertOldMultiheadToNew();
/* Connect front and rear engines of multiheaded trains */
ConnectMultiheadedTrains();
/* reinit the landscape variables (landscape might have changed) */
InitializeLandscapeVariables(true);
/* Update all vehicles */
AfterLoadVehicles(true);
/* Make sure there is an AI attached to an AI company */
{
Company *c;
FOR_ALL_COMPANIES(c) {
if (c->is_ai && c->ai_instance == NULL) AI::StartNew(c->index);
}
}
/* Update all waypoints */
if (CheckSavegameVersion(12)) FixOldWaypoints();
/* make sure there is a town in the game */
if (_game_mode == GM_NORMAL && !ClosestTownFromTile(0, UINT_MAX)) {
SetSaveLoadError(STR_NO_TOWN_IN_SCENARIO);
/* Restore the signals */
signal(SIGSEGV, prev_segfault);
signal(SIGABRT, prev_abort);
return false;
}
/* The void tiles on the southern border used to belong to a wrong class (pre 4.3).
* This problem appears in savegame version 21 too, see r3455. But after loading the
* savegame and saving again, the buggy map array could be converted to new savegame
* version. It didn't show up before r12070. */
if (CheckSavegameVersion(87)) UpdateVoidTiles();
/* If Load Scenario / New (Scenario) Game is used,
* a company does not exist yet. So create one here.
* 1 exeption: network-games. Those can have 0 companies
* But this exeption is not true for non dedicated network_servers! */
if (!IsValidCompanyID(COMPANY_FIRST) && (!_networking || (_networking && _network_server && !_network_dedicated)))
DoStartupNewCompany(false);
if (CheckSavegameVersion(72)) {
/* Locks/shiplifts in very old savegames had OWNER_WATER as owner */
for (TileIndex t = 0; t < MapSize(); t++) {
switch (GetTileType(t)) {
default: break;
case MP_WATER:
if (GetWaterTileType(t) == WATER_TILE_LOCK && GetTileOwner(t) == OWNER_WATER) SetTileOwner(t, OWNER_NONE);
break;
case MP_STATION: {
if (HasBit(_m[t].m6, 3)) SetBit(_m[t].m6, 2);
StationGfx gfx = GetStationGfx(t);
StationType st;
if ( IsInsideMM(gfx, 0, 8)) { // Railway station
st = STATION_RAIL;
SetStationGfx(t, gfx - 0);
} else if (IsInsideMM(gfx, 8, 67)) { // Airport
st = STATION_AIRPORT;
SetStationGfx(t, gfx - 8);
} else if (IsInsideMM(gfx, 67, 71)) { // Truck
st = STATION_TRUCK;
SetStationGfx(t, gfx - 67);
} else if (IsInsideMM(gfx, 71, 75)) { // Bus
st = STATION_BUS;
SetStationGfx(t, gfx - 71);
} else if (gfx == 75) { // Oil rig
st = STATION_OILRIG;
SetStationGfx(t, gfx - 75);
} else if (IsInsideMM(gfx, 76, 82)) { // Dock
st = STATION_DOCK;
SetStationGfx(t, gfx - 76);
} else if (gfx == 82) { // Buoy
st = STATION_BUOY;
SetStationGfx(t, gfx - 82);
} else if (IsInsideMM(gfx, 83, 168)) { // Extended airport
st = STATION_AIRPORT;
SetStationGfx(t, gfx - 83 + 67 - 8);
} else if (IsInsideMM(gfx, 168, 170)) { // Drive through truck
st = STATION_TRUCK;
SetStationGfx(t, gfx - 168 + GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET);
} else if (IsInsideMM(gfx, 170, 172)) { // Drive through bus
st = STATION_BUS;
SetStationGfx(t, gfx - 170 + GFX_TRUCK_BUS_DRIVETHROUGH_OFFSET);
} else {
/* Restore the signals */
signal(SIGSEGV, prev_segfault);
signal(SIGABRT, prev_abort);
return false;
}
SB(_m[t].m6, 3, 3, st);
} break;
}
}
}
for (TileIndex t = 0; t < map_size; t++) {
switch (GetTileType(t)) {
case MP_STATION: {
Station *st = GetStationByTile(t);
/* Set up station spread; buoys do not have one */
if (!IsBuoy(t)) st->rect.BeforeAddTile(t, StationRect::ADD_FORCE);
switch (GetStationType(t)) {
case STATION_TRUCK:
case STATION_BUS:
if (CheckSavegameVersion(6)) {
/* From this version on there can be multiple road stops of the
* same type per station. Convert the existing stops to the new
* internal data structure. */
RoadStop *rs = new RoadStop(t);
if (rs == NULL) error("Too many road stops in savegame");
RoadStop **head =
IsTruckStop(t) ? &st->truck_stops : &st->bus_stops;
*head = rs;
}
break;
case STATION_OILRIG: {
/* Very old savegames sometimes have phantom oil rigs, i.e.
* an oil rig which got shut down, but not completly removed from
* the map
*/
TileIndex t1 = TILE_ADDXY(t, 0, 1);
if (IsTileType(t1, MP_INDUSTRY) &&
GetIndustryGfx(t1) == GFX_OILRIG_1) {
/* The internal encoding of oil rigs was changed twice.
* It was 3 (till 2.2) and later 5 (till 5.1).
* Setting it unconditionally does not hurt.
*/
GetStationByTile(t)->airport_type = AT_OILRIG;
} else {
DeleteOilRig(t);
}
break;
}
default: break;
}
break;
}
default: break;
}
}
/* In version 2.2 of the savegame, we have new airports, so status of all aircraft is reset.
* This has to be called after the oilrig airport_type update above ^^^ ! */
if (CheckSavegameVersionOldStyle(2, 2)) UpdateOldAircraft();
/* In version 6.1 we put the town index in the map-array. To do this, we need
* to use m2 (16bit big), so we need to clean m2, and that is where this is
* all about ;) */
if (CheckSavegameVersionOldStyle(6, 1)) {
for (TileIndex t = 0; t < map_size; t++) {
switch (GetTileType(t)) {
case MP_HOUSE:
_m[t].m4 = _m[t].m2;
SetTownIndex(t, CalcClosestTownFromTile(t)->index);
break;
case MP_ROAD:
_m[t].m4 |= (_m[t].m2 << 4);
if ((GB(_m[t].m5, 4, 2) == ROAD_TILE_CROSSING ? (Owner)_m[t].m3 : GetTileOwner(t)) == OWNER_TOWN) {
SetTownIndex(t, CalcClosestTownFromTile(t)->index);
} else {
SetTownIndex(t, 0);
}
break;
default: break;
}
}
}
/* Force the freeform edges to false for old savegames. */
if (CheckSavegameVersion(111)) {
_settings_game.construction.freeform_edges = false;
}
/* From version 9.0, we update the max passengers of a town (was sometimes negative
* before that. */
if (CheckSavegameVersion(9)) {
Town *t;
FOR_ALL_TOWNS(t) UpdateTownMaxPass(t);
}
/* From version 16.0, we included autorenew on engines, which are now saved, but
* of course, we do need to initialize them for older savegames. */
if (CheckSavegameVersion(16)) {
FOR_ALL_COMPANIES(c) {
c->engine_renew_list = NULL;
c->engine_renew = false;
c->engine_renew_months = -6;
c->engine_renew_money = 100000;
}
/* When loading a game, _local_company is not yet set to the correct value.
* However, in a dedicated server we are a spectator, so nothing needs to
* happen. In case we are not a dedicated server, the local company always
* becomes company 0, unless we are in the scenario editor where all the
* companies are 'invalid'.
*/
if (!_network_dedicated && IsValidCompanyID(COMPANY_FIRST)) {
c = GetCompany(COMPANY_FIRST);
c->engine_renew = _settings_client.gui.autorenew;
c->engine_renew_months = _settings_client.gui.autorenew_months;
c->engine_renew_money = _settings_client.gui.autorenew_money;
}
}
if (CheckSavegameVersion(48)) {
for (TileIndex t = 0; t < map_size; t++) {
switch (GetTileType(t)) {
case MP_RAILWAY:
if (IsPlainRailTile(t)) {
/* Swap ground type and signal type for plain rail tiles, so the
* ground type uses the same bits as for depots and waypoints. */
uint tmp = GB(_m[t].m4, 0, 4);
SB(_m[t].m4, 0, 4, GB(_m[t].m2, 0, 4));
SB(_m[t].m2, 0, 4, tmp);
} else if (HasBit(_m[t].m5, 2)) {
/* Split waypoint and depot rail type and remove the subtype. */
ClrBit(_m[t].m5, 2);
ClrBit(_m[t].m5, 6);
}
break;
case MP_ROAD:
/* Swap m3 and m4, so the track type for rail crossings is the
* same as for normal rail. */
Swap(_m[t].m3, _m[t].m4);
break;
default: break;
}
}
}
if (CheckSavegameVersion(61)) {
/* Added the RoadType */
bool old_bridge = CheckSavegameVersion(42);
for (TileIndex t = 0; t < map_size; t++) {
switch (GetTileType(t)) {
case MP_ROAD:
SB(_m[t].m5, 6, 2, GB(_m[t].m5, 4, 2));
switch (GetRoadTileType(t)) {
default: NOT_REACHED();
case ROAD_TILE_NORMAL:
SB(_m[t].m4, 0, 4, GB(_m[t].m5, 0, 4));
SB(_m[t].m4, 4, 4, 0);
SB(_m[t].m6, 2, 4, 0);
break;
case ROAD_TILE_CROSSING:
SB(_m[t].m4, 5, 2, GB(_m[t].m5, 2, 2));
break;
case ROAD_TILE_DEPOT: break;
}
SetRoadTypes(t, ROADTYPES_ROAD);
break;
case MP_STATION:
if (IsRoadStop(t)) SetRoadTypes(t, ROADTYPES_ROAD);
break;
case MP_TUNNELBRIDGE:
/* Middle part of "old" bridges */
if (old_bridge && IsBridge(t) && HasBit(_m[t].m5, 6)) break;
if (((old_bridge && IsBridge(t)) ? (TransportType)GB(_m[t].m5, 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
SetRoadTypes(t, ROADTYPES_ROAD);
}
break;
default: break;
}
}
}
if (CheckSavegameVersion(114)) {
bool fix_roadtypes = !CheckSavegameVersion(61);
bool old_bridge = CheckSavegameVersion(42);
for (TileIndex t = 0; t < map_size; t++) {
switch (GetTileType(t)) {
case MP_ROAD:
if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_me[t].m7, 5, 3));
SB(_me[t].m7, 5, 1, GB(_m[t].m3, 7, 1)); // snow/desert
switch (GetRoadTileType(t)) {
default: NOT_REACHED();
case ROAD_TILE_NORMAL:
SB(_me[t].m7, 0, 4, GB(_m[t].m3, 0, 4)); // road works
SB(_m[t].m6, 3, 3, GB(_m[t].m3, 4, 3)); // ground
SB(_m[t].m3, 0, 4, GB(_m[t].m4, 4, 4)); // tram bits
SB(_m[t].m3, 4, 4, GB(_m[t].m5, 0, 4)); // tram owner
SB(_m[t].m5, 0, 4, GB(_m[t].m4, 0, 4)); // road bits
break;
case ROAD_TILE_CROSSING:
SB(_me[t].m7, 0, 5, GB(_m[t].m4, 0, 5)); // road owner
SB(_m[t].m6, 3, 3, GB(_m[t].m3, 4, 3)); // ground
SB(_m[t].m3, 4, 4, GB(_m[t].m5, 0, 4)); // tram owner
SB(_m[t].m5, 0, 1, GB(_m[t].m4, 6, 1)); // road axis
SB(_m[t].m5, 5, 1, GB(_m[t].m4, 5, 1)); // crossing state
break;
case ROAD_TILE_DEPOT:
break;
}
if (!HasTownOwnedRoad(t)) {
const Town *town = CalcClosestTownFromTile(t);
if (town != NULL) SetTownIndex(t, town->index);
}
_m[t].m4 = 0;
break;
case MP_STATION:
if (!IsRoadStop(t)) break;
if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_m[t].m3, 0, 3));
SB(_me[t].m7, 0, 5, HasBit(_m[t].m6, 2) ? OWNER_TOWN : GetTileOwner(t));
SB(_m[t].m3, 4, 4, _m[t].m1);
_m[t].m4 = 0;
break;
case MP_TUNNELBRIDGE:
if (old_bridge && IsBridge(t) && HasBit(_m[t].m5, 6)) break;
if (((old_bridge && IsBridge(t)) ? (TransportType)GB(_m[t].m5, 1, 2) : GetTunnelBridgeTransportType(t)) == TRANSPORT_ROAD) {
if (fix_roadtypes) SetRoadTypes(t, (RoadTypes)GB(_m[t].m3, 0, 3));
Owner o = GetTileOwner(t);
SB(_me[t].m7, 0, 5, o); // road owner
SB(_m[t].m3, 4, 4, o == OWNER_NONE ? OWNER_TOWN : o); // tram owner
}
SB(_m[t].m6, 2, 4, GB(_m[t].m2, 4, 4)); // bridge type
SB(_me[t].m7, 5, 1, GB(_m[t].m4, 7, 1)); // snow/desert
_m[t].m2 = 0;
_m[t].m4 = 0;
break;
default: break;
}
}
}
if (CheckSavegameVersion(42)) {
Vehicle *v;
for (TileIndex t = 0; t < map_size; t++) {
if (MayHaveBridgeAbove(t)) ClearBridgeMiddle(t);
if (IsBridgeTile(t)) {
if (HasBit(_m[t].m5, 6)) { // middle part
Axis axis = (Axis)GB(_m[t].m5, 0, 1);
if (HasBit(_m[t].m5, 5)) { // transport route under bridge?
if (GB(_m[t].m5, 3, 2) == TRANSPORT_RAIL) {
MakeRailNormal(
t,
GetTileOwner(t),
axis == AXIS_X ? TRACK_BIT_Y : TRACK_BIT_X,
GetRailType(t)
);
} else {
TownID town = IsTileOwner(t, OWNER_TOWN) ? ClosestTownFromTile(t, UINT_MAX)->index : 0;
MakeRoadNormal(
t,
axis == AXIS_X ? ROAD_Y : ROAD_X,
ROADTYPES_ROAD,
town,
GetTileOwner(t), OWNER_NONE
);
}
} else {
if (GB(_m[t].m5, 3, 2) == 0) {
MakeClear(t, CLEAR_GRASS, 3);
} else {
if (GetTileSlope(t, NULL) != SLOPE_FLAT) {
MakeShore(t);
} else {
if (GetTileOwner(t) == OWNER_WATER) {
MakeWater(t);
} else {
MakeCanal(t, GetTileOwner(t), Random());
}
}
}
}
SetBridgeMiddle(t, axis);
} else { // ramp
Axis axis = (Axis)GB(_m[t].m5, 0, 1);
uint north_south = GB(_m[t].m5, 5, 1);
DiagDirection dir = ReverseDiagDir(XYNSToDiagDir(axis, north_south));
TransportType type = (TransportType)GB(_m[t].m5, 1, 2);
_m[t].m5 = 1 << 7 | type << 2 | dir;
}
}
}
FOR_ALL_VEHICLES(v) {
if (v->type != VEH_TRAIN && v->type != VEH_ROAD) continue;
if (IsBridgeTile(v->tile)) {
DiagDirection dir = GetTunnelBridgeDirection(v->tile);
if (dir != DirToDiagDir(v->direction)) continue;
switch (dir) {
default: NOT_REACHED();
case DIAGDIR_NE: if ((v->x_pos & 0xF) != 0) continue; break;
case DIAGDIR_SE: if ((v->y_pos & 0xF) != TILE_SIZE - 1) continue; break;
case DIAGDIR_SW: if ((v->x_pos & 0xF) != TILE_SIZE - 1) continue; break;
case DIAGDIR_NW: if ((v->y_pos & 0xF) != 0) continue; break;
}
} else if (v->z_pos > GetSlopeZ(v->x_pos, v->y_pos)) {
v->tile = GetNorthernBridgeEnd(v->tile);
} else {
continue;
}
if (v->type == VEH_TRAIN) {
v->u.rail.track = TRACK_BIT_WORMHOLE;
} else {
v->u.road.state = RVSB_WORMHOLE;
}
}
}
/* Elrails got added in rev 24 */
if (CheckSavegameVersion(24)) {
Vehicle *v;
RailType min_rail = RAILTYPE_ELECTRIC;
FOR_ALL_VEHICLES(v) {
if (v->type == VEH_TRAIN) {
RailType rt = RailVehInfo(v->engine_type)->railtype;
v->u.rail.railtype = rt;
if (rt == RAILTYPE_ELECTRIC) min_rail = RAILTYPE_RAIL;
}
}
/* .. so we convert the entire map from normal to elrail (so maintain "fairness") */
for (TileIndex t = 0; t < map_size; t++) {
switch (GetTileType(t)) {
case MP_RAILWAY:
SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
break;
case MP_ROAD:
if (IsLevelCrossing(t)) {
SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
}
break;
case MP_STATION:
if (IsRailwayStation(t)) {
SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
}
break;
case MP_TUNNELBRIDGE:
if (GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL) {
SetRailType(t, UpdateRailType(GetRailType(t), min_rail));
}
break;
default:
break;
}
}
FOR_ALL_VEHICLES(v) {
if (v->type == VEH_TRAIN && (IsFrontEngine(v) || IsFreeWagon(v))) TrainConsistChanged(v, true);
}
}
/* In version 16.1 of the savegame a company can decide if trains, which get
* replaced, shall keep their old length. In all prior versions, just default
* to false */
if (CheckSavegameVersionOldStyle(16, 1)) {
FOR_ALL_COMPANIES(c) c->renew_keep_length = false;
}
/* In version 17, ground type is moved from m2 to m4 for depots and
* waypoints to make way for storing the index in m2. The custom graphics
* id which was stored in m4 is now saved as a grf/id reference in the
* waypoint struct. */
if (CheckSavegameVersion(17)) {
Waypoint *wp;
FOR_ALL_WAYPOINTS(wp) {
if (wp->deleted == 0) {
const StationSpec *statspec = NULL;
if (HasBit(_m[wp->xy].m3, 4))
statspec = GetCustomStationSpec(STAT_CLASS_WAYP, _m[wp->xy].m4 + 1);
if (statspec != NULL) {
wp->stat_id = _m[wp->xy].m4 + 1;
wp->grfid = statspec->grffile->grfid;
wp->localidx = statspec->localidx;
} else {
/* No custom graphics set, so set to default. */
wp->stat_id = 0;
wp->grfid = 0;
wp->localidx = 0;
}
/* Move ground type bits from m2 to m4. */
_m[wp->xy].m4 = GB(_m[wp->xy].m2, 0, 4);
/* Store waypoint index in the tile. */
_m[wp->xy].m2 = wp->index;
}
}
} else {
/* As of version 17, we recalculate the custom graphic ID of waypoints
* from the GRF ID / station index. */
AfterLoadWaypoints();
}
/* From version 15, we moved a semaphore bit from bit 2 to bit 3 in m4, making
* room for PBS. Now in version 21 move it back :P. */
if (CheckSavegameVersion(21) && !CheckSavegameVersion(15)) {
for (TileIndex t = 0; t < map_size; t++) {
switch (GetTileType(t)) {
case MP_RAILWAY:
if (HasSignals(t)) {
/* convert PBS signals to combo-signals */
if (HasBit(_m[t].m2, 2)) SetSignalType(t, TRACK_X, SIGTYPE_COMBO);
/* move the signal variant back */
SetSignalVariant(t, TRACK_X, HasBit(_m[t].m2, 3) ? SIG_SEMAPHORE : SIG_ELECTRIC);
ClrBit(_m[t].m2, 3);
}
/* Clear PBS reservation on track */
if (!IsRailDepotTile(t)) {
SB(_m[t].m4, 4, 4, 0);
} else {
ClrBit(_m[t].m3, 6);
}
break;
case MP_STATION: // Clear PBS reservation on station
ClrBit(_m[t].m3, 6);
break;
default: break;
}
}
}
if (CheckSavegameVersion(25)) {
Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->type == VEH_ROAD) {
v->vehstatus &= ~0x40;
v->u.road.slot = NULL;
v->u.road.slot_age = 0;
}
}
} else {
Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->type == VEH_ROAD && v->u.road.slot != NULL) v->u.road.slot->num_vehicles++;
}
}
if (CheckSavegameVersion(26)) {
Station *st;
FOR_ALL_STATIONS(st) {
st->last_vehicle_type = VEH_INVALID;
}
}
YapfNotifyTrackLayoutChange(INVALID_TILE, INVALID_TRACK);
if (CheckSavegameVersion(34)) FOR_ALL_COMPANIES(c) ResetCompanyLivery(c);
FOR_ALL_COMPANIES(c) {
c->avail_railtypes = GetCompanyRailtypes(c->index);
c->avail_roadtypes = GetCompanyRoadtypes(c->index);
}
if (!CheckSavegameVersion(27)) AfterLoadStations();
/* Time starts at 0 instead of 1920.
* Account for this in older games by adding an offset */
if (CheckSavegameVersion(31)) {
Station *st;
Waypoint *wp;
Engine *e;
Industry *i;
Vehicle *v;
_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
_cur_year += ORIGINAL_BASE_YEAR;
FOR_ALL_STATIONS(st) st->build_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
FOR_ALL_WAYPOINTS(wp) wp->build_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
FOR_ALL_ENGINES(e) e->intro_date += DAYS_TILL_ORIGINAL_BASE_YEAR;
FOR_ALL_COMPANIES(c) c->inaugurated_year += ORIGINAL_BASE_YEAR;
FOR_ALL_INDUSTRIES(i) i->last_prod_year += ORIGINAL_BASE_YEAR;
FOR_ALL_VEHICLES(v) {
v->date_of_last_service += DAYS_TILL_ORIGINAL_BASE_YEAR;
v->build_year += ORIGINAL_BASE_YEAR;
}
}
/* From 32 on we save the industry who made the farmland.
* To give this prettyness to old savegames, we remove all farmfields and
* plant new ones. */
if (CheckSavegameVersion(32)) {
Industry *i;
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_CLEAR) && IsClearGround(t, CLEAR_FIELDS)) {
/* remove fields */
MakeClear(t, CLEAR_GRASS, 3);
} else if (IsTileType(t, MP_CLEAR) || IsTileType(t, MP_TREES)) {
/* remove fences around fields */
SetFenceSE(t, 0);
SetFenceSW(t, 0);
}
}
FOR_ALL_INDUSTRIES(i) {
uint j;
if (GetIndustrySpec(i->type)->behaviour & INDUSTRYBEH_PLANT_ON_BUILT) {
for (j = 0; j != 50; j++) PlantRandomFarmField(i);
}
}
}
/* Setting no refit flags to all orders in savegames from before refit in orders were added */
if (CheckSavegameVersion(36)) {
Order *order;
Vehicle *v;
FOR_ALL_ORDERS(order) {
order->SetRefit(CT_NO_REFIT);
}
FOR_ALL_VEHICLES(v) {
v->current_order.SetRefit(CT_NO_REFIT);
}
}
/* from version 38 we have optional elrails, since we cannot know the
* preference of a user, let elrails enabled; it can be disabled manually */
if (CheckSavegameVersion(38)) _settings_game.vehicle.disable_elrails = false;
/* do the same as when elrails were enabled/disabled manually just now */
SettingsDisableElrail(_settings_game.vehicle.disable_elrails);
InitializeRailGUI();
/* From version 53, the map array was changed for house tiles to allow
* space for newhouses grf features. A new byte, m7, was also added. */
if (CheckSavegameVersion(53)) {
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_HOUSE)) {
if (GB(_m[t].m3, 6, 2) != TOWN_HOUSE_COMPLETED) {
/* Move the construction stage from m3[7..6] to m5[5..4].
* The construction counter does not have to move. */
SB(_m[t].m5, 3, 2, GB(_m[t].m3, 6, 2));
SB(_m[t].m3, 6, 2, 0);
/* The "house is completed" bit is now in m6[2]. */
SetHouseCompleted(t, false);
} else {
/* The "lift has destination" bit has been moved from
* m5[7] to m7[0]. */
SB(_me[t].m7, 0, 1, HasBit(_m[t].m5, 7));
ClrBit(_m[t].m5, 7);
/* The "lift is moving" bit has been removed, as it does
* the same job as the "lift has destination" bit. */
ClrBit(_m[t].m1, 7);
/* The position of the lift goes from m1[7..0] to m6[7..2],
* making m1 totally free, now. The lift position does not
* have to be a full byte since the maximum value is 36. */
SetLiftPosition(t, GB(_m[t].m1, 0, 6 ));
_m[t].m1 = 0;
_m[t].m3 = 0;
SetHouseCompleted(t, true);
}
}
}
}
/* Check and update house and town values */
UpdateHousesAndTowns();
if (CheckSavegameVersion(43)) {
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_INDUSTRY)) {
switch (GetIndustryGfx(t)) {
case GFX_POWERPLANT_SPARKS:
SetIndustryAnimationState(t, GB(_m[t].m1, 2, 5));
break;
case GFX_OILWELL_ANIMATED_1:
case GFX_OILWELL_ANIMATED_2:
case GFX_OILWELL_ANIMATED_3:
SetIndustryAnimationState(t, GB(_m[t].m1, 0, 2));
break;
case GFX_COAL_MINE_TOWER_ANIMATED:
case GFX_COPPER_MINE_TOWER_ANIMATED:
case GFX_GOLD_MINE_TOWER_ANIMATED:
SetIndustryAnimationState(t, _m[t].m1);
break;
default: // No animation states to change
break;
}
}
}
}
if (CheckSavegameVersion(44)) {
Vehicle *v;
/* If we remove a station while cargo from it is still enroute, payment calculation will assume
* 0, 0 to be the source of the cargo, resulting in very high payments usually. v->source_xy
* stores the coordinates, preserving them even if the station is removed. However, if a game is loaded
* where this situation exists, the cargo-source information is lost. in this case, we set the source
* to the current tile of the vehicle to prevent excessive profits
*/
FOR_ALL_VEHICLES(v) {
const CargoList::List *packets = v->cargo.Packets();
for (CargoList::List::const_iterator it = packets->begin(); it != packets->end(); it++) {
CargoPacket *cp = *it;
cp->source_xy = IsValidStationID(cp->source) ? GetStation(cp->source)->xy : v->tile;
cp->loaded_at_xy = cp->source_xy;
}
v->cargo.InvalidateCache();
}
/* Store position of the station where the goods come from, so there
* are no very high payments when stations get removed. However, if the
* station where the goods came from is already removed, the source
* information is lost. In that case we set it to the position of this
* station */
Station *st;
FOR_ALL_STATIONS(st) {
for (CargoID c = 0; c < NUM_CARGO; c++) {
GoodsEntry *ge = &st->goods[c];
const CargoList::List *packets = ge->cargo.Packets();
for (CargoList::List::const_iterator it = packets->begin(); it != packets->end(); it++) {
CargoPacket *cp = *it;
cp->source_xy = IsValidStationID(cp->source) ? GetStation(cp->source)->xy : st->xy;
cp->loaded_at_xy = cp->source_xy;
}
}
}
}
if (CheckSavegameVersion(45)) {
Vehicle *v;
/* Originally just the fact that some cargo had been paid for was
* stored to stop people cheating and cashing in several times. This
* wasn't enough though as it was cleared when the vehicle started
* loading again, even if it didn't actually load anything, so now the
* amount of cargo that has been paid for is stored. */
FOR_ALL_VEHICLES(v) {
const CargoList::List *packets = v->cargo.Packets();
for (CargoList::List::const_iterator it = packets->begin(); it != packets->end(); it++) {
CargoPacket *cp = *it;
cp->paid_for = HasBit(v->vehicle_flags, 2);
}
ClrBit(v->vehicle_flags, 2);
v->cargo.InvalidateCache();
}
}
/* Buoys do now store the owner of the previous water tile, which can never
* be OWNER_NONE. So replace OWNER_NONE with OWNER_WATER. */
if (CheckSavegameVersion(46)) {
Station *st;
FOR_ALL_STATIONS(st) {
if (st->IsBuoy() && IsTileOwner(st->xy, OWNER_NONE) && TileHeight(st->xy) == 0) SetTileOwner(st->xy, OWNER_WATER);
}
}
if (CheckSavegameVersion(50)) {
Vehicle *v;
/* Aircraft units changed from 8 mph to 1 km/h */
FOR_ALL_VEHICLES(v) {
if (v->type == VEH_AIRCRAFT && v->subtype <= AIR_AIRCRAFT) {
const AircraftVehicleInfo *avi = AircraftVehInfo(v->engine_type);
v->cur_speed *= 129;
v->cur_speed /= 10;
v->max_speed = avi->max_speed;
v->acceleration = avi->acceleration;
}
}
}
if (CheckSavegameVersion(49)) FOR_ALL_COMPANIES(c) c->face = ConvertFromOldCompanyManagerFace(c->face);
if (CheckSavegameVersion(52)) {
for (TileIndex t = 0; t < map_size; t++) {
if (IsStatueTile(t)) {
_m[t].m2 = CalcClosestTownFromTile(t)->index;
}
}
}
/* A setting containing the proportion of towns that grow twice as
* fast was added in version 54. From version 56 this is now saved in the
* town as cities can be built specifically in the scenario editor. */
if (CheckSavegameVersion(56)) {
Town *t;
FOR_ALL_TOWNS(t) {
if (_settings_game.economy.larger_towns != 0 && (t->index % _settings_game.economy.larger_towns) == 0) {
t->larger_town = true;
}
}
}
if (CheckSavegameVersion(57)) {
Vehicle *v;
/* Added a FIFO queue of vehicles loading at stations */
FOR_ALL_VEHICLES(v) {
if ((v->type != VEH_TRAIN || IsFrontEngine(v)) && // for all locs
!(v->vehstatus & (VS_STOPPED | VS_CRASHED)) && // not stopped or crashed
v->current_order.IsType(OT_LOADING)) { // loading
GetStation(v->last_station_visited)->loading_vehicles.push_back(v);
/* The loading finished flag is *only* set when actually completely
* finished. Because the vehicle is loading, it is not finished. */
ClrBit(v->vehicle_flags, VF_LOADING_FINISHED);
}
}
} else if (CheckSavegameVersion(59)) {
/* For some reason non-loading vehicles could be in the station's loading vehicle list */
Station *st;
FOR_ALL_STATIONS(st) {
std::list<Vehicle *>::iterator iter;
for (iter = st->loading_vehicles.begin(); iter != st->loading_vehicles.end();) {
Vehicle *v = *iter;
iter++;
if (!v->current_order.IsType(OT_LOADING)) st->loading_vehicles.remove(v);
}
}
}
if (CheckSavegameVersion(58)) {
/* Setting difficulty number_industries other than zero get bumped to +1
* since a new option (very low at position1) has been added */
if (_settings_game.difficulty.number_industries > 0) {
_settings_game.difficulty.number_industries++;
}
/* Same goes for number of towns, although no test is needed, just an increment */
_settings_game.difficulty.number_towns++;
}
if (CheckSavegameVersion(64)) {
/* copy the signal type/variant and move signal states bits */
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_RAILWAY) && HasSignals(t)) {
SetSignalStates(t, GB(_m[t].m2, 4, 4));
SetSignalVariant(t, INVALID_TRACK, GetSignalVariant(t, TRACK_X));
SetSignalType(t, INVALID_TRACK, GetSignalType(t, TRACK_X));
ClrBit(_m[t].m2, 7);
}
}
}
if (CheckSavegameVersion(69)) {
/* In some old savegames a bit was cleared when it should not be cleared */
Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->type == VEH_ROAD && (v->u.road.state == 250 || v->u.road.state == 251)) {
SetBit(v->u.road.state, RVS_IS_STOPPING);
}
}
}
if (CheckSavegameVersion(70)) {
/* Added variables to support newindustries */
Industry *i;
FOR_ALL_INDUSTRIES(i) i->founder = OWNER_NONE;
}
/* From version 82, old style canals (above sealevel (0), WATER owner) are no longer supported.
Replace the owner for those by OWNER_NONE. */
if (CheckSavegameVersion(82)) {
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_WATER) &&
GetWaterTileType(t) == WATER_TILE_CLEAR &&
GetTileOwner(t) == OWNER_WATER &&
TileHeight(t) != 0) {
SetTileOwner(t, OWNER_NONE);
}
}
}
/*
* Add the 'previous' owner to the ship depots so we can reset it with
* the correct values when it gets destroyed. This prevents that
* someone can remove canals owned by somebody else and it prevents
* making floods using the removal of ship depots.
*/
if (CheckSavegameVersion(83)) {
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_WATER) && IsShipDepot(t)) {
_m[t].m4 = (TileHeight(t) == 0) ? OWNER_WATER : OWNER_NONE;
}
}
}
if (CheckSavegameVersion(74)) {
Station *st;
FOR_ALL_STATIONS(st) {
for (CargoID c = 0; c < NUM_CARGO; c++) {
st->goods[c].last_speed = 0;
if (st->goods[c].cargo.Count() != 0) SetBit(st->goods[c].acceptance_pickup, GoodsEntry::PICKUP);
}
}
}
if (CheckSavegameVersion(78)) {
Industry *i;
uint j;
FOR_ALL_INDUSTRIES(i) {
const IndustrySpec *indsp = GetIndustrySpec(i->type);
for (j = 0; j < lengthof(i->produced_cargo); j++) {
i->produced_cargo[j] = indsp->produced_cargo[j];
}
for (j = 0; j < lengthof(i->accepts_cargo); j++) {
i->accepts_cargo[j] = indsp->accepts_cargo[j];
}
}
}
/* Before version 81, the density of grass was always stored as zero, and
* grassy trees were always drawn fully grassy. Furthermore, trees on rough
* land used to have zero density, now they have full density. Therefore,
* make all grassy/rough land trees have a density of 3. */
if (CheckSavegameVersion(81)) {
for (TileIndex t = 0; t < map_size; t++) {
if (GetTileType(t) == MP_TREES) {
TreeGround groundType = GetTreeGround(t);
if (groundType != TREE_GROUND_SNOW_DESERT) SetTreeGroundDensity(t, groundType, 3);
}
}
}
if (CheckSavegameVersion(93)) {
/* Rework of orders. */
Order *order;
FOR_ALL_ORDERS(order) order->ConvertFromOldSavegame();
Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->orders.list != NULL && v->orders.list->GetFirstOrder() != NULL && !v->orders.list->GetFirstOrder()->IsValid()) {
v->orders.list->FreeChain();
v->orders.list = NULL;
}
v->current_order.ConvertFromOldSavegame();
if (v->type == VEH_ROAD && v->IsPrimaryVehicle() && v->FirstShared() == v) {
FOR_VEHICLE_ORDERS(v, order) order->SetNonStopType(ONSF_NO_STOP_AT_INTERMEDIATE_STATIONS);
}
}
} else if (CheckSavegameVersion(94)) {
/* Unload and transfer are now mutual exclusive. */
Order *order;
FOR_ALL_ORDERS(order) {
if ((order->GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
order->SetUnloadType(OUFB_TRANSFER);
order->SetLoadType(OLFB_NO_LOAD);
}
}
Vehicle *v;
FOR_ALL_VEHICLES(v) {
if ((v->current_order.GetUnloadType() & (OUFB_UNLOAD | OUFB_TRANSFER)) == (OUFB_UNLOAD | OUFB_TRANSFER)) {
v->current_order.SetUnloadType(OUFB_TRANSFER);
v->current_order.SetLoadType(OLFB_NO_LOAD);
}
}
}
if (CheckSavegameVersion(84)) {
/* Update go to buoy orders because they are just waypoints */
Order *order;
FOR_ALL_ORDERS(order) {
if (order->IsType(OT_GOTO_STATION) && GetStation(order->GetDestination())->IsBuoy()) {
order->SetLoadType(OLF_LOAD_IF_POSSIBLE);
order->SetUnloadType(OUF_UNLOAD_IF_POSSIBLE);
}
}
/* Set all share owners to INVALID_COMPANY for
* 1) all inactive companies
* (when inactive companies were stored in the savegame - TTD, TTDP and some
* *really* old revisions of OTTD; else it is already set in InitializeCompanies())
* 2) shares that are owned by inactive companies or self
* (caused by cheating clients in earlier revisions) */
FOR_ALL_COMPANIES(c) {
for (uint i = 0; i < 4; i++) {
CompanyID company = c->share_owners[i];
if (company == INVALID_COMPANY) continue;
if (!IsValidCompanyID(company) || company == c->index) c->share_owners[i] = INVALID_COMPANY;
}
}
}
if (CheckSavegameVersion(86)) {
for (TileIndex t = 0; t < map_size; t++) {
/* Move river flag and update canals to use water class */
if (IsTileType(t, MP_WATER)) {
if (GetWaterClass(t) != WATER_CLASS_RIVER) {
if (IsWater(t)) {
Owner o = GetTileOwner(t);
if (o == OWNER_WATER) {
MakeWater(t);
} else {
MakeCanal(t, o, Random());
}
} else if (IsShipDepot(t)) {
Owner o = (Owner)_m[t].m4; // Original water owner
SetWaterClass(t, o == OWNER_WATER ? WATER_CLASS_SEA : WATER_CLASS_CANAL);
}
}
}
}
/* Update locks, depots, docks and buoys to have a water class based
* on its neighbouring tiles. Done after river and canal updates to
* ensure neighbours are correct. */
for (TileIndex t = 0; t < map_size; t++) {
if (GetTileSlope(t, NULL) != SLOPE_FLAT) continue;
if (IsTileType(t, MP_WATER) && IsLock(t)) SetWaterClassDependingOnSurroundings(t, false);
if (IsTileType(t, MP_STATION) && (IsDock(t) || IsBuoy(t))) SetWaterClassDependingOnSurroundings(t, false);
}
}
if (CheckSavegameVersion(87)) {
for (TileIndex t = 0; t < map_size; t++) {
/* skip oil rigs at borders! */
if ((IsTileType(t, MP_WATER) || IsBuoyTile(t)) &&
(TileX(t) == 0 || TileY(t) == 0 || TileX(t) == MapMaxX() - 1 || TileY(t) == MapMaxY() - 1)) {
/* Some version 86 savegames have wrong water class at map borders (under buoy, or after removing buoy).
* This conversion has to be done before buoys with invalid owner are removed. */
SetWaterClass(t, WATER_CLASS_SEA);
}
if (IsBuoyTile(t) || IsDriveThroughStopTile(t) || IsTileType(t, MP_WATER)) {
Owner o = GetTileOwner(t);
if (o < MAX_COMPANIES && !IsValidCompanyID(o)) {
_current_company = o;
ChangeTileOwner(t, o, INVALID_OWNER);
}
if (IsBuoyTile(t)) {
/* reset buoy owner to OWNER_NONE in the station struct
* (even if it is owned by active company) */
GetStationByTile(t)->owner = OWNER_NONE;
}
} else if (IsTileType(t, MP_ROAD)) {
/* works for all RoadTileType */
for (RoadType rt = ROADTYPE_ROAD; rt < ROADTYPE_END; rt++) {
/* update even non-existing road types to update tile owner too */
Owner o = GetRoadOwner(t, rt);
if (o < MAX_COMPANIES && !IsValidCompanyID(o)) SetRoadOwner(t, rt, OWNER_NONE);
}
if (IsLevelCrossing(t)) {
if (!IsValidCompanyID(GetTileOwner(t))) FixOwnerOfRailTrack(t);
}
} else if (IsTileType(t, MP_RAILWAY) && IsPlainRailTile(t)) {
if (!IsValidCompanyID(GetTileOwner(t))) FixOwnerOfRailTrack(t);
}
}
/* Convert old PF settings to new */
if (_settings_game.pf.yapf.rail_use_yapf || CheckSavegameVersion(28)) {
_settings_game.pf.pathfinder_for_trains = VPF_YAPF;
} else {
_settings_game.pf.pathfinder_for_trains = (_settings_game.pf.new_pathfinding_all ? VPF_NPF : VPF_NTP);
}
if (_settings_game.pf.yapf.road_use_yapf || CheckSavegameVersion(28)) {
_settings_game.pf.pathfinder_for_roadvehs = VPF_YAPF;
} else {
_settings_game.pf.pathfinder_for_roadvehs = (_settings_game.pf.new_pathfinding_all ? VPF_NPF : VPF_OPF);
}
if (_settings_game.pf.yapf.ship_use_yapf) {
_settings_game.pf.pathfinder_for_ships = VPF_YAPF;
} else {
_settings_game.pf.pathfinder_for_ships = (_settings_game.pf.new_pathfinding_all ? VPF_NPF : VPF_OPF);
}
}
if (CheckSavegameVersion(88)) {
/* Profits are now with 8 bit fract */
Vehicle *v;
FOR_ALL_VEHICLES(v) {
v->profit_this_year <<= 8;
v->profit_last_year <<= 8;
v->running_ticks = 0;
}
}
if (CheckSavegameVersion(91)) {
/* Increase HouseAnimationFrame from 5 to 7 bits */
for (TileIndex t = 0; t < map_size; t++) {
if (IsTileType(t, MP_HOUSE) && GetHouseType(t) >= NEW_HOUSE_OFFSET) {
SetHouseAnimationFrame(t, GB(_m[t].m6, 3, 5));
}
}
}
if (CheckSavegameVersion(62)) {
/* Remove all trams from savegames without tram support.
* There would be trams without tram track under causing crashes sooner or later. */
Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->type == VEH_ROAD && v->First() == v &&
HasBit(EngInfo(v->engine_type)->misc_flags, EF_ROAD_TRAM)) {
if (_switch_mode_errorstr == INVALID_STRING_ID || _switch_mode_errorstr == STR_NEWGRF_COMPATIBLE_LOAD_WARNING) {
_switch_mode_errorstr = STR_LOADGAME_REMOVED_TRAMS;
}
delete v;
}
}
}
if (CheckSavegameVersion(99)) {
for (TileIndex t = 0; t < map_size; t++) {
/* Set newly introduced WaterClass of industry tiles */
if (IsTileType(t, MP_STATION) && IsOilRig(t)) {
SetWaterClassDependingOnSurroundings(t, true);
}
if (IsTileType(t, MP_INDUSTRY)) {
if ((GetIndustrySpec(GetIndustryType(t))->behaviour & INDUSTRYBEH_BUILT_ONWATER) != 0) {
SetWaterClassDependingOnSurroundings(t, true);
} else {
SetWaterClass(t, WATER_CLASS_INVALID);
}
}
/* Replace "house construction year" with "house age" */
if (IsTileType(t, MP_HOUSE) && IsHouseCompleted(t)) {
_m[t].m5 = Clamp(_cur_year - (_m[t].m5 + ORIGINAL_BASE_YEAR), 0, 0xFF);
}
}
}
/* Move the signal variant back up one bit for PBS. We don't convert the old PBS
* format here, as an old layout wouldn't work properly anyway. To be safe, we
* clear any possible PBS reservations as well. */
if (CheckSavegameVersion(100)) {
for (TileIndex t = 0; t < map_size; t++) {
switch (GetTileType(t)) {
case MP_RAILWAY:
if (HasSignals(t)) {
/* move the signal variant */
SetSignalVariant(t, TRACK_UPPER, HasBit(_m[t].m2, 2) ? SIG_SEMAPHORE : SIG_ELECTRIC);
SetSignalVariant(t, TRACK_LOWER, HasBit(_m[t].m2, 6) ? SIG_SEMAPHORE : SIG_ELECTRIC);
ClrBit(_m[t].m2, 2);
ClrBit(_m[t].m2, 6);
}
/* Clear PBS reservation on track */
if (IsRailDepot(t) ||IsRailWaypoint(t)) {
SetDepotWaypointReservation(t, false);
} else {
SetTrackReservation(t, TRACK_BIT_NONE);
}
break;
case MP_ROAD: // Clear PBS reservation on crossing
if (IsLevelCrossing(t)) SetCrossingReservation(t, false);
break;
case MP_STATION: // Clear PBS reservation on station
if (IsRailwayStation(t)) SetRailwayStationReservation(t, false);
break;
case MP_TUNNELBRIDGE: // Clear PBS reservation on tunnels/birdges
if (GetTunnelBridgeTransportType(t) == TRANSPORT_RAIL) SetTunnelBridgeReservation(t, false);
break;
default: break;
}
}
}
/* Reserve all tracks trains are currently on. */
if (CheckSavegameVersion(101)) {
Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->type == VEH_TRAIN) {
if ((v->u.rail.track & TRACK_BIT_WORMHOLE) == TRACK_BIT_WORMHOLE) {
TryReserveRailTrack(v->tile, DiagDirToDiagTrack(GetTunnelBridgeDirection(v->tile)));
} else if ((v->u.rail.track & TRACK_BIT_MASK) != TRACK_BIT_NONE) {
TryReserveRailTrack(v->tile, TrackBitsToTrack(v->u.rail.track));
}
}
}
}
if (CheckSavegameVersion(102)) {
for (TileIndex t = 0; t < map_size; t++) {
/* Now all crossings should be in correct state */
if (IsLevelCrossingTile(t)) UpdateLevelCrossing(t, false);
}
}
if (CheckSavegameVersion(103)) {
/* Non-town-owned roads now store the closest town */
UpdateNearestTownForRoadTiles(false);
/* signs with invalid owner left from older savegames */
Sign *si;
FOR_ALL_SIGNS(si) {
if (si->owner != OWNER_NONE && !IsValidCompanyID(si->owner)) si->owner = OWNER_NONE;
}
/* Station can get named based on an industry type, but the current ones
* are not, so mark them as if they are not named by an industry. */
Station *st;
FOR_ALL_STATIONS(st) {
st->indtype = IT_INVALID;
}
}
if (CheckSavegameVersion(104)) {
Vehicle *v;
FOR_ALL_VEHICLES(v) {
/* Set engine_type of shadow and rotor */
if (v->type == VEH_AIRCRAFT && !IsNormalAircraft(v)) {
v->engine_type = v->First()->engine_type;
}
}
/* More companies ... */
Company *c;
FOR_ALL_COMPANIES(c) {
if (c->bankrupt_asked == 0xFF) c->bankrupt_asked = 0xFFFF;
}
Engine *e;
FOR_ALL_ENGINES(e) {
if (e->company_avail == 0xFF) e->company_avail = 0xFFFF;
}
Town *t;
FOR_ALL_TOWNS(t) {
if (t->have_ratings == 0xFF) t->have_ratings = 0xFFFF;
for (uint i = 8; i != MAX_COMPANIES; i++) t->ratings[i] = RATING_INITIAL;
}
}
if (CheckSavegameVersion(112)) {
for (TileIndex t = 0; t < map_size; t++) {
/* Check for HQ bit being set, instead of using map accessor,
* since we've already changed it code-wise */
if (IsTileType(t, MP_UNMOVABLE) && HasBit(_m[t].m5, 7)) {
/* Move size and part identification of HQ out of the m5 attribute,
* on new locations */
uint8 old_m5 = _m[t].m5;
_m[t].m5 = UNMOVABLE_HQ;
SetCompanyHQSize(t, GB(old_m5, 2, 3));
SetCompanyHQSection(t, GB(old_m5, 0, 2));
}
}
}
if (CheckSavegameVersion(113)) {
/* allow_town_roads is added, set it if town_layout wasn't TL_NO_ROADS */
if (_settings_game.economy.town_layout == 0) { // was TL_NO_ROADS
_settings_game.economy.allow_town_roads = false;
_settings_game.economy.town_layout = TL_BETTER_ROADS;
} else {
_settings_game.economy.allow_town_roads = true;
_settings_game.economy.town_layout = _settings_game.economy.town_layout - 1;
}
/* Initialize layout of all towns. Older versions were using different
* generator for random town layout, use it if needed. */
Town *t;
FOR_ALL_TOWNS(t) {
if (_settings_game.economy.town_layout != TL_RANDOM) {
t->layout = _settings_game.economy.town_layout;
continue;
}
/* Use old layout randomizer code */
byte layout = TileHash(TileX(t->xy), TileY(t->xy)) % 6;
switch (layout) {
default: break;
case 5: layout = 1; break;
case 0: layout = 2; break;
}
t->layout = layout - 1;
}
}
if (CheckSavegameVersion(114)) {
/* There could be (deleted) stations with invalid owner, set owner to OWNER NONE.
* The conversion affects oil rigs and buoys too, but it doesn't matter as
* they have st->owner == OWNER_NONE already. */
Station *st;
FOR_ALL_STATIONS(st) {
if (!IsValidCompanyID(st->owner)) st->owner = OWNER_NONE;
}
/* Give owners to waypoints, based on rail tracks it is sitting on.
* If none is available, specify OWNER_NONE.
* This code was in CheckSavegameVersion(101) in the past, but in some cases,
* the owner of waypoints could be incorrect. */
Waypoint *wp;
FOR_ALL_WAYPOINTS(wp) {
Owner owner = IsTileType(wp->xy, MP_RAILWAY) ? GetTileOwner(wp->xy) : OWNER_NONE;
wp->owner = IsValidCompanyID(owner) ? owner : OWNER_NONE;
}
}
GamelogPrintDebug(1);
bool ret = InitializeWindowsAndCaches();
/* Restore the signals */
signal(SIGSEGV, prev_segfault);
signal(SIGABRT, prev_abort);
return ret;
}
/** Reload all NewGRF files during a running game. This is a cut-down
* version of AfterLoadGame().
* XXX - We need to reset the vehicle position hash because with a non-empty
* hash AfterLoadVehicles() will loop infinitely. We need AfterLoadVehicles()
* to recalculate vehicle data as some NewGRF vehicle sets could have been
* removed or added and changed statistics */
void ReloadNewGRFData()
{
/* reload grf data */
GfxLoadSprites();
LoadStringWidthTable();
ResetEconomy();
/* reload vehicles */
ResetVehiclePosHash();
AfterLoadVehicles(false);
StartupEngines();
SetCachedEngineCounts();
/* update station and waypoint graphics */
AfterLoadWaypoints();
AfterLoadStations();
/* Check and update house and town values */
UpdateHousesAndTowns();
/* Update livery selection windows */
for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) InvalidateWindowData(WC_COMPANY_COLOUR, i, _loaded_newgrf_features.has_2CC);
/* redraw the whole screen */
MarkWholeScreenDirty();
CheckTrainsLengths();
}
| 58,978
|
C++
|
.cpp
| 1,598
| 32.836045
| 157
| 0.656172
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,224
|
industry_sl.cpp
|
EnergeticBark_OpenTTD-3DS/src/saveload/industry_sl.cpp
|
/* $Id$ */
/** @file industry_sl.cpp Code handling saving and loading of industries */
#include "../stdafx.h"
#include "../tile_type.h"
#include "../strings_type.h"
#include "../company_type.h"
#include "../industry.h"
#include "../newgrf_commons.h"
#include "saveload.h"
static const SaveLoad _industry_desc[] = {
SLE_CONDVAR(Industry, xy, SLE_FILE_U16 | SLE_VAR_U32, 0, 5),
SLE_CONDVAR(Industry, xy, SLE_UINT32, 6, SL_MAX_VERSION),
SLE_VAR(Industry, width, SLE_UINT8),
SLE_VAR(Industry, height, SLE_UINT8),
SLE_REF(Industry, town, REF_TOWN),
SLE_CONDNULL( 2, 0, 60), ///< used to be industry's produced_cargo
SLE_CONDARR(Industry, produced_cargo, SLE_UINT8, 2, 78, SL_MAX_VERSION),
SLE_CONDARR(Industry, incoming_cargo_waiting, SLE_UINT16, 3, 70, SL_MAX_VERSION),
SLE_ARR(Industry, produced_cargo_waiting, SLE_UINT16, 2),
SLE_ARR(Industry, production_rate, SLE_UINT8, 2),
SLE_CONDNULL( 3, 0, 60), ///< used to be industry's accepts_cargo
SLE_CONDARR(Industry, accepts_cargo, SLE_UINT8, 3, 78, SL_MAX_VERSION),
SLE_VAR(Industry, prod_level, SLE_UINT8),
SLE_ARR(Industry, this_month_production, SLE_UINT16, 2),
SLE_ARR(Industry, this_month_transported, SLE_UINT16, 2),
SLE_ARR(Industry, last_month_pct_transported, SLE_UINT8, 2),
SLE_ARR(Industry, last_month_production, SLE_UINT16, 2),
SLE_ARR(Industry, last_month_transported, SLE_UINT16, 2),
SLE_VAR(Industry, counter, SLE_UINT16),
SLE_VAR(Industry, type, SLE_UINT8),
SLE_VAR(Industry, owner, SLE_UINT8),
SLE_VAR(Industry, random_colour, SLE_UINT8),
SLE_CONDVAR(Industry, last_prod_year, SLE_FILE_U8 | SLE_VAR_I32, 0, 30),
SLE_CONDVAR(Industry, last_prod_year, SLE_INT32, 31, SL_MAX_VERSION),
SLE_VAR(Industry, was_cargo_delivered, SLE_UINT8),
SLE_CONDVAR(Industry, founder, SLE_UINT8, 70, SL_MAX_VERSION),
SLE_CONDVAR(Industry, construction_date, SLE_INT32, 70, SL_MAX_VERSION),
SLE_CONDVAR(Industry, construction_type, SLE_UINT8, 70, SL_MAX_VERSION),
SLE_CONDVAR(Industry, last_cargo_accepted_at, SLE_INT32, 70, SL_MAX_VERSION),
SLE_CONDVAR(Industry, selected_layout, SLE_UINT8, 73, SL_MAX_VERSION),
SLE_CONDARRX(cpp_offsetof(Industry, psa) + cpp_offsetof(Industry::PersistentStorage, storage), SLE_UINT32, 16, 76, SL_MAX_VERSION),
SLE_CONDVAR(Industry, random_triggers, SLE_UINT8, 82, SL_MAX_VERSION),
SLE_CONDVAR(Industry, random, SLE_UINT16, 82, SL_MAX_VERSION),
/* reserve extra space in savegame here. (currently 32 bytes) */
SLE_CONDNULL(32, 2, SL_MAX_VERSION),
SLE_END()
};
static void Save_INDY()
{
Industry *ind;
/* Write the industries */
FOR_ALL_INDUSTRIES(ind) {
SlSetArrayIndex(ind->index);
SlObject(ind, _industry_desc);
}
}
/* Save and load the mapping between the industry/tile id on the map, and the grf file
* it came from. */
static const SaveLoad _industries_id_mapping_desc[] = {
SLE_VAR(EntityIDMapping, grfid, SLE_UINT32),
SLE_VAR(EntityIDMapping, entity_id, SLE_UINT8),
SLE_VAR(EntityIDMapping, substitute_id, SLE_UINT8),
SLE_END()
};
static void Save_IIDS()
{
uint i;
uint j = _industry_mngr.GetMaxMapping();
for (i = 0; i < j; i++) {
SlSetArrayIndex(i);
SlObject(&_industry_mngr.mapping_ID[i], _industries_id_mapping_desc);
}
}
static void Save_TIDS()
{
uint i;
uint j = _industile_mngr.GetMaxMapping();
for (i = 0; i < j; i++) {
SlSetArrayIndex(i);
SlObject(&_industile_mngr.mapping_ID[i], _industries_id_mapping_desc);
}
}
static void Load_INDY()
{
int index;
ResetIndustryCounts();
while ((index = SlIterateArray()) != -1) {
Industry *i = new (index) Industry();
SlObject(i, _industry_desc);
IncIndustryTypeCount(i->type);
}
}
static void Load_IIDS()
{
int index;
uint max_id;
/* clear the current mapping stored.
* This will create the manager if ever it is not yet done */
_industry_mngr.ResetMapping();
/* get boundary for the temporary map loader NUM_INDUSTRYTYPES? */
max_id = _industry_mngr.GetMaxMapping();
while ((index = SlIterateArray()) != -1) {
if ((uint)index >= max_id) break;
SlObject(&_industry_mngr.mapping_ID[index], _industries_id_mapping_desc);
}
}
static void Load_TIDS()
{
int index;
uint max_id;
/* clear the current mapping stored.
* This will create the manager if ever it is not yet done */
_industile_mngr.ResetMapping();
/* get boundary for the temporary map loader NUM_INDUSTILES? */
max_id = _industile_mngr.GetMaxMapping();
while ((index = SlIterateArray()) != -1) {
if ((uint)index >= max_id) break;
SlObject(&_industile_mngr.mapping_ID[index], _industries_id_mapping_desc);
}
}
extern const ChunkHandler _industry_chunk_handlers[] = {
{ 'INDY', Save_INDY, Load_INDY, CH_ARRAY},
{ 'IIDS', Save_IIDS, Load_IIDS, CH_ARRAY},
{ 'TIDS', Save_TIDS, Load_TIDS, CH_ARRAY | CH_LAST},
};
| 5,385
|
C++
|
.cpp
| 125
| 40.48
| 132
| 0.628872
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,225
|
depot_sl.cpp
|
EnergeticBark_OpenTTD-3DS/src/saveload/depot_sl.cpp
|
/* $Id$ */
/** @file depot_sl.cpp Code handling saving and loading of depots */
#include "../stdafx.h"
#include "../depot_base.h"
#include "saveload.h"
static const SaveLoad _depot_desc[] = {
SLE_CONDVAR(Depot, xy, SLE_FILE_U16 | SLE_VAR_U32, 0, 5),
SLE_CONDVAR(Depot, xy, SLE_UINT32, 6, SL_MAX_VERSION),
SLE_VAR(Depot, town_index, SLE_UINT16),
SLE_END()
};
static void Save_DEPT()
{
Depot *depot;
FOR_ALL_DEPOTS(depot) {
SlSetArrayIndex(depot->index);
SlObject(depot, _depot_desc);
}
}
static void Load_DEPT()
{
int index;
while ((index = SlIterateArray()) != -1) {
Depot *depot = new (index) Depot();
SlObject(depot, _depot_desc);
}
}
extern const ChunkHandler _depot_chunk_handlers[] = {
{ 'DEPT', Save_DEPT, Load_DEPT, CH_ARRAY | CH_LAST},
};
| 811
|
C++
|
.cpp
| 30
| 24.966667
| 79
| 0.648964
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,227
|
saveload.cpp
|
EnergeticBark_OpenTTD-3DS/src/saveload/saveload.cpp
|
/* $Id$ */
/** @file saveload.cpp
* All actions handling saving and loading goes on in this file. The general actions
* are as follows for saving a game (loading is analogous):
* <ol>
* <li>initialize the writer by creating a temporary memory-buffer for it
* <li>go through all to-be saved elements, each 'chunk' (ChunkHandler) prefixed by a label
* <li>use their description array (SaveLoad) to know what elements to save and in what version
* of the game it was active (used when loading)
* <li>write all data byte-by-byte to the temporary buffer so it is endian-safe
* <li>when the buffer is full; flush it to the output (eg save to file) (_sl.buf, _sl.bufp, _sl.bufe)
* <li>repeat this until everything is done, and flush any remaining output to file
* </ol>
*/
#include "../stdafx.h"
#include "../openttd.h"
#include "../debug.h"
#include "../station_base.h"
#include "../thread.h"
#include "../town.h"
#include "../network/network.h"
#include "../variables.h"
#include "../window_func.h"
#include "../strings_func.h"
#include "../gfx_func.h"
#include "../core/alloc_func.hpp"
#include "../core/endian_func.hpp"
#include "../vehicle_base.h"
#include "../company_func.h"
#include "../date_func.h"
#include "../autoreplace_base.h"
#include "../statusbar_gui.h"
#include "../fileio_func.h"
#include "../gamelog.h"
#include "../string_func.h"
#include "../engine_base.h"
#include "table/strings.h"
#include "saveload_internal.h"
extern const uint16 SAVEGAME_VERSION = 116;
SavegameType _savegame_type; ///< type of savegame we are loading
uint32 _ttdp_version; ///< version of TTDP savegame (if applicable)
uint16 _sl_version; ///< the major savegame version identifier
byte _sl_minor_version; ///< the minor savegame version, DO NOT USE!
char _savegame_format[8]; ///< how to compress savegames
typedef void WriterProc(size_t len);
typedef size_t ReaderProc();
/** The saveload struct, containing reader-writer functions, bufffer, version, etc. */
static struct {
bool save; ///< are we doing a save or a load atm. True when saving
byte need_length; ///< ???
byte block_mode; ///< ???
bool error; ///< did an error occur or not
size_t obj_len; ///< the length of the current object we are busy with
int array_index, last_array_index; ///< in the case of an array, the current and last positions
size_t offs_base; ///< the offset in number of bytes since we started writing data (eg uncompressed savegame size)
WriterProc *write_bytes; ///< savegame writer function
ReaderProc *read_bytes; ///< savegame loader function
const ChunkHandler * const *chs; ///< the chunk of data that is being processed atm (vehicles, signs, etc.)
/* When saving/loading savegames, they are always saved to a temporary memory-place
* to be flushed to file (save) or to final place (load) when full. */
byte *bufp, *bufe; ///< bufp(ointer) gives the current position in the buffer bufe(nd) gives the end of the buffer
/* these 3 may be used by compressor/decompressors. */
byte *buf; ///< pointer to temporary memory to read/write, initialized by SaveLoadFormat->initread/write
byte *buf_ori; ///< pointer to the original memory location of buf, used to free it afterwards
uint bufsize; ///< the size of the temporary memory *buf
FILE *fh; ///< the file from which is read or written to
void (*excpt_uninit)(); ///< the function to execute on any encountered error
StringID error_str; ///< the translateable error message to show
char *extra_msg; ///< the error message
} _sl;
enum NeedLengthValues {NL_NONE = 0, NL_WANTLENGTH = 1, NL_CALCLENGTH = 2};
/** Error handler, calls longjmp to simulate an exception.
* @todo this was used to have a central place to handle errors, but it is
* pretty ugly, and seriously interferes with any multithreaded approaches */
static void NORETURN SlError(StringID string, const char *extra_msg = NULL)
{
_sl.error_str = string;
free(_sl.extra_msg);
_sl.extra_msg = (extra_msg == NULL) ? NULL : strdup(extra_msg);
throw std::exception();
}
typedef void (*AsyncSaveFinishProc)();
static AsyncSaveFinishProc _async_save_finish = NULL;
static ThreadObject *_save_thread;
/**
* Called by save thread to tell we finished saving.
*/
static void SetAsyncSaveFinish(AsyncSaveFinishProc proc)
{
if (_exit_game) return;
while (_async_save_finish != NULL) CSleep(10);
_async_save_finish = proc;
}
/**
* Handle async save finishes.
*/
void ProcessAsyncSaveFinish()
{
if (_async_save_finish == NULL) return;
_async_save_finish();
_async_save_finish = NULL;
if (_save_thread != NULL) {
_save_thread->Join();
delete _save_thread;
_save_thread = NULL;
}
}
/**
* Fill the input buffer by reading from the file with the given reader
*/
static void SlReadFill()
{
size_t len = _sl.read_bytes();
if (len == 0) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME, "Unexpected end of chunk");
_sl.bufp = _sl.buf;
_sl.bufe = _sl.buf + len;
_sl.offs_base += len;
}
static inline size_t SlGetOffs() {return _sl.offs_base - (_sl.bufe - _sl.bufp);}
/** Return the size in bytes of a certain type of normal/atomic variable
* as it appears in memory. See VarTypes
* @param conv VarType type of variable that is used for calculating the size
* @return Return the size of this type in bytes */
static inline byte SlCalcConvMemLen(VarType conv)
{
static const byte conv_mem_size[] = {1, 1, 1, 2, 2, 4, 4, 8, 8, 0};
byte length = GB(conv, 4, 4);
assert(length < lengthof(conv_mem_size));
return conv_mem_size[length];
}
/** Return the size in bytes of a certain type of normal/atomic variable
* as it appears in a saved game. See VarTypes
* @param conv VarType type of variable that is used for calculating the size
* @return Return the size of this type in bytes */
static inline byte SlCalcConvFileLen(VarType conv)
{
static const byte conv_file_size[] = {1, 1, 2, 2, 4, 4, 8, 8, 2};
byte length = GB(conv, 0, 4);
assert(length < lengthof(conv_file_size));
return conv_file_size[length];
}
/** Return the size in bytes of a reference (pointer) */
static inline size_t SlCalcRefLen() {return CheckSavegameVersion(69) ? 2 : 4;}
/** Flush the output buffer by writing to disk with the given reader.
* If the buffer pointer has not yet been set up, set it up now. Usually
* only called when the buffer is full, or there is no more data to be processed
*/
static void SlWriteFill()
{
/* flush the buffer to disk (the writer) */
if (_sl.bufp != NULL) {
uint len = _sl.bufp - _sl.buf;
_sl.offs_base += len;
if (len) _sl.write_bytes(len);
}
/* All the data from the buffer has been written away, rewind to the beginning
* to start reading in more data */
_sl.bufp = _sl.buf;
_sl.bufe = _sl.buf + _sl.bufsize;
}
/** Read in a single byte from file. If the temporary buffer is full,
* flush it to its final destination
* @return return the read byte from file
*/
static inline byte SlReadByteInternal()
{
if (_sl.bufp == _sl.bufe) SlReadFill();
return *_sl.bufp++;
}
/** Wrapper for SlReadByteInternal */
byte SlReadByte() {return SlReadByteInternal();}
/** Write away a single byte from memory. If the temporary buffer is full,
* flush it to its destination (file)
* @param b the byte that is currently written
*/
static inline void SlWriteByteInternal(byte b)
{
if (_sl.bufp == _sl.bufe) SlWriteFill();
*_sl.bufp++ = b;
}
/** Wrapper for SlWriteByteInternal */
void SlWriteByte(byte b) {SlWriteByteInternal(b);}
static inline int SlReadUint16()
{
int x = SlReadByte() << 8;
return x | SlReadByte();
}
static inline uint32 SlReadUint32()
{
uint32 x = SlReadUint16() << 16;
return x | SlReadUint16();
}
static inline uint64 SlReadUint64()
{
uint32 x = SlReadUint32();
uint32 y = SlReadUint32();
return (uint64)x << 32 | y;
}
static inline void SlWriteUint16(uint16 v)
{
SlWriteByte(GB(v, 8, 8));
SlWriteByte(GB(v, 0, 8));
}
static inline void SlWriteUint32(uint32 v)
{
SlWriteUint16(GB(v, 16, 16));
SlWriteUint16(GB(v, 0, 16));
}
static inline void SlWriteUint64(uint64 x)
{
SlWriteUint32((uint32)(x >> 32));
SlWriteUint32((uint32)x);
}
/**
* Read in the header descriptor of an object or an array.
* If the highest bit is set (7), then the index is bigger than 127
* elements, so use the next byte to read in the real value.
* The actual value is then both bytes added with the first shifted
* 8 bits to the left, and dropping the highest bit (which only indicated a big index).
* x = ((x & 0x7F) << 8) + SlReadByte();
* @return Return the value of the index
*/
static uint SlReadSimpleGamma()
{
uint i = SlReadByte();
if (HasBit(i, 7)) {
i &= ~0x80;
if (HasBit(i, 6)) {
i &= ~0x40;
if (HasBit(i, 5)) {
i &= ~0x20;
if (HasBit(i, 4))
SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME, "Unsupported gamma");
i = (i << 8) | SlReadByte();
}
i = (i << 8) | SlReadByte();
}
i = (i << 8) | SlReadByte();
}
return i;
}
/**
* Write the header descriptor of an object or an array.
* If the element is bigger than 127, use 2 bytes for saving
* and use the highest byte of the first written one as a notice
* that the length consists of 2 bytes, etc.. like this:
* 0xxxxxxx
* 10xxxxxx xxxxxxxx
* 110xxxxx xxxxxxxx xxxxxxxx
* 1110xxxx xxxxxxxx xxxxxxxx xxxxxxxx
* @param i Index being written
*/
static void SlWriteSimpleGamma(size_t i)
{
if (i >= (1 << 7)) {
if (i >= (1 << 14)) {
if (i >= (1 << 21)) {
assert(i < (1 << 28));
SlWriteByte((byte)(0xE0 | (i >> 24)));
SlWriteByte((byte)(i >> 16));
} else {
SlWriteByte((byte)(0xC0 | (i >> 16)));
}
SlWriteByte((byte)(i >> 8));
} else {
SlWriteByte((byte)(0x80 | (i >> 8)));
}
}
SlWriteByte((byte)i);
}
/** Return how many bytes used to encode a gamma value */
static inline uint SlGetGammaLength(size_t i)
{
return 1 + (i >= (1 << 7)) + (i >= (1 << 14)) + (i >= (1 << 21));
}
static inline uint SlReadSparseIndex() {return SlReadSimpleGamma();}
static inline void SlWriteSparseIndex(uint index) {SlWriteSimpleGamma(index);}
static inline uint SlReadArrayLength() {return SlReadSimpleGamma();}
static inline void SlWriteArrayLength(size_t length) {SlWriteSimpleGamma(length);}
static inline uint SlGetArrayLength(size_t length) {return SlGetGammaLength(length);}
void SlSetArrayIndex(uint index)
{
_sl.need_length = NL_WANTLENGTH;
_sl.array_index = index;
}
static size_t _next_offs;
/**
* Iterate through the elements of an array and read the whole thing
* @return The index of the object, or -1 if we have reached the end of current block
*/
int SlIterateArray()
{
int index;
/* After reading in the whole array inside the loop
* we must have read in all the data, so we must be at end of current block. */
if (_next_offs != 0 && SlGetOffs() != _next_offs) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME, "Invalid chunk size");
while (true) {
uint length = SlReadArrayLength();
if (length == 0) {
_next_offs = 0;
return -1;
}
_sl.obj_len = --length;
_next_offs = SlGetOffs() + length;
switch (_sl.block_mode) {
case CH_SPARSE_ARRAY: index = (int)SlReadSparseIndex(); break;
case CH_ARRAY: index = _sl.array_index++; break;
default:
DEBUG(sl, 0, "SlIterateArray error");
return -1; // error
}
if (length != 0) return index;
}
}
/**
* Sets the length of either a RIFF object or the number of items in an array.
* This lets us load an object or an array of arbitrary size
* @param length The length of the sought object/array
*/
void SlSetLength(size_t length)
{
assert(_sl.save);
switch (_sl.need_length) {
case NL_WANTLENGTH:
_sl.need_length = NL_NONE;
switch (_sl.block_mode) {
case CH_RIFF:
/* Ugly encoding of >16M RIFF chunks
* The lower 24 bits are normal
* The uppermost 4 bits are bits 24:27 */
assert(length < (1 << 28));
SlWriteUint32((uint32)((length & 0xFFFFFF) | ((length >> 24) << 28)));
break;
case CH_ARRAY:
assert(_sl.last_array_index <= _sl.array_index);
while (++_sl.last_array_index <= _sl.array_index)
SlWriteArrayLength(1);
SlWriteArrayLength(length + 1);
break;
case CH_SPARSE_ARRAY:
SlWriteArrayLength(length + 1 + SlGetArrayLength(_sl.array_index)); // Also include length of sparse index.
SlWriteSparseIndex(_sl.array_index);
break;
default: NOT_REACHED();
} break;
case NL_CALCLENGTH:
_sl.obj_len += (int)length;
break;
}
}
/**
* Save/Load bytes. These do not need to be converted to Little/Big Endian
* so directly write them or read them to/from file
* @param ptr The source or destination of the object being manipulated
* @param length number of bytes this fast CopyBytes lasts
*/
static void SlCopyBytes(void *ptr, size_t length)
{
byte *p = (byte*)ptr;
if (_sl.save) {
for (; length != 0; length--) {SlWriteByteInternal(*p++);}
} else {
for (; length != 0; length--) {*p++ = SlReadByteInternal();}
}
}
/** Read in bytes from the file/data structure but don't do
* anything with them, discarding them in effect
* @param length The amount of bytes that is being treated this way
*/
static inline void SlSkipBytes(size_t length)
{
for (; length != 0; length--) SlReadByte();
}
/* Get the length of the current object */
size_t SlGetFieldLength() {return _sl.obj_len;}
/** Return a signed-long version of the value of a setting
* @param ptr pointer to the variable
* @param conv type of variable, can be a non-clean
* type, eg one with other flags because it is parsed
* @return returns the value of the pointer-setting */
int64 ReadValue(const void *ptr, VarType conv)
{
switch (GetVarMemType(conv)) {
case SLE_VAR_BL: return (*(bool*)ptr != 0);
case SLE_VAR_I8: return *(int8* )ptr;
case SLE_VAR_U8: return *(byte* )ptr;
case SLE_VAR_I16: return *(int16* )ptr;
case SLE_VAR_U16: return *(uint16*)ptr;
case SLE_VAR_I32: return *(int32* )ptr;
case SLE_VAR_U32: return *(uint32*)ptr;
case SLE_VAR_I64: return *(int64* )ptr;
case SLE_VAR_U64: return *(uint64*)ptr;
case SLE_VAR_NULL:return 0;
default: NOT_REACHED();
}
/* useless, but avoids compiler warning this way */
return 0;
}
/** Write the value of a setting
* @param ptr pointer to the variable
* @param conv type of variable, can be a non-clean type, eg
* with other flags. It is parsed upon read
* @param val the new value being given to the variable */
void WriteValue(void *ptr, VarType conv, int64 val)
{
switch (GetVarMemType(conv)) {
case SLE_VAR_BL: *(bool *)ptr = (val != 0); break;
case SLE_VAR_I8: *(int8 *)ptr = val; break;
case SLE_VAR_U8: *(byte *)ptr = val; break;
case SLE_VAR_I16: *(int16 *)ptr = val; break;
case SLE_VAR_U16: *(uint16*)ptr = val; break;
case SLE_VAR_I32: *(int32 *)ptr = val; break;
case SLE_VAR_U32: *(uint32*)ptr = val; break;
case SLE_VAR_I64: *(int64 *)ptr = val; break;
case SLE_VAR_U64: *(uint64*)ptr = val; break;
case SLE_VAR_NAME: *(char**)ptr = CopyFromOldName(val); break;
case SLE_VAR_NULL: break;
default: NOT_REACHED();
}
}
/**
* Handle all conversion and typechecking of variables here.
* In the case of saving, read in the actual value from the struct
* and then write them to file, endian safely. Loading a value
* goes exactly the opposite way
* @param ptr The object being filled/read
* @param conv VarType type of the current element of the struct
*/
static void SlSaveLoadConv(void *ptr, VarType conv)
{
int64 x = 0;
if (_sl.save) { // SAVE values
/* Read a value from the struct. These ARE endian safe. */
x = ReadValue(ptr, conv);
/* Write the value to the file and check if its value is in the desired range */
switch (GetVarFileType(conv)) {
case SLE_FILE_I8: assert(x >= -128 && x <= 127); SlWriteByte(x);break;
case SLE_FILE_U8: assert(x >= 0 && x <= 255); SlWriteByte(x);break;
case SLE_FILE_I16:assert(x >= -32768 && x <= 32767); SlWriteUint16(x);break;
case SLE_FILE_STRINGID:
case SLE_FILE_U16:assert(x >= 0 && x <= 65535); SlWriteUint16(x);break;
case SLE_FILE_I32:
case SLE_FILE_U32: SlWriteUint32((uint32)x);break;
case SLE_FILE_I64:
case SLE_FILE_U64: SlWriteUint64(x);break;
default: NOT_REACHED();
}
} else { // LOAD values
/* Read a value from the file */
switch (GetVarFileType(conv)) {
case SLE_FILE_I8: x = (int8 )SlReadByte(); break;
case SLE_FILE_U8: x = (byte )SlReadByte(); break;
case SLE_FILE_I16: x = (int16 )SlReadUint16(); break;
case SLE_FILE_U16: x = (uint16)SlReadUint16(); break;
case SLE_FILE_I32: x = (int32 )SlReadUint32(); break;
case SLE_FILE_U32: x = (uint32)SlReadUint32(); break;
case SLE_FILE_I64: x = (int64 )SlReadUint64(); break;
case SLE_FILE_U64: x = (uint64)SlReadUint64(); break;
case SLE_FILE_STRINGID: x = RemapOldStringID((uint16)SlReadUint16()); break;
default: NOT_REACHED();
}
/* Write The value to the struct. These ARE endian safe. */
WriteValue(ptr, conv, x);
}
}
/** Calculate the net length of a string. This is in almost all cases
* just strlen(), but if the string is not properly terminated, we'll
* resort to the maximum length of the buffer.
* @param ptr pointer to the stringbuffer
* @param length maximum length of the string (buffer). If -1 we don't care
* about a maximum length, but take string length as it is.
* @return return the net length of the string */
static inline size_t SlCalcNetStringLen(const char *ptr, size_t length)
{
if (ptr == NULL) return 0;
return min(strlen(ptr), length - 1);
}
/** Calculate the gross length of the string that it
* will occupy in the savegame. This includes the real length, returned
* by SlCalcNetStringLen and the length that the index will occupy.
* @param ptr pointer to the stringbuffer
* @param length maximum length of the string (buffer size, etc.)
* @param conv type of data been used
* @return return the gross length of the string */
static inline size_t SlCalcStringLen(const void *ptr, size_t length, VarType conv)
{
size_t len;
const char *str;
switch (GetVarMemType(conv)) {
default: NOT_REACHED();
case SLE_VAR_STR:
case SLE_VAR_STRQ:
str = *(const char**)ptr;
len = SIZE_MAX;
break;
case SLE_VAR_STRB:
case SLE_VAR_STRBQ:
str = (const char*)ptr;
len = length;
break;
}
len = SlCalcNetStringLen(str, len);
return len + SlGetArrayLength(len); // also include the length of the index
}
/**
* Save/Load a string.
* @param ptr the string being manipulated
* @param length of the string (full length)
* @param conv must be SLE_FILE_STRING */
static void SlString(void *ptr, size_t length, VarType conv)
{
size_t len;
if (_sl.save) { // SAVE string
switch (GetVarMemType(conv)) {
default: NOT_REACHED();
case SLE_VAR_STRB:
case SLE_VAR_STRBQ:
len = SlCalcNetStringLen((char*)ptr, length);
break;
case SLE_VAR_STR:
case SLE_VAR_STRQ:
ptr = *(char**)ptr;
len = SlCalcNetStringLen((char*)ptr, SIZE_MAX);
break;
}
SlWriteArrayLength(len);
SlCopyBytes(ptr, len);
} else { // LOAD string
len = SlReadArrayLength();
switch (GetVarMemType(conv)) {
default: NOT_REACHED();
case SLE_VAR_STRB:
case SLE_VAR_STRBQ:
if (len >= length) {
DEBUG(sl, 1, "String length in savegame is bigger than buffer, truncating");
SlCopyBytes(ptr, length);
SlSkipBytes(len - length);
len = length - 1;
} else {
SlCopyBytes(ptr, len);
}
break;
case SLE_VAR_STR:
case SLE_VAR_STRQ: // Malloc'd string, free previous incarnation, and allocate
free(*(char**)ptr);
if (len == 0) {
*(char**)ptr = NULL;
} else {
*(char**)ptr = MallocT<char>(len + 1); // terminating '\0'
ptr = *(char**)ptr;
SlCopyBytes(ptr, len);
}
break;
}
((char*)ptr)[len] = '\0'; // properly terminate the string
str_validate((char*)ptr, (char*)ptr + len);
}
}
/**
* Return the size in bytes of a certain type of atomic array
* @param length The length of the array counted in elements
* @param conv VarType type of the variable that is used in calculating the size
*/
static inline size_t SlCalcArrayLen(size_t length, VarType conv)
{
return SlCalcConvFileLen(conv) * length;
}
/**
* Save/Load an array.
* @param array The array being manipulated
* @param length The length of the array in elements
* @param conv VarType type of the atomic array (int, byte, uint64, etc.)
*/
void SlArray(void *array, size_t length, VarType conv)
{
/* Automatically calculate the length? */
if (_sl.need_length != NL_NONE) {
SlSetLength(SlCalcArrayLen(length, conv));
/* Determine length only? */
if (_sl.need_length == NL_CALCLENGTH) return;
}
/* NOTICE - handle some buggy stuff, in really old versions everything was saved
* as a byte-type. So detect this, and adjust array size accordingly */
if (!_sl.save && _sl_version == 0) {
/* all arrays except difficulty settings */
if (conv == SLE_INT16 || conv == SLE_UINT16 || conv == SLE_STRINGID ||
conv == SLE_INT32 || conv == SLE_UINT32) {
SlCopyBytes(array, length * SlCalcConvFileLen(conv));
return;
}
/* used for conversion of Money 32bit->64bit */
if (conv == (SLE_FILE_I32 | SLE_VAR_I64)) {
for (uint i = 0; i < length; i++) {
((int64*)array)[i] = (int32)BSWAP32(SlReadUint32());
}
return;
}
}
/* If the size of elements is 1 byte both in file and memory, no special
* conversion is needed, use specialized copy-copy function to speed up things */
if (conv == SLE_INT8 || conv == SLE_UINT8) {
SlCopyBytes(array, length);
} else {
byte *a = (byte*)array;
byte mem_size = SlCalcConvMemLen(conv);
for (; length != 0; length --) {
SlSaveLoadConv(a, conv);
a += mem_size; // get size
}
}
}
static uint ReferenceToInt(const void *obj, SLRefType rt);
static void *IntToReference(uint index, SLRefType rt);
/**
* Return the size in bytes of a list
* @param list The std::list to find the size of
*/
static inline size_t SlCalcListLen(const void *list)
{
std::list<void *> *l = (std::list<void *> *) list;
int type_size = CheckSavegameVersion(69) ? 2 : 4;
/* Each entry is saved as type_size bytes, plus type_size bytes are used for the length
* of the list */
return l->size() * type_size + type_size;
}
/**
* Save/Load a list.
* @param list The list being manipulated
* @param conv SLRefType type of the list (Vehicle *, Station *, etc)
*/
void SlList(void *list, SLRefType conv)
{
/* Automatically calculate the length? */
if (_sl.need_length != NL_NONE) {
SlSetLength(SlCalcListLen(list));
/* Determine length only? */
if (_sl.need_length == NL_CALCLENGTH) return;
}
std::list<void *> *l = (std::list<void *> *) list;
if (_sl.save) {
SlWriteUint32((uint32)l->size());
std::list<void *>::iterator iter;
for (iter = l->begin(); iter != l->end(); ++iter) {
void *ptr = *iter;
SlWriteUint32(ReferenceToInt(ptr, conv));
}
} else {
uint length = CheckSavegameVersion(69) ? SlReadUint16() : SlReadUint32();
/* Load each reference and push to the end of the list */
for (uint i = 0; i < length; i++) {
void *ptr = IntToReference(CheckSavegameVersion(69) ? SlReadUint16() : SlReadUint32(), conv);
l->push_back(ptr);
}
}
}
/** Are we going to save this object or not? */
static inline bool SlIsObjectValidInSavegame(const SaveLoad *sld)
{
if (_sl_version < sld->version_from || _sl_version > sld->version_to) return false;
if (sld->conv & SLF_SAVE_NO) return false;
return true;
}
/** Are we going to load this variable when loading a savegame or not?
* @note If the variable is skipped it is skipped in the savegame
* bytestream itself as well, so there is no need to skip it somewhere else */
static inline bool SlSkipVariableOnLoad(const SaveLoad *sld)
{
if ((sld->conv & SLF_NETWORK_NO) && !_sl.save && _networking && !_network_server) {
SlSkipBytes(SlCalcConvMemLen(sld->conv) * sld->length);
return true;
}
return false;
}
/**
* Calculate the size of an object.
* @param object to be measured
* @param sld The SaveLoad description of the object so we know how to manipulate it
* @return size of given objetc
*/
size_t SlCalcObjLength(const void *object, const SaveLoad *sld)
{
size_t length = 0;
/* Need to determine the length and write a length tag. */
for (; sld->cmd != SL_END; sld++) {
length += SlCalcObjMemberLength(object, sld);
}
return length;
}
size_t SlCalcObjMemberLength(const void *object, const SaveLoad *sld)
{
assert(_sl.save);
switch (sld->cmd) {
case SL_VAR:
case SL_REF:
case SL_ARR:
case SL_STR:
case SL_LST:
/* CONDITIONAL saveload types depend on the savegame version */
if (!SlIsObjectValidInSavegame(sld)) break;
switch (sld->cmd) {
case SL_VAR: return SlCalcConvFileLen(sld->conv);
case SL_REF: return SlCalcRefLen();
case SL_ARR: return SlCalcArrayLen(sld->length, sld->conv);
case SL_STR: return SlCalcStringLen(GetVariableAddress(object, sld), sld->length, sld->conv);
case SL_LST: return SlCalcListLen(GetVariableAddress(object, sld));
default: NOT_REACHED();
}
break;
case SL_WRITEBYTE: return 1; // a byte is logically of size 1
case SL_VEH_INCLUDE: return SlCalcObjLength(object, GetVehicleDescription(VEH_END));
default: NOT_REACHED();
}
return 0;
}
bool SlObjectMember(void *ptr, const SaveLoad *sld)
{
VarType conv = GB(sld->conv, 0, 8);
switch (sld->cmd) {
case SL_VAR:
case SL_REF:
case SL_ARR:
case SL_STR:
case SL_LST:
/* CONDITIONAL saveload types depend on the savegame version */
if (!SlIsObjectValidInSavegame(sld)) return false;
if (SlSkipVariableOnLoad(sld)) return false;
switch (sld->cmd) {
case SL_VAR: SlSaveLoadConv(ptr, conv); break;
case SL_REF: // Reference variable, translate
if (_sl.save) {
SlWriteUint32(ReferenceToInt(*(void**)ptr, (SLRefType)conv));
} else {
*(void**)ptr = IntToReference(CheckSavegameVersion(69) ? SlReadUint16() : SlReadUint32(), (SLRefType)conv);
}
break;
case SL_ARR: SlArray(ptr, sld->length, conv); break;
case SL_STR: SlString(ptr, sld->length, conv); break;
case SL_LST: SlList(ptr, (SLRefType)conv); break;
default: NOT_REACHED();
}
break;
/* SL_WRITEBYTE translates a value of a variable to another one upon
* saving or loading.
* XXX - variable renaming abuse
* game_value: the value of the variable ingame is abused by sld->version_from
* file_value: the value of the variable in the savegame is abused by sld->version_to */
case SL_WRITEBYTE:
if (_sl.save) {
SlWriteByte(sld->version_to);
} else {
*(byte*)ptr = sld->version_from;
}
break;
/* SL_VEH_INCLUDE loads common code for vehicles */
case SL_VEH_INCLUDE:
SlObject(ptr, GetVehicleDescription(VEH_END));
break;
default: NOT_REACHED();
}
return true;
}
/**
* Main SaveLoad function.
* @param object The object that is being saved or loaded
* @param sld The SaveLoad description of the object so we know how to manipulate it
*/
void SlObject(void *object, const SaveLoad *sld)
{
/* Automatically calculate the length? */
if (_sl.need_length != NL_NONE) {
SlSetLength(SlCalcObjLength(object, sld));
if (_sl.need_length == NL_CALCLENGTH) return;
}
for (; sld->cmd != SL_END; sld++) {
void *ptr = sld->global ? sld->address : GetVariableAddress(object, sld);
SlObjectMember(ptr, sld);
}
}
/**
* Save or Load (a list of) global variables
* @param sldg The global variable that is being loaded or saved
*/
void SlGlobList(const SaveLoadGlobVarList *sldg)
{
SlObject(NULL, (const SaveLoad*)sldg);
}
/**
* Do something of which I have no idea what it is :P
* @param proc The callback procedure that is called
* @param arg The variable that will be used for the callback procedure
*/
void SlAutolength(AutolengthProc *proc, void *arg)
{
size_t offs;
assert(_sl.save);
/* Tell it to calculate the length */
_sl.need_length = NL_CALCLENGTH;
_sl.obj_len = 0;
proc(arg);
/* Setup length */
_sl.need_length = NL_WANTLENGTH;
SlSetLength(_sl.obj_len);
offs = SlGetOffs() + _sl.obj_len;
/* And write the stuff */
proc(arg);
if (offs != SlGetOffs()) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME, "Invalid chunk size");
}
/**
* Load a chunk of data (eg vehicles, stations, etc.)
* @param ch The chunkhandler that will be used for the operation
*/
static void SlLoadChunk(const ChunkHandler *ch)
{
byte m = SlReadByte();
size_t len;
size_t endoffs;
_sl.block_mode = m;
_sl.obj_len = 0;
switch (m) {
case CH_ARRAY:
_sl.array_index = 0;
ch->load_proc();
break;
case CH_SPARSE_ARRAY:
ch->load_proc();
break;
default:
if ((m & 0xF) == CH_RIFF) {
/* Read length */
len = (SlReadByte() << 16) | ((m >> 4) << 24);
len += SlReadUint16();
_sl.obj_len = len;
endoffs = SlGetOffs() + len;
ch->load_proc();
if (SlGetOffs() != endoffs) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME, "Invalid chunk size");
} else {
SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME, "Invalid chunk type");
}
break;
}
}
/* Stub Chunk handlers to only calculate length and do nothing else */
static ChunkSaveLoadProc *_tmp_proc_1;
static inline void SlStubSaveProc2(void *arg) {_tmp_proc_1();}
static void SlStubSaveProc() {SlAutolength(SlStubSaveProc2, NULL);}
/** Save a chunk of data (eg. vehicles, stations, etc.). Each chunk is
* prefixed by an ID identifying it, followed by data, and terminator where appropiate
* @param ch The chunkhandler that will be used for the operation
*/
static void SlSaveChunk(const ChunkHandler *ch)
{
ChunkSaveLoadProc *proc = ch->save_proc;
/* Don't save any chunk information if there is no save handler. */
if (proc == NULL) return;
SlWriteUint32(ch->id);
DEBUG(sl, 2, "Saving chunk %c%c%c%c", ch->id >> 24, ch->id >> 16, ch->id >> 8, ch->id);
if (ch->flags & CH_AUTO_LENGTH) {
/* Need to calculate the length. Solve that by calling SlAutoLength in the save_proc. */
_tmp_proc_1 = proc;
proc = SlStubSaveProc;
}
_sl.block_mode = ch->flags & CH_TYPE_MASK;
switch (ch->flags & CH_TYPE_MASK) {
case CH_RIFF:
_sl.need_length = NL_WANTLENGTH;
proc();
break;
case CH_ARRAY:
_sl.last_array_index = 0;
SlWriteByte(CH_ARRAY);
proc();
SlWriteArrayLength(0); // Terminate arrays
break;
case CH_SPARSE_ARRAY:
SlWriteByte(CH_SPARSE_ARRAY);
proc();
SlWriteArrayLength(0); // Terminate arrays
break;
default: NOT_REACHED();
}
}
/** Save all chunks */
static void SlSaveChunks()
{
const ChunkHandler *ch;
const ChunkHandler * const *chsc;
uint p;
for (p = 0; p != CH_NUM_PRI_LEVELS; p++) {
for (chsc = _sl.chs; (ch = *chsc++) != NULL;) {
while (true) {
if (((ch->flags >> CH_PRI_SHL) & (CH_NUM_PRI_LEVELS - 1)) == p)
SlSaveChunk(ch);
if (ch->flags & CH_LAST)
break;
ch++;
}
}
}
/* Terminator */
SlWriteUint32(0);
}
/** Find the ChunkHandler that will be used for processing the found
* chunk in the savegame or in memory
* @param id the chunk in question
* @return returns the appropiate chunkhandler
*/
static const ChunkHandler *SlFindChunkHandler(uint32 id)
{
const ChunkHandler *ch;
const ChunkHandler *const *chsc;
for (chsc = _sl.chs; (ch = *chsc++) != NULL;) {
for (;;) {
if (ch->id == id) return ch;
if (ch->flags & CH_LAST) break;
ch++;
}
}
return NULL;
}
/** Load all chunks */
static void SlLoadChunks()
{
uint32 id;
const ChunkHandler *ch;
for (id = SlReadUint32(); id != 0; id = SlReadUint32()) {
DEBUG(sl, 2, "Loading chunk %c%c%c%c", id >> 24, id >> 16, id >> 8, id);
ch = SlFindChunkHandler(id);
if (ch == NULL) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME, "Unknown chunk type");
SlLoadChunk(ch);
}
}
/*******************************************
********** START OF LZO CODE **************
*******************************************/
#define LZO_SIZE 8192
#include "../minilzo.h"
static size_t ReadLZO()
{
byte out[LZO_SIZE + LZO_SIZE / 64 + 16 + 3 + 8];
uint32 tmp[2];
uint32 size;
uint len;
/* Read header*/
if (fread(tmp, sizeof(tmp), 1, _sl.fh) != 1) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE, "File read failed");
/* Check if size is bad */
((uint32*)out)[0] = size = tmp[1];
if (_sl_version != 0) {
tmp[0] = TO_BE32(tmp[0]);
size = TO_BE32(size);
}
if (size >= sizeof(out)) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME, "Inconsistent size");
/* Read block */
if (fread(out + sizeof(uint32), size, 1, _sl.fh) != 1) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
/* Verify checksum */
if (tmp[0] != lzo_adler32(0, out, size + sizeof(uint32))) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME, "Bad checksum");
/* Decompress */
lzo1x_decompress(out + sizeof(uint32) * 1, size, _sl.buf, &len, NULL);
return len;
}
/* p contains the pointer to the buffer, len contains the pointer to the length.
* len bytes will be written, p and l will be updated to reflect the next buffer. */
static void WriteLZO(size_t size)
{
byte out[LZO_SIZE + LZO_SIZE / 64 + 16 + 3 + 8];
byte wrkmem[sizeof(byte*) * 4096];
uint outlen;
lzo1x_1_compress(_sl.buf, (lzo_uint)size, out + sizeof(uint32) * 2, &outlen, wrkmem);
((uint32*)out)[1] = TO_BE32(outlen);
((uint32*)out)[0] = TO_BE32(lzo_adler32(0, out + sizeof(uint32), outlen + sizeof(uint32)));
if (fwrite(out, outlen + sizeof(uint32) * 2, 1, _sl.fh) != 1) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_WRITEABLE);
}
static bool InitLZO()
{
_sl.bufsize = LZO_SIZE;
_sl.buf = _sl.buf_ori = MallocT<byte>(LZO_SIZE);
return true;
}
static void UninitLZO()
{
free(_sl.buf_ori);
}
/*********************************************
******** START OF NOCOMP CODE (uncompressed)*
*********************************************/
static size_t ReadNoComp()
{
return fread(_sl.buf, 1, LZO_SIZE, _sl.fh);
}
static void WriteNoComp(size_t size)
{
if (fwrite(_sl.buf, 1, size, _sl.fh) != size) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_WRITEABLE);
}
static bool InitNoComp()
{
_sl.bufsize = LZO_SIZE;
_sl.buf = _sl.buf_ori = MallocT<byte>(LZO_SIZE);
return true;
}
static void UninitNoComp()
{
free(_sl.buf_ori);
}
/********************************************
********** START OF MEMORY CODE (in ram)****
********************************************/
#include "../gui.h"
struct ThreadedSave {
uint count;
byte ff_state;
bool saveinprogress;
CursorID cursor;
};
/* A maximum size of of 128K * 500 = 64.000KB savegames */
STATIC_OLD_POOL(Savegame, byte, 17, 500, NULL, NULL)
static ThreadedSave _ts;
static bool InitMem()
{
_ts.count = 0;
_Savegame_pool.CleanPool();
_Savegame_pool.AddBlockToPool();
/* A block from the pool is a contigious area of memory, so it is safe to write to it sequentially */
_sl.bufsize = GetSavegamePoolSize();
_sl.buf = GetSavegame(_ts.count);
return true;
}
static void UnInitMem()
{
_Savegame_pool.CleanPool();
}
static void WriteMem(size_t size)
{
_ts.count += (uint)size;
/* Allocate new block and new buffer-pointer */
_Savegame_pool.AddBlockIfNeeded(_ts.count);
_sl.buf = GetSavegame(_ts.count);
}
/********************************************
********** START OF ZLIB CODE **************
********************************************/
#if defined(WITH_ZLIB)
#include <zlib.h>
static z_stream _z;
static bool InitReadZlib()
{
memset(&_z, 0, sizeof(_z));
if (inflateInit(&_z) != Z_OK) return false;
_sl.bufsize = 4096;
_sl.buf = _sl.buf_ori = MallocT<byte>(4096 + 4096); // also contains fread buffer
return true;
}
static size_t ReadZlib()
{
int r;
_z.next_out = _sl.buf;
_z.avail_out = 4096;
do {
/* read more bytes from the file? */
if (_z.avail_in == 0) {
_z.avail_in = (uint)fread(_z.next_in = _sl.buf + 4096, 1, 4096, _sl.fh);
}
/* inflate the data */
r = inflate(&_z, 0);
if (r == Z_STREAM_END)
break;
if (r != Z_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "inflate() failed");
} while (_z.avail_out);
return 4096 - _z.avail_out;
}
static void UninitReadZlib()
{
inflateEnd(&_z);
free(_sl.buf_ori);
}
static bool InitWriteZlib()
{
memset(&_z, 0, sizeof(_z));
if (deflateInit(&_z, 6) != Z_OK) return false;
_sl.bufsize = 4096;
_sl.buf = _sl.buf_ori = MallocT<byte>(4096);
return true;
}
static void WriteZlibLoop(z_streamp z, byte *p, size_t len, int mode)
{
byte buf[1024]; // output buffer
int r;
uint n;
z->next_in = p;
z->avail_in = (uInt)len;
do {
z->next_out = buf;
z->avail_out = sizeof(buf);
/**
* For the poor next soul who sees many valgrind warnings of the
* "Conditional jump or move depends on uninitialised value(s)" kind:
* According to the author of zlib it is not a bug and it won't be fixed.
* http://groups.google.com/group/comp.compression/browse_thread/thread/b154b8def8c2a3ef/cdf9b8729ce17ee2
* [Mark Adler, Feb 24 2004, 'zlib-1.2.1 valgrind warnings' in the newgroup comp.compression]
**/
r = deflate(z, mode);
/* bytes were emitted? */
if ((n = sizeof(buf) - z->avail_out) != 0) {
if (fwrite(buf, n, 1, _sl.fh) != 1) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_WRITEABLE);
}
if (r == Z_STREAM_END)
break;
if (r != Z_OK) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "zlib returned error code");
} while (z->avail_in || !z->avail_out);
}
static void WriteZlib(size_t len)
{
WriteZlibLoop(&_z, _sl.buf, len, 0);
}
static void UninitWriteZlib()
{
/* flush any pending output. */
if (_sl.fh) WriteZlibLoop(&_z, NULL, 0, Z_FINISH);
deflateEnd(&_z);
free(_sl.buf_ori);
}
#endif /* WITH_ZLIB */
/*******************************************
************* END OF CODE *****************
*******************************************/
/* these define the chunks */
extern const ChunkHandler _gamelog_chunk_handlers[];
extern const ChunkHandler _map_chunk_handlers[];
extern const ChunkHandler _misc_chunk_handlers[];
extern const ChunkHandler _name_chunk_handlers[];
extern const ChunkHandler _cheat_chunk_handlers[] ;
extern const ChunkHandler _setting_chunk_handlers[];
extern const ChunkHandler _company_chunk_handlers[];
extern const ChunkHandler _engine_chunk_handlers[];
extern const ChunkHandler _veh_chunk_handlers[];
extern const ChunkHandler _waypoint_chunk_handlers[];
extern const ChunkHandler _depot_chunk_handlers[];
extern const ChunkHandler _order_chunk_handlers[];
extern const ChunkHandler _town_chunk_handlers[];
extern const ChunkHandler _sign_chunk_handlers[];
extern const ChunkHandler _station_chunk_handlers[];
extern const ChunkHandler _industry_chunk_handlers[];
extern const ChunkHandler _economy_chunk_handlers[];
extern const ChunkHandler _subsidy_chunk_handlers[];
extern const ChunkHandler _ai_chunk_handlers[];
extern const ChunkHandler _animated_tile_chunk_handlers[];
extern const ChunkHandler _newgrf_chunk_handlers[];
extern const ChunkHandler _group_chunk_handlers[];
extern const ChunkHandler _cargopacket_chunk_handlers[];
extern const ChunkHandler _autoreplace_chunk_handlers[];
static const ChunkHandler * const _chunk_handlers[] = {
_gamelog_chunk_handlers,
_map_chunk_handlers,
_misc_chunk_handlers,
_name_chunk_handlers,
_cheat_chunk_handlers,
_setting_chunk_handlers,
_veh_chunk_handlers,
_waypoint_chunk_handlers,
_depot_chunk_handlers,
_order_chunk_handlers,
_industry_chunk_handlers,
_economy_chunk_handlers,
_subsidy_chunk_handlers,
_engine_chunk_handlers,
_town_chunk_handlers,
_sign_chunk_handlers,
_station_chunk_handlers,
_company_chunk_handlers,
_ai_chunk_handlers,
_animated_tile_chunk_handlers,
_newgrf_chunk_handlers,
_group_chunk_handlers,
_cargopacket_chunk_handlers,
_autoreplace_chunk_handlers,
NULL,
};
/**
* Pointers cannot be saved to a savegame, so this functions gets
* the index of the item, and if not available, it hussles with
* pointers (looks really bad :()
* Remember that a NULL item has value 0, and all
* indeces have +1, so vehicle 0 is saved as index 1.
* @param obj The object that we want to get the index of
* @param rt SLRefType type of the object the index is being sought of
* @return Return the pointer converted to an index of the type pointed to
*/
static uint ReferenceToInt(const void *obj, SLRefType rt)
{
if (obj == NULL) return 0;
switch (rt) {
case REF_VEHICLE_OLD: // Old vehicles we save as new onces
case REF_VEHICLE: return ((const Vehicle*)obj)->index + 1;
case REF_STATION: return ((const Station*)obj)->index + 1;
case REF_TOWN: return ((const Town*)obj)->index + 1;
case REF_ORDER: return ((const Order*)obj)->index + 1;
case REF_ROADSTOPS: return ((const RoadStop*)obj)->index + 1;
case REF_ENGINE_RENEWS: return ((const EngineRenew*)obj)->index + 1;
case REF_CARGO_PACKET: return ((const CargoPacket*)obj)->index + 1;
case REF_ORDERLIST: return ((const OrderList*)obj)->index + 1;
default: NOT_REACHED();
}
return 0; // avoid compiler warning
}
/**
* Pointers cannot be loaded from a savegame, so this function
* gets the index from the savegame and returns the appropiate
* pointer from the already loaded base.
* Remember that an index of 0 is a NULL pointer so all indeces
* are +1 so vehicle 0 is saved as 1.
* @param index The index that is being converted to a pointer
* @param rt SLRefType type of the object the pointer is sought of
* @return Return the index converted to a pointer of any type
*/
static void *IntToReference(uint index, SLRefType rt)
{
/* After version 4.3 REF_VEHICLE_OLD is saved as REF_VEHICLE,
* and should be loaded like that */
if (rt == REF_VEHICLE_OLD && !CheckSavegameVersionOldStyle(4, 4)) {
rt = REF_VEHICLE;
}
/* No need to look up NULL pointers, just return immediately */
if (rt != REF_VEHICLE_OLD && index == 0) {
return NULL;
}
index--; // correct for the NULL index
switch (rt) {
case REF_ORDERLIST:
if (_OrderList_pool.AddBlockIfNeeded(index)) return GetOrderList(index);
SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME, "OrderList index out of range");
case REF_ORDER:
if (_Order_pool.AddBlockIfNeeded(index)) return GetOrder(index);
SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME, "Order index out of range");
case REF_VEHICLE:
if (_Vehicle_pool.AddBlockIfNeeded(index)) return GetVehicle(index);
SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME, "Vehicle index out of range");
case REF_STATION:
if (_Station_pool.AddBlockIfNeeded(index)) return GetStation(index);
SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME, "Station index out of range");
case REF_TOWN:
if (_Town_pool.AddBlockIfNeeded(index)) return GetTown(index);
SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME, "Town index out of range");
case REF_ROADSTOPS:
if (_RoadStop_pool.AddBlockIfNeeded(index)) return GetRoadStop(index);
SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME, "RoadStop index out of range");
case REF_ENGINE_RENEWS:
if (_EngineRenew_pool.AddBlockIfNeeded(index)) return GetEngineRenew(index);
SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME, "EngineRenew index out of range");
case REF_CARGO_PACKET:
if (_CargoPacket_pool.AddBlockIfNeeded(index)) return GetCargoPacket(index);
SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME, "CargoPacket index out of range");
case REF_VEHICLE_OLD:
/* Old vehicles were saved differently:
* invalid vehicle was 0xFFFF,
* and the index was not - 1.. correct for this */
index++;
if (index == INVALID_VEHICLE) return NULL;
if (_Vehicle_pool.AddBlockIfNeeded(index)) return GetVehicle(index);
SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME, "Vehicle index out of range");
default: NOT_REACHED();
}
return NULL;
}
/** The format for a reader/writer type of a savegame */
struct SaveLoadFormat {
const char *name; ///< name of the compressor/decompressor (debug-only)
uint32 tag; ///< the 4-letter tag by which it is identified in the savegame
bool (*init_read)(); ///< function executed upon initalization of the loader
ReaderProc *reader; ///< function that loads the data from the file
void (*uninit_read)(); ///< function executed when reading is finished
bool (*init_write)(); ///< function executed upon intialization of the saver
WriterProc *writer; ///< function that saves the data to the file
void (*uninit_write)(); ///< function executed when writing is done
};
static const SaveLoadFormat _saveload_formats[] = {
{"memory", 0, NULL, NULL, NULL, InitMem, WriteMem, UnInitMem},
{"lzo", TO_BE32X('OTTD'), InitLZO, ReadLZO, UninitLZO, InitLZO, WriteLZO, UninitLZO},
{"none", TO_BE32X('OTTN'), InitNoComp, ReadNoComp, UninitNoComp, InitNoComp, WriteNoComp, UninitNoComp},
#if defined(WITH_ZLIB)
{"zlib", TO_BE32X('OTTZ'), InitReadZlib, ReadZlib, UninitReadZlib, InitWriteZlib, WriteZlib, UninitWriteZlib},
#else
{"zlib", TO_BE32X('OTTZ'), NULL, NULL, NULL, NULL, NULL, NULL},
#endif
};
/**
* Return the savegameformat of the game. Whether it was create with ZLIB compression
* uncompressed, or another type
* @param s Name of the savegame format. If NULL it picks the first available one
* @return Pointer to SaveLoadFormat struct giving all characteristics of this type of savegame
*/
static const SaveLoadFormat *GetSavegameFormat(const char *s)
{
const SaveLoadFormat *def = endof(_saveload_formats) - 1;
/* find default savegame format, the highest one with which files can be written */
while (!def->init_write) def--;
if (s != NULL && s[0] != '\0') {
const SaveLoadFormat *slf;
for (slf = &_saveload_formats[0]; slf != endof(_saveload_formats); slf++) {
if (slf->init_write != NULL && strcmp(s, slf->name) == 0)
return slf;
}
ShowInfoF("Savegame format '%s' is not available. Reverting to '%s'.", s, def->name);
}
return def;
}
/* actual loader/saver function */
void InitializeGame(uint size_x, uint size_y, bool reset_date);
extern bool AfterLoadGame();
extern bool LoadOldSaveGame(const char *file);
/** Small helper function to close the to be loaded savegame an signal error */
static inline SaveOrLoadResult AbortSaveLoad()
{
if (_sl.fh != NULL) fclose(_sl.fh);
_sl.fh = NULL;
return SL_ERROR;
}
/** Update the gui accordingly when starting saving
* and set locks on saveload. Also turn off fast-forward cause with that
* saving takes Aaaaages */
static void SaveFileStart()
{
_ts.ff_state = _fast_forward;
_fast_forward = 0;
if (_cursor.sprite == SPR_CURSOR_MOUSE) SetMouseCursor(SPR_CURSOR_ZZZ, PAL_NONE);
InvalidateWindowData(WC_STATUS_BAR, 0, SBI_SAVELOAD_START);
_ts.saveinprogress = true;
}
/** Update the gui accordingly when saving is done and release locks
* on saveload */
static void SaveFileDone()
{
if (_game_mode != GM_MENU) _fast_forward = _ts.ff_state;
if (_cursor.sprite == SPR_CURSOR_ZZZ) SetMouseCursor(SPR_CURSOR_MOUSE, PAL_NONE);
InvalidateWindowData(WC_STATUS_BAR, 0, SBI_SAVELOAD_FINISH);
_ts.saveinprogress = false;
}
/** Set the error message from outside of the actual loading/saving of the game (AfterLoadGame and friends) */
void SetSaveLoadError(StringID str)
{
_sl.error_str = str;
}
/** Get the string representation of the error message */
const char *GetSaveLoadErrorString()
{
SetDParam(0, _sl.error_str);
SetDParamStr(1, _sl.extra_msg);
static char err_str[512];
GetString(err_str, _sl.save ? STR_4007_GAME_SAVE_FAILED : STR_4009_GAME_LOAD_FAILED, lastof(err_str));
return err_str;
}
/** Show a gui message when saving has failed */
static void SaveFileError()
{
SetDParamStr(0, GetSaveLoadErrorString());
ShowErrorMessage(STR_JUST_RAW_STRING, STR_NULL, 0, 0);
SaveFileDone();
}
/** We have written the whole game into memory, _Savegame_pool, now find
* and appropiate compressor and start writing to file.
*/
static SaveOrLoadResult SaveFileToDisk(bool threaded)
{
const SaveLoadFormat *fmt;
uint32 hdr[2];
_sl.excpt_uninit = NULL;
try {
fmt = GetSavegameFormat(_savegame_format);
/* We have written our stuff to memory, now write it to file! */
hdr[0] = fmt->tag;
hdr[1] = TO_BE32(SAVEGAME_VERSION << 16);
if (fwrite(hdr, sizeof(hdr), 1, _sl.fh) != 1) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_WRITEABLE);
if (!fmt->init_write()) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, "cannot initialize compressor");
{
uint i;
uint count = 1 << Savegame_POOL_BLOCK_SIZE_BITS;
if (_ts.count != _sl.offs_base) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME, "Unexpected size of chunk");
for (i = 0; i != _Savegame_pool.GetBlockCount() - 1; i++) {
_sl.buf = _Savegame_pool.blocks[i];
fmt->writer(count);
}
/* The last block is (almost) always not fully filled, so only write away
* as much data as it is in there */
_sl.buf = _Savegame_pool.blocks[i];
fmt->writer(_ts.count - (i * count));
}
fmt->uninit_write();
if (_ts.count != _sl.offs_base) SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_SAVEGAME, "Unexpected size of chunk");
GetSavegameFormat("memory")->uninit_write(); // clean the memorypool
fclose(_sl.fh);
if (threaded) SetAsyncSaveFinish(SaveFileDone);
return SL_OK;
}
catch (...) {
AbortSaveLoad();
if (_sl.excpt_uninit != NULL) _sl.excpt_uninit();
/* Skip the "colour" character */
DEBUG(sl, 0, GetSaveLoadErrorString() + 3);
if (threaded) {
SetAsyncSaveFinish(SaveFileError);
} else {
SaveFileError();
}
return SL_ERROR;
}
}
static void SaveFileToDiskThread(void *arg)
{
SaveFileToDisk(true);
}
void WaitTillSaved()
{
if (_save_thread == NULL) return;
_save_thread->Join();
delete _save_thread;
_save_thread = NULL;
}
/**
* Main Save or Load function where the high-level saveload functions are
* handled. It opens the savegame, selects format and checks versions
* @param filename The name of the savegame being created/loaded
* @param mode Save or load. Load can also be a TTD(Patch) game. Use SL_LOAD, SL_OLD_LOAD or SL_SAVE
* @return Return the results of the action. SL_OK, SL_ERROR or SL_REINIT ("unload" the game)
*/
SaveOrLoadResult SaveOrLoad(const char *filename, int mode, Subdirectory sb)
{
uint32 hdr[2];
const SaveLoadFormat *fmt;
/* An instance of saving is already active, so don't go saving again */
if (_ts.saveinprogress && mode == SL_SAVE) {
/* if not an autosave, but a user action, show error message */
if (!_do_autosave) ShowErrorMessage(INVALID_STRING_ID, STR_SAVE_STILL_IN_PROGRESS, 0, 0);
return SL_OK;
}
WaitTillSaved();
_next_offs = 0;
/* Load a TTDLX or TTDPatch game */
if (mode == SL_OLD_LOAD) {
_engine_mngr.ResetToDefaultMapping();
InitializeGame(256, 256, true); // set a mapsize of 256x256 for TTDPatch games or it might get confused
GamelogReset();
if (!LoadOldSaveGame(filename)) return SL_REINIT;
_sl_version = 0;
_sl_minor_version = 0;
GamelogStartAction(GLAT_LOAD);
if (!AfterLoadGame()) {
GamelogStopAction();
return SL_REINIT;
}
GamelogStopAction();
return SL_OK;
}
_sl.excpt_uninit = NULL;
try {
_sl.fh = (mode == SL_SAVE) ? FioFOpenFile(filename, "wb", sb) : FioFOpenFile(filename, "rb", sb);
/* Make it a little easier to load savegames from the console */
if (_sl.fh == NULL && mode == SL_LOAD) _sl.fh = FioFOpenFile(filename, "rb", SAVE_DIR);
if (_sl.fh == NULL && mode == SL_LOAD) _sl.fh = FioFOpenFile(filename, "rb", BASE_DIR);
if (_sl.fh == NULL) {
SlError(mode == SL_SAVE ? STR_GAME_SAVELOAD_ERROR_FILE_NOT_WRITEABLE : STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
}
_sl.bufe = _sl.bufp = NULL;
_sl.offs_base = 0;
_sl.save = (mode != 0);
_sl.chs = _chunk_handlers;
/* General tactic is to first save the game to memory, then use an available writer
* to write it to file, either in threaded mode if possible, or single-threaded */
if (mode == SL_SAVE) { // SAVE game
DEBUG(desync, 1, "save: %s\n", filename);
fmt = GetSavegameFormat("memory"); // write to memory
_sl.write_bytes = fmt->writer;
_sl.excpt_uninit = fmt->uninit_write;
if (!fmt->init_write()) {
DEBUG(sl, 0, "Initializing writer '%s' failed.", fmt->name);
return AbortSaveLoad();
}
_sl_version = SAVEGAME_VERSION;
SaveViewportBeforeSaveGame();
SlSaveChunks();
SlWriteFill(); // flush the save buffer
SaveFileStart();
if (_network_server ||
!ThreadObject::New(&SaveFileToDiskThread, NULL, &_save_thread)) {
if (!_network_server) DEBUG(sl, 1, "Cannot create savegame thread, reverting to single-threaded mode...");
SaveOrLoadResult result = SaveFileToDisk(false);
SaveFileDone();
return result;
}
} else { // LOAD game
assert(mode == SL_LOAD);
DEBUG(desync, 1, "load: %s\n", filename);
/* Can't fseek to 0 as in tar files that is not correct */
long pos = ftell(_sl.fh);
if (fread(hdr, sizeof(hdr), 1, _sl.fh) != 1) SlError(STR_GAME_SAVELOAD_ERROR_FILE_NOT_READABLE);
/* see if we have any loader for this type. */
for (fmt = _saveload_formats; ; fmt++) {
/* No loader found, treat as version 0 and use LZO format */
if (fmt == endof(_saveload_formats)) {
DEBUG(sl, 0, "Unknown savegame type, trying to load it as the buggy format");
clearerr(_sl.fh);
fseek(_sl.fh, pos, SEEK_SET);
_sl_version = 0;
_sl_minor_version = 0;
fmt = _saveload_formats + 1; // LZO
break;
}
if (fmt->tag == hdr[0]) {
/* check version number */
_sl_version = TO_BE32(hdr[1]) >> 16;
/* Minor is not used anymore from version 18.0, but it is still needed
* in versions before that (4 cases) which can't be removed easy.
* Therefor it is loaded, but never saved (or, it saves a 0 in any scenario).
* So never EVER use this minor version again. -- TrueLight -- 22-11-2005 */
_sl_minor_version = (TO_BE32(hdr[1]) >> 8) & 0xFF;
DEBUG(sl, 1, "Loading savegame version %d", _sl_version);
/* Is the version higher than the current? */
if (_sl_version > SAVEGAME_VERSION) SlError(STR_GAME_SAVELOAD_ERROR_TOO_NEW_SAVEGAME);
break;
}
}
_sl.read_bytes = fmt->reader;
_sl.excpt_uninit = fmt->uninit_read;
/* loader for this savegame type is not implemented? */
if (fmt->init_read == NULL) {
char err_str[64];
snprintf(err_str, lengthof(err_str), "Loader for '%s' is not available.", fmt->name);
SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, err_str);
}
if (!fmt->init_read()) {
char err_str[64];
snprintf(err_str, lengthof(err_str), "Initializing loader '%s' failed", fmt->name);
SlError(STR_GAME_SAVELOAD_ERROR_BROKEN_INTERNAL_ERROR, err_str);
}
_engine_mngr.ResetToDefaultMapping();
/* Old maps were hardcoded to 256x256 and thus did not contain
* any mapsize information. Pre-initialize to 256x256 to not to
* confuse old games */
InitializeGame(256, 256, true);
GamelogReset();
SlLoadChunks();
fmt->uninit_read();
fclose(_sl.fh);
GamelogStartAction(GLAT_LOAD);
_savegame_type = SGT_OTTD;
/* After loading fix up savegame for any internal changes that
* might've occured since then. If it fails, load back the old game */
if (!AfterLoadGame()) {
GamelogStopAction();
return SL_REINIT;
}
GamelogStopAction();
}
return SL_OK;
}
catch (...) {
AbortSaveLoad();
/* deinitialize compressor. */
if (_sl.excpt_uninit != NULL) _sl.excpt_uninit();
/* Skip the "colour" character */
DEBUG(sl, 0, GetSaveLoadErrorString() + 3);
/* A saver/loader exception!! reinitialize all variables to prevent crash! */
return (mode == SL_LOAD) ? SL_REINIT : SL_ERROR;
}
}
/** Do a save when exiting the game (_settings_client.gui.autosave_on_exit) */
void DoExitSave()
{
SaveOrLoad("exit.sav", SL_SAVE, AUTOSAVE_DIR);
}
/**
* Fill the buffer with the default name for a savegame *or* screenshot.
* @param buf the buffer to write to.
* @param last the last element in the buffer.
*/
void GenerateDefaultSaveName(char *buf, const char *last)
{
/* Check if we have a name for this map, which is the name of the first
* available company. When there's no company available we'll use
* 'Spectator' as "company" name. */
CompanyID cid = _local_company;
if (!IsValidCompanyID(cid)) {
const Company *c;
FOR_ALL_COMPANIES(c) {
cid = c->index;
break;
}
}
SetDParam(0, cid);
/* Insert current date */
switch (_settings_client.gui.date_format_in_default_names) {
case 0: SetDParam(1, STR_JUST_DATE_LONG); break;
case 1: SetDParam(1, STR_JUST_DATE_TINY); break;
case 2: SetDParam(1, STR_JUST_DATE_ISO); break;
default: NOT_REACHED();
}
SetDParam(2, _date);
/* Get the correct string (special string for when there's not company) */
GetString(buf, !IsValidCompanyID(cid) ? STR_GAME_SAVELOAD_SPECTATOR_SAVEGAME : STR_4004, last);
SanitizeFilename(buf);
}
#if 0
/**
* Function to get the type of the savegame by looking at the file header.
* NOTICE: Not used right now, but could be used if extensions of savegames are garbled
* @param file Savegame to be checked
* @return SL_OLD_LOAD or SL_LOAD of the file
*/
int GetSavegameType(char *file)
{
const SaveLoadFormat *fmt;
uint32 hdr;
FILE *f;
int mode = SL_OLD_LOAD;
f = fopen(file, "rb");
if (fread(&hdr, sizeof(hdr), 1, f) != 1) {
DEBUG(sl, 0, "Savegame is obsolete or invalid format");
mode = SL_LOAD; // don't try to get filename, just show name as it is written
} else {
/* see if we have any loader for this type. */
for (fmt = _saveload_formats; fmt != endof(_saveload_formats); fmt++) {
if (fmt->tag == hdr) {
mode = SL_LOAD; // new type of savegame
break;
}
}
}
fclose(f);
return mode;
}
#endif
| 57,925
|
C++
|
.cpp
| 1,627
| 33.097726
| 134
| 0.685536
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,228
|
autoreplace_sl.cpp
|
EnergeticBark_OpenTTD-3DS/src/saveload/autoreplace_sl.cpp
|
/* $Id$ */
/** @file autoreplace_sl.cpp Code handling saving and loading of autoreplace rules */
#include "../stdafx.h"
#include "../engine_type.h"
#include "../group_type.h"
#include "../autoreplace_base.h"
#include "saveload.h"
static const SaveLoad _engine_renew_desc[] = {
SLE_VAR(EngineRenew, from, SLE_UINT16),
SLE_VAR(EngineRenew, to, SLE_UINT16),
SLE_REF(EngineRenew, next, REF_ENGINE_RENEWS),
SLE_CONDVAR(EngineRenew, group_id, SLE_UINT16, 60, SL_MAX_VERSION),
SLE_END()
};
static void Save_ERNW()
{
EngineRenew *er;
FOR_ALL_ENGINE_RENEWS(er) {
SlSetArrayIndex(er->index);
SlObject(er, _engine_renew_desc);
}
}
static void Load_ERNW()
{
int index;
while ((index = SlIterateArray()) != -1) {
EngineRenew *er = new (index) EngineRenew();
SlObject(er, _engine_renew_desc);
/* Advanced vehicle lists, ungrouped vehicles got added */
if (CheckSavegameVersion(60)) {
er->group_id = ALL_GROUP;
} else if (CheckSavegameVersion(71)) {
if (er->group_id == DEFAULT_GROUP) er->group_id = ALL_GROUP;
}
}
}
extern const ChunkHandler _autoreplace_chunk_handlers[] = {
{ 'ERNW', Save_ERNW, Load_ERNW, CH_ARRAY | CH_LAST},
};
| 1,197
|
C++
|
.cpp
| 39
| 28.230769
| 85
| 0.680907
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
1,539,229
|
engine_sl.cpp
|
EnergeticBark_OpenTTD-3DS/src/saveload/engine_sl.cpp
|
/* $Id$ */
/** @file engine_sl.cpp Code handling saving and loading of engines */
#include "../stdafx.h"
#include "saveload_internal.h"
#include "../engine_base.h"
#include <map>
static const SaveLoad _engine_desc[] = {
SLE_CONDVAR(Engine, intro_date, SLE_FILE_U16 | SLE_VAR_I32, 0, 30),
SLE_CONDVAR(Engine, intro_date, SLE_INT32, 31, SL_MAX_VERSION),
SLE_CONDVAR(Engine, age, SLE_FILE_U16 | SLE_VAR_I32, 0, 30),
SLE_CONDVAR(Engine, age, SLE_INT32, 31, SL_MAX_VERSION),
SLE_VAR(Engine, reliability, SLE_UINT16),
SLE_VAR(Engine, reliability_spd_dec, SLE_UINT16),
SLE_VAR(Engine, reliability_start, SLE_UINT16),
SLE_VAR(Engine, reliability_max, SLE_UINT16),
SLE_VAR(Engine, reliability_final, SLE_UINT16),
SLE_VAR(Engine, duration_phase_1, SLE_UINT16),
SLE_VAR(Engine, duration_phase_2, SLE_UINT16),
SLE_VAR(Engine, duration_phase_3, SLE_UINT16),
SLE_VAR(Engine, lifelength, SLE_UINT8),
SLE_VAR(Engine, flags, SLE_UINT8),
SLE_VAR(Engine, preview_company_rank,SLE_UINT8),
SLE_VAR(Engine, preview_wait, SLE_UINT8),
SLE_CONDNULL(1, 0, 44),
SLE_CONDVAR(Engine, company_avail, SLE_FILE_U8 | SLE_VAR_U16, 0, 103),
SLE_CONDVAR(Engine, company_avail, SLE_UINT16, 104, SL_MAX_VERSION),
SLE_CONDSTR(Engine, name, SLE_STR, 0, 84, SL_MAX_VERSION),
/* reserve extra space in savegame here. (currently 16 bytes) */
SLE_CONDNULL(16, 2, SL_MAX_VERSION),
SLE_END()
};
static std::map<EngineID, Engine> _temp_engine;
Engine *GetTempDataEngine(EngineID index)
{
return &_temp_engine[index];
}
static void Save_ENGN()
{
Engine *e;
FOR_ALL_ENGINES(e) {
SlSetArrayIndex(e->index);
SlObject(e, _engine_desc);
}
}
static void Load_ENGN()
{
/* As engine data is loaded before engines are initialized we need to load
* this information into a temporary array. This is then copied into the
* engine pool after processing NewGRFs by CopyTempEngineData(). */
int index;
while ((index = SlIterateArray()) != -1) {
Engine *e = GetTempDataEngine(index);
SlObject(e, _engine_desc);
}
}
/**
* Copy data from temporary engine array into the real engine pool.
*/
void CopyTempEngineData()
{
Engine *e;
FOR_ALL_ENGINES(e) {
if (e->index >= _temp_engine.size()) break;
const Engine *se = GetTempDataEngine(e->index);
e->intro_date = se->intro_date;
e->age = se->age;
e->reliability = se->reliability;
e->reliability_spd_dec = se->reliability_spd_dec;
e->reliability_start = se->reliability_start;
e->reliability_max = se->reliability_max;
e->reliability_final = se->reliability_final;
e->duration_phase_1 = se->duration_phase_1;
e->duration_phase_2 = se->duration_phase_2;
e->duration_phase_3 = se->duration_phase_3;
e->lifelength = se->lifelength;
e->flags = se->flags;
e->preview_company_rank= se->preview_company_rank;
e->preview_wait = se->preview_wait;
e->company_avail = se->company_avail;
if (se->name != NULL) e->name = strdup(se->name);
}
/* Get rid of temporary data */
_temp_engine.clear();
}
static void Load_ENGS()
{
/* Load old separate String ID list into a temporary array. This
* was always 256 entries. */
StringID names[256];
SlArray(names, lengthof(names), SLE_STRINGID);
/* Copy each string into the temporary engine array. */
for (EngineID engine = 0; engine < lengthof(names); engine++) {
Engine *e = GetTempDataEngine(engine);
e->name = CopyFromOldName(names[engine]);
}
}
/** Save and load the mapping between the engine id in the pool, and the grf file it came from. */
static const SaveLoad _engine_id_mapping_desc[] = {
SLE_VAR(EngineIDMapping, grfid, SLE_UINT32),
SLE_VAR(EngineIDMapping, internal_id, SLE_UINT16),
SLE_VAR(EngineIDMapping, type, SLE_UINT8),
SLE_VAR(EngineIDMapping, substitute_id, SLE_UINT8),
SLE_END()
};
static void Save_EIDS()
{
const EngineIDMapping *end = _engine_mngr.End();
uint index = 0;
for (EngineIDMapping *eid = _engine_mngr.Begin(); eid != end; eid++, index++) {
SlSetArrayIndex(index);
SlObject(eid, _engine_id_mapping_desc);
}
}
static void Load_EIDS()
{
int index;
_engine_mngr.Clear();
while ((index = SlIterateArray()) != -1) {
EngineIDMapping *eid = _engine_mngr.Append();
SlObject(eid, _engine_id_mapping_desc);
}
}
extern const ChunkHandler _engine_chunk_handlers[] = {
{ 'EIDS', Save_EIDS, Load_EIDS, CH_ARRAY },
{ 'ENGN', Save_ENGN, Load_ENGN, CH_ARRAY },
{ 'ENGS', NULL, Load_ENGS, CH_RIFF | CH_LAST },
};
| 4,784
|
C++
|
.cpp
| 127
| 35.15748
| 98
| 0.649838
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
1,539,231
|
town_sl.cpp
|
EnergeticBark_OpenTTD-3DS/src/saveload/town_sl.cpp
|
/* $Id$ */
/** @file town_sl.cpp Code handling saving and loading of towns and houses */
#include "../stdafx.h"
#include "../newgrf_house.h"
#include "../newgrf_commons.h"
#include "../variables.h"
#include "../town_map.h"
#include "saveload.h"
extern uint _total_towns;
/**
* Check and update town and house values.
*
* Checked are the HouseIDs. Updated are the
* town population the number of houses per
* town, the town radius and the max passengers
* of the town.
*/
void UpdateHousesAndTowns()
{
Town *town;
InitializeBuildingCounts();
/* Reset town population and num_houses */
FOR_ALL_TOWNS(town) {
town->population = 0;
town->num_houses = 0;
}
for (TileIndex t = 0; t < MapSize(); t++) {
HouseID house_id;
if (!IsTileType(t, MP_HOUSE)) continue;
house_id = GetHouseType(t);
if (!GetHouseSpecs(house_id)->enabled && house_id >= NEW_HOUSE_OFFSET) {
/* The specs for this type of house are not available any more, so
* replace it with the substitute original house type. */
house_id = _house_mngr.GetSubstituteID(house_id);
SetHouseType(t, house_id);
}
town = GetTownByTile(t);
IncreaseBuildingCount(town, house_id);
if (IsHouseCompleted(t)) town->population += GetHouseSpecs(house_id)->population;
/* Increase the number of houses for every house, but only once. */
if (GetHouseNorthPart(house_id) == 0) town->num_houses++;
}
/* Update the population and num_house dependant values */
FOR_ALL_TOWNS(town) {
UpdateTownRadius(town);
}
}
/** Save and load of towns. */
static const SaveLoad _town_desc[] = {
SLE_CONDVAR(Town, xy, SLE_FILE_U16 | SLE_VAR_U32, 0, 5),
SLE_CONDVAR(Town, xy, SLE_UINT32, 6, SL_MAX_VERSION),
SLE_CONDNULL(2, 0, 2), ///< population, no longer in use
SLE_CONDNULL(4, 3, 84), ///< population, no longer in use
SLE_CONDNULL(2, 0, 91), ///< num_houses, no longer in use
SLE_CONDVAR(Town, townnamegrfid, SLE_UINT32, 66, SL_MAX_VERSION),
SLE_VAR(Town, townnametype, SLE_UINT16),
SLE_VAR(Town, townnameparts, SLE_UINT32),
SLE_CONDSTR(Town, name, SLE_STR, 0, 84, SL_MAX_VERSION),
SLE_VAR(Town, flags12, SLE_UINT8),
SLE_CONDVAR(Town, statues, SLE_FILE_U8 | SLE_VAR_U16, 0, 103),
SLE_CONDVAR(Town, statues, SLE_UINT16, 104, SL_MAX_VERSION),
SLE_CONDNULL(1, 0, 1), ///< sort_index, no longer in use
SLE_CONDVAR(Town, have_ratings, SLE_FILE_U8 | SLE_VAR_U16, 0, 103),
SLE_CONDVAR(Town, have_ratings, SLE_UINT16, 104, SL_MAX_VERSION),
SLE_CONDARR(Town, ratings, SLE_INT16, 8, 0, 103),
SLE_CONDARR(Town, ratings, SLE_INT16, MAX_COMPANIES, 104, SL_MAX_VERSION),
/* failed bribe attempts are stored since savegame format 4 */
SLE_CONDARR(Town, unwanted, SLE_INT8, 8, 4, 103),
SLE_CONDARR(Town, unwanted, SLE_INT8, MAX_COMPANIES, 104, SL_MAX_VERSION),
SLE_CONDVAR(Town, max_pass, SLE_FILE_U16 | SLE_VAR_U32, 0, 8),
SLE_CONDVAR(Town, max_mail, SLE_FILE_U16 | SLE_VAR_U32, 0, 8),
SLE_CONDVAR(Town, new_max_pass, SLE_FILE_U16 | SLE_VAR_U32, 0, 8),
SLE_CONDVAR(Town, new_max_mail, SLE_FILE_U16 | SLE_VAR_U32, 0, 8),
SLE_CONDVAR(Town, act_pass, SLE_FILE_U16 | SLE_VAR_U32, 0, 8),
SLE_CONDVAR(Town, act_mail, SLE_FILE_U16 | SLE_VAR_U32, 0, 8),
SLE_CONDVAR(Town, new_act_pass, SLE_FILE_U16 | SLE_VAR_U32, 0, 8),
SLE_CONDVAR(Town, new_act_mail, SLE_FILE_U16 | SLE_VAR_U32, 0, 8),
SLE_CONDVAR(Town, max_pass, SLE_UINT32, 9, SL_MAX_VERSION),
SLE_CONDVAR(Town, max_mail, SLE_UINT32, 9, SL_MAX_VERSION),
SLE_CONDVAR(Town, new_max_pass, SLE_UINT32, 9, SL_MAX_VERSION),
SLE_CONDVAR(Town, new_max_mail, SLE_UINT32, 9, SL_MAX_VERSION),
SLE_CONDVAR(Town, act_pass, SLE_UINT32, 9, SL_MAX_VERSION),
SLE_CONDVAR(Town, act_mail, SLE_UINT32, 9, SL_MAX_VERSION),
SLE_CONDVAR(Town, new_act_pass, SLE_UINT32, 9, SL_MAX_VERSION),
SLE_CONDVAR(Town, new_act_mail, SLE_UINT32, 9, SL_MAX_VERSION),
SLE_VAR(Town, pct_pass_transported, SLE_UINT8),
SLE_VAR(Town, pct_mail_transported, SLE_UINT8),
SLE_VAR(Town, act_food, SLE_UINT16),
SLE_VAR(Town, act_water, SLE_UINT16),
SLE_VAR(Town, new_act_food, SLE_UINT16),
SLE_VAR(Town, new_act_water, SLE_UINT16),
SLE_CONDVAR(Town, time_until_rebuild, SLE_UINT8, 0, 53),
SLE_CONDVAR(Town, grow_counter, SLE_UINT8, 0, 53),
SLE_CONDVAR(Town, growth_rate, SLE_UINT8, 0, 53),
SLE_CONDVAR(Town, time_until_rebuild, SLE_UINT16, 54, SL_MAX_VERSION),
SLE_CONDVAR(Town, grow_counter, SLE_UINT16, 54, SL_MAX_VERSION),
SLE_CONDVAR(Town, growth_rate, SLE_INT16, 54, SL_MAX_VERSION),
SLE_VAR(Town, fund_buildings_months, SLE_UINT8),
SLE_VAR(Town, road_build_months, SLE_UINT8),
SLE_CONDVAR(Town, exclusivity, SLE_UINT8, 2, SL_MAX_VERSION),
SLE_CONDVAR(Town, exclusive_counter, SLE_UINT8, 2, SL_MAX_VERSION),
SLE_CONDVAR(Town, larger_town, SLE_BOOL, 56, SL_MAX_VERSION),
SLE_CONDVAR(Town, layout, SLE_UINT8, 113, SL_MAX_VERSION),
/* reserve extra space in savegame here. (currently 30 bytes) */
SLE_CONDNULL(30, 2, SL_MAX_VERSION),
SLE_END()
};
/* Save and load the mapping between the house id on the map, and the grf file
* it came from. */
static const SaveLoad _house_id_mapping_desc[] = {
SLE_VAR(EntityIDMapping, grfid, SLE_UINT32),
SLE_VAR(EntityIDMapping, entity_id, SLE_UINT8),
SLE_VAR(EntityIDMapping, substitute_id, SLE_UINT8),
SLE_END()
};
static void Save_HOUSEIDS()
{
uint j = _house_mngr.GetMaxMapping();
for (uint i = 0; i < j; i++) {
SlSetArrayIndex(i);
SlObject(&_house_mngr.mapping_ID[i], _house_id_mapping_desc);
}
}
static void Load_HOUSEIDS()
{
int index;
_house_mngr.ResetMapping();
uint max_id = _house_mngr.GetMaxMapping();
while ((index = SlIterateArray()) != -1) {
if ((uint)index >= max_id) break;
SlObject(&_house_mngr.mapping_ID[index], _house_id_mapping_desc);
}
}
static void Save_TOWN()
{
Town *t;
FOR_ALL_TOWNS(t) {
SlSetArrayIndex(t->index);
SlObject(t, _town_desc);
}
}
static void Load_TOWN()
{
int index;
_total_towns = 0;
while ((index = SlIterateArray()) != -1) {
Town *t = new (index) Town();
SlObject(t, _town_desc);
_total_towns++;
}
/* This is to ensure all pointers are within the limits of
* the size of the TownPool */
if (_cur_town_ctr > GetMaxTownIndex())
_cur_town_ctr = 0;
}
extern const ChunkHandler _town_chunk_handlers[] = {
{ 'HIDS', Save_HOUSEIDS, Load_HOUSEIDS, CH_ARRAY },
{ 'CITY', Save_TOWN, Load_TOWN, CH_ARRAY | CH_LAST},
};
| 7,298
|
C++
|
.cpp
| 159
| 43.352201
| 89
| 0.602734
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,232
|
misc_sl.cpp
|
EnergeticBark_OpenTTD-3DS/src/saveload/misc_sl.cpp
|
/* $Id$ */
/** @file misc_sl.cpp Saving and loading of things that didn't fit anywhere else */
#include "../stdafx.h"
#include "../date_func.h"
#include "../variables.h"
#include "../core/random_func.hpp"
#include "../openttd.h"
#include "../zoom_func.h"
#include "../vehicle_func.h"
#include "../window_gui.h"
#include "../window_func.h"
#include "../viewport_func.h"
#include "../gfx_func.h"
#include "../company_base.h"
#include "../town.h"
#include "saveload.h"
extern TileIndex _cur_tileloop_tile;
/* Keep track of current game position */
int _saved_scrollpos_x;
int _saved_scrollpos_y;
void SaveViewportBeforeSaveGame()
{
const Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
if (w != NULL) {
_saved_scrollpos_x = w->viewport->scrollpos_x;
_saved_scrollpos_y = w->viewport->scrollpos_y;
_saved_scrollpos_zoom = w->viewport->zoom;
}
}
void ResetViewportAfterLoadGame()
{
Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
w->viewport->scrollpos_x = _saved_scrollpos_x;
w->viewport->scrollpos_y = _saved_scrollpos_y;
w->viewport->dest_scrollpos_x = _saved_scrollpos_x;
w->viewport->dest_scrollpos_y = _saved_scrollpos_y;
ViewPort *vp = w->viewport;
vp->zoom = min(_saved_scrollpos_zoom, ZOOM_LVL_MAX);
vp->virtual_width = ScaleByZoom(vp->width, vp->zoom);
vp->virtual_height = ScaleByZoom(vp->height, vp->zoom);
DoZoomInOutWindow(ZOOM_NONE, w); // update button status
MarkWholeScreenDirty();
}
static const SaveLoadGlobVarList _date_desc[] = {
SLEG_CONDVAR(_date, SLE_FILE_U16 | SLE_VAR_I32, 0, 30),
SLEG_CONDVAR(_date, SLE_INT32, 31, SL_MAX_VERSION),
SLEG_VAR(_date_fract, SLE_UINT16),
SLEG_VAR(_tick_counter, SLE_UINT16),
SLEG_VAR(_vehicle_id_ctr_day, SLE_UINT16),
SLEG_VAR(_age_cargo_skip_counter, SLE_UINT8),
SLE_CONDNULL(1, 0, 45),
SLEG_CONDVAR(_cur_tileloop_tile, SLE_FILE_U16 | SLE_VAR_U32, 0, 5),
SLEG_CONDVAR(_cur_tileloop_tile, SLE_UINT32, 6, SL_MAX_VERSION),
SLEG_VAR(_disaster_delay, SLE_UINT16),
SLEG_VAR(_station_tick_ctr, SLE_UINT16),
SLEG_VAR(_random.state[0], SLE_UINT32),
SLEG_VAR(_random.state[1], SLE_UINT32),
SLEG_CONDVAR(_cur_town_ctr, SLE_FILE_U8 | SLE_VAR_U32, 0, 9),
SLEG_CONDVAR(_cur_town_ctr, SLE_UINT32, 10, SL_MAX_VERSION),
SLEG_VAR(_cur_company_tick_index, SLE_FILE_U8 | SLE_VAR_U32),
SLEG_CONDVAR(_next_competitor_start, SLE_FILE_U16 | SLE_VAR_U32, 0, 108),
SLEG_CONDVAR(_next_competitor_start, SLE_UINT32, 109, SL_MAX_VERSION),
SLEG_VAR(_trees_tick_ctr, SLE_UINT8),
SLEG_CONDVAR(_pause_game, SLE_UINT8, 4, SL_MAX_VERSION),
SLEG_CONDVAR(_cur_town_iter, SLE_UINT32, 11, SL_MAX_VERSION),
SLEG_END()
};
/* Save load date related variables as well as persistent tick counters
* XXX: currently some unrelated stuff is just put here */
static void SaveLoad_DATE()
{
SlGlobList(_date_desc);
}
static const SaveLoadGlobVarList _view_desc[] = {
SLEG_CONDVAR(_saved_scrollpos_x, SLE_FILE_I16 | SLE_VAR_I32, 0, 5),
SLEG_CONDVAR(_saved_scrollpos_x, SLE_INT32, 6, SL_MAX_VERSION),
SLEG_CONDVAR(_saved_scrollpos_y, SLE_FILE_I16 | SLE_VAR_I32, 0, 5),
SLEG_CONDVAR(_saved_scrollpos_y, SLE_INT32, 6, SL_MAX_VERSION),
SLEG_VAR(_saved_scrollpos_zoom, SLE_UINT8),
SLEG_END()
};
static void SaveLoad_VIEW()
{
SlGlobList(_view_desc);
}
extern const ChunkHandler _misc_chunk_handlers[] = {
{ 'DATE', SaveLoad_DATE, SaveLoad_DATE, CH_RIFF},
{ 'VIEW', SaveLoad_VIEW, SaveLoad_VIEW, CH_RIFF | CH_LAST},
};
| 3,738
|
C++
|
.cpp
| 89
| 39.617978
| 87
| 0.646929
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,233
|
map_sl.cpp
|
EnergeticBark_OpenTTD-3DS/src/saveload/map_sl.cpp
|
/* $Id$ */
/** @file map_sl.cpp Code handling saving and loading of map */
#include "../stdafx.h"
#include "../map_func.h"
#include "../core/alloc_type.hpp"
#include "../core/bitmath_func.hpp"
#include "saveload.h"
static uint32 _map_dim_x;
static uint32 _map_dim_y;
static const SaveLoadGlobVarList _map_dimensions[] = {
SLEG_CONDVAR(_map_dim_x, SLE_UINT32, 6, SL_MAX_VERSION),
SLEG_CONDVAR(_map_dim_y, SLE_UINT32, 6, SL_MAX_VERSION),
SLEG_END()
};
static void Save_MAPS()
{
_map_dim_x = MapSizeX();
_map_dim_y = MapSizeY();
SlGlobList(_map_dimensions);
}
static void Load_MAPS()
{
SlGlobList(_map_dimensions);
AllocateMap(_map_dim_x, _map_dim_y);
}
enum {
MAP_SL_BUF_SIZE = 4096
};
static void Load_MAPT()
{
SmallStackSafeStackAlloc<byte, MAP_SL_BUF_SIZE> buf;
TileIndex size = MapSize();
for (TileIndex i = 0; i != size;) {
SlArray(buf, MAP_SL_BUF_SIZE, SLE_UINT8);
for (uint j = 0; j != MAP_SL_BUF_SIZE; j++) _m[i++].type_height = buf[j];
}
}
static void Save_MAPT()
{
SmallStackSafeStackAlloc<byte, MAP_SL_BUF_SIZE> buf;
TileIndex size = MapSize();
SlSetLength(size);
for (TileIndex i = 0; i != size;) {
for (uint j = 0; j != MAP_SL_BUF_SIZE; j++) buf[j] = _m[i++].type_height;
SlArray(buf, MAP_SL_BUF_SIZE, SLE_UINT8);
}
}
static void Load_MAP1()
{
SmallStackSafeStackAlloc<byte, MAP_SL_BUF_SIZE> buf;
TileIndex size = MapSize();
for (TileIndex i = 0; i != size;) {
SlArray(buf, MAP_SL_BUF_SIZE, SLE_UINT8);
for (uint j = 0; j != MAP_SL_BUF_SIZE; j++) _m[i++].m1 = buf[j];
}
}
static void Save_MAP1()
{
SmallStackSafeStackAlloc<byte, MAP_SL_BUF_SIZE> buf;
TileIndex size = MapSize();
SlSetLength(size);
for (TileIndex i = 0; i != size;) {
for (uint j = 0; j != MAP_SL_BUF_SIZE; j++) buf[j] = _m[i++].m1;
SlArray(buf, MAP_SL_BUF_SIZE, SLE_UINT8);
}
}
static void Load_MAP2()
{
SmallStackSafeStackAlloc<uint16, MAP_SL_BUF_SIZE> buf;
TileIndex size = MapSize();
for (TileIndex i = 0; i != size;) {
SlArray(buf, MAP_SL_BUF_SIZE,
/* In those versions the m2 was 8 bits */
CheckSavegameVersion(5) ? SLE_FILE_U8 | SLE_VAR_U16 : SLE_UINT16
);
for (uint j = 0; j != MAP_SL_BUF_SIZE; j++) _m[i++].m2 = buf[j];
}
}
static void Save_MAP2()
{
SmallStackSafeStackAlloc<uint16, MAP_SL_BUF_SIZE> buf;
TileIndex size = MapSize();
SlSetLength(size * sizeof(uint16));
for (TileIndex i = 0; i != size;) {
for (uint j = 0; j != MAP_SL_BUF_SIZE; j++) buf[j] = _m[i++].m2;
SlArray(buf, MAP_SL_BUF_SIZE, SLE_UINT16);
}
}
static void Load_MAP3()
{
SmallStackSafeStackAlloc<byte, MAP_SL_BUF_SIZE> buf;
TileIndex size = MapSize();
for (TileIndex i = 0; i != size;) {
SlArray(buf, MAP_SL_BUF_SIZE, SLE_UINT8);
for (uint j = 0; j != MAP_SL_BUF_SIZE; j++) _m[i++].m3 = buf[j];
}
}
static void Save_MAP3()
{
SmallStackSafeStackAlloc<byte, MAP_SL_BUF_SIZE> buf;
TileIndex size = MapSize();
SlSetLength(size);
for (TileIndex i = 0; i != size;) {
for (uint j = 0; j != MAP_SL_BUF_SIZE; j++) buf[j] = _m[i++].m3;
SlArray(buf, MAP_SL_BUF_SIZE, SLE_UINT8);
}
}
static void Load_MAP4()
{
SmallStackSafeStackAlloc<byte, MAP_SL_BUF_SIZE> buf;
TileIndex size = MapSize();
for (TileIndex i = 0; i != size;) {
SlArray(buf, MAP_SL_BUF_SIZE, SLE_UINT8);
for (uint j = 0; j != MAP_SL_BUF_SIZE; j++) _m[i++].m4 = buf[j];
}
}
static void Save_MAP4()
{
SmallStackSafeStackAlloc<byte, MAP_SL_BUF_SIZE> buf;
TileIndex size = MapSize();
SlSetLength(size);
for (TileIndex i = 0; i != size;) {
for (uint j = 0; j != MAP_SL_BUF_SIZE; j++) buf[j] = _m[i++].m4;
SlArray(buf, MAP_SL_BUF_SIZE, SLE_UINT8);
}
}
static void Load_MAP5()
{
SmallStackSafeStackAlloc<byte, MAP_SL_BUF_SIZE> buf;
TileIndex size = MapSize();
for (TileIndex i = 0; i != size;) {
SlArray(buf, MAP_SL_BUF_SIZE, SLE_UINT8);
for (uint j = 0; j != MAP_SL_BUF_SIZE; j++) _m[i++].m5 = buf[j];
}
}
static void Save_MAP5()
{
SmallStackSafeStackAlloc<byte, MAP_SL_BUF_SIZE> buf;
TileIndex size = MapSize();
SlSetLength(size);
for (TileIndex i = 0; i != size;) {
for (uint j = 0; j != MAP_SL_BUF_SIZE; j++) buf[j] = _m[i++].m5;
SlArray(buf, MAP_SL_BUF_SIZE, SLE_UINT8);
}
}
static void Load_MAP6()
{
SmallStackSafeStackAlloc<byte, MAP_SL_BUF_SIZE> buf;
TileIndex size = MapSize();
if (CheckSavegameVersion(42)) {
for (TileIndex i = 0; i != size;) {
/* 1024, otherwise we overflow on 64x64 maps! */
SlArray(buf, 1024, SLE_UINT8);
for (uint j = 0; j != 1024; j++) {
_m[i++].m6 = GB(buf[j], 0, 2);
_m[i++].m6 = GB(buf[j], 2, 2);
_m[i++].m6 = GB(buf[j], 4, 2);
_m[i++].m6 = GB(buf[j], 6, 2);
}
}
} else {
for (TileIndex i = 0; i != size;) {
SlArray(buf, MAP_SL_BUF_SIZE, SLE_UINT8);
for (uint j = 0; j != MAP_SL_BUF_SIZE; j++) _m[i++].m6 = buf[j];
}
}
}
static void Save_MAP6()
{
SmallStackSafeStackAlloc<byte, MAP_SL_BUF_SIZE> buf;
TileIndex size = MapSize();
SlSetLength(size);
for (TileIndex i = 0; i != size;) {
for (uint j = 0; j != MAP_SL_BUF_SIZE; j++) buf[j] = _m[i++].m6;
SlArray(buf, MAP_SL_BUF_SIZE, SLE_UINT8);
}
}
static void Load_MAP7()
{
SmallStackSafeStackAlloc<byte, MAP_SL_BUF_SIZE> buf;
TileIndex size = MapSize();
for (TileIndex i = 0; i != size;) {
SlArray(buf, MAP_SL_BUF_SIZE, SLE_UINT8);
for (uint j = 0; j != MAP_SL_BUF_SIZE; j++) _me[i++].m7 = buf[j];
}
}
static void Save_MAP7()
{
SmallStackSafeStackAlloc<byte, MAP_SL_BUF_SIZE> buf;
TileIndex size = MapSize();
SlSetLength(size);
for (TileIndex i = 0; i != size;) {
for (uint j = 0; j != MAP_SL_BUF_SIZE; j++) buf[j] = _me[i++].m7;
SlArray(buf, MAP_SL_BUF_SIZE, SLE_UINT8);
}
}
extern const ChunkHandler _map_chunk_handlers[] = {
{ 'MAPS', Save_MAPS, Load_MAPS, CH_RIFF },
{ 'MAPT', Save_MAPT, Load_MAPT, CH_RIFF },
{ 'MAPO', Save_MAP1, Load_MAP1, CH_RIFF },
{ 'MAP2', Save_MAP2, Load_MAP2, CH_RIFF },
{ 'M3LO', Save_MAP3, Load_MAP3, CH_RIFF },
{ 'M3HI', Save_MAP4, Load_MAP4, CH_RIFF },
{ 'MAP5', Save_MAP5, Load_MAP5, CH_RIFF },
{ 'MAPE', Save_MAP6, Load_MAP6, CH_RIFF },
{ 'MAP7', Save_MAP7, Load_MAP7, CH_RIFF | CH_LAST },
};
| 6,132
|
C++
|
.cpp
| 207
| 27.434783
| 75
| 0.630354
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
1,539,234
|
subsidy_sl.cpp
|
EnergeticBark_OpenTTD-3DS/src/saveload/subsidy_sl.cpp
|
/* $Id$ */
/** @file subsidy_sl.cpp Code handling saving and loading of subsidies */
#include "../stdafx.h"
#include "../economy_func.h"
#include "saveload.h"
static const SaveLoad _subsidies_desc[] = {
SLE_VAR(Subsidy, cargo_type, SLE_UINT8),
SLE_VAR(Subsidy, age, SLE_UINT8),
SLE_CONDVAR(Subsidy, from, SLE_FILE_U8 | SLE_VAR_U16, 0, 4),
SLE_CONDVAR(Subsidy, from, SLE_UINT16, 5, SL_MAX_VERSION),
SLE_CONDVAR(Subsidy, to, SLE_FILE_U8 | SLE_VAR_U16, 0, 4),
SLE_CONDVAR(Subsidy, to, SLE_UINT16, 5, SL_MAX_VERSION),
SLE_END()
};
void Save_SUBS()
{
int i;
Subsidy *s;
for (i = 0; i != lengthof(_subsidies); i++) {
s = &_subsidies[i];
if (s->cargo_type != CT_INVALID) {
SlSetArrayIndex(i);
SlObject(s, _subsidies_desc);
}
}
}
void Load_SUBS()
{
int index;
while ((index = SlIterateArray()) != -1)
SlObject(&_subsidies[index], _subsidies_desc);
}
extern const ChunkHandler _subsidy_chunk_handlers[] = {
{ 'SUBS', Save_SUBS, Load_SUBS, CH_ARRAY | CH_LAST},
};
| 1,071
|
C++
|
.cpp
| 35
| 28.342857
| 80
| 0.618677
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,235
|
vehicle_sl.cpp
|
EnergeticBark_OpenTTD-3DS/src/saveload/vehicle_sl.cpp
|
/* $Id$ */
/** @file vehicle_sl.cpp Code handling saving and loading of vehicles */
#include "../stdafx.h"
#include "../vehicle_func.h"
#include "../train.h"
#include "../roadveh.h"
#include "../ship.h"
#include "../aircraft.h"
#include "../effectvehicle_base.h"
#include "saveload.h"
#include <map>
/*
* Link front and rear multiheaded engines to each other
* This is done when loading a savegame
*/
void ConnectMultiheadedTrains()
{
Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->type == VEH_TRAIN) {
v->u.rail.other_multiheaded_part = NULL;
}
}
FOR_ALL_VEHICLES(v) {
if (v->type == VEH_TRAIN && (IsFrontEngine(v) || IsFreeWagon(v))) {
/* Two ways to associate multiheaded parts to each other:
* sequential-matching: Trains shall be arranged to look like <..>..<..>..<..>..
* bracket-matching: Free vehicle chains shall be arranged to look like ..<..<..>..<..>..>..
*
* Note: Old savegames might contain chains which do not comply with these rules, e.g.
* - the front and read parts have invalid orders
* - different engine types might be combined
* - there might be different amounts of front and rear parts.
*
* Note: The multiheaded parts need to be matched exactly like they are matched on the server, else desyncs will occur.
* This is why two matching strategies are needed.
*/
bool sequential_matching = IsFrontEngine(v);
for (Vehicle *u = v; u != NULL; u = GetNextVehicle(u)) {
if (u->u.rail.other_multiheaded_part != NULL) continue; // we already linked this one
if (IsMultiheaded(u)) {
if (!IsTrainEngine(u)) {
/* we got a rear car without a front car. We will convert it to a front one */
SetTrainEngine(u);
u->spritenum--;
}
/* Find a matching back part */
EngineID eid = u->engine_type;
Vehicle *w;
if (sequential_matching) {
for (w = GetNextVehicle(u); w != NULL; w = GetNextVehicle(w)) {
if (w->engine_type != eid || w->u.rail.other_multiheaded_part != NULL || !IsMultiheaded(w)) continue;
/* we found a car to partner with this engine. Now we will make sure it face the right way */
if (IsTrainEngine(w)) {
ClearTrainEngine(w);
w->spritenum++;
}
break;
}
} else {
uint stack_pos = 0;
for (w = GetNextVehicle(u); w != NULL; w = GetNextVehicle(w)) {
if (w->engine_type != eid || w->u.rail.other_multiheaded_part != NULL || !IsMultiheaded(w)) continue;
if (IsTrainEngine(w)) {
stack_pos++;
} else {
if (stack_pos == 0) break;
stack_pos--;
}
}
}
if (w != NULL) {
w->u.rail.other_multiheaded_part = u;
u->u.rail.other_multiheaded_part = w;
} else {
/* we got a front car and no rear cars. We will fake this one for forget that it should have been multiheaded */
ClearMultiheaded(u);
}
}
}
}
}
}
/**
* Converts all trains to the new subtype format introduced in savegame 16.2
* It also links multiheaded engines or make them forget they are multiheaded if no suitable partner is found
*/
void ConvertOldMultiheadToNew()
{
Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->type == VEH_TRAIN) {
SetBit(v->subtype, 7); // indicates that it's the old format and needs to be converted in the next loop
}
}
FOR_ALL_VEHICLES(v) {
if (v->type == VEH_TRAIN) {
if (HasBit(v->subtype, 7) && ((v->subtype & ~0x80) == 0 || (v->subtype & ~0x80) == 4)) {
for (Vehicle *u = v; u != NULL; u = u->Next()) {
const RailVehicleInfo *rvi = RailVehInfo(u->engine_type);
ClrBit(u->subtype, 7);
switch (u->subtype) {
case 0: // TS_Front_Engine
if (rvi->railveh_type == RAILVEH_MULTIHEAD) SetMultiheaded(u);
SetFrontEngine(u);
SetTrainEngine(u);
break;
case 1: // TS_Artic_Part
u->subtype = 0;
SetArticulatedPart(u);
break;
case 2: // TS_Not_First
u->subtype = 0;
if (rvi->railveh_type == RAILVEH_WAGON) {
/* normal wagon */
SetTrainWagon(u);
break;
}
if (rvi->railveh_type == RAILVEH_MULTIHEAD && rvi->image_index == u->spritenum - 1) {
/* rear end of a multiheaded engine */
SetMultiheaded(u);
break;
}
if (rvi->railveh_type == RAILVEH_MULTIHEAD) SetMultiheaded(u);
SetTrainEngine(u);
break;
case 4: // TS_Free_Car
u->subtype = 0;
SetTrainWagon(u);
SetFreeWagon(u);
break;
default: NOT_REACHED(); break;
}
}
}
}
}
}
/** need to be called to load aircraft from old version */
void UpdateOldAircraft()
{
/* set airport_flags to 0 for all airports just to be sure */
Station *st;
FOR_ALL_STATIONS(st) {
st->airport_flags = 0; // reset airport
}
Vehicle *v_oldstyle;
FOR_ALL_VEHICLES(v_oldstyle) {
/* airplane has another vehicle with subtype 4 (shadow), helicopter also has 3 (rotor)
* skip those */
if (v_oldstyle->type == VEH_AIRCRAFT && IsNormalAircraft(v_oldstyle)) {
/* airplane in terminal stopped doesn't hurt anyone, so goto next */
if (v_oldstyle->vehstatus & VS_STOPPED && v_oldstyle->u.air.state == 0) {
v_oldstyle->u.air.state = HANGAR;
continue;
}
AircraftLeaveHangar(v_oldstyle); // make airplane visible if it was in a depot for example
v_oldstyle->vehstatus &= ~VS_STOPPED; // make airplane moving
v_oldstyle->cur_speed = v_oldstyle->max_speed; // so aircraft don't have zero speed while in air
if (!v_oldstyle->current_order.IsType(OT_GOTO_STATION) && !v_oldstyle->current_order.IsType(OT_GOTO_DEPOT)) {
/* reset current order so aircraft doesn't have invalid "station-only" order */
v_oldstyle->current_order.MakeDummy();
}
v_oldstyle->u.air.state = FLYING;
AircraftNextAirportPos_and_Order(v_oldstyle); // move it to the entry point of the airport
GetNewVehiclePosResult gp = GetNewVehiclePos(v_oldstyle);
v_oldstyle->tile = 0; // aircraft in air is tile=0
/* correct speed of helicopter-rotors */
if (v_oldstyle->subtype == AIR_HELICOPTER) v_oldstyle->Next()->Next()->cur_speed = 32;
/* set new position x,y,z */
SetAircraftPosition(v_oldstyle, gp.x, gp.y, GetAircraftFlyingAltitude(v_oldstyle));
}
}
}
/**
* Check all vehicles to ensure their engine type is valid
* for the currently loaded NewGRFs (that includes none...)
* This only makes a difference if NewGRFs are missing, otherwise
* all vehicles will be valid. This does not make such a game
* playable, it only prevents crash.
*/
static void CheckValidVehicles()
{
uint total_engines = GetEnginePoolSize();
EngineID first_engine[4] = { INVALID_ENGINE, INVALID_ENGINE, INVALID_ENGINE, INVALID_ENGINE };
Engine *e;
FOR_ALL_ENGINES_OF_TYPE(e, VEH_TRAIN) { first_engine[VEH_TRAIN] = e->index; break; }
FOR_ALL_ENGINES_OF_TYPE(e, VEH_ROAD) { first_engine[VEH_ROAD] = e->index; break; }
FOR_ALL_ENGINES_OF_TYPE(e, VEH_SHIP) { first_engine[VEH_SHIP] = e->index; break; }
FOR_ALL_ENGINES_OF_TYPE(e, VEH_AIRCRAFT) { first_engine[VEH_AIRCRAFT] = e->index; break; }
Vehicle *v;
FOR_ALL_VEHICLES(v) {
/* Test if engine types match */
switch (v->type) {
case VEH_TRAIN:
case VEH_ROAD:
case VEH_SHIP:
case VEH_AIRCRAFT:
if (v->engine_type >= total_engines || v->type != GetEngine(v->engine_type)->type) {
v->engine_type = first_engine[v->type];
}
break;
default:
break;
}
}
}
/** Called after load to update coordinates */
void AfterLoadVehicles(bool part_of_load)
{
Vehicle *v;
FOR_ALL_VEHICLES(v) {
/* Reinstate the previous pointer */
if (v->Next() != NULL) v->Next()->previous = v;
if (v->NextShared() != NULL) v->NextShared()->previous_shared = v;
v->UpdateDeltaXY(v->direction);
if (part_of_load) v->fill_percent_te_id = INVALID_TE_ID;
v->first = NULL;
if (v->type == VEH_TRAIN) v->u.rail.first_engine = INVALID_ENGINE;
if (v->type == VEH_ROAD) v->u.road.first_engine = INVALID_ENGINE;
v->cargo.InvalidateCache();
}
/* AfterLoadVehicles may also be called in case of NewGRF reload, in this
* case we may not convert orders again. */
if (part_of_load) {
/* Create shared vehicle chain for very old games (pre 5,2) and create
* OrderList from shared vehicle chains. For this to work correctly, the
* following conditions must be fulfilled:
* a) both next_shared and previous_shared are not set for pre 5,2 games
* b) both next_shared and previous_shared are set for later games
*/
std::map<Order*, OrderList*> mapping;
FOR_ALL_VEHICLES(v) {
if (v->orders.old != NULL) {
if (CheckSavegameVersion(105)) { // Pre-105 didn't save an OrderList
if (mapping[v->orders.old] == NULL) {
/* This adds the whole shared vehicle chain for case b */
v->orders.list = mapping[v->orders.old] = new OrderList(v->orders.old, v);
} else {
v->orders.list = mapping[v->orders.old];
/* For old games (case a) we must create the shared vehicle chain */
if (CheckSavegameVersionOldStyle(5, 2)) {
v->AddToShared(v->orders.list->GetFirstSharedVehicle());
}
}
} else { // OrderList was saved as such, only recalculate not saved values
if (v->PreviousShared() == NULL) {
new (v->orders.list) OrderList(v->orders.list->GetFirstOrder(), v);
}
}
}
}
}
FOR_ALL_VEHICLES(v) {
/* Fill the first pointers */
if (v->Previous() == NULL) {
for (Vehicle *u = v; u != NULL; u = u->Next()) {
u->first = v;
}
}
}
CheckValidVehicles();
FOR_ALL_VEHICLES(v) {
assert(v->first != NULL);
if (v->type == VEH_TRAIN && (IsFrontEngine(v) || IsFreeWagon(v))) {
if (IsFrontEngine(v)) v->u.rail.last_speed = v->cur_speed; // update displayed train speed
TrainConsistChanged(v, false);
} else if (v->type == VEH_ROAD && IsRoadVehFront(v)) {
RoadVehUpdateCache(v);
}
}
/* Stop non-front engines */
if (CheckSavegameVersion(112)) {
FOR_ALL_VEHICLES(v) {
if (v->type == VEH_TRAIN && !IsFrontEngine(v)) {
if (IsTrainEngine(v)) v->vehstatus |= VS_STOPPED;
/* cur_speed is now relevant for non-front parts - nonzero breaks
* moving-wagons-inside-depot- and autoreplace- code */
v->cur_speed = 0;
}
/* trains weren't stopping gradually in old OTTD versions (and TTO/TTD)
* other vehicle types didn't have zero speed while stopped (even in 'recent' OTTD versions) */
if ((v->vehstatus & VS_STOPPED) && (v->type != VEH_TRAIN || CheckSavegameVersionOldStyle(2, 1))) {
v->cur_speed = 0;
}
}
}
FOR_ALL_VEHICLES(v) {
switch (v->type) {
case VEH_ROAD:
v->u.road.roadtype = HasBit(EngInfo(v->First()->engine_type)->misc_flags, EF_ROAD_TRAM) ? ROADTYPE_TRAM : ROADTYPE_ROAD;
v->u.road.compatible_roadtypes = RoadTypeToRoadTypes(v->u.road.roadtype);
/* FALL THROUGH */
case VEH_TRAIN:
case VEH_SHIP:
v->cur_image = v->GetImage(v->direction);
break;
case VEH_AIRCRAFT:
if (IsNormalAircraft(v)) {
v->cur_image = v->GetImage(v->direction);
/* The plane's shadow will have the same image as the plane */
Vehicle *shadow = v->Next();
shadow->cur_image = v->cur_image;
/* In the case of a helicopter we will update the rotor sprites */
if (v->subtype == AIR_HELICOPTER) {
Vehicle *rotor = shadow->Next();
rotor->cur_image = GetRotorImage(v);
}
UpdateAircraftCache(v);
}
break;
default: break;
}
v->coord.left = INVALID_COORD;
VehicleMove(v, false);
}
}
static uint8 _cargo_days;
static uint16 _cargo_source;
static uint32 _cargo_source_xy;
static uint16 _cargo_count;
static uint16 _cargo_paid_for;
static Money _cargo_feeder_share;
static uint32 _cargo_loaded_at_xy;
/**
* Make it possible to make the saveload tables "friends" of other classes.
* @param vt the vehicle type. Can be VEH_END for the common vehicle description data
* @return the saveload description
*/
const SaveLoad *GetVehicleDescription(VehicleType vt)
{
/** Save and load of vehicles */
static const SaveLoad _common_veh_desc[] = {
SLE_VAR(Vehicle, subtype, SLE_UINT8),
SLE_REF(Vehicle, next, REF_VEHICLE_OLD),
SLE_CONDVAR(Vehicle, name, SLE_NAME, 0, 83),
SLE_CONDSTR(Vehicle, name, SLE_STR, 0, 84, SL_MAX_VERSION),
SLE_CONDVAR(Vehicle, unitnumber, SLE_FILE_U8 | SLE_VAR_U16, 0, 7),
SLE_CONDVAR(Vehicle, unitnumber, SLE_UINT16, 8, SL_MAX_VERSION),
SLE_VAR(Vehicle, owner, SLE_UINT8),
SLE_CONDVAR(Vehicle, tile, SLE_FILE_U16 | SLE_VAR_U32, 0, 5),
SLE_CONDVAR(Vehicle, tile, SLE_UINT32, 6, SL_MAX_VERSION),
SLE_CONDVAR(Vehicle, dest_tile, SLE_FILE_U16 | SLE_VAR_U32, 0, 5),
SLE_CONDVAR(Vehicle, dest_tile, SLE_UINT32, 6, SL_MAX_VERSION),
SLE_CONDVAR(Vehicle, x_pos, SLE_FILE_U16 | SLE_VAR_U32, 0, 5),
SLE_CONDVAR(Vehicle, x_pos, SLE_UINT32, 6, SL_MAX_VERSION),
SLE_CONDVAR(Vehicle, y_pos, SLE_FILE_U16 | SLE_VAR_U32, 0, 5),
SLE_CONDVAR(Vehicle, y_pos, SLE_UINT32, 6, SL_MAX_VERSION),
SLE_VAR(Vehicle, z_pos, SLE_UINT8),
SLE_VAR(Vehicle, direction, SLE_UINT8),
SLE_CONDNULL(2, 0, 57),
SLE_VAR(Vehicle, spritenum, SLE_UINT8),
SLE_CONDNULL(5, 0, 57),
SLE_VAR(Vehicle, engine_type, SLE_UINT16),
SLE_VAR(Vehicle, max_speed, SLE_UINT16),
SLE_VAR(Vehicle, cur_speed, SLE_UINT16),
SLE_VAR(Vehicle, subspeed, SLE_UINT8),
SLE_VAR(Vehicle, acceleration, SLE_UINT8),
SLE_VAR(Vehicle, progress, SLE_UINT8),
SLE_VAR(Vehicle, vehstatus, SLE_UINT8),
SLE_CONDVAR(Vehicle, last_station_visited, SLE_FILE_U8 | SLE_VAR_U16, 0, 4),
SLE_CONDVAR(Vehicle, last_station_visited, SLE_UINT16, 5, SL_MAX_VERSION),
SLE_VAR(Vehicle, cargo_type, SLE_UINT8),
SLE_CONDVAR(Vehicle, cargo_subtype, SLE_UINT8, 35, SL_MAX_VERSION),
SLEG_CONDVAR( _cargo_days, SLE_UINT8, 0, 67),
SLEG_CONDVAR( _cargo_source, SLE_FILE_U8 | SLE_VAR_U16, 0, 6),
SLEG_CONDVAR( _cargo_source, SLE_UINT16, 7, 67),
SLEG_CONDVAR( _cargo_source_xy, SLE_UINT32, 44, 67),
SLE_VAR(Vehicle, cargo_cap, SLE_UINT16),
SLEG_CONDVAR( _cargo_count, SLE_UINT16, 0, 67),
SLE_CONDLST(Vehicle, cargo, REF_CARGO_PACKET, 68, SL_MAX_VERSION),
SLE_VAR(Vehicle, day_counter, SLE_UINT8),
SLE_VAR(Vehicle, tick_counter, SLE_UINT8),
SLE_CONDVAR(Vehicle, running_ticks, SLE_UINT8, 88, SL_MAX_VERSION),
SLE_VAR(Vehicle, cur_order_index, SLE_UINT8),
/* num_orders is now part of OrderList and is not saved but counted */
SLE_CONDNULL(1, 0, 104),
/* This next line is for version 4 and prior compatibility.. it temporarily reads
type and flags (which were both 4 bits) into type. Later on this is
converted correctly */
SLE_CONDVARX(cpp_offsetof(Vehicle, current_order) + cpp_offsetof(Order, type), SLE_UINT8, 0, 4),
SLE_CONDVARX(cpp_offsetof(Vehicle, current_order) + cpp_offsetof(Order, dest), SLE_FILE_U8 | SLE_VAR_U16, 0, 4),
/* Orders for version 5 and on */
SLE_CONDVARX(cpp_offsetof(Vehicle, current_order) + cpp_offsetof(Order, type), SLE_UINT8, 5, SL_MAX_VERSION),
SLE_CONDVARX(cpp_offsetof(Vehicle, current_order) + cpp_offsetof(Order, flags), SLE_UINT8, 5, SL_MAX_VERSION),
SLE_CONDVARX(cpp_offsetof(Vehicle, current_order) + cpp_offsetof(Order, dest), SLE_UINT16, 5, SL_MAX_VERSION),
/* Refit in current order */
SLE_CONDVARX(cpp_offsetof(Vehicle, current_order) + cpp_offsetof(Order, refit_cargo), SLE_UINT8, 36, SL_MAX_VERSION),
SLE_CONDVARX(cpp_offsetof(Vehicle, current_order) + cpp_offsetof(Order, refit_subtype), SLE_UINT8, 36, SL_MAX_VERSION),
/* Timetable in current order */
SLE_CONDVARX(cpp_offsetof(Vehicle, current_order) + cpp_offsetof(Order, wait_time), SLE_UINT16, 67, SL_MAX_VERSION),
SLE_CONDVARX(cpp_offsetof(Vehicle, current_order) + cpp_offsetof(Order, travel_time), SLE_UINT16, 67, SL_MAX_VERSION),
SLE_CONDREF(Vehicle, orders, REF_ORDER, 0, 104),
SLE_CONDREF(Vehicle, orders, REF_ORDERLIST, 105, SL_MAX_VERSION),
SLE_CONDVAR(Vehicle, age, SLE_FILE_U16 | SLE_VAR_I32, 0, 30),
SLE_CONDVAR(Vehicle, age, SLE_INT32, 31, SL_MAX_VERSION),
SLE_CONDVAR(Vehicle, max_age, SLE_FILE_U16 | SLE_VAR_I32, 0, 30),
SLE_CONDVAR(Vehicle, max_age, SLE_INT32, 31, SL_MAX_VERSION),
SLE_CONDVAR(Vehicle, date_of_last_service, SLE_FILE_U16 | SLE_VAR_I32, 0, 30),
SLE_CONDVAR(Vehicle, date_of_last_service, SLE_INT32, 31, SL_MAX_VERSION),
SLE_CONDVAR(Vehicle, service_interval, SLE_FILE_U16 | SLE_VAR_I32, 0, 30),
SLE_CONDVAR(Vehicle, service_interval, SLE_INT32, 31, SL_MAX_VERSION),
SLE_VAR(Vehicle, reliability, SLE_UINT16),
SLE_VAR(Vehicle, reliability_spd_dec, SLE_UINT16),
SLE_VAR(Vehicle, breakdown_ctr, SLE_UINT8),
SLE_VAR(Vehicle, breakdown_delay, SLE_UINT8),
SLE_VAR(Vehicle, breakdowns_since_last_service, SLE_UINT8),
SLE_VAR(Vehicle, breakdown_chance, SLE_UINT8),
SLE_CONDVAR(Vehicle, build_year, SLE_FILE_U8 | SLE_VAR_I32, 0, 30),
SLE_CONDVAR(Vehicle, build_year, SLE_INT32, 31, SL_MAX_VERSION),
SLE_VAR(Vehicle, load_unload_time_rem, SLE_UINT16),
SLEG_CONDVAR( _cargo_paid_for, SLE_UINT16, 45, SL_MAX_VERSION),
SLE_CONDVAR(Vehicle, vehicle_flags, SLE_UINT8, 40, SL_MAX_VERSION),
SLE_CONDVAR(Vehicle, profit_this_year, SLE_FILE_I32 | SLE_VAR_I64, 0, 64),
SLE_CONDVAR(Vehicle, profit_this_year, SLE_INT64, 65, SL_MAX_VERSION),
SLE_CONDVAR(Vehicle, profit_last_year, SLE_FILE_I32 | SLE_VAR_I64, 0, 64),
SLE_CONDVAR(Vehicle, profit_last_year, SLE_INT64, 65, SL_MAX_VERSION),
SLEG_CONDVAR( _cargo_feeder_share, SLE_FILE_I32 | SLE_VAR_I64, 51, 64),
SLEG_CONDVAR( _cargo_feeder_share, SLE_INT64, 65, 67),
SLEG_CONDVAR( _cargo_loaded_at_xy, SLE_UINT32, 51, 67),
SLE_CONDVAR(Vehicle, value, SLE_FILE_I32 | SLE_VAR_I64, 0, 64),
SLE_CONDVAR(Vehicle, value, SLE_INT64, 65, SL_MAX_VERSION),
SLE_CONDVAR(Vehicle, random_bits, SLE_UINT8, 2, SL_MAX_VERSION),
SLE_CONDVAR(Vehicle, waiting_triggers, SLE_UINT8, 2, SL_MAX_VERSION),
SLE_CONDREF(Vehicle, next_shared, REF_VEHICLE, 2, SL_MAX_VERSION),
SLE_CONDNULL(2, 2, 68),
SLE_CONDNULL(4, 69, 100),
SLE_CONDVAR(Vehicle, group_id, SLE_UINT16, 60, SL_MAX_VERSION),
SLE_CONDVAR(Vehicle, current_order_time, SLE_UINT32, 67, SL_MAX_VERSION),
SLE_CONDVAR(Vehicle, lateness_counter, SLE_INT32, 67, SL_MAX_VERSION),
/* reserve extra space in savegame here. (currently 10 bytes) */
SLE_CONDNULL(10, 2, SL_MAX_VERSION),
SLE_END()
};
static const SaveLoad _train_desc[] = {
SLE_WRITEBYTE(Vehicle, type, VEH_TRAIN),
SLE_VEH_INCLUDEX(),
SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRail, crash_anim_pos), SLE_UINT16),
SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRail, force_proceed), SLE_UINT8),
SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRail, railtype), SLE_UINT8),
SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRail, track), SLE_UINT8),
SLE_CONDVARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRail, flags), SLE_FILE_U8 | SLE_VAR_U16, 2, 99),
SLE_CONDVARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRail, flags), SLE_UINT16, 100, SL_MAX_VERSION),
SLE_CONDNULL(2, 2, 59),
SLE_CONDNULL(2, 2, 19),
/* reserve extra space in savegame here. (currently 11 bytes) */
SLE_CONDNULL(11, 2, SL_MAX_VERSION),
SLE_END()
};
static const SaveLoad _roadveh_desc[] = {
SLE_WRITEBYTE(Vehicle, type, VEH_ROAD),
SLE_VEH_INCLUDEX(),
SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRoad, state), SLE_UINT8),
SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRoad, frame), SLE_UINT8),
SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRoad, blocked_ctr), SLE_UINT16),
SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRoad, overtaking), SLE_UINT8),
SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRoad, overtaking_ctr), SLE_UINT8),
SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRoad, crashed_ctr), SLE_UINT16),
SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRoad, reverse_ctr), SLE_UINT8),
SLE_CONDREFX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRoad, slot), REF_ROADSTOPS, 6, SL_MAX_VERSION),
SLE_CONDNULL(1, 6, SL_MAX_VERSION),
SLE_CONDVARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleRoad, slot_age), SLE_UINT8, 6, SL_MAX_VERSION),
/* reserve extra space in savegame here. (currently 16 bytes) */
SLE_CONDNULL(16, 2, SL_MAX_VERSION),
SLE_END()
};
static const SaveLoad _ship_desc[] = {
SLE_WRITEBYTE(Vehicle, type, VEH_SHIP),
SLE_VEH_INCLUDEX(),
SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleShip, state), SLE_UINT8),
/* reserve extra space in savegame here. (currently 16 bytes) */
SLE_CONDNULL(16, 2, SL_MAX_VERSION),
SLE_END()
};
static const SaveLoad _aircraft_desc[] = {
SLE_WRITEBYTE(Vehicle, type, VEH_AIRCRAFT),
SLE_VEH_INCLUDEX(),
SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleAir, crashed_counter), SLE_UINT16),
SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleAir, pos), SLE_UINT8),
SLE_CONDVARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleAir, targetairport), SLE_FILE_U8 | SLE_VAR_U16, 0, 4),
SLE_CONDVARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleAir, targetairport), SLE_UINT16, 5, SL_MAX_VERSION),
SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleAir, state), SLE_UINT8),
SLE_CONDVARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleAir, previous_pos), SLE_UINT8, 2, SL_MAX_VERSION),
/* reserve extra space in savegame here. (currently 15 bytes) */
SLE_CONDNULL(15, 2, SL_MAX_VERSION),
SLE_END()
};
static const SaveLoad _special_desc[] = {
SLE_WRITEBYTE(Vehicle, type, VEH_EFFECT),
SLE_VAR(Vehicle, subtype, SLE_UINT8),
SLE_CONDVAR(Vehicle, tile, SLE_FILE_U16 | SLE_VAR_U32, 0, 5),
SLE_CONDVAR(Vehicle, tile, SLE_UINT32, 6, SL_MAX_VERSION),
SLE_CONDVAR(Vehicle, x_pos, SLE_FILE_I16 | SLE_VAR_I32, 0, 5),
SLE_CONDVAR(Vehicle, x_pos, SLE_INT32, 6, SL_MAX_VERSION),
SLE_CONDVAR(Vehicle, y_pos, SLE_FILE_I16 | SLE_VAR_I32, 0, 5),
SLE_CONDVAR(Vehicle, y_pos, SLE_INT32, 6, SL_MAX_VERSION),
SLE_VAR(Vehicle, z_pos, SLE_UINT8),
SLE_VAR(Vehicle, cur_image, SLE_UINT16),
SLE_CONDNULL(5, 0, 57),
SLE_VAR(Vehicle, progress, SLE_UINT8),
SLE_VAR(Vehicle, vehstatus, SLE_UINT8),
SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleEffect, animation_state), SLE_UINT16),
SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleEffect, animation_substate), SLE_UINT8),
SLE_CONDVAR(Vehicle, spritenum, SLE_UINT8, 2, SL_MAX_VERSION),
/* reserve extra space in savegame here. (currently 15 bytes) */
SLE_CONDNULL(15, 2, SL_MAX_VERSION),
SLE_END()
};
static const SaveLoad _disaster_desc[] = {
SLE_WRITEBYTE(Vehicle, type, VEH_DISASTER),
SLE_REF(Vehicle, next, REF_VEHICLE_OLD),
SLE_VAR(Vehicle, subtype, SLE_UINT8),
SLE_CONDVAR(Vehicle, tile, SLE_FILE_U16 | SLE_VAR_U32, 0, 5),
SLE_CONDVAR(Vehicle, tile, SLE_UINT32, 6, SL_MAX_VERSION),
SLE_CONDVAR(Vehicle, dest_tile, SLE_FILE_U16 | SLE_VAR_U32, 0, 5),
SLE_CONDVAR(Vehicle, dest_tile, SLE_UINT32, 6, SL_MAX_VERSION),
SLE_CONDVAR(Vehicle, x_pos, SLE_FILE_I16 | SLE_VAR_I32, 0, 5),
SLE_CONDVAR(Vehicle, x_pos, SLE_INT32, 6, SL_MAX_VERSION),
SLE_CONDVAR(Vehicle, y_pos, SLE_FILE_I16 | SLE_VAR_I32, 0, 5),
SLE_CONDVAR(Vehicle, y_pos, SLE_INT32, 6, SL_MAX_VERSION),
SLE_VAR(Vehicle, z_pos, SLE_UINT8),
SLE_VAR(Vehicle, direction, SLE_UINT8),
SLE_CONDNULL(5, 0, 57),
SLE_VAR(Vehicle, owner, SLE_UINT8),
SLE_VAR(Vehicle, vehstatus, SLE_UINT8),
SLE_CONDVARX(cpp_offsetof(Vehicle, current_order) + cpp_offsetof(Order, dest), SLE_FILE_U8 | SLE_VAR_U16, 0, 4),
SLE_CONDVARX(cpp_offsetof(Vehicle, current_order) + cpp_offsetof(Order, dest), SLE_UINT16, 5, SL_MAX_VERSION),
SLE_VAR(Vehicle, cur_image, SLE_UINT16),
SLE_CONDVAR(Vehicle, age, SLE_FILE_U16 | SLE_VAR_I32, 0, 30),
SLE_CONDVAR(Vehicle, age, SLE_INT32, 31, SL_MAX_VERSION),
SLE_VAR(Vehicle, tick_counter, SLE_UINT8),
SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleDisaster, image_override), SLE_UINT16),
SLE_VARX(cpp_offsetof(Vehicle, u) + cpp_offsetof(VehicleDisaster, big_ufo_destroyer_target), SLE_UINT16),
/* reserve extra space in savegame here. (currently 16 bytes) */
SLE_CONDNULL(16, 2, SL_MAX_VERSION),
SLE_END()
};
static const SaveLoad *_veh_descs[] = {
_train_desc,
_roadveh_desc,
_ship_desc,
_aircraft_desc,
_special_desc,
_disaster_desc,
_common_veh_desc,
};
return _veh_descs[vt];
}
/** Will be called when the vehicles need to be saved. */
static void Save_VEHS()
{
Vehicle *v;
/* Write the vehicles */
FOR_ALL_VEHICLES(v) {
SlSetArrayIndex(v->index);
SlObject(v, GetVehicleDescription(v->type));
}
}
/** Will be called when vehicles need to be loaded. */
void Load_VEHS()
{
int index;
_cargo_count = 0;
while ((index = SlIterateArray()) != -1) {
Vehicle *v;
VehicleType vtype = (VehicleType)SlReadByte();
switch (vtype) {
case VEH_TRAIN: v = new (index) Train(); break;
case VEH_ROAD: v = new (index) RoadVehicle(); break;
case VEH_SHIP: v = new (index) Ship(); break;
case VEH_AIRCRAFT: v = new (index) Aircraft(); break;
case VEH_EFFECT: v = new (index) EffectVehicle(); break;
case VEH_DISASTER: v = new (index) DisasterVehicle(); break;
case VEH_INVALID: v = new (index) InvalidVehicle(); break;
default: NOT_REACHED();
}
SlObject(v, GetVehicleDescription(vtype));
if (_cargo_count != 0 && IsCompanyBuildableVehicleType(v)) {
/* Don't construct the packet with station here, because that'll fail with old savegames */
CargoPacket *cp = new CargoPacket();
cp->source = _cargo_source;
cp->source_xy = _cargo_source_xy;
cp->count = _cargo_count;
cp->days_in_transit = _cargo_days;
cp->feeder_share = _cargo_feeder_share;
cp->loaded_at_xy = _cargo_loaded_at_xy;
v->cargo.Append(cp);
}
/* Old savegames used 'last_station_visited = 0xFF' */
if (CheckSavegameVersion(5) && v->last_station_visited == 0xFF)
v->last_station_visited = INVALID_STATION;
if (CheckSavegameVersion(5)) {
/* Convert the current_order.type (which is a mix of type and flags, because
* in those versions, they both were 4 bits big) to type and flags */
v->current_order.flags = GB(v->current_order.type, 4, 4);
v->current_order.type &= 0x0F;
}
/* Advanced vehicle lists got added */
if (CheckSavegameVersion(60)) v->group_id = DEFAULT_GROUP;
}
}
extern const ChunkHandler _veh_chunk_handlers[] = {
{ 'VEHS', Save_VEHS, Load_VEHS, CH_SPARSE_ARRAY | CH_LAST},
};
| 30,339
|
C++
|
.cpp
| 604
| 45.81457
| 140
| 0.59276
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,236
|
waypoint_sl.cpp
|
EnergeticBark_OpenTTD-3DS/src/saveload/waypoint_sl.cpp
|
/* $Id$ */
/** @file waypoint_sl.cpp Code handling saving and loading of waypoints */
#include "../stdafx.h"
#include "../waypoint.h"
#include "../newgrf_station.h"
#include "../town.h"
#include "table/strings.h"
#include "saveload.h"
/**
* Update waypoint graphics id against saved GRFID/localidx.
* This is to ensure the chosen graphics are correct if GRF files are changed.
*/
void AfterLoadWaypoints()
{
Waypoint *wp;
FOR_ALL_WAYPOINTS(wp) {
uint i;
if (wp->grfid == 0) continue;
for (i = 0; i < GetNumCustomStations(STAT_CLASS_WAYP); i++) {
const StationSpec *statspec = GetCustomStationSpec(STAT_CLASS_WAYP, i);
if (statspec != NULL && statspec->grffile->grfid == wp->grfid && statspec->localidx == wp->localidx) {
wp->stat_id = i;
break;
}
}
}
}
/**
* Fix savegames which stored waypoints in their old format
*/
void FixOldWaypoints()
{
Waypoint *wp;
/* Convert the old 'town_or_string', to 'string' / 'town' / 'town_cn' */
FOR_ALL_WAYPOINTS(wp) {
wp->town_index = ClosestTownFromTile(wp->xy, UINT_MAX)->index;
wp->town_cn = 0;
if (wp->string & 0xC000) {
wp->town_cn = wp->string & 0x3F;
wp->string = STR_NULL;
}
}
}
static const SaveLoad _waypoint_desc[] = {
SLE_CONDVAR(Waypoint, xy, SLE_FILE_U16 | SLE_VAR_U32, 0, 5),
SLE_CONDVAR(Waypoint, xy, SLE_UINT32, 6, SL_MAX_VERSION),
SLE_CONDVAR(Waypoint, town_index, SLE_UINT16, 12, SL_MAX_VERSION),
SLE_CONDVAR(Waypoint, town_cn, SLE_FILE_U8 | SLE_VAR_U16, 12, 88),
SLE_CONDVAR(Waypoint, town_cn, SLE_UINT16, 89, SL_MAX_VERSION),
SLE_CONDVAR(Waypoint, string, SLE_STRINGID, 0, 83),
SLE_CONDSTR(Waypoint, name, SLE_STR, 0, 84, SL_MAX_VERSION),
SLE_VAR(Waypoint, deleted, SLE_UINT8),
SLE_CONDVAR(Waypoint, build_date, SLE_FILE_U16 | SLE_VAR_I32, 3, 30),
SLE_CONDVAR(Waypoint, build_date, SLE_INT32, 31, SL_MAX_VERSION),
SLE_CONDVAR(Waypoint, localidx, SLE_UINT8, 3, SL_MAX_VERSION),
SLE_CONDVAR(Waypoint, grfid, SLE_UINT32, 17, SL_MAX_VERSION),
SLE_CONDVAR(Waypoint, owner, SLE_UINT8, 101, SL_MAX_VERSION),
SLE_END()
};
static void Save_WAYP()
{
Waypoint *wp;
FOR_ALL_WAYPOINTS(wp) {
SlSetArrayIndex(wp->index);
SlObject(wp, _waypoint_desc);
}
}
static void Load_WAYP()
{
int index;
while ((index = SlIterateArray()) != -1) {
Waypoint *wp = new (index) Waypoint();
SlObject(wp, _waypoint_desc);
}
}
extern const ChunkHandler _waypoint_chunk_handlers[] = {
{ 'CHKP', Save_WAYP, Load_WAYP, CH_ARRAY | CH_LAST},
};
| 2,663
|
C++
|
.cpp
| 78
| 31.833333
| 105
| 0.63732
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,237
|
station_sl.cpp
|
EnergeticBark_OpenTTD-3DS/src/saveload/station_sl.cpp
|
/* $Id$ */
/** @file station_sl.cpp Code handling saving and loading of economy data */
#include "../stdafx.h"
#include "../station_base.h"
#include "../core/bitmath_func.hpp"
#include "../core/alloc_func.hpp"
#include "../variables.h"
#include "../newgrf_station.h"
#include "saveload.h"
void AfterLoadStations()
{
/* Update the speclists of all stations to point to the currently loaded custom stations. */
Station *st;
FOR_ALL_STATIONS(st) {
for (uint i = 0; i < st->num_specs; i++) {
if (st->speclist[i].grfid == 0) continue;
st->speclist[i].spec = GetCustomStationSpecByGrf(st->speclist[i].grfid, st->speclist[i].localidx, NULL);
}
for (CargoID c = 0; c < NUM_CARGO; c++) st->goods[c].cargo.InvalidateCache();
StationUpdateAnimTriggers(st);
}
}
static const SaveLoad _roadstop_desc[] = {
SLE_VAR(RoadStop, xy, SLE_UINT32),
SLE_CONDNULL(1, 0, 44),
SLE_VAR(RoadStop, status, SLE_UINT8),
/* Index was saved in some versions, but this is not needed */
SLE_CONDNULL(4, 0, 8),
SLE_CONDNULL(2, 0, 44),
SLE_CONDNULL(1, 0, 25),
SLE_REF(RoadStop, next, REF_ROADSTOPS),
SLE_CONDNULL(2, 0, 44),
SLE_CONDNULL(4, 0, 24),
SLE_CONDNULL(1, 25, 25),
SLE_END()
};
static const SaveLoad _station_desc[] = {
SLE_CONDVAR(Station, xy, SLE_FILE_U16 | SLE_VAR_U32, 0, 5),
SLE_CONDVAR(Station, xy, SLE_UINT32, 6, SL_MAX_VERSION),
SLE_CONDNULL(4, 0, 5), ///< bus/lorry tile
SLE_CONDVAR(Station, train_tile, SLE_FILE_U16 | SLE_VAR_U32, 0, 5),
SLE_CONDVAR(Station, train_tile, SLE_UINT32, 6, SL_MAX_VERSION),
SLE_CONDVAR(Station, airport_tile, SLE_FILE_U16 | SLE_VAR_U32, 0, 5),
SLE_CONDVAR(Station, airport_tile, SLE_UINT32, 6, SL_MAX_VERSION),
SLE_CONDVAR(Station, dock_tile, SLE_FILE_U16 | SLE_VAR_U32, 0, 5),
SLE_CONDVAR(Station, dock_tile, SLE_UINT32, 6, SL_MAX_VERSION),
SLE_REF(Station, town, REF_TOWN),
SLE_VAR(Station, trainst_w, SLE_UINT8),
SLE_CONDVAR(Station, trainst_h, SLE_UINT8, 2, SL_MAX_VERSION),
SLE_CONDNULL(1, 0, 3), ///< alpha_order
SLE_VAR(Station, string_id, SLE_STRINGID),
SLE_CONDSTR(Station, name, SLE_STR, 0, 84, SL_MAX_VERSION),
SLE_CONDVAR(Station, indtype, SLE_UINT8, 103, SL_MAX_VERSION),
SLE_VAR(Station, had_vehicle_of_type, SLE_UINT16),
SLE_VAR(Station, time_since_load, SLE_UINT8),
SLE_VAR(Station, time_since_unload, SLE_UINT8),
SLE_VAR(Station, delete_ctr, SLE_UINT8),
SLE_VAR(Station, owner, SLE_UINT8),
SLE_VAR(Station, facilities, SLE_UINT8),
SLE_VAR(Station, airport_type, SLE_UINT8),
SLE_CONDNULL(2, 0, 5), ///< Truck/bus stop status
SLE_CONDNULL(1, 0, 4), ///< Blocked months
SLE_CONDVAR(Station, airport_flags, SLE_VAR_U64 | SLE_FILE_U16, 0, 2),
SLE_CONDVAR(Station, airport_flags, SLE_VAR_U64 | SLE_FILE_U32, 3, 45),
SLE_CONDVAR(Station, airport_flags, SLE_UINT64, 46, SL_MAX_VERSION),
SLE_CONDNULL(2, 0, 25), ///< last-vehicle
SLE_CONDVAR(Station, last_vehicle_type, SLE_UINT8, 26, SL_MAX_VERSION),
SLE_CONDNULL(2, 3, 25), ///< custom station class and id
SLE_CONDVAR(Station, build_date, SLE_FILE_U16 | SLE_VAR_I32, 3, 30),
SLE_CONDVAR(Station, build_date, SLE_INT32, 31, SL_MAX_VERSION),
SLE_CONDREF(Station, bus_stops, REF_ROADSTOPS, 6, SL_MAX_VERSION),
SLE_CONDREF(Station, truck_stops, REF_ROADSTOPS, 6, SL_MAX_VERSION),
/* Used by newstations for graphic variations */
SLE_CONDVAR(Station, random_bits, SLE_UINT16, 27, SL_MAX_VERSION),
SLE_CONDVAR(Station, waiting_triggers, SLE_UINT8, 27, SL_MAX_VERSION),
SLE_CONDVAR(Station, num_specs, SLE_UINT8, 27, SL_MAX_VERSION),
SLE_CONDLST(Station, loading_vehicles, REF_VEHICLE, 57, SL_MAX_VERSION),
/* reserve extra space in savegame here. (currently 32 bytes) */
SLE_CONDNULL(32, 2, SL_MAX_VERSION),
SLE_END()
};
static uint16 _waiting_acceptance;
static uint16 _cargo_source;
static uint32 _cargo_source_xy;
static uint16 _cargo_days;
static Money _cargo_feeder_share;
static const SaveLoad _station_speclist_desc[] = {
SLE_CONDVAR(StationSpecList, grfid, SLE_UINT32, 27, SL_MAX_VERSION),
SLE_CONDVAR(StationSpecList, localidx, SLE_UINT8, 27, SL_MAX_VERSION),
SLE_END()
};
void SaveLoad_STNS(Station *st)
{
static const SaveLoad _goods_desc[] = {
SLEG_CONDVAR( _waiting_acceptance, SLE_UINT16, 0, 67),
SLE_CONDVAR(GoodsEntry, acceptance_pickup, SLE_UINT8, 68, SL_MAX_VERSION),
SLE_CONDNULL(2, 51, 67),
SLE_VAR(GoodsEntry, days_since_pickup, SLE_UINT8),
SLE_VAR(GoodsEntry, rating, SLE_UINT8),
SLEG_CONDVAR( _cargo_source, SLE_FILE_U8 | SLE_VAR_U16, 0, 6),
SLEG_CONDVAR( _cargo_source, SLE_UINT16, 7, 67),
SLEG_CONDVAR( _cargo_source_xy, SLE_UINT32, 44, 67),
SLEG_CONDVAR( _cargo_days, SLE_UINT8, 0, 67),
SLE_VAR(GoodsEntry, last_speed, SLE_UINT8),
SLE_VAR(GoodsEntry, last_age, SLE_UINT8),
SLEG_CONDVAR( _cargo_feeder_share, SLE_FILE_U32 | SLE_VAR_I64, 14, 64),
SLEG_CONDVAR( _cargo_feeder_share, SLE_INT64, 65, 67),
SLE_CONDLST(GoodsEntry, cargo.packets, REF_CARGO_PACKET, 68, SL_MAX_VERSION),
SLE_END()
};
SlObject(st, _station_desc);
_waiting_acceptance = 0;
uint num_cargo = CheckSavegameVersion(55) ? 12 : NUM_CARGO;
for (CargoID i = 0; i < num_cargo; i++) {
GoodsEntry *ge = &st->goods[i];
SlObject(ge, _goods_desc);
if (CheckSavegameVersion(68)) {
SB(ge->acceptance_pickup, GoodsEntry::ACCEPTANCE, 1, HasBit(_waiting_acceptance, 15));
if (GB(_waiting_acceptance, 0, 12) != 0) {
/* Don't construct the packet with station here, because that'll fail with old savegames */
CargoPacket *cp = new CargoPacket();
/* In old versions, enroute_from used 0xFF as INVALID_STATION */
cp->source = (CheckSavegameVersion(7) && _cargo_source == 0xFF) ? INVALID_STATION : _cargo_source;
cp->count = GB(_waiting_acceptance, 0, 12);
cp->days_in_transit = _cargo_days;
cp->feeder_share = _cargo_feeder_share;
cp->source_xy = _cargo_source_xy;
cp->days_in_transit = _cargo_days;
cp->feeder_share = _cargo_feeder_share;
SB(ge->acceptance_pickup, GoodsEntry::PICKUP, 1, 1);
ge->cargo.Append(cp);
}
}
}
if (st->num_specs != 0) {
/* Allocate speclist memory when loading a game */
if (st->speclist == NULL) st->speclist = CallocT<StationSpecList>(st->num_specs);
for (uint i = 0; i < st->num_specs; i++) {
SlObject(&st->speclist[i], _station_speclist_desc);
}
}
}
static void Save_STNS()
{
Station *st;
/* Write the stations */
FOR_ALL_STATIONS(st) {
SlSetArrayIndex(st->index);
SlAutolength((AutolengthProc*)SaveLoad_STNS, st);
}
}
static void Load_STNS()
{
int index;
while ((index = SlIterateArray()) != -1) {
Station *st = new (index) Station();
SaveLoad_STNS(st);
}
/* This is to ensure all pointers are within the limits of _stations_size */
if (_station_tick_ctr > GetMaxStationIndex()) _station_tick_ctr = 0;
}
static void Save_ROADSTOP()
{
RoadStop *rs;
FOR_ALL_ROADSTOPS(rs) {
SlSetArrayIndex(rs->index);
SlObject(rs, _roadstop_desc);
}
}
static void Load_ROADSTOP()
{
int index;
while ((index = SlIterateArray()) != -1) {
RoadStop *rs = new (index) RoadStop(INVALID_TILE);
SlObject(rs, _roadstop_desc);
}
}
extern const ChunkHandler _station_chunk_handlers[] = {
{ 'STNS', Save_STNS, Load_STNS, CH_ARRAY },
{ 'ROAD', Save_ROADSTOP, Load_ROADSTOP, CH_ARRAY | CH_LAST},
};
| 8,446
|
C++
|
.cpp
| 181
| 43.828729
| 111
| 0.59545
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,240
|
network_gamelist.cpp
|
EnergeticBark_OpenTTD-3DS/src/network/network_gamelist.cpp
|
/* $Id$ */
/**
* @file network_gamelist.cpp This file handles the GameList
* Also, it handles the request to a server for data about the server
*/
#ifdef ENABLE_NETWORK
#include "../stdafx.h"
#include "../debug.h"
#include "../core/alloc_func.hpp"
#include "../thread.h"
#include "../string_func.h"
#include "network_internal.h"
#include "network_udp.h"
#include "network_gamelist.h"
NetworkGameList *_network_game_list = NULL;
ThreadMutex *_network_game_list_mutex = ThreadMutex::New();
NetworkGameList *_network_game_delayed_insertion_list = NULL;
/** Add a new item to the linked gamelist, but do it delayed in the next tick
* or so to prevent race conditions.
* @param item the item to add. Will be freed once added.
*/
void NetworkGameListAddItemDelayed(NetworkGameList *item)
{
_network_game_list_mutex->BeginCritical();
item->next = _network_game_delayed_insertion_list;
_network_game_delayed_insertion_list = item;
_network_game_list_mutex->EndCritical();
}
/** Perform the delayed (thread safe) insertion into the game list */
static void NetworkGameListHandleDelayedInsert()
{
_network_game_list_mutex->BeginCritical();
while (_network_game_delayed_insertion_list != NULL) {
NetworkGameList *ins_item = _network_game_delayed_insertion_list;
_network_game_delayed_insertion_list = ins_item->next;
NetworkGameList *item = NetworkGameListAddItem(ins_item->ip, ins_item->port);
if (item != NULL) {
if (StrEmpty(item->info.server_name)) {
memset(&item->info, 0, sizeof(item->info));
strecpy(item->info.server_name, ins_item->info.server_name, lastof(item->info.server_name));
strecpy(item->info.hostname, ins_item->info.hostname, lastof(item->info.hostname));
item->online = false;
}
item->manually = ins_item->manually;
UpdateNetworkGameWindow(false);
}
free(ins_item);
}
_network_game_list_mutex->EndCritical();
}
/** Add a new item to the linked gamelist. If the IP and Port match
* return the existing item instead of adding it again
* @param ip the IP-address (inet_addr) of the to-be added item
* @param port the port the server is running on
* @return a point to the newly added or already existing item */
NetworkGameList *NetworkGameListAddItem(uint32 ip, uint16 port)
{
if (ip == 0) return NULL;
NetworkGameList *item, *prev_item;
prev_item = NULL;
for (item = _network_game_list; item != NULL; item = item->next) {
if (item->ip == ip && item->port == port) return item;
prev_item = item;
}
item = CallocT<NetworkGameList>(1);
item->next = NULL;
item->ip = ip;
item->port = port;
if (prev_item == NULL) {
_network_game_list = item;
} else {
prev_item->next = item;
}
DEBUG(net, 4, "[gamelist] added server to list");
UpdateNetworkGameWindow(false);
return item;
}
/** Remove an item from the gamelist linked list
* @param remove pointer to the item to be removed */
void NetworkGameListRemoveItem(NetworkGameList *remove)
{
NetworkGameList *item, *prev_item;
prev_item = NULL;
for (item = _network_game_list; item != NULL; item = item->next) {
if (remove == item) {
if (prev_item == NULL) {
_network_game_list = remove->next;
} else {
prev_item->next = remove->next;
}
/* Remove GRFConfig information */
ClearGRFConfigList(&remove->info.grfconfig);
free(remove);
remove = NULL;
DEBUG(net, 4, "[gamelist] removed server from list");
UpdateNetworkGameWindow(false);
return;
}
prev_item = item;
}
}
enum {
MAX_GAME_LIST_REQUERY_COUNT = 5, ///< How often do we requery in number of times per server?
REQUERY_EVERY_X_GAMELOOPS = 60, ///< How often do we requery in time?
REFRESH_GAMEINFO_X_REQUERIES = 50, ///< Refresh the game info itself after REFRESH_GAMEINFO_X_REQUERIES * REQUERY_EVERY_X_GAMELOOPS game loops
};
/** Requeries the (game) servers we have not gotten a reply from */
void NetworkGameListRequery()
{
NetworkGameListHandleDelayedInsert();
static uint8 requery_cnt = 0;
if (++requery_cnt < REQUERY_EVERY_X_GAMELOOPS) return;
requery_cnt = 0;
for (NetworkGameList *item = _network_game_list; item != NULL; item = item->next) {
item->retries++;
if (item->retries < REFRESH_GAMEINFO_X_REQUERIES && (item->online || item->retries >= MAX_GAME_LIST_REQUERY_COUNT)) continue;
/* item gets mostly zeroed by NetworkUDPQueryServer */
uint8 retries = item->retries;
NetworkUDPQueryServer(NetworkAddress(item->ip, item->port));
item->retries = (retries >= REFRESH_GAMEINFO_X_REQUERIES) ? 0 : retries;
}
}
#endif /* ENABLE_NETWORK */
| 4,529
|
C++
|
.cpp
| 123
| 34.373984
| 143
| 0.720027
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,241
|
network_udp.cpp
|
EnergeticBark_OpenTTD-3DS/src/network/network_udp.cpp
|
/* $Id$ */
/**
* @file network_udp.cpp This file handles the UDP related communication.
*
* This is the GameServer <-> MasterServer and GameServer <-> GameClient
* communication before the game is being joined.
*/
#ifdef ENABLE_NETWORK
#include "../stdafx.h"
#include "../date_func.h"
#include "../map_func.h"
#include "network_gamelist.h"
#include "network_internal.h"
#include "network_udp.h"
#include "core/host.h"
#include "../core/endian_func.hpp"
#include "../core/alloc_func.hpp"
#include "../string_func.h"
#include "../company_base.h"
#include "../settings_type.h"
#include "../thread.h"
#include "../rev.h"
#include "core/udp.h"
ThreadMutex *_network_udp_mutex = ThreadMutex::New();
enum {
ADVERTISE_NORMAL_INTERVAL = 30000, // interval between advertising in ticks (15 minutes)
ADVERTISE_RETRY_INTERVAL = 300, // readvertise when no response after this many ticks (9 seconds)
ADVERTISE_RETRY_TIMES = 3 // give up readvertising after this much failed retries
};
NetworkUDPSocketHandler *_udp_client_socket = NULL; ///< udp client socket
NetworkUDPSocketHandler *_udp_server_socket = NULL; ///< udp server socket
NetworkUDPSocketHandler *_udp_master_socket = NULL; ///< udp master socket
///*** Communication with the masterserver ***/
class MasterNetworkUDPSocketHandler : public NetworkUDPSocketHandler {
protected:
DECLARE_UDP_RECEIVE_COMMAND(PACKET_UDP_MASTER_ACK_REGISTER);
public:
virtual ~MasterNetworkUDPSocketHandler() {}
};
DEF_UDP_RECEIVE_COMMAND(Master, PACKET_UDP_MASTER_ACK_REGISTER)
{
_network_advertise_retries = 0;
DEBUG(net, 2, "[udp] advertising on master server successful");
/* We are advertised, but we don't want to! */
if (!_settings_client.network.server_advertise) NetworkUDPRemoveAdvertise();
}
///*** Communication with clients (we are server) ***/
class ServerNetworkUDPSocketHandler : public NetworkUDPSocketHandler {
protected:
DECLARE_UDP_RECEIVE_COMMAND(PACKET_UDP_CLIENT_FIND_SERVER);
DECLARE_UDP_RECEIVE_COMMAND(PACKET_UDP_CLIENT_DETAIL_INFO);
DECLARE_UDP_RECEIVE_COMMAND(PACKET_UDP_CLIENT_GET_NEWGRFS);
public:
virtual ~ServerNetworkUDPSocketHandler() {}
};
DEF_UDP_RECEIVE_COMMAND(Server, PACKET_UDP_CLIENT_FIND_SERVER)
{
/* Just a fail-safe.. should never happen */
if (!_network_udp_server) {
return;
}
NetworkGameInfo ngi;
/* Update some game_info */
ngi.clients_on = _network_game_info.clients_on;
ngi.start_date = _network_game_info.start_date;
ngi.server_lang = _settings_client.network.server_lang;
ngi.use_password = !StrEmpty(_settings_client.network.server_password);
ngi.clients_max = _settings_client.network.max_clients;
ngi.companies_on = ActiveCompanyCount();
ngi.companies_max = _settings_client.network.max_companies;
ngi.spectators_on = NetworkSpectatorCount();
ngi.spectators_max = _settings_client.network.max_spectators;
ngi.game_date = _date;
ngi.map_width = MapSizeX();
ngi.map_height = MapSizeY();
ngi.map_set = _settings_game.game_creation.landscape;
ngi.dedicated = _network_dedicated;
ngi.grfconfig = _grfconfig;
strecpy(ngi.map_name, _network_game_info.map_name, lastof(ngi.map_name));
strecpy(ngi.server_name, _settings_client.network.server_name, lastof(ngi.server_name));
strecpy(ngi.server_revision, _openttd_revision, lastof(ngi.server_revision));
Packet packet(PACKET_UDP_SERVER_RESPONSE);
this->Send_NetworkGameInfo(&packet, &ngi);
/* Let the client know that we are here */
this->SendPacket(&packet, client_addr);
DEBUG(net, 2, "[udp] queried from '%s'", inet_ntoa(client_addr->sin_addr));
}
DEF_UDP_RECEIVE_COMMAND(Server, PACKET_UDP_CLIENT_DETAIL_INFO)
{
/* Just a fail-safe.. should never happen */
if (!_network_udp_server) return;
Packet packet(PACKET_UDP_SERVER_DETAIL_INFO);
/* Send the amount of active companies */
packet.Send_uint8 (NETWORK_COMPANY_INFO_VERSION);
packet.Send_uint8 (ActiveCompanyCount());
/* Fetch the latest version of the stats */
NetworkCompanyStats company_stats[MAX_COMPANIES];
NetworkPopulateCompanyStats(company_stats);
Company *company;
/* Go through all the companies */
FOR_ALL_COMPANIES(company) {
/* Send the information */
this->Send_CompanyInformation(&packet, company, &company_stats[company->index]);
}
this->SendPacket(&packet, client_addr);
}
/**
* A client has requested the names of some NewGRFs.
*
* Replying this can be tricky as we have a limit of SEND_MTU bytes
* in the reply packet and we can send up to 100 bytes per NewGRF
* (GRF ID, MD5sum and NETWORK_GRF_NAME_LENGTH bytes for the name).
* As SEND_MTU is _much_ less than 100 * NETWORK_MAX_GRF_COUNT, it
* could be that a packet overflows. To stop this we only reply
* with the first N NewGRFs so that if the first N + 1 NewGRFs
* would be sent, the packet overflows.
* in_reply and in_reply_count are used to keep a list of GRFs to
* send in the reply.
*/
DEF_UDP_RECEIVE_COMMAND(Server, PACKET_UDP_CLIENT_GET_NEWGRFS)
{
uint8 num_grfs;
uint i;
const GRFConfig *in_reply[NETWORK_MAX_GRF_COUNT];
uint8 in_reply_count = 0;
size_t packet_len = 0;
DEBUG(net, 6, "[udp] newgrf data request from %s:%d", inet_ntoa(client_addr->sin_addr), ntohs(client_addr->sin_port));
num_grfs = p->Recv_uint8 ();
if (num_grfs > NETWORK_MAX_GRF_COUNT) return;
for (i = 0; i < num_grfs; i++) {
GRFConfig c;
const GRFConfig *f;
this->Recv_GRFIdentifier(p, &c);
/* Find the matching GRF file */
f = FindGRFConfig(c.grfid, c.md5sum);
if (f == NULL) continue; // The GRF is unknown to this server
/* If the reply might exceed the size of the packet, only reply
* the current list and do not send the other data.
* The name could be an empty string, if so take the filename. */
packet_len += sizeof(c.grfid) + sizeof(c.md5sum) +
min(strlen((f->name != NULL && !StrEmpty(f->name)) ? f->name : f->filename) + 1, (size_t)NETWORK_GRF_NAME_LENGTH);
if (packet_len > SEND_MTU - 4) { // 4 is 3 byte header + grf count in reply
break;
}
in_reply[in_reply_count] = f;
in_reply_count++;
}
if (in_reply_count == 0) return;
Packet packet(PACKET_UDP_SERVER_NEWGRFS);
packet.Send_uint8(in_reply_count);
for (i = 0; i < in_reply_count; i++) {
char name[NETWORK_GRF_NAME_LENGTH];
/* The name could be an empty string, if so take the filename */
strecpy(name, (in_reply[i]->name != NULL && !StrEmpty(in_reply[i]->name)) ?
in_reply[i]->name : in_reply[i]->filename, lastof(name));
this->Send_GRFIdentifier(&packet, in_reply[i]);
packet.Send_string(name);
}
this->SendPacket(&packet, client_addr);
}
///*** Communication with servers (we are client) ***/
class ClientNetworkUDPSocketHandler : public NetworkUDPSocketHandler {
protected:
DECLARE_UDP_RECEIVE_COMMAND(PACKET_UDP_SERVER_RESPONSE);
DECLARE_UDP_RECEIVE_COMMAND(PACKET_UDP_MASTER_RESPONSE_LIST);
DECLARE_UDP_RECEIVE_COMMAND(PACKET_UDP_SERVER_NEWGRFS);
virtual void HandleIncomingNetworkGameInfoGRFConfig(GRFConfig *config);
public:
virtual ~ClientNetworkUDPSocketHandler() {}
};
DEF_UDP_RECEIVE_COMMAND(Client, PACKET_UDP_SERVER_RESPONSE)
{
NetworkGameList *item;
/* Just a fail-safe.. should never happen */
if (_network_udp_server) return;
DEBUG(net, 4, "[udp] server response from %s:%d", inet_ntoa(client_addr->sin_addr), ntohs(client_addr->sin_port));
/* Find next item */
item = NetworkGameListAddItem(inet_addr(inet_ntoa(client_addr->sin_addr)), ntohs(client_addr->sin_port));
this->Recv_NetworkGameInfo(p, &item->info);
item->info.compatible = true;
{
/* Checks whether there needs to be a request for names of GRFs and makes
* the request if necessary. GRFs that need to be requested are the GRFs
* that do not exist on the clients system and we do not have the name
* resolved of, i.e. the name is still UNKNOWN_GRF_NAME_PLACEHOLDER.
* The in_request array and in_request_count are used so there is no need
* to do a second loop over the GRF list, which can be relatively expensive
* due to the string comparisons. */
const GRFConfig *in_request[NETWORK_MAX_GRF_COUNT];
const GRFConfig *c;
uint in_request_count = 0;
struct sockaddr_in out_addr;
for (c = item->info.grfconfig; c != NULL; c = c->next) {
if (c->status == GCS_NOT_FOUND) item->info.compatible = false;
if (c->status != GCS_NOT_FOUND || strcmp(c->name, UNKNOWN_GRF_NAME_PLACEHOLDER) != 0) continue;
in_request[in_request_count] = c;
in_request_count++;
}
if (in_request_count > 0) {
/* There are 'unknown' GRFs, now send a request for them */
uint i;
Packet packet(PACKET_UDP_CLIENT_GET_NEWGRFS);
packet.Send_uint8(in_request_count);
for (i = 0; i < in_request_count; i++) {
this->Send_GRFIdentifier(&packet, in_request[i]);
}
out_addr.sin_family = AF_INET;
out_addr.sin_port = htons(item->port);
out_addr.sin_addr.s_addr = item->ip;
this->SendPacket(&packet, &out_addr);
}
}
if (item->info.hostname[0] == '\0')
snprintf(item->info.hostname, sizeof(item->info.hostname), "%s", inet_ntoa(client_addr->sin_addr));
/* Check if we are allowed on this server based on the revision-match */
item->info.version_compatible = IsNetworkCompatibleVersion(item->info.server_revision);
item->info.compatible &= item->info.version_compatible; // Already contains match for GRFs
item->online = true;
UpdateNetworkGameWindow(false);
}
DEF_UDP_RECEIVE_COMMAND(Client, PACKET_UDP_MASTER_RESPONSE_LIST)
{
/* packet begins with the protocol version (uint8)
* then an uint16 which indicates how many
* ip:port pairs are in this packet, after that
* an uint32 (ip) and an uint16 (port) for each pair
*/
uint8 ver = p->Recv_uint8();
if (ver == 1) {
for (int i = p->Recv_uint16(); i != 0 ; i--) {
uint32 ip = TO_LE32(p->Recv_uint32());
uint16 port = p->Recv_uint16();
/* Somehow we reached the end of the packet */
if (this->HasClientQuit()) return;
NetworkUDPQueryServer(NetworkAddress(ip, port));
}
}
}
/** The return of the client's request of the names of some NewGRFs */
DEF_UDP_RECEIVE_COMMAND(Client, PACKET_UDP_SERVER_NEWGRFS)
{
uint8 num_grfs;
uint i;
DEBUG(net, 6, "[udp] newgrf data reply from %s:%d", inet_ntoa(client_addr->sin_addr), ntohs(client_addr->sin_port));
num_grfs = p->Recv_uint8 ();
if (num_grfs > NETWORK_MAX_GRF_COUNT) return;
for (i = 0; i < num_grfs; i++) {
char *unknown_name;
char name[NETWORK_GRF_NAME_LENGTH];
GRFConfig c;
this->Recv_GRFIdentifier(p, &c);
p->Recv_string(name, sizeof(name));
/* An empty name is not possible under normal circumstances
* and causes problems when showing the NewGRF list. */
if (StrEmpty(name)) continue;
/* Finds the fake GRFConfig for the just read GRF ID and MD5sum tuple.
* If it exists and not resolved yet, then name of the fake GRF is
* overwritten with the name from the reply. */
unknown_name = FindUnknownGRFName(c.grfid, c.md5sum, false);
if (unknown_name != NULL && strcmp(unknown_name, UNKNOWN_GRF_NAME_PLACEHOLDER) == 0) {
ttd_strlcpy(unknown_name, name, NETWORK_GRF_NAME_LENGTH);
}
}
}
void ClientNetworkUDPSocketHandler::HandleIncomingNetworkGameInfoGRFConfig(GRFConfig *config)
{
/* Find the matching GRF file */
const GRFConfig *f = FindGRFConfig(config->grfid, config->md5sum);
if (f == NULL) {
/* Don't know the GRF, so mark game incompatible and the (possibly)
* already resolved name for this GRF (another server has sent the
* name of the GRF already */
config->name = FindUnknownGRFName(config->grfid, config->md5sum, true);
config->status = GCS_NOT_FOUND;
} else {
config->filename = f->filename;
config->name = f->name;
config->info = f->info;
}
SetBit(config->flags, GCF_COPY);
}
/* Close UDP connection */
void NetworkUDPCloseAll()
{
DEBUG(net, 1, "[udp] closed listeners");
_network_udp_mutex->BeginCritical();
_udp_server_socket->Close();
_udp_master_socket->Close();
_udp_client_socket->Close();
_network_udp_mutex->EndCritical();
_network_udp_server = false;
_network_udp_broadcast = 0;
}
/* Broadcast to all ips */
static void NetworkUDPBroadCast(NetworkUDPSocketHandler *socket)
{
uint i;
for (i = 0; _broadcast_list[i] != 0; i++) {
Packet p(PACKET_UDP_CLIENT_FIND_SERVER);
struct sockaddr_in out_addr;
out_addr.sin_family = AF_INET;
out_addr.sin_port = htons(_settings_client.network.server_port);
out_addr.sin_addr.s_addr = _broadcast_list[i];
DEBUG(net, 4, "[udp] broadcasting to %s", inet_ntoa(out_addr.sin_addr));
socket->SendPacket(&p, &out_addr);
}
}
/* Request the the server-list from the master server */
void NetworkUDPQueryMasterServer()
{
struct sockaddr_in out_addr;
if (!_udp_client_socket->IsConnected()) {
if (!_udp_client_socket->Listen(0, 0, true)) return;
}
Packet p(PACKET_UDP_CLIENT_GET_LIST);
out_addr.sin_family = AF_INET;
out_addr.sin_port = htons(NETWORK_MASTER_SERVER_PORT);
out_addr.sin_addr.s_addr = NetworkResolveHost(NETWORK_MASTER_SERVER_HOST);
/* packet only contains protocol version */
p.Send_uint8(NETWORK_MASTER_SERVER_VERSION);
_udp_client_socket->SendPacket(&p, &out_addr);
DEBUG(net, 2, "[udp] master server queried at %s:%d", inet_ntoa(out_addr.sin_addr), ntohs(out_addr.sin_port));
}
/* Find all servers */
void NetworkUDPSearchGame()
{
/* We are still searching.. */
if (_network_udp_broadcast > 0) return;
/* No UDP-socket yet.. */
if (!_udp_client_socket->IsConnected()) {
if (!_udp_client_socket->Listen(0, 0, true)) return;
}
DEBUG(net, 0, "[udp] searching server");
NetworkUDPBroadCast(_udp_client_socket);
_network_udp_broadcast = 300; // Stay searching for 300 ticks
}
/** Simpler wrapper struct for NetworkUDPQueryServerThread */
struct NetworkUDPQueryServerInfo : NetworkAddress {
bool manually; ///< Did we connect manually or not?
NetworkUDPQueryServerInfo(const NetworkAddress &address, bool manually) :
NetworkAddress(address),
manually(manually)
{
}
};
/**
* Threaded part for resolving the IP of a server and querying it.
* @param pntr the NetworkUDPQueryServerInfo.
*/
void NetworkUDPQueryServerThread(void *pntr)
{
NetworkUDPQueryServerInfo *info = (NetworkUDPQueryServerInfo*)pntr;
struct sockaddr_in out_addr;
out_addr.sin_family = AF_INET;
out_addr.sin_port = htons(info->GetPort());
out_addr.sin_addr.s_addr = info->GetIP();
/* Clear item in gamelist */
NetworkGameList *item = CallocT<NetworkGameList>(1);
item->ip = info->GetIP();
item->port = info->GetPort();
strecpy(item->info.server_name, info->GetHostname(), lastof(item->info.server_name));
strecpy(item->info.hostname, info->GetHostname(), lastof(item->info.hostname));
item->manually = info->manually;
NetworkGameListAddItemDelayed(item);
_network_udp_mutex->BeginCritical();
/* Init the packet */
Packet p(PACKET_UDP_CLIENT_FIND_SERVER);
if (_udp_client_socket != NULL) _udp_client_socket->SendPacket(&p, &out_addr);
_network_udp_mutex->EndCritical();
delete info;
}
void NetworkUDPQueryServer(NetworkAddress address, bool manually)
{
/* No UDP-socket yet.. */
if (!_udp_client_socket->IsConnected()) {
if (!_udp_client_socket->Listen(0, 0, true)) return;
}
NetworkUDPQueryServerInfo *info = new NetworkUDPQueryServerInfo(address, manually);
if (address.IsResolved() || !ThreadObject::New(NetworkUDPQueryServerThread, info)) {
NetworkUDPQueryServerThread(info);
}
}
void NetworkUDPRemoveAdvertiseThread(void *pntr)
{
DEBUG(net, 1, "[udp] removing advertise from master server");
/* Find somewhere to send */
struct sockaddr_in out_addr;
out_addr.sin_family = AF_INET;
out_addr.sin_port = htons(NETWORK_MASTER_SERVER_PORT);
out_addr.sin_addr.s_addr = NetworkResolveHost(NETWORK_MASTER_SERVER_HOST);
/* Send the packet */
Packet p(PACKET_UDP_SERVER_UNREGISTER);
/* Packet is: Version, server_port */
p.Send_uint8 (NETWORK_MASTER_SERVER_VERSION);
p.Send_uint16(_settings_client.network.server_port);
_network_udp_mutex->BeginCritical();
if (_udp_master_socket != NULL) _udp_master_socket->SendPacket(&p, &out_addr);
_network_udp_mutex->EndCritical();
}
/* Remove our advertise from the master-server */
void NetworkUDPRemoveAdvertise()
{
/* Check if we are advertising */
if (!_networking || !_network_server || !_network_udp_server) return;
/* check for socket */
if (!_udp_master_socket->IsConnected()) {
if (!_udp_master_socket->Listen(_network_server_bind_ip, 0, false)) return;
}
if (!ThreadObject::New(NetworkUDPRemoveAdvertiseThread, NULL)) {
NetworkUDPRemoveAdvertiseThread(NULL);
}
}
void NetworkUDPAdvertiseThread(void *pntr)
{
/* Find somewhere to send */
struct sockaddr_in out_addr;
out_addr.sin_family = AF_INET;
out_addr.sin_port = htons(NETWORK_MASTER_SERVER_PORT);
out_addr.sin_addr.s_addr = NetworkResolveHost(NETWORK_MASTER_SERVER_HOST);
DEBUG(net, 1, "[udp] advertising to master server");
/* Send the packet */
Packet p(PACKET_UDP_SERVER_REGISTER);
/* Packet is: WELCOME_MESSAGE, Version, server_port */
p.Send_string(NETWORK_MASTER_SERVER_WELCOME_MESSAGE);
p.Send_uint8 (NETWORK_MASTER_SERVER_VERSION);
p.Send_uint16(_settings_client.network.server_port);
_network_udp_mutex->BeginCritical();
if (_udp_master_socket != NULL) _udp_master_socket->SendPacket(&p, &out_addr);
_network_udp_mutex->EndCritical();
}
/* Register us to the master server
This function checks if it needs to send an advertise */
void NetworkUDPAdvertise()
{
/* Check if we should send an advertise */
if (!_networking || !_network_server || !_network_udp_server || !_settings_client.network.server_advertise)
return;
/* check for socket */
if (!_udp_master_socket->IsConnected()) {
if (!_udp_master_socket->Listen(_network_server_bind_ip, 0, false)) return;
}
if (_network_need_advertise) {
_network_need_advertise = false;
_network_advertise_retries = ADVERTISE_RETRY_TIMES;
} else {
/* Only send once every ADVERTISE_NORMAL_INTERVAL ticks */
if (_network_advertise_retries == 0) {
if ((_network_last_advertise_frame + ADVERTISE_NORMAL_INTERVAL) > _frame_counter)
return;
_network_advertise_retries = ADVERTISE_RETRY_TIMES;
}
if ((_network_last_advertise_frame + ADVERTISE_RETRY_INTERVAL) > _frame_counter)
return;
}
_network_advertise_retries--;
_network_last_advertise_frame = _frame_counter;
if (!ThreadObject::New(NetworkUDPAdvertiseThread, NULL)) {
NetworkUDPAdvertiseThread(NULL);
}
}
void NetworkUDPInitialize()
{
assert(_udp_client_socket == NULL && _udp_server_socket == NULL && _udp_master_socket == NULL);
_network_udp_mutex->BeginCritical();
_udp_client_socket = new ClientNetworkUDPSocketHandler();
_udp_server_socket = new ServerNetworkUDPSocketHandler();
_udp_master_socket = new MasterNetworkUDPSocketHandler();
_network_udp_server = false;
_network_udp_broadcast = 0;
_network_udp_mutex->EndCritical();
}
void NetworkUDPShutdown()
{
NetworkUDPCloseAll();
_network_udp_mutex->BeginCritical();
delete _udp_client_socket;
delete _udp_server_socket;
delete _udp_master_socket;
_udp_client_socket = NULL;
_udp_server_socket = NULL;
_udp_master_socket = NULL;
_network_udp_mutex->EndCritical();
}
#endif /* ENABLE_NETWORK */
| 19,149
|
C++
|
.cpp
| 484
| 37.206612
| 119
| 0.727126
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,242
|
network.cpp
|
EnergeticBark_OpenTTD-3DS/src/network/network.cpp
|
/* $Id$ */
/** @file network.cpp Base functions for networking support. */
#include "../stdafx.h"
#include "../company_type.h"
#ifdef ENABLE_NETWORK
#include "../openttd.h"
#include "../strings_func.h"
#include "../command_func.h"
#include "../variables.h"
#include "../date_func.h"
#include "network_internal.h"
#include "network_client.h"
#include "network_server.h"
#include "network_content.h"
#include "network_udp.h"
#include "network_gamelist.h"
#include "core/udp.h"
#include "core/host.h"
#include "network_gui.h"
#include "../console_func.h"
#include "../md5.h"
#include "../core/random_func.hpp"
#include "../window_func.h"
#include "../string_func.h"
#include "../company_func.h"
#include "../company_base.h"
#include "../settings_type.h"
#include "../landscape_type.h"
#include "../rev.h"
#include "../core/alloc_func.hpp"
#ifdef DEBUG_DUMP_COMMANDS
#include "../fileio_func.h"
#endif /* DEBUG_DUMP_COMMANDS */
#include "table/strings.h"
#include "../oldpool_func.h"
DECLARE_POSTFIX_INCREMENT(ClientID);
typedef ClientIndex NetworkClientInfoID;
DEFINE_OLD_POOL_GENERIC(NetworkClientInfo, NetworkClientInfo);
bool _networking; ///< are we in networking mode?
bool _network_server; ///< network-server is active
bool _network_available; ///< is network mode available?
bool _network_dedicated; ///< are we a dedicated server?
bool _is_network_server; ///< Does this client wants to be a network-server?
NetworkServerGameInfo _network_game_info;
NetworkCompanyState *_network_company_states = NULL;
ClientID _network_own_client_id;
ClientID _redirect_console_to_client;
bool _network_need_advertise;
uint32 _network_last_advertise_frame;
uint8 _network_reconnect;
char *_network_host_list[10];
char *_network_ban_list[25];
uint32 _frame_counter_server; // The frame_counter of the server, if in network-mode
uint32 _frame_counter_max; // To where we may go with our clients
uint32 _frame_counter;
uint32 _last_sync_frame; // Used in the server to store the last time a sync packet was sent to clients.
uint32 _broadcast_list[MAX_INTERFACES + 1];
uint32 _network_server_bind_ip;
uint32 _sync_seed_1, _sync_seed_2;
uint32 _sync_frame;
bool _network_first_time;
bool _network_udp_server;
uint16 _network_udp_broadcast;
uint8 _network_advertise_retries;
CompanyMask _network_company_passworded; ///< Bitmask of the password status of all companies.
/* Check whether NETWORK_NUM_LANDSCAPES is still in sync with NUM_LANDSCAPE */
assert_compile((int)NETWORK_NUM_LANDSCAPES == (int)NUM_LANDSCAPE);
assert_compile((int)NETWORK_COMPANY_NAME_LENGTH == MAX_LENGTH_COMPANY_NAME_BYTES);
extern NetworkUDPSocketHandler *_udp_client_socket; ///< udp client socket
extern NetworkUDPSocketHandler *_udp_server_socket; ///< udp server socket
extern NetworkUDPSocketHandler *_udp_master_socket; ///< udp master socket
/* The listen socket for the server */
static SOCKET _listensocket;
/* The amount of clients connected */
static byte _network_clients_connected = 0;
/* The identifier counter for new clients (is never decreased) */
static ClientID _network_client_id = CLIENT_ID_FIRST;
/* Some externs / forwards */
extern void StateGameLoop();
/**
* Return the CI given it's raw index
* @param index the index to search for
* @return return a pointer to the corresponding NetworkClientInfo struct
*/
NetworkClientInfo *NetworkFindClientInfoFromIndex(ClientIndex index)
{
return IsValidNetworkClientInfoIndex(index) ? GetNetworkClientInfo(index) : NULL;
}
/**
* Return the CI given it's client-identifier
* @param client_id the ClientID to search for
* @return return a pointer to the corresponding NetworkClientInfo struct or NULL when not found
*/
NetworkClientInfo *NetworkFindClientInfoFromClientID(ClientID client_id)
{
NetworkClientInfo *ci;
FOR_ALL_CLIENT_INFOS(ci) {
if (ci->client_id == client_id) return ci;
}
return NULL;
}
/**
* Return the CI for a given IP
* @param ip IP of the client we are looking for. This must be in string-format
* @return return a pointer to the corresponding NetworkClientInfo struct or NULL when not found
*/
NetworkClientInfo *NetworkFindClientInfoFromIP(const char *ip)
{
NetworkClientInfo *ci;
uint32 ip_number = inet_addr(ip);
FOR_ALL_CLIENT_INFOS(ci) {
if (ci->client_ip == ip_number) return ci;
}
return NULL;
}
/**
* Return the client state given it's client-identifier
* @param client_id the ClientID to search for
* @return return a pointer to the corresponding NetworkClientSocket struct or NULL when not found
*/
NetworkClientSocket *NetworkFindClientStateFromClientID(ClientID client_id)
{
NetworkClientSocket *cs;
FOR_ALL_CLIENT_SOCKETS(cs) {
if (cs->client_id == client_id) return cs;
}
return NULL;
}
/* NetworkGetClientName is a server-safe function to get the name of the client
* if the user did not send it yet, Client #<no> is used. */
void NetworkGetClientName(char *client_name, size_t size, const NetworkClientSocket *cs)
{
const NetworkClientInfo *ci = cs->GetInfo();
if (StrEmpty(ci->client_name)) {
snprintf(client_name, size, "Client #%4d", cs->client_id);
} else {
ttd_strlcpy(client_name, ci->client_name, size);
}
}
byte NetworkSpectatorCount()
{
const NetworkClientInfo *ci;
byte count = 0;
FOR_ALL_CLIENT_INFOS(ci) {
if (ci->client_playas == COMPANY_SPECTATOR) count++;
}
/* Don't count a dedicated server as spectator */
if (_network_dedicated) count--;
return count;
}
/**
* Check if the company we want to join requires a password.
* @param company_id id of the company we want to check the 'passworded' flag for.
* @return true if the company requires a password.
*/
bool NetworkCompanyIsPassworded(CompanyID company_id)
{
return HasBit(_network_company_passworded, company_id);
}
/* This puts a text-message to the console, or in the future, the chat-box,
* (to keep it all a bit more general)
* If 'self_send' is true, this is the client who is sending the message */
void NetworkTextMessage(NetworkAction action, ConsoleColour colour, bool self_send, const char *name, const char *str, int64 data)
{
const int duration = 10; // Game days the messages stay visible
StringID strid;
switch (action) {
case NETWORK_ACTION_SERVER_MESSAGE:
/* Ignore invalid messages */
if (data >= NETWORK_SERVER_MESSAGE_END) return;
strid = STR_NETWORK_SERVER_MESSAGE;
colour = CC_DEFAULT;
data = STR_NETWORK_SERVER_MESSAGE_GAME_PAUSED_PLAYERS + data;
break;
case NETWORK_ACTION_COMPANY_SPECTATOR:
colour = CC_DEFAULT;
strid = STR_NETWORK_CLIENT_COMPANY_SPECTATE;
break;
case NETWORK_ACTION_COMPANY_JOIN:
colour = CC_DEFAULT;
strid = STR_NETWORK_CLIENT_COMPANY_JOIN;
break;
case NETWORK_ACTION_COMPANY_NEW:
colour = CC_DEFAULT;
strid = STR_NETWORK_CLIENT_COMPANY_NEW;
break;
case NETWORK_ACTION_JOIN: strid = STR_NETWORK_CLIENT_JOINED; break;
case NETWORK_ACTION_LEAVE: strid = STR_NETWORK_CLIENT_LEFT; break;
case NETWORK_ACTION_NAME_CHANGE: strid = STR_NETWORK_NAME_CHANGE; break;
case NETWORK_ACTION_GIVE_MONEY: strid = self_send ? STR_NETWORK_GAVE_MONEY_AWAY : STR_NETWORK_GIVE_MONEY; break;
case NETWORK_ACTION_CHAT_COMPANY: strid = self_send ? STR_NETWORK_CHAT_TO_COMPANY : STR_NETWORK_CHAT_COMPANY; break;
case NETWORK_ACTION_CHAT_CLIENT: strid = self_send ? STR_NETWORK_CHAT_TO_CLIENT : STR_NETWORK_CHAT_CLIENT; break;
default: strid = STR_NETWORK_CHAT_ALL; break;
}
char message[1024];
SetDParamStr(0, name);
SetDParamStr(1, str);
SetDParam(2, data);
GetString(message, strid, lastof(message));
DEBUG(desync, 1, "msg: %d; %d; %s\n", _date, _date_fract, message);
IConsolePrintF(colour, "%s", message);
NetworkAddChatMessage((TextColour)colour, duration, "%s", message);
}
/* Calculate the frame-lag of a client */
uint NetworkCalculateLag(const NetworkClientSocket *cs)
{
int lag = cs->last_frame_server - cs->last_frame;
/* This client has missed his ACK packet after 1 DAY_TICKS..
* so we increase his lag for every frame that passes!
* The packet can be out by a max of _net_frame_freq */
if (cs->last_frame_server + DAY_TICKS + _settings_client.network.frame_freq < _frame_counter)
lag += _frame_counter - (cs->last_frame_server + DAY_TICKS + _settings_client.network.frame_freq);
return lag;
}
/* There was a non-recoverable error, drop back to the main menu with a nice
* error */
static void NetworkError(StringID error_string)
{
_switch_mode = SM_MENU;
extern StringID _switch_mode_errorstr;
_switch_mode_errorstr = error_string;
}
static void ServerStartError(const char *error)
{
DEBUG(net, 0, "[server] could not start network: %s",error);
NetworkError(STR_NETWORK_ERR_SERVER_START);
}
static void NetworkClientError(NetworkRecvStatus res, NetworkClientSocket *cs)
{
/* First, send a CLIENT_ERROR to the server, so he knows we are
* disconnection (and why!) */
NetworkErrorCode errorno;
/* We just want to close the connection.. */
if (res == NETWORK_RECV_STATUS_CLOSE_QUERY) {
cs->has_quit = true;
NetworkCloseClient(cs);
_networking = false;
DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
return;
}
switch (res) {
case NETWORK_RECV_STATUS_DESYNC: errorno = NETWORK_ERROR_DESYNC; break;
case NETWORK_RECV_STATUS_SAVEGAME: errorno = NETWORK_ERROR_SAVEGAME_FAILED; break;
case NETWORK_RECV_STATUS_NEWGRF_MISMATCH: errorno = NETWORK_ERROR_NEWGRF_MISMATCH; break;
default: errorno = NETWORK_ERROR_GENERAL; break;
}
/* This means we fucked up and the server closed the connection */
if (res != NETWORK_RECV_STATUS_SERVER_ERROR && res != NETWORK_RECV_STATUS_SERVER_FULL &&
res != NETWORK_RECV_STATUS_SERVER_BANNED) {
SEND_COMMAND(PACKET_CLIENT_ERROR)(errorno);
}
_switch_mode = SM_MENU;
NetworkCloseClient(cs);
_networking = false;
}
/**
* Retrieve the string id of an internal error number
* @param err NetworkErrorCode
* @return the StringID
*/
StringID GetNetworkErrorMsg(NetworkErrorCode err)
{
/* List of possible network errors, used by
* PACKET_SERVER_ERROR and PACKET_CLIENT_ERROR */
static const StringID network_error_strings[] = {
STR_NETWORK_ERR_CLIENT_GENERAL,
STR_NETWORK_ERR_CLIENT_DESYNC,
STR_NETWORK_ERR_CLIENT_SAVEGAME,
STR_NETWORK_ERR_CLIENT_CONNECTION_LOST,
STR_NETWORK_ERR_CLIENT_PROTOCOL_ERROR,
STR_NETWORK_ERR_CLIENT_NEWGRF_MISMATCH,
STR_NETWORK_ERR_CLIENT_NOT_AUTHORIZED,
STR_NETWORK_ERR_CLIENT_NOT_EXPECTED,
STR_NETWORK_ERR_CLIENT_WRONG_REVISION,
STR_NETWORK_ERR_CLIENT_NAME_IN_USE,
STR_NETWORK_ERR_CLIENT_WRONG_PASSWORD,
STR_NETWORK_ERR_CLIENT_COMPANY_MISMATCH,
STR_NETWORK_ERR_CLIENT_KICKED,
STR_NETWORK_ERR_CLIENT_CHEATER,
STR_NETWORK_ERR_CLIENT_SERVER_FULL
};
if (err >= (ptrdiff_t)lengthof(network_error_strings)) err = NETWORK_ERROR_GENERAL;
return network_error_strings[err];
}
/* Count the number of active clients connected */
static uint NetworkCountActiveClients()
{
const NetworkClientInfo *ci;
uint count = 0;
FOR_ALL_CLIENT_INFOS(ci) {
if (IsValidCompanyID(ci->client_playas)) count++;
}
return count;
}
static bool _min_active_clients_paused = false;
/* Check if the minimum number of active clients has been reached and pause or unpause the game as appropriate */
static void CheckMinActiveClients()
{
if (!_network_dedicated) return;
if (NetworkCountActiveClients() < _settings_client.network.min_active_clients) {
if (_min_active_clients_paused) return;
_min_active_clients_paused = true;
DoCommandP(0, 1, 0, CMD_PAUSE);
NetworkServerSendChat(NETWORK_ACTION_SERVER_MESSAGE, DESTTYPE_BROADCAST, 0, "", CLIENT_ID_SERVER, NETWORK_SERVER_MESSAGE_GAME_PAUSED_PLAYERS);
} else {
if (!_min_active_clients_paused) return;
_min_active_clients_paused = false;
DoCommandP(0, 0, 0, CMD_PAUSE);
NetworkServerSendChat(NETWORK_ACTION_SERVER_MESSAGE, DESTTYPE_BROADCAST, 0, "", CLIENT_ID_SERVER, NETWORK_SERVER_MESSAGE_GAME_UNPAUSED_PLAYERS);
}
}
/** Converts a string to ip/port/company
* Format: IP#company:port
*
* connection_string will be re-terminated to seperate out the hostname, and company and port will
* be set to the company and port strings given by the user, inside the memory area originally
* occupied by connection_string. */
void ParseConnectionString(const char **company, const char **port, char *connection_string)
{
char *p;
for (p = connection_string; *p != '\0'; p++) {
switch (*p) {
case '#':
*company = p + 1;
*p = '\0';
break;
case ':':
*port = p + 1;
*p = '\0';
break;
}
}
}
/* Creates a new client from a socket
* Used both by the server and the client */
static NetworkClientSocket *NetworkAllocClient(SOCKET s)
{
if (_network_server) {
/* Can we handle a new client? */
if (_network_clients_connected >= MAX_CLIENTS) return NULL;
if (_network_game_info.clients_on >= _settings_client.network.max_clients) return NULL;
/* Register the login */
_network_clients_connected++;
}
NetworkClientSocket *cs = new NetworkClientSocket(INVALID_CLIENT_ID);
cs->sock = s;
cs->last_frame = _frame_counter;
cs->last_frame_server = _frame_counter;
if (_network_server) {
cs->client_id = _network_client_id++;
NetworkClientInfo *ci = new NetworkClientInfo(cs->client_id);
cs->SetInfo(ci);
ci->client_playas = COMPANY_INACTIVE_CLIENT;
ci->join_date = _date;
InvalidateWindow(WC_CLIENT_LIST, 0);
}
return cs;
}
/* Close a connection */
void NetworkCloseClient(NetworkClientSocket *cs)
{
/*
* Sending a message just before leaving the game calls cs->Send_Packets.
* This might invoke this function, which means that when we close the
* connection after cs->Send_Packets we will close an already closed
* connection. This handles that case gracefully without having to make
* that code any more complex or more aware of the validity of the socket.
*/
if (cs->sock == INVALID_SOCKET) return;
DEBUG(net, 1, "Closed client connection %d", cs->client_id);
if (!cs->has_quit && _network_server && cs->status > STATUS_INACTIVE) {
/* We did not receive a leave message from this client... */
char client_name[NETWORK_CLIENT_NAME_LENGTH];
NetworkClientSocket *new_cs;
NetworkGetClientName(client_name, sizeof(client_name), cs);
NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, NULL, STR_NETWORK_ERR_CLIENT_CONNECTION_LOST);
/* Inform other clients of this... strange leaving ;) */
FOR_ALL_CLIENT_SOCKETS(new_cs) {
if (new_cs->status > STATUS_AUTH && cs != new_cs) {
SEND_COMMAND(PACKET_SERVER_ERROR_QUIT)(new_cs, cs->client_id, NETWORK_ERROR_CONNECTION_LOST);
}
}
}
/* When the client was PRE_ACTIVE, the server was in pause mode, so unpause */
if (cs->status == STATUS_PRE_ACTIVE && _settings_client.network.pause_on_join) {
DoCommandP(0, 0, 0, CMD_PAUSE);
NetworkServerSendChat(NETWORK_ACTION_SERVER_MESSAGE, DESTTYPE_BROADCAST, 0, "", CLIENT_ID_SERVER, NETWORK_SERVER_MESSAGE_GAME_UNPAUSED_CONNECT_FAIL);
}
if (_network_server) {
/* We just lost one client :( */
if (cs->status >= STATUS_AUTH) _network_game_info.clients_on--;
_network_clients_connected--;
InvalidateWindow(WC_CLIENT_LIST, 0);
}
delete cs->GetInfo();
delete cs;
}
/* For the server, to accept new clients */
static void NetworkAcceptClients()
{
struct sockaddr_in sin;
NetworkClientSocket *cs;
uint i;
bool banned;
/* Should never ever happen.. is it possible?? */
assert(_listensocket != INVALID_SOCKET);
for (;;) {
socklen_t sin_len = sizeof(sin);
SOCKET s = accept(_listensocket, (struct sockaddr*)&sin, &sin_len);
if (s == INVALID_SOCKET) return;
SetNonBlocking(s); // XXX error handling?
DEBUG(net, 1, "Client connected from %s on frame %d", inet_ntoa(sin.sin_addr), _frame_counter);
SetNoDelay(s); // XXX error handling?
/* Check if the client is banned */
banned = false;
for (i = 0; i < lengthof(_network_ban_list); i++) {
if (_network_ban_list[i] == NULL) continue;
/* Check for CIDR separator */
char *chr_cidr = strchr(_network_ban_list[i], '/');
if (chr_cidr != NULL) {
int cidr = atoi(chr_cidr + 1);
/* Invalid CIDR, treat as single host */
if (cidr <= 0 || cidr > 32) cidr = 32;
/* Remove and then replace the / so that inet_addr() works on the IP portion */
*chr_cidr = '\0';
uint32 ban_ip = inet_addr(_network_ban_list[i]);
*chr_cidr = '/';
/* Convert CIDR to mask in network format */
uint32 mask = htonl(-(1 << (32 - cidr)));
if ((sin.sin_addr.s_addr & mask) == (ban_ip & mask)) banned = true;
} else {
/* No CIDR used, so just perform a simple IP test */
if (sin.sin_addr.s_addr == inet_addr(_network_ban_list[i])) banned = true;
}
if (banned) {
Packet p(PACKET_SERVER_BANNED);
p.PrepareToSend();
DEBUG(net, 1, "Banned ip tried to join (%s), refused", _network_ban_list[i]);
send(s, (const char*)p.buffer, p.size, 0);
closesocket(s);
break;
}
}
/* If this client is banned, continue with next client */
if (banned) continue;
cs = NetworkAllocClient(s);
if (cs == NULL) {
/* no more clients allowed?
* Send to the client that we are full! */
Packet p(PACKET_SERVER_FULL);
p.PrepareToSend();
send(s, (const char*)p.buffer, p.size, 0);
closesocket(s);
continue;
}
/* a new client has connected. We set him at inactive for now
* maybe he is only requesting server-info. Till he has sent a PACKET_CLIENT_MAP_OK
* the client stays inactive */
cs->status = STATUS_INACTIVE;
cs->GetInfo()->client_ip = sin.sin_addr.s_addr; // Save the IP of the client
}
}
/* Set up the listen socket for the server */
static bool NetworkListen()
{
SOCKET ls;
struct sockaddr_in sin;
DEBUG(net, 1, "Listening on %s:%d", _settings_client.network.server_bind_ip, _settings_client.network.server_port);
ls = socket(AF_INET, SOCK_STREAM, 0);
if (ls == INVALID_SOCKET) {
ServerStartError("socket() on listen socket failed");
return false;
}
{ // reuse the socket
int reuse = 1;
/* The (const char*) cast is needed for windows!! */
if (setsockopt(ls, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse)) == -1) {
ServerStartError("setsockopt() on listen socket failed");
return false;
}
}
if (!SetNonBlocking(ls)) DEBUG(net, 0, "Setting non-blocking mode failed"); // XXX should this be an error?
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = _network_server_bind_ip;
sin.sin_port = htons(_settings_client.network.server_port);
if (bind(ls, (struct sockaddr*)&sin, sizeof(sin)) != 0) {
ServerStartError("bind() failed");
return false;
}
if (listen(ls, 1) != 0) {
ServerStartError("listen() failed");
return false;
}
_listensocket = ls;
return true;
}
/** Resets both pools used for network clients */
static void InitializeNetworkPools()
{
_NetworkClientSocket_pool.CleanPool();
_NetworkClientSocket_pool.AddBlockToPool();
_NetworkClientInfo_pool.CleanPool();
_NetworkClientInfo_pool.AddBlockToPool();
}
/* Close all current connections */
static void NetworkClose()
{
NetworkClientSocket *cs;
FOR_ALL_CLIENT_SOCKETS(cs) {
if (!_network_server) {
SEND_COMMAND(PACKET_CLIENT_QUIT)();
cs->Send_Packets();
}
NetworkCloseClient(cs);
}
if (_network_server) {
/* We are a server, also close the listensocket */
closesocket(_listensocket);
_listensocket = INVALID_SOCKET;
DEBUG(net, 1, "Closed listener");
}
NetworkUDPCloseAll();
TCPConnecter::KillAll();
_networking = false;
_network_server = false;
NetworkFreeLocalCommandQueue();
free(_network_company_states);
_network_company_states = NULL;
InitializeNetworkPools();
}
/* Inits the network (cleans sockets and stuff) */
static void NetworkInitialize()
{
InitializeNetworkPools();
_sync_frame = 0;
_network_first_time = true;
_network_reconnect = 0;
}
/** Non blocking connection create to query servers */
class TCPQueryConnecter : TCPConnecter {
public:
TCPQueryConnecter(const NetworkAddress &address) : TCPConnecter(address) {}
virtual void OnFailure()
{
NetworkDisconnect();
}
virtual void OnConnect(SOCKET s)
{
_networking = true;
NetworkAllocClient(s);
SEND_COMMAND(PACKET_CLIENT_COMPANY_INFO)();
}
};
/* Query a server to fetch his game-info
* If game_info is true, only the gameinfo is fetched,
* else only the client_info is fetched */
void NetworkTCPQueryServer(NetworkAddress address)
{
if (!_network_available) return;
NetworkDisconnect();
NetworkInitialize();
new TCPQueryConnecter(address);
}
/* Validates an address entered as a string and adds the server to
* the list. If you use this function, the games will be marked
* as manually added. */
void NetworkAddServer(const char *b)
{
if (*b != '\0') {
const char *port = NULL;
const char *company = NULL;
char host[NETWORK_HOSTNAME_LENGTH];
uint16 rport;
strecpy(host, b, lastof(host));
strecpy(_settings_client.network.connect_to_ip, b, lastof(_settings_client.network.connect_to_ip));
rport = NETWORK_DEFAULT_PORT;
ParseConnectionString(&company, &port, host);
if (port != NULL) rport = atoi(port);
NetworkUDPQueryServer(NetworkAddress(host, rport), true);
}
}
/* Generates the list of manually added hosts from NetworkGameList and
* dumps them into the array _network_host_list. This array is needed
* by the function that generates the config file. */
void NetworkRebuildHostList()
{
uint i = 0;
const NetworkGameList *item = _network_game_list;
while (item != NULL && i != lengthof(_network_host_list)) {
if (item->manually) {
free(_network_host_list[i]);
_network_host_list[i++] = str_fmt("%s:%i", item->info.hostname, item->port);
}
item = item->next;
}
for (; i < lengthof(_network_host_list); i++) {
free(_network_host_list[i]);
_network_host_list[i] = NULL;
}
}
/** Non blocking connection create to actually connect to servers */
class TCPClientConnecter : TCPConnecter {
public:
TCPClientConnecter(const NetworkAddress &address) : TCPConnecter(address) {}
virtual void OnFailure()
{
NetworkError(STR_NETWORK_ERR_NOCONNECTION);
}
virtual void OnConnect(SOCKET s)
{
_networking = true;
NetworkAllocClient(s);
IConsoleCmdExec("exec scripts/on_client.scr 0");
NetworkClient_Connected();
}
};
/* Used by clients, to connect to a server */
void NetworkClientConnectGame(NetworkAddress address)
{
if (!_network_available) return;
if (address.GetPort() == 0) return;
strecpy(_settings_client.network.last_host, address.GetHostname(), lastof(_settings_client.network.last_host));
_settings_client.network.last_port = address.GetPort();
NetworkDisconnect();
NetworkInitialize();
_network_join_status = NETWORK_JOIN_STATUS_CONNECTING;
ShowJoinStatusWindow();
new TCPClientConnecter(address);
}
static void NetworkInitGameInfo()
{
if (StrEmpty(_settings_client.network.server_name)) {
snprintf(_settings_client.network.server_name, sizeof(_settings_client.network.server_name), "Unnamed Server");
}
/* The server is a client too */
_network_game_info.clients_on = _network_dedicated ? 0 : 1;
_network_game_info.start_date = ConvertYMDToDate(_settings_game.game_creation.starting_year, 0, 1);
NetworkClientInfo *ci = new NetworkClientInfo(CLIENT_ID_SERVER);
ci->client_playas = _network_dedicated ? COMPANY_SPECTATOR : _local_company;
strecpy(ci->client_name, _settings_client.network.client_name, lastof(ci->client_name));
strecpy(ci->unique_id, _settings_client.network.network_id, lastof(ci->unique_id));
}
bool NetworkServerStart()
{
if (!_network_available) return false;
/* Call the pre-scripts */
IConsoleCmdExec("exec scripts/pre_server.scr 0");
if (_network_dedicated) IConsoleCmdExec("exec scripts/pre_dedicated.scr 0");
NetworkInitialize();
if (!NetworkListen()) return false;
/* Try to start UDP-server */
_network_udp_server = true;
_network_udp_server = _udp_server_socket->Listen(_network_server_bind_ip, _settings_client.network.server_port, false);
_network_company_states = CallocT<NetworkCompanyState>(MAX_COMPANIES);
_network_server = true;
_networking = true;
_frame_counter = 0;
_frame_counter_server = 0;
_frame_counter_max = 0;
_last_sync_frame = 0;
_network_own_client_id = CLIENT_ID_SERVER;
/* Non-dedicated server will always be company #1 */
if (!_network_dedicated) _network_playas = COMPANY_FIRST;
_network_clients_connected = 0;
NetworkInitGameInfo();
/* execute server initialization script */
IConsoleCmdExec("exec scripts/on_server.scr 0");
/* if the server is dedicated ... add some other script */
if (_network_dedicated) IConsoleCmdExec("exec scripts/on_dedicated.scr 0");
_min_active_clients_paused = false;
/* Try to register us to the master server */
_network_last_advertise_frame = 0;
_network_need_advertise = true;
NetworkUDPAdvertise();
return true;
}
/* The server is rebooting...
* The only difference with NetworkDisconnect, is the packets that is sent */
void NetworkReboot()
{
if (_network_server) {
NetworkClientSocket *cs;
FOR_ALL_CLIENT_SOCKETS(cs) {
SEND_COMMAND(PACKET_SERVER_NEWGAME)(cs);
cs->Send_Packets();
}
}
NetworkClose();
}
/* We want to disconnect from the host/clients */
void NetworkDisconnect()
{
if (_network_server) {
NetworkClientSocket *cs;
FOR_ALL_CLIENT_SOCKETS(cs) {
SEND_COMMAND(PACKET_SERVER_SHUTDOWN)(cs);
cs->Send_Packets();
}
}
if (_settings_client.network.server_advertise) NetworkUDPRemoveAdvertise();
DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
NetworkClose();
}
/* Receives something from the network */
static bool NetworkReceive()
{
NetworkClientSocket *cs;
int n;
fd_set read_fd, write_fd;
struct timeval tv;
FD_ZERO(&read_fd);
FD_ZERO(&write_fd);
FOR_ALL_CLIENT_SOCKETS(cs) {
FD_SET(cs->sock, &read_fd);
FD_SET(cs->sock, &write_fd);
}
/* take care of listener port */
if (_network_server) FD_SET(_listensocket, &read_fd);
tv.tv_sec = tv.tv_usec = 0; // don't block at all.
#if !defined(__MORPHOS__) && !defined(__AMIGA__)
n = select(FD_SETSIZE, &read_fd, &write_fd, NULL, &tv);
#else
n = WaitSelect(FD_SETSIZE, &read_fd, &write_fd, NULL, &tv, NULL);
#endif
if (n == -1 && !_network_server) NetworkError(STR_NETWORK_ERR_LOSTCONNECTION);
/* accept clients.. */
if (_network_server && FD_ISSET(_listensocket, &read_fd)) NetworkAcceptClients();
/* read stuff from clients */
FOR_ALL_CLIENT_SOCKETS(cs) {
cs->writable = !!FD_ISSET(cs->sock, &write_fd);
if (FD_ISSET(cs->sock, &read_fd)) {
if (_network_server) {
NetworkServer_ReadPackets(cs);
} else {
NetworkRecvStatus res;
/* The client already was quiting! */
if (cs->has_quit) return false;
res = NetworkClient_ReadPackets(cs);
if (res != NETWORK_RECV_STATUS_OKAY) {
/* The client made an error of which we can not recover
* close the client and drop back to main menu */
NetworkClientError(res, cs);
return false;
}
}
}
}
return true;
}
/* This sends all buffered commands (if possible) */
static void NetworkSend()
{
NetworkClientSocket *cs;
FOR_ALL_CLIENT_SOCKETS(cs) {
if (cs->writable) {
cs->Send_Packets();
if (cs->status == STATUS_MAP) {
/* This client is in the middle of a map-send, call the function for that */
SEND_COMMAND(PACKET_SERVER_MAP)(cs);
}
}
}
}
static bool NetworkDoClientLoop()
{
_frame_counter++;
NetworkExecuteLocalCommandQueue();
StateGameLoop();
/* Check if we are in sync! */
if (_sync_frame != 0) {
if (_sync_frame == _frame_counter) {
#ifdef NETWORK_SEND_DOUBLE_SEED
if (_sync_seed_1 != _random.state[0] || _sync_seed_2 != _random.state[1]) {
#else
if (_sync_seed_1 != _random.state[0]) {
#endif
NetworkError(STR_NETWORK_ERR_DESYNC);
DEBUG(desync, 1, "sync_err: %d; %d\n", _date, _date_fract);
DEBUG(net, 0, "Sync error detected!");
NetworkClientError(NETWORK_RECV_STATUS_DESYNC, GetNetworkClientSocket(0));
return false;
}
/* If this is the first time we have a sync-frame, we
* need to let the server know that we are ready and at the same
* frame as he is.. so we can start playing! */
if (_network_first_time) {
_network_first_time = false;
SEND_COMMAND(PACKET_CLIENT_ACK)();
}
_sync_frame = 0;
} else if (_sync_frame < _frame_counter) {
DEBUG(net, 1, "Missed frame for sync-test (%d / %d)", _sync_frame, _frame_counter);
_sync_frame = 0;
}
}
return true;
}
/* We have to do some UDP checking */
void NetworkUDPGameLoop()
{
_network_content_client.SendReceive();
TCPConnecter::CheckCallbacks();
if (_network_udp_server) {
_udp_server_socket->ReceivePackets();
_udp_master_socket->ReceivePackets();
} else {
_udp_client_socket->ReceivePackets();
if (_network_udp_broadcast > 0) _network_udp_broadcast--;
NetworkGameListRequery();
}
}
/* The main loop called from ttd.c
* Here we also have to do StateGameLoop if needed! */
void NetworkGameLoop()
{
if (!_networking) return;
if (!NetworkReceive()) return;
if (_network_server) {
#ifdef DEBUG_DUMP_COMMANDS
static FILE *f = FioFOpenFile("commands.log", "rb", SAVE_DIR);
static Date next_date = 0;
static uint32 next_date_fract;
static CommandPacket *cp = NULL;
if (f == NULL && next_date == 0) {
printf("Cannot open commands.log\n");
next_date = 1;
}
while (f != NULL && !feof(f)) {
if (cp != NULL && _date == next_date && _date_fract == next_date_fract) {
_current_company = cp->company;
DoCommandP(cp->tile, cp->p1, cp->p2, cp->cmd, NULL, cp->text);
free(cp);
cp = NULL;
}
if (cp != NULL) break;
char buff[4096];
if (fgets(buff, lengthof(buff), f) == NULL) break;
if (strncmp(buff, "cmd: ", 8) != 0) continue;
cp = MallocT<CommandPacket>(1);
int company;
sscanf(&buff[8], "%d; %d; %d; %d; %d; %d; %d; %s", &next_date, &next_date_fract, &company, &cp->tile, &cp->p1, &cp->p2, &cp->cmd, cp->text);
cp->company = (CompanyID)company;
}
#endif /* DEBUG_DUMP_COMMANDS */
CheckMinActiveClients();
bool send_frame = false;
/* We first increase the _frame_counter */
_frame_counter++;
/* Update max-frame-counter */
if (_frame_counter > _frame_counter_max) {
_frame_counter_max = _frame_counter + _settings_client.network.frame_freq;
send_frame = true;
}
NetworkExecuteLocalCommandQueue();
/* Then we make the frame */
StateGameLoop();
_sync_seed_1 = _random.state[0];
#ifdef NETWORK_SEND_DOUBLE_SEED
_sync_seed_2 = _random.state[1];
#endif
NetworkServer_Tick(send_frame);
} else {
/* Client */
/* Make sure we are at the frame were the server is (quick-frames) */
if (_frame_counter_server > _frame_counter) {
while (_frame_counter_server > _frame_counter) {
if (!NetworkDoClientLoop()) break;
}
} else {
/* Else, keep on going till _frame_counter_max */
if (_frame_counter_max > _frame_counter) NetworkDoClientLoop();
}
}
NetworkSend();
}
static void NetworkGenerateUniqueId()
{
Md5 checksum;
uint8 digest[16];
char hex_output[16 * 2 + 1];
char coding_string[NETWORK_NAME_LENGTH];
int di;
snprintf(coding_string, sizeof(coding_string), "%d%s", (uint)Random(), "OpenTTD Unique ID");
/* Generate the MD5 hash */
checksum.Append((const uint8*)coding_string, strlen(coding_string));
checksum.Finish(digest);
for (di = 0; di < 16; ++di)
sprintf(hex_output + di * 2, "%02x", digest[di]);
/* _network_unique_id is our id */
snprintf(_settings_client.network.network_id, sizeof(_settings_client.network.network_id), "%s", hex_output);
}
void NetworkStartDebugLog(NetworkAddress address)
{
extern SOCKET _debug_socket; // Comes from debug.c
SOCKET s;
struct sockaddr_in sin;
DEBUG(net, 0, "Redirecting DEBUG() to %s:%d", address.GetHostname(), address.GetPort());
s = socket(AF_INET, SOCK_STREAM, 0);
if (s == INVALID_SOCKET) {
DEBUG(net, 0, "Failed to open socket for redirection DEBUG()");
return;
}
if (!SetNoDelay(s)) DEBUG(net, 1, "Setting TCP_NODELAY failed");
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = address.GetIP();
sin.sin_port = htons(address.GetPort());
if (connect(s, (struct sockaddr *)&sin, sizeof(sin)) != 0) {
DEBUG(net, 0, "Failed to redirection DEBUG() to %s:%d", address.GetHostname(), address.GetPort());
return;
}
if (!SetNonBlocking(s)) DEBUG(net, 0, "Setting non-blocking mode failed");
_debug_socket = s;
DEBUG(net, 0, "DEBUG() is now redirected");
}
/** This tries to launch the network for a given OS */
void NetworkStartUp()
{
DEBUG(net, 3, "[core] starting network...");
/* Network is available */
_network_available = NetworkCoreInitialize();;
_network_dedicated = false;
_network_last_advertise_frame = 0;
_network_need_advertise = true;
_network_advertise_retries = 0;
/* Load the ip from the openttd.cfg */
_network_server_bind_ip = inet_addr(_settings_client.network.server_bind_ip);
/* And put the data back in it in case it was an invalid ip */
snprintf(_settings_client.network.server_bind_ip, sizeof(_settings_client.network.server_bind_ip), "%s", inet_ntoa(*(struct in_addr *)&_network_server_bind_ip));
/* Generate an unique id when there is none yet */
if (StrEmpty(_settings_client.network.network_id)) NetworkGenerateUniqueId();
memset(&_network_game_info, 0, sizeof(_network_game_info));
NetworkUDPInitialize();
NetworkInitialize();
DEBUG(net, 3, "[core] network online, multiplayer available");
NetworkFindBroadcastIPs(_broadcast_list, MAX_INTERFACES);
}
/** This shuts the network down */
void NetworkShutDown()
{
NetworkDisconnect();
NetworkUDPShutdown();
DEBUG(net, 3, "[core] shutting down network");
_network_available = false;
NetworkCoreShutdown();
}
/**
* Checks whether the given version string is compatible with our version.
* @param other the version string to compare to
*/
bool IsNetworkCompatibleVersion(const char *other)
{
return strncmp(_openttd_revision, other, NETWORK_REVISION_LENGTH - 1) == 0;
}
#endif /* ENABLE_NETWORK */
/* NOTE: this variable needs to be always available */
CompanyID _network_playas;
| 34,074
|
C++
|
.cpp
| 956
| 33.135983
| 162
| 0.719036
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,243
|
network_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/network/network_gui.cpp
|
/* $Id$ */
/** @file network_gui.cpp Implementation of the Network related GUIs. */
#ifdef ENABLE_NETWORK
#include "../stdafx.h"
#include "../openttd.h"
#include "../strings_func.h"
#include "../date_func.h"
#include "../fios.h"
#include "network_internal.h"
#include "network_client.h"
#include "network_gui.h"
#include "network_gamelist.h"
#include "../gui.h"
#include "network_server.h"
#include "network_udp.h"
#include "../window_func.h"
#include "../string_func.h"
#include "../gfx_func.h"
#include "../settings_type.h"
#include "../widgets/dropdown_func.h"
#include "../querystring_gui.h"
#include "../sortlist_type.h"
#include "../company_base.h"
#include "table/strings.h"
#include "../table/sprites.h"
static void ShowNetworkStartServerWindow();
static void ShowNetworkLobbyWindow(NetworkGameList *ngl);
extern void SwitchToMode(SwitchMode new_mode);
static const StringID _connection_types_dropdown[] = {
STR_NETWORK_LAN_INTERNET,
STR_NETWORK_INTERNET_ADVERTISE,
INVALID_STRING_ID
};
static const StringID _lan_internet_types_dropdown[] = {
STR_NETWORK_LAN,
STR_NETWORK_INTERNET,
INVALID_STRING_ID
};
static StringID _language_dropdown[NETLANG_COUNT + 1] = {STR_NULL};
void SortNetworkLanguages()
{
/* Init the strings */
if (_language_dropdown[0] == STR_NULL) {
for (int i = 0; i < NETLANG_COUNT; i++) _language_dropdown[i] = STR_NETWORK_LANG_ANY + i;
_language_dropdown[NETLANG_COUNT] = INVALID_STRING_ID;
}
/* Sort the strings (we don't move 'any' and the 'invalid' one) */
qsort(&_language_dropdown[1], NETLANG_COUNT - 1, sizeof(StringID), &StringIDSorter);
}
enum {
NET_PRC__OFFSET_TOP_WIDGET = 54,
NET_PRC__OFFSET_TOP_WIDGET_COMPANY = 52,
NET_PRC__SIZE_OF_ROW = 14,
};
/** Update the network new window because a new server is
* found on the network.
* @param unselect unselect the currently selected item */
void UpdateNetworkGameWindow(bool unselect)
{
InvalidateWindowData(WC_NETWORK_WINDOW, 0, unselect ? 1 : 0);
}
/** Enum for NetworkGameWindow, referring to _network_game_window_widgets */
enum NetworkGameWindowWidgets {
NGWW_CLOSE, ///< Close 'X' button
NGWW_CAPTION, ///< Caption of the window
NGWW_MAIN, ///< Main panel
NGWW_CONNECTION, ///< Label in from of connection droplist
NGWW_CONN_BTN, ///< 'Connection' droplist button
NGWW_CLIENT, ///< Panel with editbox to set client name
NGWW_NAME, ///< 'Name' button
NGWW_CLIENTS, ///< 'Clients' button
NGWW_MAPSIZE, ///< 'Map size' button
NGWW_DATE, ///< 'Date' button
NGWW_YEARS, ///< 'Years' button
NGWW_INFO, ///< Third button in the game list panel
NGWW_MATRIX, ///< Panel with list of games
NGWW_SCROLLBAR, ///< Scrollbar of matrix
NGWW_LASTJOINED_LABEL, ///< Label "Last joined server:"
NGWW_LASTJOINED, ///< Info about the last joined server
NGWW_DETAILS, ///< Panel with game details
NGWW_JOIN, ///< 'Join game' button
NGWW_REFRESH, ///< 'Refresh server' button
NGWW_NEWGRF, ///< 'NewGRF Settings' button
NGWW_FIND, ///< 'Find server' button
NGWW_ADD, ///< 'Add server' button
NGWW_START, ///< 'Start server' button
NGWW_CANCEL, ///< 'Cancel' button
NGWW_RESIZE, ///< Resize button
};
typedef GUIList<NetworkGameList*> GUIGameServerList;
typedef uint16 ServerListPosition;
static const ServerListPosition SLP_INVALID = 0xFFFF;
class NetworkGameWindow : public QueryStringBaseWindow {
protected:
/* Runtime saved values */
static Listing last_sorting;
/* Constants for sorting servers */
static GUIGameServerList::SortFunction * const sorter_funcs[];
byte field; ///< selected text-field
NetworkGameList *server; ///< selected server
GUIGameServerList servers; ///< list with game servers.
ServerListPosition list_pos; ///< position of the selected server
/**
* (Re)build the network game list as its amount has changed because
* an item has been added or deleted for example
*/
void BuildNetworkGameList()
{
if (!this->servers.NeedRebuild()) return;
/* Create temporary array of games to use for listing */
this->servers.Clear();
for (NetworkGameList *ngl = _network_game_list; ngl != NULL; ngl = ngl->next) {
*this->servers.Append() = ngl;
}
this->servers.Compact();
this->servers.RebuildDone();
}
/** Sort servers by name. */
static int CDECL NGameNameSorter(NetworkGameList * const *a, NetworkGameList * const *b)
{
return strcasecmp((*a)->info.server_name, (*b)->info.server_name);
}
/** Sort servers by the amount of clients online on a
* server. If the two servers have the same amount, the one with the
* higher maximum is preferred. */
static int CDECL NGameClientSorter(NetworkGameList * const *a, NetworkGameList * const *b)
{
/* Reverse as per default we are interested in most-clients first */
int r = (*a)->info.clients_on - (*b)->info.clients_on;
if (r == 0) r = (*a)->info.clients_max - (*b)->info.clients_max;
if (r == 0) r = NGameNameSorter(a, b);
return r;
}
/** Sort servers by map size */
static int CDECL NGameMapSizeSorter(NetworkGameList * const *a, NetworkGameList * const *b)
{
/* Sort by the area of the map. */
int r = ((*a)->info.map_height) * ((*a)->info.map_width) - ((*b)->info.map_height) * ((*b)->info.map_width);
if (r == 0) r = (*a)->info.map_width - (*b)->info.map_width;
return (r != 0) ? r : NGameClientSorter(a, b);
}
/** Sort servers by current date */
static int CDECL NGameDateSorter(NetworkGameList * const *a, NetworkGameList * const *b)
{
int r = (*a)->info.game_date - (*b)->info.game_date;
return (r != 0) ? r : NGameClientSorter(a, b);
}
/** Sort servers by the number of days the game is running */
static int CDECL NGameYearsSorter(NetworkGameList * const *a, NetworkGameList * const *b)
{
int r = (*a)->info.game_date - (*a)->info.start_date - (*b)->info.game_date + (*b)->info.start_date;
return (r != 0) ? r : NGameDateSorter(a, b);
}
/** Sort servers by joinability. If both servers are the
* same, prefer the non-passworded server first. */
static int CDECL NGameAllowedSorter(NetworkGameList * const *a, NetworkGameList * const *b)
{
/* The servers we do not know anything about (the ones that did not reply) should be at the bottom) */
int r = StrEmpty((*a)->info.server_revision) - StrEmpty((*b)->info.server_revision);
/* Reverse default as we are interested in version-compatible clients first */
if (r == 0) r = (*b)->info.version_compatible - (*a)->info.version_compatible;
/* The version-compatible ones are then sorted with NewGRF compatible first, incompatible last */
if (r == 0) r = (*b)->info.compatible - (*a)->info.compatible;
/* Passworded servers should be below unpassworded servers */
if (r == 0) r = (*a)->info.use_password - (*b)->info.use_password;
/* Finally sort on the name of the server */
if (r == 0) r = NGameNameSorter(a, b);
return r;
}
/** Sort the server list */
void SortNetworkGameList()
{
if (!this->servers.Sort()) return;
/* After sorting ngl->sort_list contains the sorted items. Put these back
* into the original list. Basically nothing has changed, we are only
* shuffling the ->next pointers. While iterating, look for the
* currently selected server and set list_pos to its position */
this->list_pos = SLP_INVALID;
_network_game_list = this->servers[0];
NetworkGameList *item = _network_game_list;
if (item == this->server) this->list_pos = 0;
for (uint i = 1; i != this->servers.Length(); i++) {
item->next = this->servers[i];
item = item->next;
if (item == this->server) this->list_pos = i;
}
item->next = NULL;
}
/**
* Draw a single server line.
* @param cur_item the server to draw.
* @param y from where to draw?
* @param highlight does the line need to be highlighted?
*/
void DrawServerLine(const NetworkGameList *cur_item, uint y, bool highlight)
{
/* show highlighted item with a different colour */
if (highlight) GfxFillRect(this->widget[NGWW_NAME].left + 1, y - 2, this->widget[NGWW_INFO].right - 1, y + 9, 10);
SetDParamStr(0, cur_item->info.server_name);
DrawStringTruncated(this->widget[NGWW_NAME].left + 5, y, STR_JUST_RAW_STRING, TC_BLACK, this->widget[NGWW_NAME].right - this->widget[NGWW_NAME].left - 5);
/* only draw details if the server is online */
if (cur_item->online) {
SetDParam(0, cur_item->info.clients_on);
SetDParam(1, cur_item->info.clients_max);
SetDParam(2, cur_item->info.companies_on);
SetDParam(3, cur_item->info.companies_max);
DrawStringCentered(this->widget[NGWW_CLIENTS].left + 39, y, STR_NETWORK_GENERAL_ONLINE, TC_GOLD);
/* map size */
if (!this->IsWidgetHidden(NGWW_MAPSIZE)) {
SetDParam(0, cur_item->info.map_width);
SetDParam(1, cur_item->info.map_height);
DrawStringCentered(this->widget[NGWW_MAPSIZE].left + 39, y, STR_NETWORK_MAP_SIZE_SHORT, TC_BLACK);
}
/* current date */
if (!this->IsWidgetHidden(NGWW_DATE)) {
YearMonthDay ymd;
ConvertDateToYMD(cur_item->info.game_date, &ymd);
SetDParam(0, ymd.year);
DrawStringCentered(this->widget[NGWW_DATE].left + 29, y, STR_JUST_INT, TC_BLACK);
}
/* number of years the game is running */
if (!this->IsWidgetHidden(NGWW_YEARS)) {
YearMonthDay ymd_cur, ymd_start;
ConvertDateToYMD(cur_item->info.game_date, &ymd_cur);
ConvertDateToYMD(cur_item->info.start_date, &ymd_start);
SetDParam(0, ymd_cur.year - ymd_start.year);
DrawStringCentered(this->widget[NGWW_YEARS].left + 29, y, STR_JUST_INT, TC_BLACK);
}
/* draw a lock if the server is password protected */
if (cur_item->info.use_password) DrawSprite(SPR_LOCK, PAL_NONE, this->widget[NGWW_INFO].left + 5, y - 1);
/* draw red or green icon, depending on compatibility with server */
DrawSprite(SPR_BLOT, (cur_item->info.compatible ? PALETTE_TO_GREEN : (cur_item->info.version_compatible ? PALETTE_TO_YELLOW : PALETTE_TO_RED)), this->widget[NGWW_INFO].left + 15, y);
/* draw flag according to server language */
DrawSprite(SPR_FLAGS_BASE + cur_item->info.server_lang, PAL_NONE, this->widget[NGWW_INFO].left + 25, y);
}
}
/**
* Scroll the list up or down to the currently selected server.
* If the server is below the currently displayed servers, it will
* scroll down an amount so that the server appears at the bottom.
* If the server is above the currently displayed servers, it will
* scroll up so that the server appears at the top.
*/
void ScrollToSelectedServer()
{
if (this->list_pos == SLP_INVALID) return; // no server selected
if (this->list_pos < this->vscroll.pos) {
/* scroll up to the server */
this->vscroll.pos = this->list_pos;
} else if (this->list_pos >= this->vscroll.pos + this->vscroll.cap) {
/* scroll down so that the server is at the bottom */
this->vscroll.pos = this->list_pos - this->vscroll.cap + 1;
}
}
public:
NetworkGameWindow(const WindowDesc *desc) : QueryStringBaseWindow(NETWORK_NAME_LENGTH, desc)
{
ttd_strlcpy(this->edit_str_buf, _settings_client.network.client_name, this->edit_str_size);
this->afilter = CS_ALPHANUMERAL;
InitializeTextBuffer(&this->text, this->edit_str_buf, this->edit_str_size, 120);
this->SetFocusedWidget(NGWW_CLIENT);
UpdateNetworkGameWindow(true);
this->vscroll.cap = 11;
this->resize.step_height = NET_PRC__SIZE_OF_ROW;
this->field = NGWW_CLIENT;
this->server = NULL;
this->list_pos = SLP_INVALID;
this->servers.SetListing(this->last_sorting);
this->servers.SetSortFuncs(this->sorter_funcs);
this->servers.ForceRebuild();
this->SortNetworkGameList();
this->FindWindowPlacementAndResize(desc);
}
~NetworkGameWindow()
{
this->last_sorting = this->servers.GetListing();
}
virtual void OnPaint()
{
const NetworkGameList *sel = this->server;
const SortButtonState arrow = this->servers.IsDescSortOrder() ? SBS_DOWN : SBS_UP;
if (this->servers.NeedRebuild()) {
this->BuildNetworkGameList();
SetVScrollCount(this, this->servers.Length());
}
this->SortNetworkGameList();
/* 'Refresh' button invisible if no server selected */
this->SetWidgetDisabledState(NGWW_REFRESH, sel == NULL);
/* 'Join' button disabling conditions */
this->SetWidgetDisabledState(NGWW_JOIN, sel == NULL || // no Selected Server
!sel->online || // Server offline
sel->info.clients_on >= sel->info.clients_max || // Server full
!sel->info.compatible); // Revision mismatch
/* 'NewGRF Settings' button invisible if no NewGRF is used */
this->SetWidgetHiddenState(NGWW_NEWGRF, sel == NULL ||
!sel->online ||
sel->info.grfconfig == NULL);
SetDParam(0, 0x00);
SetDParam(1, _lan_internet_types_dropdown[_settings_client.network.lan_internet]);
this->DrawWidgets();
/* Edit box to set client name */
this->DrawEditBox(NGWW_CLIENT);
DrawString(this->widget[NGWW_CLIENT].left - 100, 23, STR_NETWORK_PLAYER_NAME, TC_GOLD);
/* Sort based on widgets: name, clients, compatibility */
switch (this->servers.SortType()) {
case NGWW_NAME - NGWW_NAME: this->DrawSortButtonState(NGWW_NAME, arrow); break;
case NGWW_CLIENTS - NGWW_NAME: this->DrawSortButtonState(NGWW_CLIENTS, arrow); break;
case NGWW_MAPSIZE - NGWW_NAME: if (!this->IsWidgetHidden(NGWW_MAPSIZE)) this->DrawSortButtonState(NGWW_MAPSIZE, arrow); break;
case NGWW_DATE - NGWW_NAME: if (!this->IsWidgetHidden(NGWW_DATE)) this->DrawSortButtonState(NGWW_DATE, arrow); break;
case NGWW_YEARS - NGWW_NAME: if (!this->IsWidgetHidden(NGWW_YEARS)) this->DrawSortButtonState(NGWW_YEARS, arrow); break;
case NGWW_INFO - NGWW_NAME: this->DrawSortButtonState(NGWW_INFO, arrow); break;
}
uint16 y = NET_PRC__OFFSET_TOP_WIDGET + 3;
const int max = min(this->vscroll.pos + this->vscroll.cap, (int)this->servers.Length());
for (int i = this->vscroll.pos; i < max; ++i) {
const NetworkGameList *ngl = this->servers[i];
this->DrawServerLine(ngl, y, ngl == sel);
y += NET_PRC__SIZE_OF_ROW;
}
const NetworkGameList *last_joined = NetworkGameListAddItem(inet_addr(_settings_client.network.last_host), _settings_client.network.last_port);
/* Draw the last joined server, if any */
if (last_joined != NULL) this->DrawServerLine(last_joined, y = this->widget[NGWW_LASTJOINED].top + 3, last_joined == sel);
/* Draw the right menu */
GfxFillRect(this->widget[NGWW_DETAILS].left + 1, 43, this->widget[NGWW_DETAILS].right - 1, 92, 157);
if (sel == NULL) {
DrawStringCentered(this->widget[NGWW_DETAILS].left + 115, 58, STR_NETWORK_GAME_INFO, TC_FROMSTRING);
} else if (!sel->online) {
SetDParamStr(0, sel->info.server_name);
DrawStringCentered(this->widget[NGWW_DETAILS].left + 115, 68, STR_JUST_RAW_STRING, TC_ORANGE); // game name
DrawStringCentered(this->widget[NGWW_DETAILS].left + 115, 132, STR_NETWORK_SERVER_OFFLINE, TC_FROMSTRING); // server offline
} else { // show game info
uint16 y = 100;
const uint16 x = this->widget[NGWW_DETAILS].left + 5;
DrawStringCentered(this->widget[NGWW_DETAILS].left + 115, 48, STR_NETWORK_GAME_INFO, TC_FROMSTRING);
SetDParamStr(0, sel->info.server_name);
DrawStringCenteredTruncated(this->widget[NGWW_DETAILS].left, this->widget[NGWW_DETAILS].right, 62, STR_JUST_RAW_STRING, TC_ORANGE); // game name
SetDParamStr(0, sel->info.map_name);
DrawStringCenteredTruncated(this->widget[NGWW_DETAILS].left, this->widget[NGWW_DETAILS].right, 74, STR_JUST_RAW_STRING, TC_BLACK); // map name
SetDParam(0, sel->info.clients_on);
SetDParam(1, sel->info.clients_max);
SetDParam(2, sel->info.companies_on);
SetDParam(3, sel->info.companies_max);
DrawString(x, y, STR_NETWORK_CLIENTS, TC_GOLD);
y += 10;
SetDParam(0, STR_NETWORK_LANG_ANY + sel->info.server_lang);
DrawString(x, y, STR_NETWORK_LANGUAGE, TC_GOLD); // server language
y += 10;
SetDParam(0, STR_TEMPERATE_LANDSCAPE + sel->info.map_set);
DrawString(x, y, STR_NETWORK_TILESET, TC_GOLD); // tileset
y += 10;
SetDParam(0, sel->info.map_width);
SetDParam(1, sel->info.map_height);
DrawString(x, y, STR_NETWORK_MAP_SIZE, TC_GOLD); // map size
y += 10;
SetDParamStr(0, sel->info.server_revision);
DrawString(x, y, STR_NETWORK_SERVER_VERSION, TC_GOLD); // server version
y += 10;
SetDParamStr(0, sel->info.hostname);
SetDParam(1, sel->port);
DrawString(x, y, STR_NETWORK_SERVER_ADDRESS, TC_GOLD); // server address
y += 10;
SetDParam(0, sel->info.start_date);
DrawString(x, y, STR_NETWORK_START_DATE, TC_GOLD); // start date
y += 10;
SetDParam(0, sel->info.game_date);
DrawString(x, y, STR_NETWORK_CURRENT_DATE, TC_GOLD); // current date
y += 10;
y += 2;
if (!sel->info.compatible) {
DrawStringCentered(this->widget[NGWW_DETAILS].left + 115, y, sel->info.version_compatible ? STR_NETWORK_GRF_MISMATCH : STR_NETWORK_VERSION_MISMATCH, TC_FROMSTRING); // server mismatch
} else if (sel->info.clients_on == sel->info.clients_max) {
/* Show: server full, when clients_on == max_clients */
DrawStringCentered(this->widget[NGWW_DETAILS].left + 115, y, STR_NETWORK_SERVER_FULL, TC_FROMSTRING); // server full
} else if (sel->info.use_password) {
DrawStringCentered(this->widget[NGWW_DETAILS].left + 115, y, STR_NETWORK_PASSWORD, TC_FROMSTRING); // password warning
}
y += 10;
}
}
virtual void OnClick(Point pt, int widget)
{
this->field = widget;
switch (widget) {
case NGWW_CANCEL: // Cancel button
DeleteWindowById(WC_NETWORK_WINDOW, 0);
break;
case NGWW_CONN_BTN: // 'Connection' droplist
ShowDropDownMenu(this, _lan_internet_types_dropdown, _settings_client.network.lan_internet, NGWW_CONN_BTN, 0, 0); // do it for widget NSSW_CONN_BTN
break;
case NGWW_NAME: // Sort by name
case NGWW_CLIENTS: // Sort by connected clients
case NGWW_MAPSIZE: // Sort by map size
case NGWW_DATE: // Sort by date
case NGWW_YEARS: // Sort by years
case NGWW_INFO: // Connectivity (green dot)
if (this->servers.SortType() == widget - NGWW_NAME) {
this->servers.ToggleSortOrder();
if (this->list_pos != SLP_INVALID) this->list_pos = this->servers.Length() - this->list_pos - 1;
} else {
this->servers.SetSortType(widget - NGWW_NAME);
this->servers.ForceResort();
this->SortNetworkGameList();
}
this->ScrollToSelectedServer();
this->SetDirty();
break;
case NGWW_MATRIX: { // Matrix to show networkgames
uint32 id_v = (pt.y - NET_PRC__OFFSET_TOP_WIDGET) / NET_PRC__SIZE_OF_ROW;
if (id_v >= this->vscroll.cap) return; // click out of bounds
id_v += this->vscroll.pos;
this->server = (id_v < this->servers.Length()) ? this->servers[id_v] : NULL;
this->list_pos = (server == NULL) ? SLP_INVALID : id_v;
this->SetDirty();
} break;
case NGWW_LASTJOINED: {
NetworkGameList *last_joined = NetworkGameListAddItem(inet_addr(_settings_client.network.last_host), _settings_client.network.last_port);
if (last_joined != NULL) {
this->server = last_joined;
/* search the position of the newly selected server */
for (uint i = 0; i < this->servers.Length(); i++) {
if (this->servers[i] == this->server) {
this->list_pos = i;
break;
}
}
this->ScrollToSelectedServer();
this->SetDirty();
}
} break;
case NGWW_FIND: // Find server automatically
switch (_settings_client.network.lan_internet) {
case 0: NetworkUDPSearchGame(); break;
case 1: NetworkUDPQueryMasterServer(); break;
}
break;
case NGWW_ADD: // Add a server
SetDParamStr(0, _settings_client.network.connect_to_ip);
ShowQueryString(
STR_JUST_RAW_STRING,
STR_NETWORK_ENTER_IP,
31, // maximum number of characters
250, // characters up to this width pixels, whichever is satisfied first
this, CS_ALPHANUMERAL, QSF_ACCEPT_UNCHANGED);
break;
case NGWW_START: // Start server
ShowNetworkStartServerWindow();
break;
case NGWW_JOIN: // Join Game
if (this->server != NULL) {
snprintf(_settings_client.network.last_host, sizeof(_settings_client.network.last_host), "%s", inet_ntoa(*(struct in_addr *)&this->server->ip));
_settings_client.network.last_port = this->server->port;
ShowNetworkLobbyWindow(this->server);
}
break;
case NGWW_REFRESH: // Refresh
if (this->server != NULL) NetworkUDPQueryServer(NetworkAddress(this->server->info.hostname, this->server->port));
break;
case NGWW_NEWGRF: // NewGRF Settings
if (this->server != NULL) ShowNewGRFSettings(false, false, false, &this->server->info.grfconfig);
break;
}
}
virtual void OnDoubleClick(Point pt, int widget)
{
if (widget == NGWW_MATRIX || widget == NGWW_LASTJOINED) {
/* is the Join button enabled? */
if (!this->IsWidgetDisabled(NGWW_JOIN)) this->OnClick(pt, NGWW_JOIN);
}
}
virtual void OnDropdownSelect(int widget, int index)
{
switch (widget) {
case NGWW_CONN_BTN:
_settings_client.network.lan_internet = index;
break;
default:
NOT_REACHED();
}
this->SetDirty();
}
virtual void OnMouseLoop()
{
if (this->field == NGWW_CLIENT) this->HandleEditBox(NGWW_CLIENT);
}
virtual void OnInvalidateData(int data)
{
switch (data) {
/* Remove the selection */
case 1:
this->server = NULL;
this->list_pos = SLP_INVALID;
break;
/* Reiterate the whole server list as we downloaded some files */
case 2:
for (NetworkGameList **iter = this->servers.Begin(); iter != this->servers.End(); iter++) {
NetworkGameList *item = *iter;
bool missing_grfs = false;
for (GRFConfig *c = item->info.grfconfig; c != NULL; c = c->next) {
if (c->status != GCS_NOT_FOUND) continue;
const GRFConfig *f = FindGRFConfig(c->grfid, c->md5sum);
if (f == NULL) {
missing_grfs = true;
continue;
}
c->filename = f->filename;
c->name = f->name;
c->info = f->info;
c->status = GCS_UNKNOWN;
}
if (!missing_grfs) item->info.compatible = item->info.version_compatible;
}
break;
}
this->servers.ForceRebuild();
this->SetDirty();
}
virtual EventState OnKeyPress(uint16 key, uint16 keycode)
{
EventState state = ES_NOT_HANDLED;
/* handle up, down, pageup, pagedown, home and end */
if (keycode == WKC_UP || keycode == WKC_DOWN || keycode == WKC_PAGEUP || keycode == WKC_PAGEDOWN || keycode == WKC_HOME || keycode == WKC_END) {
if (this->servers.Length() == 0) return ES_HANDLED;
switch (keycode) {
case WKC_UP:
/* scroll up by one */
if (this->server == NULL) return ES_HANDLED;
if (this->list_pos > 0) this->list_pos--;
break;
case WKC_DOWN:
/* scroll down by one */
if (this->server == NULL) return ES_HANDLED;
if (this->list_pos < this->servers.Length() - 1) this->list_pos++;
break;
case WKC_PAGEUP:
/* scroll up a page */
if (this->server == NULL) return ES_HANDLED;
this->list_pos = (this->list_pos < this->vscroll.cap) ? 0 : this->list_pos - this->vscroll.cap;
break;
case WKC_PAGEDOWN:
/* scroll down a page */
if (this->server == NULL) return ES_HANDLED;
this->list_pos = min(this->list_pos + this->vscroll.cap, (int)this->servers.Length() - 1);
break;
case WKC_HOME:
/* jump to beginning */
this->list_pos = 0;
break;
case WKC_END:
/* jump to end */
this->list_pos = this->servers.Length() - 1;
break;
default: break;
}
this->server = this->servers[this->list_pos];
/* scroll to the new server if it is outside the current range */
this->ScrollToSelectedServer();
/* redraw window */
this->SetDirty();
return ES_HANDLED;
}
if (this->field != NGWW_CLIENT) {
if (this->server != NULL) {
if (keycode == WKC_DELETE) { // Press 'delete' to remove servers
NetworkGameListRemoveItem(this->server);
NetworkRebuildHostList();
this->server = NULL;
this->list_pos = SLP_INVALID;
}
}
return state;
}
if (this->HandleEditBoxKey(NGWW_CLIENT, key, keycode, state) == HEBR_CONFIRM) return state;
/* The name is only allowed when it starts with a letter! */
if (!StrEmpty(this->edit_str_buf) && this->edit_str_buf[0] != ' ') {
strecpy(_settings_client.network.client_name, this->edit_str_buf, lastof(_settings_client.network.client_name));
} else {
strecpy(_settings_client.network.client_name, "Player", lastof(_settings_client.network.client_name));
}
return state;
}
virtual void OnQueryTextFinished(char *str)
{
if (!StrEmpty(str)) {
NetworkAddServer(str);
NetworkRebuildHostList();
}
}
virtual void OnResize(Point new_size, Point delta)
{
this->vscroll.cap += delta.y / (int)this->resize.step_height;
this->widget[NGWW_MATRIX].data = (this->vscroll.cap << 8) + 1;
SetVScrollCount(this, this->servers.Length());
/* Additional colums in server list */
if (this->width > NetworkGameWindow::MIN_EXTRA_COLUMNS_WIDTH + GetWidgetWidth(NGWW_MAPSIZE) +
GetWidgetWidth(NGWW_DATE) + GetWidgetWidth(NGWW_YEARS)) {
/* show columns 'Map size', 'Date' and 'Years' */
this->SetWidgetsHiddenState(false, NGWW_MAPSIZE, NGWW_DATE, NGWW_YEARS, WIDGET_LIST_END);
AlignWidgetRight(NGWW_YEARS, NGWW_INFO);
AlignWidgetRight(NGWW_DATE, NGWW_YEARS);
AlignWidgetRight(NGWW_MAPSIZE, NGWW_DATE);
AlignWidgetRight(NGWW_CLIENTS, NGWW_MAPSIZE);
} else if (this->width > NetworkGameWindow::MIN_EXTRA_COLUMNS_WIDTH + GetWidgetWidth(NGWW_MAPSIZE) + GetWidgetWidth(NGWW_DATE)) {
/* show columns 'Map size' and 'Date' */
this->SetWidgetsHiddenState(false, NGWW_MAPSIZE, NGWW_DATE, WIDGET_LIST_END);
this->HideWidget(NGWW_YEARS);
AlignWidgetRight(NGWW_DATE, NGWW_INFO);
AlignWidgetRight(NGWW_MAPSIZE, NGWW_DATE);
AlignWidgetRight(NGWW_CLIENTS, NGWW_MAPSIZE);
} else if (this->width > NetworkGameWindow::MIN_EXTRA_COLUMNS_WIDTH + GetWidgetWidth(NGWW_MAPSIZE)) {
/* show column 'Map size' */
this->ShowWidget(NGWW_MAPSIZE);
this->SetWidgetsHiddenState(true, NGWW_DATE, NGWW_YEARS, WIDGET_LIST_END);
AlignWidgetRight(NGWW_MAPSIZE, NGWW_INFO);
AlignWidgetRight(NGWW_CLIENTS, NGWW_MAPSIZE);
} else {
/* hide columns 'Map size', 'Date' and 'Years' */
this->SetWidgetsHiddenState(true, NGWW_MAPSIZE, NGWW_DATE, NGWW_YEARS, WIDGET_LIST_END);
AlignWidgetRight(NGWW_CLIENTS, NGWW_INFO);
}
this->widget[NGWW_NAME].right = this->widget[NGWW_CLIENTS].left - 1;
/* BOTTOM */
int widget_width = this->widget[NGWW_FIND].right - this->widget[NGWW_FIND].left;
int space = (this->width - 4 * widget_width - 25) / 3;
int offset = 10;
for (uint i = 0; i < 4; i++) {
this->widget[NGWW_FIND + i].left = offset;
offset += widget_width;
this->widget[NGWW_FIND + i].right = offset;
offset += space;
}
}
static const int MIN_EXTRA_COLUMNS_WIDTH = 550; ///< default width of the window
};
Listing NetworkGameWindow::last_sorting = {false, 5};
GUIGameServerList::SortFunction * const NetworkGameWindow::sorter_funcs[] = {
&NGameNameSorter,
&NGameClientSorter,
&NGameMapSizeSorter,
&NGameDateSorter,
&NGameYearsSorter,
&NGameAllowedSorter
};
static const Widget _network_game_window_widgets[] = {
/* TOP */
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_LIGHT_BLUE, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // NGWW_CLOSE
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_LIGHT_BLUE, 11, 449, 0, 13, STR_NETWORK_MULTIPLAYER, STR_NULL}, // NGWW_CAPTION
{ WWT_PANEL, RESIZE_RB, COLOUR_LIGHT_BLUE, 0, 449, 14, 263, 0x0, STR_NULL}, // NGWW_MAIN
{ WWT_TEXT, RESIZE_NONE, COLOUR_LIGHT_BLUE, 9, 85, 23, 35, STR_NETWORK_CONNECTION, STR_NULL}, // NGWW_CONNECTION
{ WWT_DROPDOWNIN, RESIZE_NONE, COLOUR_LIGHT_BLUE, 90, 181, 22, 33, STR_NETWORK_LAN_INTERNET_COMBO, STR_NETWORK_CONNECTION_TIP}, // NGWW_CONN_BTN
{ WWT_EDITBOX, RESIZE_LR, COLOUR_LIGHT_BLUE, 290, 440, 22, 33, STR_NETWORK_PLAYER_NAME_OSKTITLE, STR_NETWORK_ENTER_NAME_TIP}, // NGWW_CLIENT
/* LEFT SIDE */
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_WHITE, 10, 70, 42, 53, STR_NETWORK_GAME_NAME, STR_NETWORK_GAME_NAME_TIP}, // NGWW_NAME
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_WHITE, 71, 150, 42, 53, STR_NETWORK_CLIENTS_CAPTION, STR_NETWORK_CLIENTS_CAPTION_TIP}, // NGWW_CLIENTS
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_WHITE, 71, 150, 42, 53, STR_NETWORK_MAP_SIZE_CAPTION, STR_NETWORK_MAP_SIZE_CAPTION_TIP}, // NGWW_MAPSIZE
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_WHITE, 71, 130, 42, 53, STR_NETWORK_DATE_CAPTION, STR_NETWORK_DATE_CAPTION_TIP}, // NGWW_DATE
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_WHITE, 71, 130, 42, 53, STR_NETWORK_YEARS_CAPTION, STR_NETWORK_YEARS_CAPTION_TIP}, // NGWW_YEARS
{ WWT_PUSHTXTBTN, RESIZE_LR, COLOUR_WHITE, 151, 190, 42, 53, STR_EMPTY, STR_NETWORK_INFO_ICONS_TIP}, // NGWW_INFO
{ WWT_MATRIX, RESIZE_RB, COLOUR_LIGHT_BLUE, 10, 190, 54, 208, (11 << 8) + 1, STR_NETWORK_CLICK_GAME_TO_SELECT}, // NGWW_MATRIX
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_LIGHT_BLUE, 191, 202, 42, 208, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST}, // NGWW_SCROLLBAR
{ WWT_TEXT, RESIZE_RTB, COLOUR_LIGHT_BLUE, 10, 190, 211, 222, STR_NETWORK_LAST_JOINED_SERVER, STR_NULL}, // NGWW_LASTJOINED_LABEL
{ WWT_PANEL, RESIZE_RTB, COLOUR_LIGHT_BLUE, 10, 190, 223, 236, 0x0, STR_NETWORK_CLICK_TO_SELECT_LAST}, // NGWW_LASTJOINED
/* RIGHT SIDE */
{ WWT_PANEL, RESIZE_LRB, COLOUR_LIGHT_BLUE, 210, 440, 42, 236, 0x0, STR_NULL}, // NGWW_DETAILS
{ WWT_PUSHTXTBTN, RESIZE_LRTB, COLOUR_WHITE, 215, 315, 215, 226, STR_NETWORK_JOIN_GAME, STR_NULL}, // NGWW_JOIN
{ WWT_PUSHTXTBTN, RESIZE_LRTB, COLOUR_WHITE, 330, 435, 215, 226, STR_NETWORK_REFRESH, STR_NETWORK_REFRESH_TIP}, // NGWW_REFRESH
{ WWT_PUSHTXTBTN, RESIZE_LRTB, COLOUR_WHITE, 330, 435, 197, 208, STR_NEWGRF_SETTINGS_BUTTON, STR_NULL}, // NGWW_NEWGRF
/* BOTTOM */
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_WHITE, 10, 110, 246, 257, STR_NETWORK_FIND_SERVER, STR_NETWORK_FIND_SERVER_TIP}, // NGWW_FIND
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_WHITE, 118, 218, 246, 257, STR_NETWORK_ADD_SERVER, STR_NETWORK_ADD_SERVER_TIP}, // NGWW_ADD
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_WHITE, 226, 326, 246, 257, STR_NETWORK_START_SERVER, STR_NETWORK_START_SERVER_TIP}, // NGWW_START
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_WHITE, 334, 434, 246, 257, STR_012E_CANCEL, STR_NULL}, // NGWW_CANCEL
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_LIGHT_BLUE, 438, 449, 252, 263, 0x0, STR_RESIZE_BUTTON }, // NGWW_RESIZE
{ WIDGETS_END},
};
static const WindowDesc _network_game_window_desc(
WDP_CENTER, WDP_CENTER, 450, 264, 780, 264,
WC_NETWORK_WINDOW, WC_NONE,
WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_STD_BTN | WDF_UNCLICK_BUTTONS | WDF_RESIZABLE,
_network_game_window_widgets
);
void ShowNetworkGameWindow()
{
static bool first = true;
DeleteWindowById(WC_NETWORK_WINDOW, 0);
/* Only show once */
if (first) {
char * const *srv;
first = false;
/* add all servers from the config file to our list */
for (srv = &_network_host_list[0]; srv != endof(_network_host_list) && *srv != NULL; srv++) {
NetworkAddServer(*srv);
}
}
new NetworkGameWindow(&_network_game_window_desc);
}
enum {
NSSWND_START = 64,
NSSWND_ROWSIZE = 12
};
/** Enum for NetworkStartServerWindow, referring to _network_start_server_window_widgets */
enum NetworkStartServerWidgets {
NSSW_CLOSE = 0, ///< Close 'X' button
NSSW_GAMENAME = 4, ///< Background for editbox to set game name
NSSW_SETPWD = 5, ///< 'Set password' button
NSSW_SELMAP = 7, ///< 'Select map' list
NSSW_CONNTYPE_BTN = 10, ///< 'Connection type' droplist button
NSSW_CLIENTS_BTND = 12, ///< 'Max clients' downarrow
NSSW_CLIENTS_TXT = 13, ///< 'Max clients' text
NSSW_CLIENTS_BTNU = 14, ///< 'Max clients' uparrow
NSSW_COMPANIES_BTND = 16, ///< 'Max companies' downarrow
NSSW_COMPANIES_TXT = 17, ///< 'Max companies' text
NSSW_COMPANIES_BTNU = 18, ///< 'Max companies' uparrow
NSSW_SPECTATORS_BTND = 20, ///< 'Max spectators' downarrow
NSSW_SPECTATORS_TXT = 21, ///< 'Max spectators' text
NSSW_SPECTATORS_BTNU = 22, ///< 'Max spectators' uparrow
NSSW_LANGUAGE_BTN = 24, ///< 'Language spoken' droplist button
NSSW_START = 25, ///< 'Start' button
NSSW_LOAD = 26, ///< 'Load' button
NSSW_CANCEL = 27, ///< 'Cancel' button
};
struct NetworkStartServerWindow : public QueryStringBaseWindow {
byte field; ///< Selected text-field
FiosItem *map; ///< Selected map
byte widget_id; ///< The widget that has the pop-up input menu
NetworkStartServerWindow(const WindowDesc *desc) : QueryStringBaseWindow(NETWORK_NAME_LENGTH, desc)
{
ttd_strlcpy(this->edit_str_buf, _settings_client.network.server_name, this->edit_str_size);
_saveload_mode = SLD_NEW_GAME;
BuildFileList();
this->vscroll.cap = 12;
this->vscroll.count = _fios_items.Length() + 1;
this->afilter = CS_ALPHANUMERAL;
InitializeTextBuffer(&this->text, this->edit_str_buf, this->edit_str_size, 160);
this->SetFocusedWidget(NSSW_GAMENAME);
this->field = NSSW_GAMENAME;
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
int y = NSSWND_START;
const FiosItem *item;
/* draw basic widgets */
SetDParam(1, _connection_types_dropdown[_settings_client.network.server_advertise]);
SetDParam(2, _settings_client.network.max_clients);
SetDParam(3, _settings_client.network.max_companies);
SetDParam(4, _settings_client.network.max_spectators);
SetDParam(5, STR_NETWORK_LANG_ANY + _settings_client.network.server_lang);
this->DrawWidgets();
/* editbox to set game name */
this->DrawEditBox(NSSW_GAMENAME);
/* if password is set, draw red '*' next to 'Set password' button */
if (!StrEmpty(_settings_client.network.server_password)) DoDrawString("*", 408, 23, TC_RED);
/* draw list of maps */
GfxFillRect(11, 63, 258, 215, 0xD7); // black background of maps list
for (uint pos = this->vscroll.pos; pos < _fios_items.Length() + 1; pos++) {
item = _fios_items.Get(pos - 1);
if (item == this->map || (pos == 0 && this->map == NULL))
GfxFillRect(11, y - 1, 258, y + 10, 155); // show highlighted item with a different colour
if (pos == 0) {
DrawString(14, y, STR_4010_GENERATE_RANDOM_NEW_GAME, TC_DARK_GREEN);
} else {
DoDrawString(item->title, 14, y, _fios_colours[item->type] );
}
y += NSSWND_ROWSIZE;
if (y >= this->vscroll.cap * NSSWND_ROWSIZE + NSSWND_START) break;
}
}
virtual void OnClick(Point pt, int widget)
{
this->field = widget;
switch (widget) {
case NSSW_CLOSE: // Close 'X'
case NSSW_CANCEL: // Cancel button
ShowNetworkGameWindow();
break;
case NSSW_SETPWD: // Set password button
this->widget_id = NSSW_SETPWD;
SetDParamStr(0, _settings_client.network.server_password);
ShowQueryString(STR_JUST_RAW_STRING, STR_NETWORK_SET_PASSWORD, 20, 250, this, CS_ALPHANUMERAL, QSF_NONE);
break;
case NSSW_SELMAP: { // Select map
int y = (pt.y - NSSWND_START) / NSSWND_ROWSIZE;
y += this->vscroll.pos;
if (y >= this->vscroll.count) return;
this->map = (y == 0) ? NULL : _fios_items.Get(y - 1);
this->SetDirty();
} break;
case NSSW_CONNTYPE_BTN: // Connection type
ShowDropDownMenu(this, _connection_types_dropdown, _settings_client.network.server_advertise, NSSW_CONNTYPE_BTN, 0, 0); // do it for widget NSSW_CONNTYPE_BTN
break;
case NSSW_CLIENTS_BTND: case NSSW_CLIENTS_BTNU: // Click on up/down button for number of clients
case NSSW_COMPANIES_BTND: case NSSW_COMPANIES_BTNU: // Click on up/down button for number of companies
case NSSW_SPECTATORS_BTND: case NSSW_SPECTATORS_BTNU: // Click on up/down button for number of spectators
/* Don't allow too fast scrolling */
if ((this->flags4 & WF_TIMEOUT_MASK) <= WF_TIMEOUT_TRIGGER) {
this->HandleButtonClick(widget);
this->SetDirty();
switch (widget) {
default: NOT_REACHED();
case NSSW_CLIENTS_BTND: case NSSW_CLIENTS_BTNU:
_settings_client.network.max_clients = Clamp(_settings_client.network.max_clients + widget - NSSW_CLIENTS_TXT, 2, MAX_CLIENTS);
break;
case NSSW_COMPANIES_BTND: case NSSW_COMPANIES_BTNU:
_settings_client.network.max_companies = Clamp(_settings_client.network.max_companies + widget - NSSW_COMPANIES_TXT, 1, MAX_COMPANIES);
break;
case NSSW_SPECTATORS_BTND: case NSSW_SPECTATORS_BTNU:
_settings_client.network.max_spectators = Clamp(_settings_client.network.max_spectators + widget - NSSW_SPECTATORS_TXT, 0, MAX_CLIENTS);
break;
}
}
_left_button_clicked = false;
break;
case NSSW_CLIENTS_TXT: // Click on number of clients
this->widget_id = NSSW_CLIENTS_TXT;
SetDParam(0, _settings_client.network.max_clients);
ShowQueryString(STR_CONFIG_SETTING_INT32, STR_NETWORK_NUMBER_OF_CLIENTS, 4, 50, this, CS_NUMERAL, QSF_NONE);
break;
case NSSW_COMPANIES_TXT: // Click on number of companies
this->widget_id = NSSW_COMPANIES_TXT;
SetDParam(0, _settings_client.network.max_companies);
ShowQueryString(STR_CONFIG_SETTING_INT32, STR_NETWORK_NUMBER_OF_COMPANIES, 3, 50, this, CS_NUMERAL, QSF_NONE);
break;
case NSSW_SPECTATORS_TXT: // Click on number of spectators
this->widget_id = NSSW_SPECTATORS_TXT;
SetDParam(0, _settings_client.network.max_spectators);
ShowQueryString(STR_CONFIG_SETTING_INT32, STR_NETWORK_NUMBER_OF_SPECTATORS, 4, 50, this, CS_NUMERAL, QSF_NONE);
break;
case NSSW_LANGUAGE_BTN: { // Language
uint sel = 0;
for (uint i = 0; i < lengthof(_language_dropdown) - 1; i++) {
if (_language_dropdown[i] == STR_NETWORK_LANG_ANY + _settings_client.network.server_lang) {
sel = i;
break;
}
}
ShowDropDownMenu(this, _language_dropdown, sel, NSSW_LANGUAGE_BTN, 0, 0);
} break;
case NSSW_START: // Start game
_is_network_server = true;
if (this->map == NULL) { // start random new game
ShowGenerateLandscape();
} else { // load a scenario
const char *name = FiosBrowseTo(this->map);
if (name != NULL) {
SetFiosType(this->map->type);
_file_to_saveload.filetype = FT_SCENARIO;
strecpy(_file_to_saveload.name, name, lastof(_file_to_saveload.name));
strecpy(_file_to_saveload.title, this->map->title, lastof(_file_to_saveload.title));
delete this;
SwitchToMode(SM_START_SCENARIO);
}
}
break;
case NSSW_LOAD: // Load game
_is_network_server = true;
/* XXX - WC_NETWORK_WINDOW (this window) should stay, but if it stays, it gets
* copied all the elements of 'load game' and upon closing that, it segfaults */
delete this;
ShowSaveLoadDialog(SLD_LOAD_GAME);
break;
}
}
virtual void OnDropdownSelect(int widget, int index)
{
switch (widget) {
case NSSW_CONNTYPE_BTN:
_settings_client.network.server_advertise = (index != 0);
break;
case NSSW_LANGUAGE_BTN:
_settings_client.network.server_lang = _language_dropdown[index] - STR_NETWORK_LANG_ANY;
break;
default:
NOT_REACHED();
}
this->SetDirty();
}
virtual void OnMouseLoop()
{
if (this->field == NSSW_GAMENAME) this->HandleEditBox(NSSW_GAMENAME);
}
virtual EventState OnKeyPress(uint16 key, uint16 keycode)
{
EventState state = ES_NOT_HANDLED;
if (this->field == NSSW_GAMENAME) {
if (this->HandleEditBoxKey(NSSW_GAMENAME, key, keycode, state) == HEBR_CONFIRM) return state;
strecpy(_settings_client.network.server_name, this->text.buf, lastof(_settings_client.network.server_name));
}
return state;
}
virtual void OnQueryTextFinished(char *str)
{
if (str == NULL) return;
if (this->widget_id == NSSW_SETPWD) {
strecpy(_settings_client.network.server_password, str, lastof(_settings_client.network.server_password));
} else {
int32 value = atoi(str);
this->InvalidateWidget(this->widget_id);
switch (this->widget_id) {
default: NOT_REACHED();
case NSSW_CLIENTS_TXT: _settings_client.network.max_clients = Clamp(value, 2, MAX_CLIENTS); break;
case NSSW_COMPANIES_TXT: _settings_client.network.max_companies = Clamp(value, 1, MAX_COMPANIES); break;
case NSSW_SPECTATORS_TXT: _settings_client.network.max_spectators = Clamp(value, 0, MAX_CLIENTS); break;
}
}
this->SetDirty();
}
};
static const Widget _network_start_server_window_widgets[] = {
/* Window decoration and background panel */
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_LIGHT_BLUE, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW }, // NSSW_CLOSE
{ WWT_CAPTION, RESIZE_NONE, COLOUR_LIGHT_BLUE, 11, 419, 0, 13, STR_NETWORK_START_GAME_WINDOW, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_LIGHT_BLUE, 0, 419, 14, 243, 0x0, STR_NULL},
/* Set game name and password widgets */
{ WWT_TEXT, RESIZE_NONE, COLOUR_LIGHT_BLUE, 10, 90, 22, 34, STR_NETWORK_NEW_GAME_NAME, STR_NULL},
{ WWT_EDITBOX, RESIZE_NONE, COLOUR_LIGHT_BLUE, 100, 272, 22, 33, STR_NETWORK_NEW_GAME_NAME_OSKTITLE, STR_NETWORK_NEW_GAME_NAME_TIP}, // NSSW_GAMENAME
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_WHITE, 285, 405, 22, 33, STR_NETWORK_SET_PASSWORD, STR_NETWORK_PASSWORD_TIP}, // NSSW_SETPWD
/* List of playable scenarios */
{ WWT_TEXT, RESIZE_NONE, COLOUR_LIGHT_BLUE, 10, 110, 43, 55, STR_NETWORK_SELECT_MAP, STR_NULL},
{ WWT_INSET, RESIZE_NONE, COLOUR_LIGHT_BLUE, 10, 271, 62, 216, STR_NULL, STR_NETWORK_SELECT_MAP_TIP}, // NSSW_SELMAP
{ WWT_SCROLLBAR, RESIZE_NONE, COLOUR_LIGHT_BLUE, 259, 270, 63, 215, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST},
/* Combo/selection boxes to control Connection Type / Max Clients / Max Companies / Max Observers / Language */
{ WWT_TEXT, RESIZE_NONE, COLOUR_LIGHT_BLUE, 280, 419, 63, 75, STR_NETWORK_CONNECTION, STR_NULL},
{ WWT_DROPDOWNIN, RESIZE_NONE, COLOUR_LIGHT_BLUE, 280, 410, 77, 88, STR_NETWORK_LAN_INTERNET_COMBO, STR_NETWORK_CONNECTION_TIP}, // NSSW_CONNTYPE_BTN
{ WWT_TEXT, RESIZE_NONE, COLOUR_LIGHT_BLUE, 280, 419, 95, 107, STR_NETWORK_NUMBER_OF_CLIENTS, STR_NULL},
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_LIGHT_BLUE, 280, 291, 109, 120, SPR_ARROW_DOWN, STR_NETWORK_NUMBER_OF_CLIENTS_TIP}, // NSSW_CLIENTS_BTND
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_LIGHT_BLUE, 292, 397, 109, 120, STR_NETWORK_CLIENTS_SELECT, STR_NETWORK_NUMBER_OF_CLIENTS_TIP}, // NSSW_CLIENTS_TXT
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_LIGHT_BLUE, 398, 410, 109, 120, SPR_ARROW_UP, STR_NETWORK_NUMBER_OF_CLIENTS_TIP}, // NSSW_CLIENTS_BTNU
{ WWT_TEXT, RESIZE_NONE, COLOUR_LIGHT_BLUE, 280, 419, 127, 139, STR_NETWORK_NUMBER_OF_COMPANIES, STR_NULL},
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_LIGHT_BLUE, 280, 291, 141, 152, SPR_ARROW_DOWN, STR_NETWORK_NUMBER_OF_COMPANIES_TIP}, // NSSW_COMPANIES_BTND
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_LIGHT_BLUE, 292, 397, 141, 152, STR_NETWORK_COMPANIES_SELECT, STR_NETWORK_NUMBER_OF_COMPANIES_TIP}, // NSSW_COMPANIES_TXT
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_LIGHT_BLUE, 398, 410, 141, 152, SPR_ARROW_UP, STR_NETWORK_NUMBER_OF_COMPANIES_TIP}, // NSSW_COMPANIES_BTNU
{ WWT_TEXT, RESIZE_NONE, COLOUR_LIGHT_BLUE, 280, 419, 159, 171, STR_NETWORK_NUMBER_OF_SPECTATORS, STR_NULL},
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_LIGHT_BLUE, 280, 291, 173, 184, SPR_ARROW_DOWN, STR_NETWORK_NUMBER_OF_SPECTATORS_TIP}, // NSSW_SPECTATORS_BTND
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_LIGHT_BLUE, 292, 397, 173, 184, STR_NETWORK_SPECTATORS_SELECT, STR_NETWORK_NUMBER_OF_SPECTATORS_TIP}, // NSSW_SPECTATORS_TXT
{ WWT_IMGBTN, RESIZE_NONE, COLOUR_LIGHT_BLUE, 398, 410, 173, 184, SPR_ARROW_UP, STR_NETWORK_NUMBER_OF_SPECTATORS_TIP}, // NSSW_SPECTATORS_BTNU
{ WWT_TEXT, RESIZE_NONE, COLOUR_LIGHT_BLUE, 280, 419, 191, 203, STR_NETWORK_LANGUAGE_SPOKEN, STR_NULL},
{ WWT_DROPDOWNIN, RESIZE_NONE, COLOUR_LIGHT_BLUE, 280, 410, 205, 216, STR_NETWORK_LANGUAGE_COMBO, STR_NETWORK_LANGUAGE_TIP}, // NSSW_LANGUAGE_BTN
/* Buttons Start / Load / Cancel */
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_WHITE, 40, 140, 224, 235, STR_NETWORK_START_GAME, STR_NETWORK_START_GAME_TIP}, // NSSW_START
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_WHITE, 150, 250, 224, 235, STR_NETWORK_LOAD_GAME, STR_NETWORK_LOAD_GAME_TIP}, // NSSW_LOAD
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_WHITE, 260, 360, 224, 235, STR_012E_CANCEL, STR_NULL}, // NSSW_CANCEL
{ WIDGETS_END},
};
static const WindowDesc _network_start_server_window_desc(
WDP_CENTER, WDP_CENTER, 420, 244, 420, 244,
WC_NETWORK_WINDOW, WC_NONE,
WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
_network_start_server_window_widgets
);
static void ShowNetworkStartServerWindow()
{
DeleteWindowById(WC_NETWORK_WINDOW, 0);
new NetworkStartServerWindow(&_network_start_server_window_desc);
}
/** Enum for NetworkLobbyWindow, referring to _network_lobby_window_widgets */
enum NetworkLobbyWindowWidgets {
NLWW_CLOSE = 0, ///< Close 'X' button
NLWW_MATRIX = 5, ///< List of companies
NLWW_DETAILS = 7, ///< Company details
NLWW_JOIN = 8, ///< 'Join company' button
NLWW_NEW = 9, ///< 'New company' button
NLWW_SPECTATE = 10, ///< 'Spectate game' button
NLWW_REFRESH = 11, ///< 'Refresh server' button
NLWW_CANCEL = 12, ///< 'Cancel' button
};
struct NetworkLobbyWindow : public Window {
CompanyID company; ///< Select company
NetworkGameList *server; ///< Selected server
NetworkCompanyInfo company_info[MAX_COMPANIES];
NetworkLobbyWindow(const WindowDesc *desc, NetworkGameList *ngl) :
Window(desc), company(INVALID_COMPANY), server(ngl)
{
this->vscroll.cap = 10;
this->FindWindowPlacementAndResize(desc);
}
CompanyID NetworkLobbyFindCompanyIndex(byte pos)
{
/* Scroll through all this->company_info and get the 'pos' item that is not empty */
for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) {
if (!StrEmpty(this->company_info[i].company_name)) {
if (pos-- == 0) return i;
}
}
return COMPANY_FIRST;
}
virtual void OnPaint()
{
const NetworkGameInfo *gi = &this->server->info;
int y = NET_PRC__OFFSET_TOP_WIDGET_COMPANY, pos;
/* Join button is disabled when no company is selected and for AI companies*/
this->SetWidgetDisabledState(NLWW_JOIN, this->company == INVALID_COMPANY || GetLobbyCompanyInfo(this->company)->ai);
/* Cannot start new company if there are too many */
this->SetWidgetDisabledState(NLWW_NEW, gi->companies_on >= gi->companies_max);
/* Cannot spectate if there are too many spectators */
this->SetWidgetDisabledState(NLWW_SPECTATE, gi->spectators_on >= gi->spectators_max);
/* Draw window widgets */
SetDParamStr(0, gi->server_name);
this->DrawWidgets();
SetVScrollCount(this, gi->companies_on);
/* Draw company list */
pos = this->vscroll.pos;
while (pos < gi->companies_on) {
byte company = NetworkLobbyFindCompanyIndex(pos);
bool income = false;
if (this->company == company) {
GfxFillRect(11, y - 1, 154, y + 10, 10); // show highlighted item with a different colour
}
DoDrawStringTruncated(this->company_info[company].company_name, 13, y, TC_BLACK, 135 - 13);
if (this->company_info[company].use_password != 0) DrawSprite(SPR_LOCK, PAL_NONE, 135, y);
/* If the company's income was positive puts a green dot else a red dot */
if (this->company_info[company].income >= 0) income = true;
DrawSprite(SPR_BLOT, income ? PALETTE_TO_GREEN : PALETTE_TO_RED, 145, y);
pos++;
y += NET_PRC__SIZE_OF_ROW;
if (pos >= this->vscroll.pos + this->vscroll.cap) break;
}
/* Draw info about selected company when it is selected in the left window */
GfxFillRect(174, 39, 403, 75, 157);
DrawStringCentered(290, 50, STR_NETWORK_COMPANY_INFO, TC_FROMSTRING);
if (this->company != INVALID_COMPANY && !StrEmpty(this->company_info[this->company].company_name)) {
const uint x = 183;
const uint trunc_width = this->widget[NLWW_DETAILS].right - x;
y = 80;
SetDParam(0, gi->clients_on);
SetDParam(1, gi->clients_max);
SetDParam(2, gi->companies_on);
SetDParam(3, gi->companies_max);
DrawString(x, y, STR_NETWORK_CLIENTS, TC_GOLD);
y += 10;
SetDParamStr(0, this->company_info[this->company].company_name);
DrawStringTruncated(x, y, STR_NETWORK_COMPANY_NAME, TC_GOLD, trunc_width);
y += 10;
SetDParam(0, this->company_info[this->company].inaugurated_year);
DrawString(x, y, STR_NETWORK_INAUGURATION_YEAR, TC_GOLD); // inauguration year
y += 10;
SetDParam(0, this->company_info[this->company].company_value);
DrawString(x, y, STR_NETWORK_VALUE, TC_GOLD); // company value
y += 10;
SetDParam(0, this->company_info[this->company].money);
DrawString(x, y, STR_NETWORK_CURRENT_BALANCE, TC_GOLD); // current balance
y += 10;
SetDParam(0, this->company_info[this->company].income);
DrawString(x, y, STR_NETWORK_LAST_YEARS_INCOME, TC_GOLD); // last year's income
y += 10;
SetDParam(0, this->company_info[this->company].performance);
DrawString(x, y, STR_NETWORK_PERFORMANCE, TC_GOLD); // performance
y += 10;
SetDParam(0, this->company_info[this->company].num_vehicle[0]);
SetDParam(1, this->company_info[this->company].num_vehicle[1]);
SetDParam(2, this->company_info[this->company].num_vehicle[2]);
SetDParam(3, this->company_info[this->company].num_vehicle[3]);
SetDParam(4, this->company_info[this->company].num_vehicle[4]);
DrawString(x, y, STR_NETWORK_VEHICLES, TC_GOLD); // vehicles
y += 10;
SetDParam(0, this->company_info[this->company].num_station[0]);
SetDParam(1, this->company_info[this->company].num_station[1]);
SetDParam(2, this->company_info[this->company].num_station[2]);
SetDParam(3, this->company_info[this->company].num_station[3]);
SetDParam(4, this->company_info[this->company].num_station[4]);
DrawString(x, y, STR_NETWORK_STATIONS, TC_GOLD); // stations
y += 10;
SetDParamStr(0, this->company_info[this->company].clients);
DrawStringTruncated(x, y, STR_NETWORK_PLAYERS, TC_GOLD, trunc_width); // players
}
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case NLWW_CLOSE: // Close 'X'
case NLWW_CANCEL: // Cancel button
ShowNetworkGameWindow();
break;
case NLWW_MATRIX: { // Company list
uint32 id_v = (pt.y - NET_PRC__OFFSET_TOP_WIDGET_COMPANY) / NET_PRC__SIZE_OF_ROW;
if (id_v >= this->vscroll.cap) break;
id_v += this->vscroll.pos;
this->company = (id_v >= this->server->info.companies_on) ? INVALID_COMPANY : NetworkLobbyFindCompanyIndex(id_v);
this->SetDirty();
} break;
case NLWW_JOIN: // Join company
/* Button can be clicked only when it is enabled */
_network_playas = this->company;
NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port));
break;
case NLWW_NEW: // New company
_network_playas = COMPANY_NEW_COMPANY;
NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port));
break;
case NLWW_SPECTATE: // Spectate game
_network_playas = COMPANY_SPECTATOR;
NetworkClientConnectGame(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port));
break;
case NLWW_REFRESH: // Refresh
NetworkTCPQueryServer(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port)); // company info
NetworkUDPQueryServer(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port)); // general data
/* Clear the information so removed companies don't remain */
memset(this->company_info, 0, sizeof(this->company_info));
break;
}
}
virtual void OnDoubleClick(Point pt, int widget)
{
if (widget == NLWW_MATRIX) {
/* is the Join button enabled? */
if (!this->IsWidgetDisabled(NLWW_JOIN)) this->OnClick(pt, NLWW_JOIN);
}
}
};
static const Widget _network_lobby_window_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_LIGHT_BLUE, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW }, // NLWW_CLOSE
{ WWT_CAPTION, RESIZE_NONE, COLOUR_LIGHT_BLUE, 11, 419, 0, 13, STR_NETWORK_GAME_LOBBY, STR_NULL},
{ WWT_PANEL, RESIZE_NONE, COLOUR_LIGHT_BLUE, 0, 419, 14, 234, 0x0, STR_NULL},
{ WWT_TEXT, RESIZE_NONE, COLOUR_LIGHT_BLUE, 10, 419, 22, 34, STR_NETWORK_PREPARE_TO_JOIN, STR_NULL},
/* company list */
{ WWT_PANEL, RESIZE_NONE, COLOUR_WHITE, 10, 155, 38, 49, 0x0, STR_NULL},
{ WWT_MATRIX, RESIZE_NONE, COLOUR_LIGHT_BLUE, 10, 155, 50, 190, (10 << 8) + 1, STR_NETWORK_COMPANY_LIST_TIP}, // NLWW_MATRIX
{ WWT_SCROLLBAR, RESIZE_NONE, COLOUR_LIGHT_BLUE, 156, 167, 38, 190, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST},
/* company info */
{ WWT_PANEL, RESIZE_NONE, COLOUR_LIGHT_BLUE, 173, 404, 38, 190, 0x0, STR_NULL}, // NLWW_DETAILS
/* buttons */
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_WHITE, 10, 151, 200, 211, STR_NETWORK_JOIN_COMPANY, STR_NETWORK_JOIN_COMPANY_TIP}, // NLWW_JOIN
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_WHITE, 10, 151, 215, 226, STR_NETWORK_NEW_COMPANY, STR_NETWORK_NEW_COMPANY_TIP}, // NLWW_NEW
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_WHITE, 158, 268, 200, 211, STR_NETWORK_SPECTATE_GAME, STR_NETWORK_SPECTATE_GAME_TIP}, // NLWW_SPECTATE
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_WHITE, 158, 268, 215, 226, STR_NETWORK_REFRESH, STR_NETWORK_REFRESH_TIP}, // NLWW_REFRESH
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_WHITE, 278, 388, 200, 211, STR_012E_CANCEL, STR_NULL}, // NLWW_CANCEL
{ WIDGETS_END},
};
static const WindowDesc _network_lobby_window_desc(
WDP_CENTER, WDP_CENTER, 420, 235, 420, 235,
WC_NETWORK_WINDOW, WC_NONE,
WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
_network_lobby_window_widgets
);
/* Show the networklobbywindow with the selected server
* @param ngl Selected game pointer which is passed to the new window */
static void ShowNetworkLobbyWindow(NetworkGameList *ngl)
{
DeleteWindowById(WC_NETWORK_WINDOW, 0);
NetworkTCPQueryServer(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port)); // company info
NetworkUDPQueryServer(NetworkAddress(_settings_client.network.last_host, _settings_client.network.last_port)); // general data
new NetworkLobbyWindow(&_network_lobby_window_desc, ngl);
}
/**
* Get the company information of a given company to fill for the lobby.
* @param company the company to get the company info struct from.
* @return the company info struct to write the (downloaded) data to.
*/
NetworkCompanyInfo *GetLobbyCompanyInfo(CompanyID company)
{
NetworkLobbyWindow *lobby = dynamic_cast<NetworkLobbyWindow*>(FindWindowById(WC_NETWORK_WINDOW, 0));
return (lobby != NULL && company < MAX_COMPANIES) ? &lobby->company_info[company] : NULL;
}
/* The window below gives information about the connected clients
* and also makes able to give money to them, kick them (if server)
* and stuff like that. */
extern void DrawCompanyIcon(CompanyID cid, int x, int y);
/* Every action must be of this form */
typedef void ClientList_Action_Proc(byte client_no);
/* Max 10 actions per client */
#define MAX_CLIENTLIST_ACTION 10
enum {
CLNWND_OFFSET = 16,
CLNWND_ROWSIZE = 10
};
static const Widget _client_list_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 11, 237, 0, 13, STR_NETWORK_CLIENT_LIST, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_STICKYBOX, RESIZE_NONE, COLOUR_GREY, 238, 249, 0, 13, STR_NULL, STR_STICKY_BUTTON},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 249, 14, 14 + CLNWND_ROWSIZE + 1, 0x0, STR_NULL},
{ WIDGETS_END},
};
static const Widget _client_list_popup_widgets[] = {
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 99, 0, 0, 0, STR_NULL},
{ WIDGETS_END},
};
static const WindowDesc _client_list_desc(
WDP_AUTO, WDP_AUTO, 250, 1, 250, 1,
WC_CLIENT_LIST, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_STICKY_BUTTON,
_client_list_widgets
);
/* Finds the Xth client-info that is active */
static const NetworkClientInfo *NetworkFindClientInfo(byte client_no)
{
const NetworkClientInfo *ci;
FOR_ALL_CLIENT_INFOS(ci) {
if (client_no == 0) return ci;
client_no--;
}
return NULL;
}
/* Here we start to define the options out of the menu */
static void ClientList_Kick(byte client_no)
{
const NetworkClientInfo *ci = NetworkFindClientInfo(client_no);
if (ci == NULL) return;
NetworkServerKickClient(ci->client_id);
}
static void ClientList_Ban(byte client_no)
{
const NetworkClientInfo *ci = NetworkFindClientInfo(client_no);
if (ci == NULL) return;
NetworkServerBanIP(GetClientIP(ci));
}
static void ClientList_GiveMoney(byte client_no)
{
if (NetworkFindClientInfo(client_no) != NULL) {
ShowNetworkGiveMoneyWindow(NetworkFindClientInfo(client_no)->client_playas);
}
}
static void ClientList_SpeakToClient(byte client_no)
{
if (NetworkFindClientInfo(client_no) != NULL) {
ShowNetworkChatQueryWindow(DESTTYPE_CLIENT, NetworkFindClientInfo(client_no)->client_id);
}
}
static void ClientList_SpeakToCompany(byte client_no)
{
if (NetworkFindClientInfo(client_no) != NULL) {
ShowNetworkChatQueryWindow(DESTTYPE_TEAM, NetworkFindClientInfo(client_no)->client_playas);
}
}
static void ClientList_SpeakToAll(byte client_no)
{
ShowNetworkChatQueryWindow(DESTTYPE_BROADCAST, 0);
}
static void ClientList_None(byte client_no)
{
/* No action ;) */
}
struct NetworkClientListPopupWindow : Window {
int sel_index;
int client_no;
char action[MAX_CLIENTLIST_ACTION][50];
ClientList_Action_Proc *proc[MAX_CLIENTLIST_ACTION];
NetworkClientListPopupWindow(int x, int y, const Widget *widgets, int client_no) :
Window(x, y, 150, 100, WC_TOOLBAR_MENU, widgets),
sel_index(0), client_no(client_no)
{
/*
* Fill the actions this client has.
* Watch is, max 50 chars long!
*/
const NetworkClientInfo *ci = NetworkFindClientInfo(client_no);
int i = 0;
if (_network_own_client_id != ci->client_id) {
GetString(this->action[i], STR_NETWORK_CLIENTLIST_SPEAK_TO_CLIENT, lastof(this->action[i]));
this->proc[i++] = &ClientList_SpeakToClient;
}
if (IsValidCompanyID(ci->client_playas) || ci->client_playas == COMPANY_SPECTATOR) {
GetString(this->action[i], STR_NETWORK_CLIENTLIST_SPEAK_TO_COMPANY, lastof(this->action[i]));
this->proc[i++] = &ClientList_SpeakToCompany;
}
GetString(this->action[i], STR_NETWORK_CLIENTLIST_SPEAK_TO_ALL, lastof(this->action[i]));
this->proc[i++] = &ClientList_SpeakToAll;
if (_network_own_client_id != ci->client_id) {
/* We are no spectator and the company we want to give money to is no spectator and money gifts are allowed */
if (IsValidCompanyID(_network_playas) && IsValidCompanyID(ci->client_playas) && _settings_game.economy.give_money) {
GetString(this->action[i], STR_NETWORK_CLIENTLIST_GIVE_MONEY, lastof(this->action[i]));
this->proc[i++] = &ClientList_GiveMoney;
}
}
/* A server can kick clients (but not himself) */
if (_network_server && _network_own_client_id != ci->client_id) {
GetString(this->action[i], STR_NETWORK_CLIENTLIST_KICK, lastof(this->action[i]));
this->proc[i++] = &ClientList_Kick;
seprintf(this->action[i], lastof(this->action[i]), "Ban"); // XXX GetString?
this->proc[i++] = &ClientList_Ban;
}
if (i == 0) {
GetString(this->action[i], STR_NETWORK_CLIENTLIST_NONE, lastof(this->action[i]));
this->proc[i++] = &ClientList_None;
}
/* Calculate the height */
int h = ClientListPopupHeight();
/* Allocate the popup */
this->widget[0].bottom = this->widget[0].top + h;
this->widget[0].right = this->widget[0].left + 150;
this->flags4 &= ~WF_WHITE_BORDER_MASK;
this->FindWindowPlacementAndResize(150, h + 1);
}
/**
* An action is clicked! What do we do?
*/
void HandleClientListPopupClick(byte index)
{
/* A click on the Popup of the ClientList.. handle the command */
if (index < MAX_CLIENTLIST_ACTION && this->proc[index] != NULL) {
this->proc[index](this->client_no);
}
}
/**
* Finds the amount of actions in the popup and set the height correct
*/
uint ClientListPopupHeight()
{
int num = 0;
/* Find the amount of actions */
for (int i = 0; i < MAX_CLIENTLIST_ACTION; i++) {
if (this->action[i][0] == '\0') continue;
if (this->proc[i] == NULL) continue;
num++;
}
num *= CLNWND_ROWSIZE;
return num + 1;
}
virtual void OnPaint()
{
this->DrawWidgets();
/* Draw the actions */
int sel = this->sel_index;
int y = 1;
for (int i = 0; i < MAX_CLIENTLIST_ACTION; i++, y += CLNWND_ROWSIZE) {
if (this->action[i][0] == '\0') continue;
if (this->proc[i] == NULL) continue;
TextColour colour;
if (sel-- == 0) { // Selected item, highlight it
GfxFillRect(1, y, 150 - 2, y + CLNWND_ROWSIZE - 1, 0);
colour = TC_WHITE;
} else {
colour = TC_BLACK;
}
DoDrawString(this->action[i], 4, y, colour);
}
}
virtual void OnMouseLoop()
{
/* We selected an action */
int index = (_cursor.pos.y - this->top) / CLNWND_ROWSIZE;
if (_left_button_down) {
if (index == -1 || index == this->sel_index) return;
this->sel_index = index;
this->SetDirty();
} else {
if (index >= 0 && _cursor.pos.y >= this->top) {
HandleClientListPopupClick(index);
}
DeleteWindowById(WC_TOOLBAR_MENU, 0);
}
}
};
/**
* Show the popup (action list)
*/
static void PopupClientList(int client_no, int x, int y)
{
DeleteWindowById(WC_TOOLBAR_MENU, 0);
if (NetworkFindClientInfo(client_no) == NULL) return;
new NetworkClientListPopupWindow(x, y, _client_list_popup_widgets, client_no);
}
/**
* Main handle for clientlist
*/
struct NetworkClientListWindow : Window
{
int selected_item;
int selected_y;
NetworkClientListWindow(const WindowDesc *desc, WindowNumber window_number) :
Window(desc, window_number),
selected_item(-1),
selected_y(0)
{
this->FindWindowPlacementAndResize(desc);
}
/**
* Finds the amount of clients and set the height correct
*/
bool CheckClientListHeight()
{
int num = 0;
const NetworkClientInfo *ci;
/* Should be replaced with a loop through all clients */
FOR_ALL_CLIENT_INFOS(ci) {
if (ci->client_playas != COMPANY_INACTIVE_CLIENT) num++;
}
num *= CLNWND_ROWSIZE;
/* If height is changed */
if (this->height != CLNWND_OFFSET + num + 1) {
/* XXX - magic unfortunately; (num + 2) has to be one bigger than heigh (num + 1) */
this->SetDirty();
this->widget[3].bottom = this->widget[3].top + num + 2;
this->height = CLNWND_OFFSET + num + 1;
this->SetDirty();
return false;
}
return true;
}
virtual void OnPaint()
{
NetworkClientInfo *ci;
int i = 0;
/* Check if we need to reset the height */
if (!this->CheckClientListHeight()) return;
this->DrawWidgets();
int y = CLNWND_OFFSET;
FOR_ALL_CLIENT_INFOS(ci) {
TextColour colour;
if (this->selected_item == i++) { // Selected item, highlight it
GfxFillRect(1, y, 248, y + CLNWND_ROWSIZE - 1, 0);
colour = TC_WHITE;
} else {
colour = TC_BLACK;
}
if (ci->client_id == CLIENT_ID_SERVER) {
DrawString(4, y, STR_NETWORK_SERVER, colour);
} else {
DrawString(4, y, STR_NETWORK_CLIENT, colour);
}
/* Filter out spectators */
if (IsValidCompanyID(ci->client_playas)) DrawCompanyIcon(ci->client_playas, 64, y + 1);
DoDrawString(ci->client_name, 81, y, colour);
y += CLNWND_ROWSIZE;
}
}
virtual void OnClick(Point pt, int widget)
{
/* Show the popup with option */
if (this->selected_item != -1) {
PopupClientList(this->selected_item, pt.x + this->left, pt.y + this->top);
}
}
virtual void OnMouseOver(Point pt, int widget)
{
/* -1 means we left the current window */
if (pt.y == -1) {
this->selected_y = 0;
this->selected_item = -1;
this->SetDirty();
return;
}
/* It did not change.. no update! */
if (pt.y == this->selected_y) return;
/* Find the new selected item (if any) */
this->selected_y = pt.y;
if (pt.y > CLNWND_OFFSET) {
this->selected_item = (pt.y - CLNWND_OFFSET) / CLNWND_ROWSIZE;
} else {
this->selected_item = -1;
}
/* Repaint */
this->SetDirty();
}
};
void ShowClientList()
{
AllocateWindowDescFront<NetworkClientListWindow>(&_client_list_desc, 0);
}
static NetworkPasswordType pw_type;
void ShowNetworkNeedPassword(NetworkPasswordType npt)
{
StringID caption;
pw_type = npt;
switch (npt) {
default: NOT_REACHED();
case NETWORK_GAME_PASSWORD: caption = STR_NETWORK_NEED_GAME_PASSWORD_CAPTION; break;
case NETWORK_COMPANY_PASSWORD: caption = STR_NETWORK_NEED_COMPANY_PASSWORD_CAPTION; break;
}
ShowQueryString(STR_EMPTY, caption, 20, 180, FindWindowById(WC_NETWORK_STATUS_WINDOW, 0), CS_ALPHANUMERAL, QSF_NONE);
}
/* Vars needed for the join-GUI */
NetworkJoinStatus _network_join_status;
uint8 _network_join_waiting;
uint32 _network_join_bytes;
uint32 _network_join_bytes_total;
struct NetworkJoinStatusWindow : Window {
NetworkJoinStatusWindow(const WindowDesc *desc) : Window(desc)
{
this->parent = FindWindowById(WC_NETWORK_WINDOW, 0);
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
uint8 progress; // used for progress bar
this->DrawWidgets();
DrawStringCentered(125, 35, STR_NETWORK_CONNECTING_1 + _network_join_status, TC_GREY);
switch (_network_join_status) {
case NETWORK_JOIN_STATUS_CONNECTING: case NETWORK_JOIN_STATUS_AUTHORIZING:
case NETWORK_JOIN_STATUS_GETTING_COMPANY_INFO:
progress = 10; // first two stages 10%
break;
case NETWORK_JOIN_STATUS_WAITING:
SetDParam(0, _network_join_waiting);
DrawStringCentered(125, 46, STR_NETWORK_CONNECTING_WAITING, TC_GREY);
progress = 15; // third stage is 15%
break;
case NETWORK_JOIN_STATUS_DOWNLOADING:
SetDParam(0, _network_join_bytes);
SetDParam(1, _network_join_bytes_total);
DrawStringCentered(125, 46, STR_NETWORK_CONNECTING_DOWNLOADING, TC_GREY);
/* Fallthrough */
default: // Waiting is 15%, so the resting receivement of map is maximum 70%
progress = 15 + _network_join_bytes * (100 - 15) / _network_join_bytes_total;
}
/* Draw nice progress bar :) */
DrawFrameRect(20, 18, (int)((this->width - 20) * progress / 100), 28, COLOUR_MAUVE, FR_NONE);
}
virtual void OnClick(Point pt, int widget)
{
if (widget == 2) { // Disconnect button
NetworkDisconnect();
SwitchToMode(SM_MENU);
ShowNetworkGameWindow();
}
}
virtual void OnQueryTextFinished(char *str)
{
if (StrEmpty(str)) {
NetworkDisconnect();
ShowNetworkGameWindow();
} else {
SEND_COMMAND(PACKET_CLIENT_PASSWORD)(pw_type, str);
}
}
};
static const Widget _network_join_status_window_widget[] = {
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 0, 249, 0, 13, STR_NETWORK_CONNECTING, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 249, 14, 84, 0x0, STR_NULL},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_WHITE, 75, 175, 69, 80, STR_NETWORK_DISCONNECT, STR_NULL},
{ WIDGETS_END},
};
static const WindowDesc _network_join_status_window_desc(
WDP_CENTER, WDP_CENTER, 250, 85, 250, 85,
WC_NETWORK_STATUS_WINDOW, WC_NONE,
WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_MODAL,
_network_join_status_window_widget
);
void ShowJoinStatusWindow()
{
DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
new NetworkJoinStatusWindow(&_network_join_status_window_desc);
}
/** Enum for NetworkGameWindow, referring to _network_game_window_widgets */
enum NetworkCompanyPasswordWindowWidgets {
NCPWW_CLOSE, ///< Close 'X' button
NCPWW_CAPTION, ///< Caption of the whole window
NCPWW_BACKGROUND, ///< The background of the interface
NCPWW_LABEL, ///< Label in front of the password field
NCPWW_PASSWORD, ///< Input field for the password
NCPWW_SAVE_AS_DEFAULT_PASSWORD, ///< Toggle 'button' for saving the current password as default password
NCPWW_CANCEL, ///< Close the window without changing anything
NCPWW_OK, ///< Safe the password etc.
};
struct NetworkCompanyPasswordWindow : public QueryStringBaseWindow {
NetworkCompanyPasswordWindow(const WindowDesc *desc, Window *parent) : QueryStringBaseWindow(lengthof(_settings_client.network.default_company_pass), desc)
{
this->parent = parent;
this->afilter = CS_ALPHANUMERAL;
InitializeTextBuffer(&this->text, this->edit_str_buf, this->edit_str_size, 0);
this->SetFocusedWidget(NCPWW_PASSWORD);
this->FindWindowPlacementAndResize(desc);
}
void OnOk()
{
if (this->IsWidgetLowered(NCPWW_SAVE_AS_DEFAULT_PASSWORD)) {
snprintf(_settings_client.network.default_company_pass, lengthof(_settings_client.network.default_company_pass), "%s", this->edit_str_buf);
}
/* empty password is a '*' because of console argument */
if (StrEmpty(this->edit_str_buf)) snprintf(this->edit_str_buf, this->edit_str_size, "*");
char *password = this->edit_str_buf;
NetworkChangeCompanyPassword(1, &password);
}
virtual void OnPaint()
{
this->DrawWidgets();
this->DrawEditBox(4);
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case NCPWW_OK:
this->OnOk();
/* FALL THROUGH */
case NCPWW_CANCEL:
delete this;
break;
case NCPWW_SAVE_AS_DEFAULT_PASSWORD:
this->ToggleWidgetLoweredState(NCPWW_SAVE_AS_DEFAULT_PASSWORD);
this->SetDirty();
break;
}
}
virtual void OnMouseLoop()
{
this->HandleEditBox(4);
}
virtual EventState OnKeyPress(uint16 key, uint16 keycode)
{
EventState state = ES_NOT_HANDLED;
switch (this->HandleEditBoxKey(4, key, keycode, state)) {
default: break;
case HEBR_CONFIRM:
this->OnOk();
/* FALL THROUGH */
case HEBR_CANCEL:
delete this;
break;
}
return state;
}
virtual void OnOpenOSKWindow(int wid)
{
ShowOnScreenKeyboard(this, wid, NCPWW_CANCEL, NCPWW_OK);
}
};
static const Widget _ncp_window_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW},
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 11, 299, 0, 13, STR_COMPANY_PASSWORD_CAPTION, STR_018C_WINDOW_TITLE_DRAG_THIS},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 299, 14, 50, 0x0, STR_NULL},
{ WWT_TEXT, RESIZE_NONE, COLOUR_GREY, 5, 100, 19, 30, STR_COMPANY_PASSWORD, STR_NULL},
{ WWT_EDITBOX, RESIZE_NONE, COLOUR_GREY, 101, 294, 19, 30, STR_SET_COMPANY_PASSWORD, STR_NULL},
{ WWT_TEXTBTN, RESIZE_NONE, COLOUR_GREY, 101, 294, 35, 46, STR_MAKE_DEFAULT_COMPANY_PASSWORD, STR_MAKE_DEFAULT_COMPANY_PASSWORD_TIP},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 0, 149, 51, 62, STR_012E_CANCEL, STR_COMPANY_PASSWORD_CANCEL},
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_GREY, 150, 299, 51, 62, STR_012F_OK, STR_COMPANY_PASSWORD_OK},
{ WIDGETS_END},
};
static const WindowDesc _ncp_window_desc(
WDP_AUTO, WDP_AUTO, 300, 63, 300, 63,
WC_COMPANY_PASSWORD_WINDOW, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_STICKY_BUTTON,
_ncp_window_widgets
);
void ShowNetworkCompanyPasswordWindow(Window *parent)
{
DeleteWindowById(WC_COMPANY_PASSWORD_WINDOW, 0);
new NetworkCompanyPasswordWindow(&_ncp_window_desc, parent);
}
#endif /* ENABLE_NETWORK */
| 74,052
|
C++
|
.cpp
| 1,627
| 42.224954
| 187
| 0.66792
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,244
|
network_client.cpp
|
EnergeticBark_OpenTTD-3DS/src/network/network_client.cpp
|
/* $Id$ */
/** @file network_client.cpp Client part of the network protocol. */
#ifdef ENABLE_NETWORK
#include "../stdafx.h"
#include "../debug.h"
#include "../openttd.h"
#include "../gfx_func.h"
#include "network_internal.h"
#include "network_gui.h"
#include "../saveload/saveload.h"
#include "../command_func.h"
#include "../console_func.h"
#include "../fileio_func.h"
#include "../md5.h"
#include "../strings_func.h"
#include "../window_func.h"
#include "../string_func.h"
#include "../company_func.h"
#include "../company_base.h"
#include "../company_gui.h"
#include "../settings_type.h"
#include "../rev.h"
#include "table/strings.h"
/* This file handles all the client-commands */
/* So we don't make too much typos ;) */
#define MY_CLIENT GetNetworkClientSocket(0)
static uint32 last_ack_frame;
/** One bit of 'entropy' used to generate a salt for the company passwords. */
static uint32 _password_game_seed;
/** The other bit of 'entropy' used to generate a salt for the company passwords. */
static char _password_server_unique_id[NETWORK_UNIQUE_ID_LENGTH];
/** Maximum number of companies of the currently joined server. */
static uint8 _network_server_max_companies;
/** Maximum number of spectators of the currently joined server. */
static uint8 _network_server_max_spectators;
/** Make sure the unique ID length is the same as a md5 hash. */
assert_compile(NETWORK_UNIQUE_ID_LENGTH == 16 * 2 + 1);
/**
* Generates a hashed password for the company name.
* @param password the password to 'encrypt'.
* @return the hashed password.
*/
static const char *GenerateCompanyPasswordHash(const char *password)
{
if (StrEmpty(password)) return password;
char salted_password[NETWORK_UNIQUE_ID_LENGTH];
memset(salted_password, 0, sizeof(salted_password));
snprintf(salted_password, sizeof(salted_password), "%s", password);
/* Add the game seed and the server's unique ID as the salt. */
for (uint i = 0; i < NETWORK_UNIQUE_ID_LENGTH - 1; i++) salted_password[i] ^= _password_server_unique_id[i] ^ (_password_game_seed >> i);
Md5 checksum;
uint8 digest[16];
static char hashed_password[NETWORK_UNIQUE_ID_LENGTH];
/* Generate the MD5 hash */
checksum.Append((const uint8*)salted_password, sizeof(salted_password) - 1);
checksum.Finish(digest);
for (int di = 0; di < 16; di++) sprintf(hashed_password + di * 2, "%02x", digest[di]);
hashed_password[lengthof(hashed_password) - 1] = '\0';
return hashed_password;
}
/**
* Hash the current company password; used when the server 'company' sets his/her password.
*/
void HashCurrentCompanyPassword(const char *password)
{
_password_game_seed = _settings_game.game_creation.generation_seed;
strecpy(_password_server_unique_id, _settings_client.network.network_id, lastof(_password_server_unique_id));
const char *new_pw = GenerateCompanyPasswordHash(password);
strecpy(_network_company_states[_local_company].password, new_pw, lastof(_network_company_states[_local_company].password));
if (_network_server) {
NetworkServerUpdateCompanyPassworded(_local_company, !StrEmpty(_network_company_states[_local_company].password));
}
}
/***********
* Sending functions
* DEF_CLIENT_SEND_COMMAND has no parameters
************/
DEF_CLIENT_SEND_COMMAND(PACKET_CLIENT_COMPANY_INFO)
{
/*
* Packet: CLIENT_COMPANY_INFO
* Function: Request company-info (in detail)
* Data:
* <none>
*/
Packet *p;
_network_join_status = NETWORK_JOIN_STATUS_GETTING_COMPANY_INFO;
InvalidateWindow(WC_NETWORK_STATUS_WINDOW, 0);
p = NetworkSend_Init(PACKET_CLIENT_COMPANY_INFO);
MY_CLIENT->Send_Packet(p);
}
DEF_CLIENT_SEND_COMMAND(PACKET_CLIENT_JOIN)
{
/*
* Packet: CLIENT_JOIN
* Function: Try to join the server
* Data:
* String: OpenTTD Revision (norev000 if no revision)
* String: Client Name (max NETWORK_NAME_LENGTH)
* uint8: Play as Company id (1..MAX_COMPANIES)
* uint8: Language ID
* String: Unique id to find the client back in server-listing
*/
Packet *p;
_network_join_status = NETWORK_JOIN_STATUS_AUTHORIZING;
InvalidateWindow(WC_NETWORK_STATUS_WINDOW, 0);
p = NetworkSend_Init(PACKET_CLIENT_JOIN);
p->Send_string(_openttd_revision);
p->Send_string(_settings_client.network.client_name); // Client name
p->Send_uint8 (_network_playas); // PlayAs
p->Send_uint8 (NETLANG_ANY); // Language
p->Send_string(_settings_client.network.network_id);
MY_CLIENT->Send_Packet(p);
}
DEF_CLIENT_SEND_COMMAND(PACKET_CLIENT_NEWGRFS_CHECKED)
{
/*
* Packet: CLIENT_NEWGRFS_CHECKED
* Function: Tell the server that we have the required GRFs
* Data:
*/
Packet *p = NetworkSend_Init(PACKET_CLIENT_NEWGRFS_CHECKED);
MY_CLIENT->Send_Packet(p);
}
DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_PASSWORD)(NetworkPasswordType type, const char *password)
{
/*
* Packet: CLIENT_PASSWORD
* Function: Send a password to the server to authorize
* Data:
* uint8: NetworkPasswordType
* String: Password
*/
Packet *p = NetworkSend_Init(PACKET_CLIENT_PASSWORD);
p->Send_uint8 (type);
p->Send_string(type == NETWORK_GAME_PASSWORD ? password : GenerateCompanyPasswordHash(password));
MY_CLIENT->Send_Packet(p);
}
DEF_CLIENT_SEND_COMMAND(PACKET_CLIENT_GETMAP)
{
/*
* Packet: CLIENT_GETMAP
* Function: Request the map from the server
* Data:
* <none>
*/
Packet *p = NetworkSend_Init(PACKET_CLIENT_GETMAP);
MY_CLIENT->Send_Packet(p);
}
DEF_CLIENT_SEND_COMMAND(PACKET_CLIENT_MAP_OK)
{
/*
* Packet: CLIENT_MAP_OK
* Function: Tell the server that we are done receiving/loading the map
* Data:
* <none>
*/
Packet *p = NetworkSend_Init(PACKET_CLIENT_MAP_OK);
MY_CLIENT->Send_Packet(p);
}
DEF_CLIENT_SEND_COMMAND(PACKET_CLIENT_ACK)
{
/*
* Packet: CLIENT_ACK
* Function: Tell the server we are done with this frame
* Data:
* uint32: current FrameCounter of the client
*/
Packet *p = NetworkSend_Init(PACKET_CLIENT_ACK);
p->Send_uint32(_frame_counter);
MY_CLIENT->Send_Packet(p);
}
/* Send a command packet to the server */
DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_COMMAND)(const CommandPacket *cp)
{
/*
* Packet: CLIENT_COMMAND
* Function: Send a DoCommand to the Server
* Data:
* uint8: CompanyID (0..MAX_COMPANIES-1)
* uint32: CommandID (see command.h)
* uint32: P1 (free variables used in DoCommand)
* uint32: P2
* uint32: Tile
* string: text
* uint8: CallBackID (see callback_table.c)
*/
Packet *p = NetworkSend_Init(PACKET_CLIENT_COMMAND);
MY_CLIENT->Send_Command(p, cp);
MY_CLIENT->Send_Packet(p);
}
/* Send a chat-packet over the network */
DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_CHAT)(NetworkAction action, DestType type, int dest, const char *msg, int64 data)
{
/*
* Packet: CLIENT_CHAT
* Function: Send a chat-packet to the serve
* Data:
* uint8: ActionID (see network_data.h, NetworkAction)
* uint8: Destination Type (see network_data.h, DestType);
* uint32: Destination CompanyID/Client-identifier
* String: Message (max NETWORK_CHAT_LENGTH)
* uint64: Some arbitrary number
*/
Packet *p = NetworkSend_Init(PACKET_CLIENT_CHAT);
p->Send_uint8 (action);
p->Send_uint8 (type);
p->Send_uint32(dest);
p->Send_string(msg);
p->Send_uint64(data);
MY_CLIENT->Send_Packet(p);
}
/* Send an error-packet over the network */
DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_ERROR)(NetworkErrorCode errorno)
{
/*
* Packet: CLIENT_ERROR
* Function: The client made an error and is quiting the game
* Data:
* uint8: ErrorID (see network_data.h, NetworkErrorCode)
*/
Packet *p = NetworkSend_Init(PACKET_CLIENT_ERROR);
p->Send_uint8(errorno);
MY_CLIENT->Send_Packet(p);
}
DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_SET_PASSWORD)(const char *password)
{
/*
* Packet: PACKET_CLIENT_SET_PASSWORD
* Function: Set the password for the clients current company
* Data:
* String: Password
*/
Packet *p = NetworkSend_Init(PACKET_CLIENT_SET_PASSWORD);
p->Send_string(GenerateCompanyPasswordHash(password));
MY_CLIENT->Send_Packet(p);
}
DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_SET_NAME)(const char *name)
{
/*
* Packet: PACKET_CLIENT_SET_NAME
* Function: Gives the client a new name
* Data:
* String: Name
*/
Packet *p = NetworkSend_Init(PACKET_CLIENT_SET_NAME);
p->Send_string(name);
MY_CLIENT->Send_Packet(p);
}
/* Send an quit-packet over the network */
DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_QUIT)()
{
/*
* Packet: CLIENT_QUIT
* Function: The client is quiting the game
* Data:
*/
Packet *p = NetworkSend_Init(PACKET_CLIENT_QUIT);
MY_CLIENT->Send_Packet(p);
}
DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_RCON)(const char *pass, const char *command)
{
Packet *p = NetworkSend_Init(PACKET_CLIENT_RCON);
p->Send_string(pass);
p->Send_string(command);
MY_CLIENT->Send_Packet(p);
}
DEF_CLIENT_SEND_COMMAND_PARAM(PACKET_CLIENT_MOVE)(CompanyID company, const char *pass)
{
Packet *p = NetworkSend_Init(PACKET_CLIENT_MOVE);
p->Send_uint8(company);
p->Send_string(GenerateCompanyPasswordHash(pass));
MY_CLIENT->Send_Packet(p);
}
/***********
* Receiving functions
* DEF_CLIENT_RECEIVE_COMMAND has parameter: Packet *p
************/
extern bool SafeSaveOrLoad(const char *filename, int mode, GameMode newgm, Subdirectory subdir);
extern StringID _switch_mode_errorstr;
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_FULL)
{
/* We try to join a server which is full */
_switch_mode_errorstr = STR_NETWORK_ERR_SERVER_FULL;
DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
return NETWORK_RECV_STATUS_SERVER_FULL;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_BANNED)
{
/* We try to join a server where we are banned */
_switch_mode_errorstr = STR_NETWORK_ERR_SERVER_BANNED;
DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
return NETWORK_RECV_STATUS_SERVER_BANNED;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_COMPANY_INFO)
{
byte company_info_version = p->Recv_uint8();
if (!MY_CLIENT->has_quit && company_info_version == NETWORK_COMPANY_INFO_VERSION) {
/* We have received all data... (there are no more packets coming) */
if (!p->Recv_bool()) return NETWORK_RECV_STATUS_CLOSE_QUERY;
CompanyID current = (Owner)p->Recv_uint8();
if (current >= MAX_COMPANIES) return NETWORK_RECV_STATUS_CLOSE_QUERY;
NetworkCompanyInfo *company_info = GetLobbyCompanyInfo(current);
if (company_info == NULL) return NETWORK_RECV_STATUS_CLOSE_QUERY;
p->Recv_string(company_info->company_name, sizeof(company_info->company_name));
company_info->inaugurated_year = p->Recv_uint32();
company_info->company_value = p->Recv_uint64();
company_info->money = p->Recv_uint64();
company_info->income = p->Recv_uint64();
company_info->performance = p->Recv_uint16();
company_info->use_password = p->Recv_bool();
for (int i = 0; i < NETWORK_VEHICLE_TYPES; i++)
company_info->num_vehicle[i] = p->Recv_uint16();
for (int i = 0; i < NETWORK_STATION_TYPES; i++)
company_info->num_station[i] = p->Recv_uint16();
p->Recv_string(company_info->clients, sizeof(company_info->clients));
InvalidateWindow(WC_NETWORK_WINDOW, 0);
return NETWORK_RECV_STATUS_OKAY;
}
return NETWORK_RECV_STATUS_CLOSE_QUERY;
}
/* This packet contains info about the client (playas and name)
* as client we save this in NetworkClientInfo, linked via 'client_id'
* which is always an unique number on a server. */
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_CLIENT_INFO)
{
NetworkClientInfo *ci;
ClientID client_id = (ClientID)p->Recv_uint32();
CompanyID playas = (CompanyID)p->Recv_uint8();
char name[NETWORK_NAME_LENGTH];
p->Recv_string(name, sizeof(name));
if (MY_CLIENT->has_quit) return NETWORK_RECV_STATUS_CONN_LOST;
/* Do we receive a change of data? Most likely we changed playas */
if (client_id == _network_own_client_id) _network_playas = playas;
ci = NetworkFindClientInfoFromClientID(client_id);
if (ci != NULL) {
if (playas == ci->client_playas && strcmp(name, ci->client_name) != 0) {
/* Client name changed, display the change */
NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, name);
} else if (playas != ci->client_playas) {
/* The client changed from client-player..
* Do not display that for now */
}
ci->client_playas = playas;
strecpy(ci->client_name, name, lastof(ci->client_name));
InvalidateWindow(WC_CLIENT_LIST, 0);
return NETWORK_RECV_STATUS_OKAY;
}
/* We don't have this client_id yet, find an empty client_id, and put the data there */
ci = new NetworkClientInfo(client_id);
ci->client_playas = playas;
if (client_id == _network_own_client_id) MY_CLIENT->SetInfo(ci);
strecpy(ci->client_name, name, lastof(ci->client_name));
InvalidateWindow(WC_CLIENT_LIST, 0);
return NETWORK_RECV_STATUS_OKAY;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_ERROR)
{
NetworkErrorCode error = (NetworkErrorCode)p->Recv_uint8();
switch (error) {
/* We made an error in the protocol, and our connection is closed.... */
case NETWORK_ERROR_NOT_AUTHORIZED:
case NETWORK_ERROR_NOT_EXPECTED:
case NETWORK_ERROR_COMPANY_MISMATCH:
_switch_mode_errorstr = STR_NETWORK_ERR_SERVER_ERROR;
break;
case NETWORK_ERROR_FULL:
_switch_mode_errorstr = STR_NETWORK_ERR_SERVER_FULL;
break;
case NETWORK_ERROR_WRONG_REVISION:
_switch_mode_errorstr = STR_NETWORK_ERR_WRONG_REVISION;
break;
case NETWORK_ERROR_WRONG_PASSWORD:
_switch_mode_errorstr = STR_NETWORK_ERR_WRONG_PASSWORD;
break;
case NETWORK_ERROR_KICKED:
_switch_mode_errorstr = STR_NETWORK_ERR_KICKED;
break;
case NETWORK_ERROR_CHEATER:
_switch_mode_errorstr = STR_NETWORK_ERR_CHEATER;
break;
default:
_switch_mode_errorstr = STR_NETWORK_ERR_LOSTCONNECTION;
}
DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
return NETWORK_RECV_STATUS_SERVER_ERROR;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_CHECK_NEWGRFS)
{
uint grf_count = p->Recv_uint8();
NetworkRecvStatus ret = NETWORK_RECV_STATUS_OKAY;
/* Check all GRFs */
for (; grf_count > 0; grf_count--) {
GRFConfig c;
MY_CLIENT->Recv_GRFIdentifier(p, &c);
/* Check whether we know this GRF */
const GRFConfig *f = FindGRFConfig(c.grfid, c.md5sum);
if (f == NULL) {
/* We do not know this GRF, bail out of initialization */
char buf[sizeof(c.md5sum) * 2 + 1];
md5sumToString(buf, lastof(buf), c.md5sum);
DEBUG(grf, 0, "NewGRF %08X not found; checksum %s", BSWAP32(c.grfid), buf);
ret = NETWORK_RECV_STATUS_NEWGRF_MISMATCH;
}
}
if (ret == NETWORK_RECV_STATUS_OKAY) {
/* Start receiving the map */
SEND_COMMAND(PACKET_CLIENT_NEWGRFS_CHECKED)();
} else {
/* NewGRF mismatch, bail out */
_switch_mode_errorstr = STR_NETWORK_ERR_NEWGRF_MISMATCH;
}
return ret;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_NEED_PASSWORD)
{
NetworkPasswordType type = (NetworkPasswordType)p->Recv_uint8();
switch (type) {
case NETWORK_COMPANY_PASSWORD:
/* Initialize the password hash salting variables. */
_password_game_seed = p->Recv_uint32();
p->Recv_string(_password_server_unique_id, sizeof(_password_server_unique_id));
if (MY_CLIENT->has_quit) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
case NETWORK_GAME_PASSWORD:
ShowNetworkNeedPassword(type);
return NETWORK_RECV_STATUS_OKAY;
default: return NETWORK_RECV_STATUS_MALFORMED_PACKET;
}
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_WELCOME)
{
_network_own_client_id = (ClientID)p->Recv_uint32();
/* Initialize the password hash salting variables, even if they were previously. */
_password_game_seed = p->Recv_uint32();
p->Recv_string(_password_server_unique_id, sizeof(_password_server_unique_id));
/* Start receiving the map */
SEND_COMMAND(PACKET_CLIENT_GETMAP)();
return NETWORK_RECV_STATUS_OKAY;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_WAIT)
{
_network_join_status = NETWORK_JOIN_STATUS_WAITING;
_network_join_waiting = p->Recv_uint8();
InvalidateWindow(WC_NETWORK_STATUS_WINDOW, 0);
/* We are put on hold for receiving the map.. we need GUI for this ;) */
DEBUG(net, 1, "The server is currently busy sending the map to someone else, please wait..." );
DEBUG(net, 1, "There are %d clients in front of you", _network_join_waiting);
return NETWORK_RECV_STATUS_OKAY;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_MAP)
{
static FILE *file_pointer;
byte maptype;
maptype = p->Recv_uint8();
if (MY_CLIENT->has_quit) return NETWORK_RECV_STATUS_CONN_LOST;
/* First packet, init some stuff */
if (maptype == MAP_PACKET_START) {
file_pointer = FioFOpenFile("network_client.tmp", "wb", AUTOSAVE_DIR);;
if (file_pointer == NULL) {
_switch_mode_errorstr = STR_NETWORK_ERR_SAVEGAMEERROR;
return NETWORK_RECV_STATUS_SAVEGAME;
}
_frame_counter = _frame_counter_server = _frame_counter_max = p->Recv_uint32();
_network_join_bytes = 0;
_network_join_bytes_total = p->Recv_uint32();
/* If the network connection has been closed due to loss of connection
* or when _network_join_kbytes_total is 0, the join status window will
* do a division by zero. When the connection is lost, we just return
* that. If kbytes_total is 0, the packet must be malformed as a
* savegame less than 1 kilobyte is practically impossible. */
if (MY_CLIENT->has_quit) return NETWORK_RECV_STATUS_CONN_LOST;
if (_network_join_bytes_total == 0) return NETWORK_RECV_STATUS_MALFORMED_PACKET;
_network_join_status = NETWORK_JOIN_STATUS_DOWNLOADING;
InvalidateWindow(WC_NETWORK_STATUS_WINDOW, 0);
/* The first packet does not contain any more data */
return NETWORK_RECV_STATUS_OKAY;
}
if (maptype == MAP_PACKET_NORMAL) {
/* We are still receiving data, put it to the file */
if (fwrite(p->buffer + p->pos, 1, p->size - p->pos, file_pointer) != (size_t)(p->size - p->pos)) {
_switch_mode_errorstr = STR_NETWORK_ERR_SAVEGAMEERROR;
return NETWORK_RECV_STATUS_SAVEGAME;
}
_network_join_bytes = ftell(file_pointer);
InvalidateWindow(WC_NETWORK_STATUS_WINDOW, 0);
}
/* Check if this was the last packet */
if (maptype == MAP_PACKET_END) {
fclose(file_pointer);
_network_join_status = NETWORK_JOIN_STATUS_PROCESSING;
InvalidateWindow(WC_NETWORK_STATUS_WINDOW, 0);
/* The map is done downloading, load it */
if (!SafeSaveOrLoad("network_client.tmp", SL_LOAD, GM_NORMAL, AUTOSAVE_DIR)) {
DeleteWindowById(WC_NETWORK_STATUS_WINDOW, 0);
_switch_mode_errorstr = STR_NETWORK_ERR_SAVEGAMEERROR;
return NETWORK_RECV_STATUS_SAVEGAME;
}
/* If the savegame has successfully loaded, ALL windows have been removed,
* only toolbar/statusbar and gamefield are visible */
/* Say we received the map and loaded it correctly! */
SEND_COMMAND(PACKET_CLIENT_MAP_OK)();
/* New company/spectator (invalid company) or company we want to join is not active
* Switch local company to spectator and await the server's judgement */
if (_network_playas == COMPANY_NEW_COMPANY || !IsValidCompanyID(_network_playas)) {
SetLocalCompany(COMPANY_SPECTATOR);
if (_network_playas != COMPANY_SPECTATOR) {
/* We have arrived and ready to start playing; send a command to make a new company;
* the server will give us a client-id and let us in */
_network_join_status = NETWORK_JOIN_STATUS_REGISTERING;
ShowJoinStatusWindow();
NetworkSend_Command(0, 0, 0, CMD_COMPANY_CTRL, NULL, NULL);
}
} else {
/* take control over an existing company */
SetLocalCompany(_network_playas);
}
}
return NETWORK_RECV_STATUS_OKAY;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_FRAME)
{
_frame_counter_server = p->Recv_uint32();
_frame_counter_max = p->Recv_uint32();
#ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME
/* Test if the server supports this option
* and if we are at the frame the server is */
if (p->pos < p->size) {
_sync_frame = _frame_counter_server;
_sync_seed_1 = p->Recv_uint32();
#ifdef NETWORK_SEND_DOUBLE_SEED
_sync_seed_2 = p->Recv_uint32();
#endif
}
#endif
DEBUG(net, 5, "Received FRAME %d", _frame_counter_server);
/* Let the server know that we received this frame correctly
* We do this only once per day, to save some bandwidth ;) */
if (!_network_first_time && last_ack_frame < _frame_counter) {
last_ack_frame = _frame_counter + DAY_TICKS;
DEBUG(net, 4, "Sent ACK at %d", _frame_counter);
SEND_COMMAND(PACKET_CLIENT_ACK)();
}
return NETWORK_RECV_STATUS_OKAY;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_SYNC)
{
_sync_frame = p->Recv_uint32();
_sync_seed_1 = p->Recv_uint32();
#ifdef NETWORK_SEND_DOUBLE_SEED
_sync_seed_2 = p->Recv_uint32();
#endif
return NETWORK_RECV_STATUS_OKAY;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_COMMAND)
{
CommandPacket cp;
const char *err = MY_CLIENT->Recv_Command(p, &cp);
cp.frame = p->Recv_uint32();
cp.my_cmd = p->Recv_bool();
cp.next = NULL;
if (err != NULL) {
IConsolePrintF(CC_ERROR, "WARNING: %s from server, dropping...", err);
return NETWORK_RECV_STATUS_MALFORMED_PACKET;
}
/* The server did send us this command..
* queue it in our own queue, so we can handle it in the upcoming frame! */
NetworkAddCommandQueue(cp);
return NETWORK_RECV_STATUS_OKAY;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_CHAT)
{
char name[NETWORK_NAME_LENGTH], msg[NETWORK_CHAT_LENGTH];
const NetworkClientInfo *ci = NULL, *ci_to;
NetworkAction action = (NetworkAction)p->Recv_uint8();
ClientID client_id = (ClientID)p->Recv_uint32();
bool self_send = p->Recv_bool();
p->Recv_string(msg, NETWORK_CHAT_LENGTH);
int64 data = p->Recv_uint64();
ci_to = NetworkFindClientInfoFromClientID(client_id);
if (ci_to == NULL) return NETWORK_RECV_STATUS_OKAY;
/* Did we initiate the action locally? */
if (self_send) {
switch (action) {
case NETWORK_ACTION_CHAT_CLIENT:
/* For speaking to client we need the client-name */
snprintf(name, sizeof(name), "%s", ci_to->client_name);
ci = NetworkFindClientInfoFromClientID(_network_own_client_id);
break;
/* For speaking to company or giving money, we need the company-name */
case NETWORK_ACTION_GIVE_MONEY:
if (!IsValidCompanyID(ci_to->client_playas)) return NETWORK_RECV_STATUS_OKAY;
/* fallthrough */
case NETWORK_ACTION_CHAT_COMPANY: {
StringID str = IsValidCompanyID(ci_to->client_playas) ? STR_COMPANY_NAME : STR_NETWORK_SPECTATORS;
SetDParam(0, ci_to->client_playas);
GetString(name, str, lastof(name));
ci = NetworkFindClientInfoFromClientID(_network_own_client_id);
} break;
default: return NETWORK_RECV_STATUS_MALFORMED_PACKET;
}
} else {
/* Display message from somebody else */
snprintf(name, sizeof(name), "%s", ci_to->client_name);
ci = ci_to;
}
if (ci != NULL)
NetworkTextMessage(action, (ConsoleColour)GetDrawStringCompanyColour(ci->client_playas), self_send, name, msg, data);
return NETWORK_RECV_STATUS_OKAY;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_ERROR_QUIT)
{
ClientID client_id = (ClientID)p->Recv_uint32();
NetworkClientInfo *ci = NetworkFindClientInfoFromClientID(client_id);
if (ci != NULL) {
NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, NULL, GetNetworkErrorMsg((NetworkErrorCode)p->Recv_uint8()));
delete ci;
}
InvalidateWindow(WC_CLIENT_LIST, 0);
return NETWORK_RECV_STATUS_OKAY;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_QUIT)
{
NetworkClientInfo *ci;
ClientID client_id = (ClientID)p->Recv_uint32();
ci = NetworkFindClientInfoFromClientID(client_id);
if (ci != NULL) {
NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, ci->client_name, NULL, STR_NETWORK_CLIENT_LEAVING);
delete ci;
} else {
DEBUG(net, 0, "Unknown client (%d) is leaving the game", client_id);
}
InvalidateWindow(WC_CLIENT_LIST, 0);
/* If we come here it means we could not locate the client.. strange :s */
return NETWORK_RECV_STATUS_OKAY;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_JOIN)
{
ClientID client_id = (ClientID)p->Recv_uint32();
NetworkClientInfo *ci = NetworkFindClientInfoFromClientID(client_id);
if (ci != NULL)
NetworkTextMessage(NETWORK_ACTION_JOIN, CC_DEFAULT, false, ci->client_name);
InvalidateWindow(WC_CLIENT_LIST, 0);
return NETWORK_RECV_STATUS_OKAY;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_SHUTDOWN)
{
_switch_mode_errorstr = STR_NETWORK_SERVER_SHUTDOWN;
return NETWORK_RECV_STATUS_SERVER_ERROR;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_NEWGAME)
{
/* To trottle the reconnects a bit, every clients waits
* his _local_company value before reconnecting
* COMPANY_SPECTATOR is currently 255, so to avoid long wait periods
* set the max to 10. */
_network_reconnect = min(_local_company + 1, 10);
_switch_mode_errorstr = STR_NETWORK_SERVER_REBOOT;
return NETWORK_RECV_STATUS_SERVER_ERROR;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_RCON)
{
char rcon_out[NETWORK_RCONCOMMAND_LENGTH];
ConsoleColour colour_code = (ConsoleColour)p->Recv_uint16();
p->Recv_string(rcon_out, sizeof(rcon_out));
IConsolePrint(colour_code, rcon_out);
return NETWORK_RECV_STATUS_OKAY;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_MOVE)
{
/* Nothing more in this packet... */
ClientID client_id = (ClientID)p->Recv_uint32();
CompanyID company_id = (CompanyID)p->Recv_uint8();
if (client_id == 0) {
/* definitely an invalid client id, debug message and do nothing. */
DEBUG(net, 0, "[move] received invalid client index = 0");
return NETWORK_RECV_STATUS_MALFORMED_PACKET;
}
const NetworkClientInfo *ci = NetworkFindClientInfoFromClientID(client_id);
/* Just make sure we do not try to use a client_index that does not exist */
if (ci == NULL) return NETWORK_RECV_STATUS_OKAY;
/* if not valid player, force spectator, else check player exists */
if (!IsValidCompanyID(company_id)) company_id = COMPANY_SPECTATOR;
if (client_id == _network_own_client_id) {
_network_playas = company_id;
SetLocalCompany(company_id);
}
return NETWORK_RECV_STATUS_OKAY;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_CONFIG_UPDATE)
{
_network_server_max_companies = p->Recv_uint8();
_network_server_max_spectators = p->Recv_uint8();
return NETWORK_RECV_STATUS_OKAY;
}
DEF_CLIENT_RECEIVE_COMMAND(PACKET_SERVER_COMPANY_UPDATE)
{
_network_company_passworded = p->Recv_uint16();
InvalidateWindowClasses(WC_COMPANY);
return NETWORK_RECV_STATUS_OKAY;
}
/* The layout for the receive-functions by the client */
typedef NetworkRecvStatus NetworkClientPacket(Packet *p);
/* This array matches PacketType. At an incoming
* packet it is matches against this array
* and that way the right function to handle that
* packet is found. */
static NetworkClientPacket * const _network_client_packet[] = {
RECEIVE_COMMAND(PACKET_SERVER_FULL),
RECEIVE_COMMAND(PACKET_SERVER_BANNED),
NULL, // PACKET_CLIENT_JOIN,
RECEIVE_COMMAND(PACKET_SERVER_ERROR),
NULL, // PACKET_CLIENT_COMPANY_INFO,
RECEIVE_COMMAND(PACKET_SERVER_COMPANY_INFO),
RECEIVE_COMMAND(PACKET_SERVER_CLIENT_INFO),
RECEIVE_COMMAND(PACKET_SERVER_NEED_PASSWORD),
NULL, // PACKET_CLIENT_PASSWORD,
RECEIVE_COMMAND(PACKET_SERVER_WELCOME),
NULL, // PACKET_CLIENT_GETMAP,
RECEIVE_COMMAND(PACKET_SERVER_WAIT),
RECEIVE_COMMAND(PACKET_SERVER_MAP),
NULL, // PACKET_CLIENT_MAP_OK,
RECEIVE_COMMAND(PACKET_SERVER_JOIN),
RECEIVE_COMMAND(PACKET_SERVER_FRAME),
RECEIVE_COMMAND(PACKET_SERVER_SYNC),
NULL, // PACKET_CLIENT_ACK,
NULL, // PACKET_CLIENT_COMMAND,
RECEIVE_COMMAND(PACKET_SERVER_COMMAND),
NULL, // PACKET_CLIENT_CHAT,
RECEIVE_COMMAND(PACKET_SERVER_CHAT),
NULL, // PACKET_CLIENT_SET_PASSWORD,
NULL, // PACKET_CLIENT_SET_NAME,
NULL, // PACKET_CLIENT_QUIT,
NULL, // PACKET_CLIENT_ERROR,
RECEIVE_COMMAND(PACKET_SERVER_QUIT),
RECEIVE_COMMAND(PACKET_SERVER_ERROR_QUIT),
RECEIVE_COMMAND(PACKET_SERVER_SHUTDOWN),
RECEIVE_COMMAND(PACKET_SERVER_NEWGAME),
RECEIVE_COMMAND(PACKET_SERVER_RCON),
NULL, // PACKET_CLIENT_RCON,
RECEIVE_COMMAND(PACKET_SERVER_CHECK_NEWGRFS),
NULL, // PACKET_CLIENT_NEWGRFS_CHECKED,
RECEIVE_COMMAND(PACKET_SERVER_MOVE),
NULL, // PACKET_CLIENT_MOVE
RECEIVE_COMMAND(PACKET_SERVER_COMPANY_UPDATE),
RECEIVE_COMMAND(PACKET_SERVER_CONFIG_UPDATE),
};
/* If this fails, check the array above with network_data.h */
assert_compile(lengthof(_network_client_packet) == PACKET_END);
/* Is called after a client is connected to the server */
void NetworkClient_Connected()
{
/* Set the frame-counter to 0 so nothing happens till we are ready */
_frame_counter = 0;
_frame_counter_server = 0;
last_ack_frame = 0;
/* Request the game-info */
SEND_COMMAND(PACKET_CLIENT_JOIN)();
}
/* Reads the packets from the socket-stream, if available */
NetworkRecvStatus NetworkClient_ReadPackets(NetworkClientSocket *cs)
{
Packet *p;
NetworkRecvStatus res = NETWORK_RECV_STATUS_OKAY;
while (res == NETWORK_RECV_STATUS_OKAY && (p = cs->Recv_Packet(&res)) != NULL) {
byte type = p->Recv_uint8();
if (type < PACKET_END && _network_client_packet[type] != NULL && !MY_CLIENT->has_quit) {
res = _network_client_packet[type](p);
} else {
res = NETWORK_RECV_STATUS_MALFORMED_PACKET;
DEBUG(net, 0, "[client] received invalid packet type %d", type);
}
delete p;
}
return res;
}
void NetworkClientSendRcon(const char *password, const char *command)
{
SEND_COMMAND(PACKET_CLIENT_RCON)(password, command);
}
/**
* Notify the server of this client wanting to be moved to another company.
* @param company_id id of the company the client wishes to be moved to.
* @param pass the password, is only checked on the server end if a password is needed.
* @return void
*/
void NetworkClientRequestMove(CompanyID company_id, const char *pass)
{
SEND_COMMAND(PACKET_CLIENT_MOVE)(company_id, pass);
}
void NetworkUpdateClientName()
{
NetworkClientInfo *ci = NetworkFindClientInfoFromClientID(_network_own_client_id);
if (ci == NULL) return;
/* Don't change the name if it is the same as the old name */
if (strcmp(ci->client_name, _settings_client.network.client_name) != 0) {
if (!_network_server) {
SEND_COMMAND(PACKET_CLIENT_SET_NAME)(_settings_client.network.client_name);
} else {
if (NetworkFindName(_settings_client.network.client_name)) {
NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, _settings_client.network.client_name);
strecpy(ci->client_name, _settings_client.network.client_name, lastof(ci->client_name));
NetworkUpdateClientInfo(CLIENT_ID_SERVER);
}
}
}
}
void NetworkClientSendChat(NetworkAction action, DestType type, int dest, const char *msg, int64 data)
{
SEND_COMMAND(PACKET_CLIENT_CHAT)(action, type, dest, msg, data);
}
void NetworkClientSetPassword(const char *password)
{
SEND_COMMAND(PACKET_CLIENT_SET_PASSWORD)(password);
}
/**
* Tell whether the client has team members where he/she can chat to.
* @param cio client to check members of.
* @return true if there is at least one team member.
*/
bool NetworkClientPreferTeamChat(const NetworkClientInfo *cio)
{
/* Only companies actually playing can speak to team. Eg spectators cannot */
if (!_settings_client.gui.prefer_teamchat || !IsValidCompanyID(cio->client_playas)) return false;
const NetworkClientInfo *ci;
FOR_ALL_CLIENT_INFOS(ci) {
if (ci->client_playas == cio->client_playas && ci != cio) return true;
}
return false;
}
/**
* Check if max_companies has been reached on the server (local check only).
* @return true if the max value has been reached or exceeded, false otherwise.
*/
bool NetworkMaxCompaniesReached()
{
return ActiveCompanyCount() >= (_network_server ? _settings_client.network.max_companies : _network_server_max_companies);
}
/**
* Check if max_spectatos has been reached on the server (local check only).
* @return true if the max value has been reached or exceeded, false otherwise.
*/
bool NetworkMaxSpectatorsReached()
{
return NetworkSpectatorCount() >= (_network_server ? _settings_client.network.max_spectators : _network_server_max_spectators);
}
/**
* Print all the clients to the console
*/
void NetworkPrintClients()
{
const NetworkClientInfo *ci;
FOR_ALL_CLIENT_INFOS(ci) {
IConsolePrintF(CC_INFO, "Client #%1d name: '%s' company: %1d IP: %s",
ci->client_id,
ci->client_name,
ci->client_playas + (IsValidCompanyID(ci->client_playas) ? 1 : 0),
GetClientIP(ci));
}
}
#endif /* ENABLE_NETWORK */
| 32,220
|
C++
|
.cpp
| 860
| 35.051163
| 140
| 0.732908
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,245
|
network_content_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/network/network_content_gui.cpp
|
/* $Id$ */
/** @file network_gui.cpp Implementation of the Network related GUIs. */
#if defined(ENABLE_NETWORK)
#include "../stdafx.h"
#include "../string_func.h"
#include "../strings_func.h"
#include "../gfx_func.h"
#include "../window_func.h"
#include "../window_gui.h"
#include "../gui.h"
#include "../ai/ai.hpp"
#include "../gfxinit.h"
#include "../sortlist_type.h"
#include "../querystring_gui.h"
#include "network_content.h"
#include "table/strings.h"
#include "../table/sprites.h"
/** Widgets for the download window */
static const Widget _network_content_download_status_window_widget[] = {
{ WWT_CAPTION, RESIZE_NONE, COLOUR_GREY, 0, 349, 0, 13, STR_CONTENT_DOWNLOAD_TITLE, STR_018C_WINDOW_TITLE_DRAG_THIS}, // NCDSWW_CAPTION
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 0, 349, 14, 84, 0x0, STR_NULL}, // NCDSWW_BACKGROUND
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_WHITE, 125, 225, 69, 80, STR_012E_CANCEL, STR_NULL}, // NCDSWW_CANCELOK
{ WIDGETS_END},
};
/** Window description for the download window */
static const WindowDesc _network_content_download_status_window_desc(
WDP_CENTER, WDP_CENTER, 350, 85, 350, 85,
WC_NETWORK_STATUS_WINDOW, WC_NONE,
WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_MODAL,
_network_content_download_status_window_widget
);
/** Window for showing the download status of content */
struct NetworkContentDownloadStatusWindow : public Window, ContentCallback {
/** Widgets used by this window */
enum Widgets {
NCDSWW_CAPTION, ///< Caption of the window
NCDSWW_BACKGROUND, ///< Background
NCDSWW_CANCELOK, ///< Cancel/OK button
};
private:
ClientNetworkContentSocketHandler *connection; ///< Our connection with the content server
SmallVector<ContentType, 4> receivedTypes; ///< Types we received so we can update their cache
uint total_files; ///< Number of files to download
uint downloaded_files; ///< Number of files downloaded
uint total_bytes; ///< Number of bytes to download
uint downloaded_bytes; ///< Number of bytes downloaded
uint32 cur_id; ///< The current ID of the downloaded file
char name[48]; ///< The current name of the downloaded file
public:
/**
* Create a new download window based on a list of content information
* with flags whether to download them or not.
* @param infos the list to search in
*/
NetworkContentDownloadStatusWindow() :
Window(&_network_content_download_status_window_desc),
cur_id(UINT32_MAX)
{
this->parent = FindWindowById(WC_NETWORK_WINDOW, 1);
_network_content_client.AddCallback(this);
_network_content_client.DownloadSelectedContent(this->total_files, this->total_bytes);
this->FindWindowPlacementAndResize(&_network_content_download_status_window_desc);
}
/** Free whatever we've allocated */
~NetworkContentDownloadStatusWindow()
{
/* Tell all the backends about what we've downloaded */
for (ContentType *iter = this->receivedTypes.Begin(); iter != this->receivedTypes.End(); iter++) {
switch (*iter) {
case CONTENT_TYPE_AI:
case CONTENT_TYPE_AI_LIBRARY:
AI::Rescan();
InvalidateWindowClasses(WC_AI_DEBUG);
break;
case CONTENT_TYPE_BASE_GRAPHICS:
FindGraphicsSets();
break;
case CONTENT_TYPE_NEWGRF:
ScanNewGRFFiles();
/* Yes... these are the NewGRF windows */
InvalidateWindowClasses(WC_SAVELOAD);
InvalidateWindowData(WC_GAME_OPTIONS, 0, 1);
InvalidateWindowData(WC_NETWORK_WINDOW, 1, 2);
break;
case CONTENT_TYPE_SCENARIO:
case CONTENT_TYPE_HEIGHTMAP:
extern void ScanScenarios();
ScanScenarios();
InvalidateWindowData(WC_SAVELOAD, 0, 0);
break;
default:
break;
}
}
_network_content_client.RemoveCallback(this);
}
virtual void OnPaint()
{
/* When downloading is finished change cancel in ok */
if (this->downloaded_bytes == this->total_bytes) {
this->widget[NCDSWW_CANCELOK].data = STR_012F_OK;
}
this->DrawWidgets();
/* Draw nice progress bar :) */
DrawFrameRect(20, 18, 20 + (int)((this->width - 40) * this->downloaded_bytes / this->total_bytes), 28, COLOUR_MAUVE, FR_NONE);
SetDParam(0, this->downloaded_bytes);
SetDParam(1, this->total_bytes);
SetDParam(2, this->downloaded_bytes * 100 / this->total_bytes);
DrawStringCentered(this->width / 2, 35, STR_CONTENT_DOWNLOAD_PROGRESS_SIZE, TC_GREY);
if (this->downloaded_bytes == this->total_bytes) {
DrawStringCentered(this->width / 2, 50, STR_CONTENT_DOWNLOAD_COMPLETE, TC_GREY);
} else if (!StrEmpty(this->name)) {
SetDParamStr(0, this->name);
SetDParam(1, this->downloaded_files);
SetDParam(2, this->total_files);
DrawStringMultiCenter(this->width / 2, 50, STR_CONTENT_DOWNLOAD_FILE, this->width);
} else {
DrawStringCentered(this->width / 2, 50, STR_CONTENT_DOWNLOAD_INITIALISE, TC_GREY);
}
}
virtual void OnClick(Point pt, int widget)
{
if (widget == NCDSWW_CANCELOK) {
if (this->downloaded_bytes != this->total_bytes) _network_content_client.Close();
delete this;
}
}
virtual void OnDownloadProgress(const ContentInfo *ci, uint bytes)
{
if (ci->id != this->cur_id) {
strecpy(this->name, ci->filename, lastof(this->name));
this->cur_id = ci->id;
this->downloaded_files++;
this->receivedTypes.Include(ci->type);
}
this->downloaded_bytes += bytes;
this->SetDirty();
}
};
/** Window that lists the content that's at the content server */
class NetworkContentListWindow : public QueryStringBaseWindow, ContentCallback {
typedef GUIList<const ContentInfo*> GUIContentList;
/** All widgets used */
enum Widgets {
NCLWW_CLOSE, ///< Close 'X' button
NCLWW_CAPTION, ///< Caption of the window
NCLWW_BACKGROUND, ///< Resize button
NCLWW_FILTER, ///< Filter editbox
NCLWW_CHECKBOX, ///< Button above checkboxes
NCLWW_TYPE, ///< 'Type' button
NCLWW_NAME, ///< 'Name' button
NCLWW_MATRIX, ///< Panel with list of content
NCLWW_SCROLLBAR, ///< Scrollbar of matrix
NCLWW_DETAILS, ///< Panel with content details
NCLWW_SELECT_ALL, ///< 'Select all' button
NCLWW_SELECT_UPDATE, ///< 'Select updates' button
NCLWW_UNSELECT, ///< 'Unselect all' button
NCLWW_CANCEL, ///< 'Cancel' button
NCLWW_DOWNLOAD, ///< 'Download' button
NCLWW_RESIZE, ///< Resize button
};
enum {
EDITBOX_MAX_SIZE = 50,
EDITBOX_MAX_LENGTH = 300,
};
/** Runtime saved values */
static Listing last_sorting;
static Filtering last_filtering;
/** The sorter functions */
static GUIContentList::SortFunction * const sorter_funcs[];
static GUIContentList::FilterFunction * const filter_funcs[];
GUIContentList content; ///< List with content
const ContentInfo *selected; ///< The selected content info
int list_pos; ///< Our position in the list
/**
* (Re)build the network game list as its amount has changed because
* an item has been added or deleted for example
*/
void BuildContentList()
{
if (!this->content.NeedRebuild()) return;
/* Create temporary array of games to use for listing */
this->content.Clear();
for (ConstContentIterator iter = _network_content_client.Begin(); iter != _network_content_client.End(); iter++) {
*this->content.Append() = *iter;
}
this->FilterContentList();
this->content.Compact();
this->content.RebuildDone();
}
/** Sort content by name. */
static int CDECL NameSorter(const ContentInfo * const *a, const ContentInfo * const *b)
{
return strcasecmp((*a)->name, (*b)->name);
}
/** Sort content by type. */
static int CDECL TypeSorter(const ContentInfo * const *a, const ContentInfo * const *b)
{
int r = 0;
if ((*a)->type != (*b)->type) {
char a_str[64];
char b_str[64];
GetString(a_str, STR_CONTENT_TYPE_BASE_GRAPHICS + (*a)->type - CONTENT_TYPE_BASE_GRAPHICS, lastof(a_str));
GetString(b_str, STR_CONTENT_TYPE_BASE_GRAPHICS + (*b)->type - CONTENT_TYPE_BASE_GRAPHICS, lastof(b_str));
r = strcasecmp(a_str, b_str);
}
if (r == 0) r = NameSorter(a, b);
return r;
}
/** Sort content by state. */
static int CDECL StateSorter(const ContentInfo * const *a, const ContentInfo * const *b)
{
int r = (*a)->state - (*b)->state;
if (r == 0) r = TypeSorter(a, b);
return r;
}
/** Sort the content list */
void SortContentList()
{
if (!this->content.Sort()) return;
for (ConstContentIterator iter = this->content.Begin(); iter != this->content.End(); iter++) {
if (*iter == this->selected) {
this->list_pos = iter - this->content.Begin();
break;
}
}
}
/** Filter content by tags/name */
static bool CDECL TagNameFilter(const ContentInfo * const *a, const char *filter_string)
{
for (int i = 0; i < (*a)->tag_count; i++) {
if (strcasestr((*a)->tags[i], filter_string) != NULL) return true;
}
return strcasestr((*a)->name, filter_string) != NULL;
}
/** Filter the content list */
void FilterContentList()
{
if (!this->content.Filter(this->edit_str_buf)) return;
/* update list position */
for (ConstContentIterator iter = this->content.Begin(); iter != this->content.End(); iter++) {
if (*iter == this->selected) {
this->list_pos = iter - this->content.Begin();
this->ScrollToSelected();
return;
}
}
/* previously selected item not in list anymore */
this->selected = NULL;
this->list_pos = 0;
}
/** Make sure that the currently selected content info is within the visible part of the matrix */
void ScrollToSelected()
{
if (this->selected == NULL) return;
if (this->list_pos < this->vscroll.pos) {
/* scroll up to the server */
this->vscroll.pos = this->list_pos;
} else if (this->list_pos >= this->vscroll.pos + this->vscroll.cap) {
/* scroll down so that the server is at the bottom */
this->vscroll.pos = this->list_pos - this->vscroll.cap + 1;
}
}
public:
/**
* Create the content list window.
* @param desc the window description to pass to Window's constructor.
*/
NetworkContentListWindow(const WindowDesc *desc, bool select_all) : QueryStringBaseWindow(EDITBOX_MAX_SIZE, desc, 1), selected(NULL), list_pos(0)
{
ttd_strlcpy(this->edit_str_buf, "", this->edit_str_size);
this->afilter = CS_ALPHANUMERAL;
InitializeTextBuffer(&this->text, this->edit_str_buf, this->edit_str_size, EDITBOX_MAX_LENGTH);
this->SetFocusedWidget(NCLWW_FILTER);
this->vscroll.cap = 14;
this->resize.step_height = 14;
this->resize.step_width = 2;
_network_content_client.AddCallback(this);
this->HideWidget(select_all ? NCLWW_SELECT_UPDATE : NCLWW_SELECT_ALL);
this->content.SetListing(this->last_sorting);
this->content.SetFiltering(this->last_filtering);
this->content.SetSortFuncs(this->sorter_funcs);
this->content.SetFilterFuncs(this->filter_funcs);
this->content.ForceRebuild();
this->FilterContentList();
this->SortContentList();
SetVScrollCount(this, this->content.Length());
this->FindWindowPlacementAndResize(desc);
}
/** Free everything we allocated */
~NetworkContentListWindow()
{
_network_content_client.RemoveCallback(this);
}
virtual void OnPaint()
{
const SortButtonState arrow = this->content.IsDescSortOrder() ? SBS_DOWN : SBS_UP;
if (this->content.NeedRebuild()) {
this->BuildContentList();
SetVScrollCount(this, this->content.Length());
}
this->SortContentList();
/* To sum all the bytes we intend to download */
uint filesize = 0;
bool show_select_all = false;
bool show_select_upgrade = false;
for (ConstContentIterator iter = this->content.Begin(); iter != this->content.End(); iter++) {
const ContentInfo *ci = *iter;
switch (ci->state) {
case ContentInfo::SELECTED:
case ContentInfo::AUTOSELECTED:
filesize += ci->filesize;
break;
case ContentInfo::UNSELECTED:
show_select_all = true;
show_select_upgrade |= ci->upgrade;
break;
default:
break;
}
}
this->SetWidgetDisabledState(NCLWW_DOWNLOAD, filesize == 0 || FindWindowById(WC_NETWORK_STATUS_WINDOW, 0) != NULL);
this->SetWidgetDisabledState(NCLWW_UNSELECT, filesize == 0);
this->SetWidgetDisabledState(NCLWW_SELECT_ALL, !show_select_all);
this->SetWidgetDisabledState(NCLWW_SELECT_UPDATE, !show_select_upgrade);
this->DrawWidgets();
/* Edit box to filter for keywords */
this->DrawEditBox(NCLWW_FILTER);
DrawStringRightAligned(this->widget[NCLWW_FILTER].left - 8, this->widget[NCLWW_FILTER].top + 2, STR_CONTENT_FILTER_TITLE, TC_FROMSTRING);
switch (this->content.SortType()) {
case NCLWW_CHECKBOX - NCLWW_CHECKBOX: this->DrawSortButtonState(NCLWW_CHECKBOX, arrow); break;
case NCLWW_TYPE - NCLWW_CHECKBOX: this->DrawSortButtonState(NCLWW_TYPE, arrow); break;
case NCLWW_NAME - NCLWW_CHECKBOX: this->DrawSortButtonState(NCLWW_NAME, arrow); break;
}
/* Fill the matrix with the information */
uint y = this->widget[NCLWW_MATRIX].top + 3;
int cnt = 0;
for (ConstContentIterator iter = this->content.Get(this->vscroll.pos); iter != this->content.End() && cnt < this->vscroll.cap; iter++, cnt++) {
const ContentInfo *ci = *iter;
if (ci == this->selected) GfxFillRect(this->widget[NCLWW_CHECKBOX].left + 1, y - 2, this->widget[NCLWW_NAME].right - 1, y + 9, 10);
SpriteID sprite;
SpriteID pal = PAL_NONE;
switch (ci->state) {
case ContentInfo::UNSELECTED: sprite = SPR_BOX_EMPTY; break;
case ContentInfo::SELECTED: sprite = SPR_BOX_CHECKED; break;
case ContentInfo::AUTOSELECTED: sprite = SPR_BOX_CHECKED; break;
case ContentInfo::ALREADY_HERE: sprite = SPR_BLOT; pal = PALETTE_TO_GREEN; break;
case ContentInfo::DOES_NOT_EXIST: sprite = SPR_BLOT; pal = PALETTE_TO_RED; break;
default: NOT_REACHED();
}
DrawSprite(sprite, pal, this->widget[NCLWW_CHECKBOX].left + (pal == PAL_NONE ? 3 : 4), y + (pal == PAL_NONE ? 1 : 0));
StringID str = STR_CONTENT_TYPE_BASE_GRAPHICS + ci->type - CONTENT_TYPE_BASE_GRAPHICS;
DrawStringCenteredTruncated(this->widget[NCLWW_TYPE].left, this->widget[NCLWW_TYPE].right, y, str, TC_BLACK);
SetDParamStr(0, ci->name);
DrawStringTruncated(this->widget[NCLWW_NAME].left + 5, y, STR_JUST_RAW_STRING, TC_BLACK, this->widget[NCLWW_NAME].right - this->widget[NCLWW_NAME].left - 5);
y += this->resize.step_height;
}
/* Create the nice grayish rectangle at the details top */
GfxFillRect(this->widget[NCLWW_DETAILS].left + 1, this->widget[NCLWW_DETAILS].top + 1, this->widget[NCLWW_DETAILS].right - 1, this->widget[NCLWW_DETAILS].top + 50, 157);
DrawStringCentered((this->widget[NCLWW_DETAILS].left + this->widget[NCLWW_DETAILS].right) / 2, this->widget[NCLWW_DETAILS].top + 11, STR_CONTENT_DETAIL_TITLE, TC_FROMSTRING);
if (this->selected == NULL) return;
/* And fill the rest of the details when there's information to place there */
DrawStringMultiCenter((this->widget[NCLWW_DETAILS].left + this->widget[NCLWW_DETAILS].right) / 2, this->widget[NCLWW_DETAILS].top + 32, STR_CONTENT_DETAIL_SUBTITLE_UNSELECTED + this->selected->state, this->widget[NCLWW_DETAILS].right - this->widget[NCLWW_DETAILS].left - 10);
/* Also show the total download size, so keep some space from the bottom */
const uint max_y = this->widget[NCLWW_DETAILS].bottom - 15;
y = this->widget[NCLWW_DETAILS].top + 55;
if (this->selected->upgrade) {
SetDParam(0, STR_CONTENT_TYPE_BASE_GRAPHICS + this->selected->type - CONTENT_TYPE_BASE_GRAPHICS);
y += DrawStringMultiLine(this->widget[NCLWW_DETAILS].left + 5, y, STR_CONTENT_DETAIL_UPDATE, this->widget[NCLWW_DETAILS].right - this->widget[NCLWW_DETAILS].left - 5, max_y - y);
y += 11;
}
SetDParamStr(0, this->selected->name);
y += DrawStringMultiLine(this->widget[NCLWW_DETAILS].left + 5, y, STR_CONTENT_DETAIL_NAME, this->widget[NCLWW_DETAILS].right - this->widget[NCLWW_DETAILS].left - 5, max_y - y);
if (!StrEmpty(this->selected->version)) {
SetDParamStr(0, this->selected->version);
y += DrawStringMultiLine(this->widget[NCLWW_DETAILS].left + 5, y, STR_CONTENT_DETAIL_VERSION, this->widget[NCLWW_DETAILS].right - this->widget[NCLWW_DETAILS].left - 5, max_y - y);
}
if (!StrEmpty(this->selected->description)) {
SetDParamStr(0, this->selected->description);
y += DrawStringMultiLine(this->widget[NCLWW_DETAILS].left + 5, y, STR_CONTENT_DETAIL_DESCRIPTION, this->widget[NCLWW_DETAILS].right - this->widget[NCLWW_DETAILS].left - 5, max_y - y);
}
if (!StrEmpty(this->selected->url)) {
SetDParamStr(0, this->selected->url);
y += DrawStringMultiLine(this->widget[NCLWW_DETAILS].left + 5, y, STR_CONTENT_DETAIL_URL, this->widget[NCLWW_DETAILS].right - this->widget[NCLWW_DETAILS].left - 5, max_y - y);
}
SetDParam(0, STR_CONTENT_TYPE_BASE_GRAPHICS + this->selected->type - CONTENT_TYPE_BASE_GRAPHICS);
y += DrawStringMultiLine(this->widget[NCLWW_DETAILS].left + 5, y, STR_CONTENT_DETAIL_TYPE, this->widget[NCLWW_DETAILS].right - this->widget[NCLWW_DETAILS].left - 5, max_y - y);
y += 11;
SetDParam(0, this->selected->filesize);
y += DrawStringMultiLine(this->widget[NCLWW_DETAILS].left + 5, y, STR_CONTENT_DETAIL_FILESIZE, this->widget[NCLWW_DETAILS].right - this->widget[NCLWW_DETAILS].left - 5, max_y - y);
if (this->selected->dependency_count != 0) {
/* List dependencies */
char buf[8192] = "";
char *p = buf;
for (uint i = 0; i < this->selected->dependency_count; i++) {
ContentID cid = this->selected->dependencies[i];
/* Try to find the dependency */
ConstContentIterator iter = _network_content_client.Begin();
for (; iter != _network_content_client.End(); iter++) {
const ContentInfo *ci = *iter;
if (ci->id != cid) continue;
p += seprintf(p, lastof(buf), p == buf ? "%s" : ", %s", (*iter)->name);
break;
}
}
SetDParamStr(0, buf);
y += DrawStringMultiLine(this->widget[NCLWW_DETAILS].left + 5, y, STR_CONTENT_DETAIL_DEPENDENCIES, this->widget[NCLWW_DETAILS].right - this->widget[NCLWW_DETAILS].left - 5, max_y - y);
}
if (this->selected->tag_count != 0) {
/* List all tags */
char buf[8192] = "";
char *p = buf;
for (uint i = 0; i < this->selected->tag_count; i++) {
p += seprintf(p, lastof(buf), i == 0 ? "%s" : ", %s", this->selected->tags[i]);
}
SetDParamStr(0, buf);
y += DrawStringMultiLine(this->widget[NCLWW_DETAILS].left + 5, y, STR_CONTENT_DETAIL_TAGS, this->widget[NCLWW_DETAILS].right - this->widget[NCLWW_DETAILS].left - 5, max_y - y);
}
if (this->selected->IsSelected()) {
/* When selected show all manually selected content that depends on this */
ConstContentVector tree;
_network_content_client.ReverseLookupTreeDependency(tree, this->selected);
char buf[8192] = "";
char *p = buf;
for (ConstContentIterator iter = tree.Begin(); iter != tree.End(); iter++) {
const ContentInfo *ci = *iter;
if (ci == this->selected || ci->state != ContentInfo::SELECTED) continue;
p += seprintf(p, lastof(buf), buf == p ? "%s" : ", %s", ci->name);
}
if (p != buf) {
SetDParamStr(0, buf);
y += DrawStringMultiLine(this->widget[NCLWW_DETAILS].left + 5, y, STR_CONTENT_DETAIL_SELECTED_BECAUSE_OF, this->widget[NCLWW_DETAILS].right - this->widget[NCLWW_DETAILS].left - 5, max_y - y);
}
}
/* Draw the total download size */
SetDParam(0, filesize);
DrawString(this->widget[NCLWW_DETAILS].left + 5, this->widget[NCLWW_DETAILS].bottom - 12, STR_CONTENT_TOTAL_DOWNLOAD_SIZE, TC_BLACK);
}
virtual void OnDoubleClick(Point pt, int widget)
{
/* Double clicking on a line in the matrix toggles the state of the checkbox */
if (widget != NCLWW_MATRIX) return;
pt.x = this->widget[NCLWW_CHECKBOX].left;
this->OnClick(pt, widget);
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case NCLWW_MATRIX: {
uint32 id_v = (pt.y - this->widget[NCLWW_MATRIX].top) / this->resize.step_height;
if (id_v >= this->vscroll.cap) return; // click out of bounds
id_v += this->vscroll.pos;
if (id_v >= this->content.Length()) return; // click out of bounds
this->selected = *this->content.Get(id_v);
this->list_pos = id_v;
if (pt.x <= this->widget[NCLWW_CHECKBOX].right) {
_network_content_client.ToggleSelectedState(this->selected);
this->content.ForceResort();
}
this->SetDirty();
} break;
case NCLWW_CHECKBOX:
case NCLWW_TYPE:
case NCLWW_NAME:
if (this->content.SortType() == widget - NCLWW_CHECKBOX) {
this->content.ToggleSortOrder();
this->list_pos = this->content.Length() - this->list_pos - 1;
} else {
this->content.SetSortType(widget - NCLWW_CHECKBOX);
this->content.ForceResort();
this->SortContentList();
}
this->ScrollToSelected();
this->SetDirty();
break;
case NCLWW_SELECT_ALL:
_network_content_client.SelectAll();
this->SetDirty();
break;
case NCLWW_SELECT_UPDATE:
_network_content_client.SelectUpgrade();
this->SetDirty();
break;
case NCLWW_UNSELECT:
_network_content_client.UnselectAll();
this->SetDirty();
break;
case NCLWW_CANCEL:
delete this;
break;
case NCLWW_DOWNLOAD:
if (BringWindowToFrontById(WC_NETWORK_STATUS_WINDOW, 0) == NULL) new NetworkContentDownloadStatusWindow();
break;
}
}
virtual void OnMouseLoop()
{
this->HandleEditBox(NCLWW_FILTER);
}
virtual EventState OnKeyPress(uint16 key, uint16 keycode)
{
switch (keycode) {
case WKC_UP:
/* scroll up by one */
if (this->list_pos > 0) this->list_pos--;
break;
case WKC_DOWN:
/* scroll down by one */
if (this->list_pos < (int)this->content.Length() - 1) this->list_pos++;
break;
case WKC_PAGEUP:
/* scroll up a page */
this->list_pos = (this->list_pos < this->vscroll.cap) ? 0 : this->list_pos - this->vscroll.cap;
break;
case WKC_PAGEDOWN:
/* scroll down a page */
this->list_pos = min(this->list_pos + this->vscroll.cap, (int)this->content.Length() - 1);
break;
case WKC_HOME:
/* jump to beginning */
this->list_pos = 0;
break;
case WKC_END:
/* jump to end */
this->list_pos = this->content.Length() - 1;
break;
case WKC_SPACE:
case WKC_RETURN:
if (keycode == WKC_RETURN || !IsWidgetFocused(NCLWW_FILTER)) {
if (this->selected != NULL) {
_network_content_client.ToggleSelectedState(this->selected);
this->content.ForceResort();
this->SetDirty();
}
return ES_HANDLED;
}
/* Fall through when pressing space is pressed and filter isn't focused */
default: {
/* Handle editbox input */
EventState state = ES_NOT_HANDLED;
if (this->HandleEditBoxKey(NCLWW_FILTER, key, keycode, state) == HEBR_EDITING) {
this->OnOSKInput(NCLWW_FILTER);
}
return state;
}
}
if (_network_content_client.Length() == 0) return ES_HANDLED;
this->selected = *this->content.Get(this->list_pos);
/* scroll to the new server if it is outside the current range */
this->ScrollToSelected();
/* redraw window */
this->SetDirty();
return ES_HANDLED;
}
virtual void OnOSKInput(int wid)
{
this->content.SetFilterState(!StrEmpty(this->edit_str_buf));
this->content.ForceRebuild();
this->SetDirty();
}
virtual void OnResize(Point new_size, Point delta)
{
this->vscroll.cap += delta.y / (int)this->resize.step_height;
this->widget[NCLWW_MATRIX].data = (this->vscroll.cap << 8) + 1;
SetVScrollCount(this, this->content.Length());
/* Make the matrix and details section grow both bigger (or smaller) */
delta.x /= 2;
this->widget[NCLWW_NAME].right -= delta.x;
this->widget[NCLWW_MATRIX].right -= delta.x;
this->widget[NCLWW_SCROLLBAR].left -= delta.x;
this->widget[NCLWW_SCROLLBAR].right -= delta.x;
this->widget[NCLWW_DETAILS].left -= delta.x;
}
virtual void OnReceiveContentInfo(const ContentInfo *rci)
{
this->content.ForceRebuild();
this->SetDirty();
}
virtual void OnDownloadComplete(ContentID cid)
{
this->content.ForceResort();
this->SetDirty();
}
virtual void OnConnect(bool success)
{
if (!success) {
ShowErrorMessage(INVALID_STRING_ID, STR_CONTENT_ERROR_COULD_NOT_CONNECT, 0, 0);
delete this;
}
this->SetDirty();
}
};
Listing NetworkContentListWindow::last_sorting = {false, 1};
Filtering NetworkContentListWindow::last_filtering = {false, 0};
NetworkContentListWindow::GUIContentList::SortFunction * const NetworkContentListWindow::sorter_funcs[] = {
&StateSorter,
&TypeSorter,
&NameSorter,
};
NetworkContentListWindow::GUIContentList::FilterFunction * const NetworkContentListWindow::filter_funcs[] = {
&TagNameFilter,
};
/** Widgets used for the content list */
static const Widget _network_content_list_widgets[] = {
/* TOP */
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_LIGHT_BLUE, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // NCLWW_CLOSE
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_LIGHT_BLUE, 11, 449, 0, 13, STR_CONTENT_TITLE, STR_NULL}, // NCLWW_CAPTION
{ WWT_PANEL, RESIZE_RB, COLOUR_LIGHT_BLUE, 0, 449, 14, 277, 0x0, STR_NULL}, // NCLWW_BACKGROUND
{ WWT_EDITBOX, RESIZE_LR, COLOUR_LIGHT_BLUE, 210, 440, 20, 31, STR_CONTENT_FILTER_OSKTITLE, STR_CONTENT_FILTER_TIP}, // NCLWW_FILTER
/* LEFT SIDE */
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_WHITE, 8, 20, 36, 47, STR_EMPTY, STR_NULL}, // NCLWW_CHECKBOX
{ WWT_PUSHTXTBTN, RESIZE_NONE, COLOUR_WHITE, 21, 110, 36, 47, STR_CONTENT_TYPE_CAPTION, STR_CONTENT_TYPE_CAPTION_TIP}, // NCLWW_TYPE
{ WWT_PUSHTXTBTN, RESIZE_RIGHT, COLOUR_WHITE, 111, 190, 36, 47, STR_CONTENT_NAME_CAPTION, STR_CONTENT_NAME_CAPTION_TIP}, // NCLWW_NAME
{ WWT_MATRIX, RESIZE_RB, COLOUR_LIGHT_BLUE, 8, 190, 48, 244, (14 << 8) | 1, STR_CONTENT_MATRIX_TIP}, // NCLWW_MATRIX
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_LIGHT_BLUE, 191, 202, 36, 244, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST}, // NCLWW_SCROLLBAR
/* RIGHT SIDE */
{ WWT_PANEL, RESIZE_LRB, COLOUR_LIGHT_BLUE, 210, 440, 36, 244, 0x0, STR_NULL}, // NCLWW_DETAILS
/* BOTTOM */
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_WHITE, 10, 110, 252, 263, STR_CONTENT_SELECT_ALL_CAPTION, STR_CONTENT_SELECT_ALL_CAPTION_TIP}, // NCLWW_SELECT_ALL
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_WHITE, 10, 110, 252, 263, STR_CONTENT_SELECT_UPDATES_CAPTION, STR_CONTENT_SELECT_UPDATES_CAPTION_TIP}, // NCLWW_SELECT_UPDATES
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_WHITE, 118, 218, 252, 263, STR_CONTENT_UNSELECT_ALL_CAPTION, STR_CONTENT_UNSELECT_ALL_CAPTION_TIP}, // NCLWW_UNSELECT
{ WWT_PUSHTXTBTN, RESIZE_LRTB, COLOUR_WHITE, 226, 326, 252, 263, STR_012E_CANCEL, STR_NULL}, // NCLWW_CANCEL
{ WWT_PUSHTXTBTN, RESIZE_LRTB, COLOUR_WHITE, 334, 434, 252, 263, STR_CONTENT_DOWNLOAD_CAPTION, STR_CONTENT_DOWNLOAD_CAPTION_TIP}, // NCLWW_DOWNLOAD
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_LIGHT_BLUE, 438, 449, 266, 277, 0x0, STR_RESIZE_BUTTON }, // NCLWW_RESIZE
{ WIDGETS_END},
};
/** Window description of the content list */
static const WindowDesc _network_content_list_desc(
WDP_CENTER, WDP_CENTER, 450, 278, 630, 460,
WC_NETWORK_WINDOW, WC_NONE,
WDF_STD_TOOLTIPS | WDF_DEF_WIDGET | WDF_STD_BTN | WDF_UNCLICK_BUTTONS | WDF_RESIZABLE,
_network_content_list_widgets
);
/**
* Show the content list window with a given set of content
* @param cv the content to show, or NULL when it has to search for itself
* @param type the type to (only) show
*/
void ShowNetworkContentListWindow(ContentVector *cv, ContentType type)
{
#if defined(WITH_ZLIB)
_network_content_client.Clear();
if (cv == NULL) {
_network_content_client.RequestContentList(type);
} else {
_network_content_client.RequestContentList(cv, true);
}
DeleteWindowById(WC_NETWORK_WINDOW, 1);
new NetworkContentListWindow(&_network_content_list_desc, cv != NULL);
#else
ShowErrorMessage(STR_CONTENT_NO_ZLIB_SUB, STR_CONTENT_NO_ZLIB, 0, 0);
/* Connection failed... clean up the mess */
if (cv != NULL) {
for (ContentIterator iter = cv->Begin(); iter != cv->End(); iter++) delete *iter;
}
#endif /* WITH_ZLIB */
}
#endif /* ENABLE_NETWORK */
| 28,848
|
C++
|
.cpp
| 658
| 40.468085
| 277
| 0.668829
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,246
|
network_server.cpp
|
EnergeticBark_OpenTTD-3DS/src/network/network_server.cpp
|
/* $Id$ */
/** @file network_server.cpp Server part of the network protocol. */
#ifdef ENABLE_NETWORK
#include "../stdafx.h"
#include "../debug.h"
#include "../strings_func.h"
#include "network_internal.h"
#include "../vehicle_base.h"
#include "../date_func.h"
#include "network_server.h"
#include "network_udp.h"
#include "../console_func.h"
#include "../command_func.h"
#include "../saveload/saveload.h"
#include "../station_base.h"
#include "../genworld.h"
#include "../fileio_func.h"
#include "../string_func.h"
#include "../company_func.h"
#include "../company_gui.h"
#include "../settings_type.h"
#include "../window_func.h"
#include "table/strings.h"
/* This file handles all the server-commands */
static void NetworkHandleCommandQueue(NetworkClientSocket *cs);
/***********
* Sending functions
* DEF_SERVER_SEND_COMMAND has parameter: NetworkClientSocket *cs
************/
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_CLIENT_INFO)(NetworkClientSocket *cs, NetworkClientInfo *ci)
{
/*
* Packet: SERVER_CLIENT_INFO
* Function: Sends info about a client
* Data:
* uint32: The identifier of the client (always unique on a server. 1 = server, 0 is invalid)
* uint8: As which company the client is playing
* String: The name of the client
*/
if (ci->client_id != INVALID_CLIENT_ID) {
Packet *p = NetworkSend_Init(PACKET_SERVER_CLIENT_INFO);
p->Send_uint32(ci->client_id);
p->Send_uint8 (ci->client_playas);
p->Send_string(ci->client_name);
cs->Send_Packet(p);
}
}
DEF_SERVER_SEND_COMMAND(PACKET_SERVER_COMPANY_INFO)
{
/*
* Packet: SERVER_COMPANY_INFO
* Function: Sends info about the companies
* Data:
*/
/* Fetch the latest version of the stats */
NetworkCompanyStats company_stats[MAX_COMPANIES];
NetworkPopulateCompanyStats(company_stats);
/* Make a list of all clients per company */
char clients[MAX_COMPANIES][NETWORK_CLIENTS_LENGTH];
NetworkClientSocket *csi;
memset(clients, 0, sizeof(clients));
/* Add the local player (if not dedicated) */
const NetworkClientInfo *ci = NetworkFindClientInfoFromClientID(CLIENT_ID_SERVER);
if (ci != NULL && IsValidCompanyID(ci->client_playas)) {
strecpy(clients[ci->client_playas], ci->client_name, lastof(clients[ci->client_playas]));
}
FOR_ALL_CLIENT_SOCKETS(csi) {
char client_name[NETWORK_CLIENT_NAME_LENGTH];
NetworkGetClientName(client_name, sizeof(client_name), csi);
ci = csi->GetInfo();
if (ci != NULL && IsValidCompanyID(ci->client_playas)) {
if (!StrEmpty(clients[ci->client_playas])) {
strecat(clients[ci->client_playas], ", ", lastof(clients[ci->client_playas]));
}
strecat(clients[ci->client_playas], client_name, lastof(clients[ci->client_playas]));
}
}
/* Now send the data */
Company *company;
Packet *p;
FOR_ALL_COMPANIES(company) {
p = NetworkSend_Init(PACKET_SERVER_COMPANY_INFO);
p->Send_uint8 (NETWORK_COMPANY_INFO_VERSION);
p->Send_bool (true);
cs->Send_CompanyInformation(p, company, &company_stats[company->index]);
if (StrEmpty(clients[company->index])) {
p->Send_string("<none>");
} else {
p->Send_string(clients[company->index]);
}
cs->Send_Packet(p);
}
p = NetworkSend_Init(PACKET_SERVER_COMPANY_INFO);
p->Send_uint8 (NETWORK_COMPANY_INFO_VERSION);
p->Send_bool (false);
cs->Send_Packet(p);
}
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_ERROR)(NetworkClientSocket *cs, NetworkErrorCode error)
{
/*
* Packet: SERVER_ERROR
* Function: The client made an error
* Data:
* uint8: ErrorID (see network_data.h, NetworkErrorCode)
*/
char str[100];
Packet *p = NetworkSend_Init(PACKET_SERVER_ERROR);
p->Send_uint8(error);
cs->Send_Packet(p);
StringID strid = GetNetworkErrorMsg(error);
GetString(str, strid, lastof(str));
/* Only send when the current client was in game */
if (cs->status > STATUS_AUTH) {
NetworkClientSocket *new_cs;
char client_name[NETWORK_CLIENT_NAME_LENGTH];
NetworkGetClientName(client_name, sizeof(client_name), cs);
DEBUG(net, 1, "'%s' made an error and has been disconnected. Reason: '%s'", client_name, str);
NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, NULL, strid);
FOR_ALL_CLIENT_SOCKETS(new_cs) {
if (new_cs->status > STATUS_AUTH && new_cs != cs) {
/* Some errors we filter to a more general error. Clients don't have to know the real
* reason a joining failed. */
if (error == NETWORK_ERROR_NOT_AUTHORIZED || error == NETWORK_ERROR_NOT_EXPECTED || error == NETWORK_ERROR_WRONG_REVISION)
error = NETWORK_ERROR_ILLEGAL_PACKET;
SEND_COMMAND(PACKET_SERVER_ERROR_QUIT)(new_cs, cs->client_id, error);
}
}
} else {
DEBUG(net, 1, "Client %d made an error and has been disconnected. Reason: '%s'", cs->client_id, str);
}
cs->has_quit = true;
/* Make sure the data get's there before we close the connection */
cs->Send_Packets();
/* The client made a mistake, so drop his connection now! */
NetworkCloseClient(cs);
}
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_CHECK_NEWGRFS)(NetworkClientSocket *cs)
{
/*
* Packet: PACKET_SERVER_CHECK_NEWGRFS
* Function: Sends info about the used GRFs to the client
* Data:
* uint8: Amount of GRFs
* And then for each GRF:
* uint32: GRF ID
* 16 * uint8: MD5 checksum of the GRF
*/
Packet *p = NetworkSend_Init(PACKET_SERVER_CHECK_NEWGRFS);
const GRFConfig *c;
uint grf_count = 0;
for (c = _grfconfig; c != NULL; c = c->next) {
if (!HasBit(c->flags, GCF_STATIC)) grf_count++;
}
p->Send_uint8 (grf_count);
for (c = _grfconfig; c != NULL; c = c->next) {
if (!HasBit(c->flags, GCF_STATIC)) cs->Send_GRFIdentifier(p, c);
}
cs->Send_Packet(p);
}
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_NEED_PASSWORD)(NetworkClientSocket *cs, NetworkPasswordType type)
{
/*
* Packet: SERVER_NEED_PASSWORD
* Function: Indication to the client that the server needs a password
* Data:
* uint8: Type of password
*/
/* Invalid packet when status is AUTH or higher */
if (cs->status >= STATUS_AUTH) return;
cs->status = STATUS_AUTHORIZING;
Packet *p = NetworkSend_Init(PACKET_SERVER_NEED_PASSWORD);
p->Send_uint8(type);
p->Send_uint32(_settings_game.game_creation.generation_seed);
p->Send_string(_settings_client.network.network_id);
cs->Send_Packet(p);
}
DEF_SERVER_SEND_COMMAND(PACKET_SERVER_WELCOME)
{
/*
* Packet: SERVER_WELCOME
* Function: The client is joined and ready to receive his map
* Data:
* uint32: Own Client identifier
*/
Packet *p;
NetworkClientSocket *new_cs;
/* Invalid packet when status is AUTH or higher */
if (cs->status >= STATUS_AUTH) return;
cs->status = STATUS_AUTH;
_network_game_info.clients_on++;
p = NetworkSend_Init(PACKET_SERVER_WELCOME);
p->Send_uint32(cs->client_id);
p->Send_uint32(_settings_game.game_creation.generation_seed);
p->Send_string(_settings_client.network.network_id);
cs->Send_Packet(p);
/* Transmit info about all the active clients */
FOR_ALL_CLIENT_SOCKETS(new_cs) {
if (new_cs != cs && new_cs->status > STATUS_AUTH)
SEND_COMMAND(PACKET_SERVER_CLIENT_INFO)(cs, new_cs->GetInfo());
}
/* Also send the info of the server */
SEND_COMMAND(PACKET_SERVER_CLIENT_INFO)(cs, NetworkFindClientInfoFromClientID(CLIENT_ID_SERVER));
}
DEF_SERVER_SEND_COMMAND(PACKET_SERVER_WAIT)
{
/*
* Packet: PACKET_SERVER_WAIT
* Function: The client can not receive the map at the moment because
* someone else is already receiving the map
* Data:
* uint8: Clients awaiting map
*/
int waiting = 0;
NetworkClientSocket *new_cs;
Packet *p;
/* Count how many clients are waiting in the queue */
FOR_ALL_CLIENT_SOCKETS(new_cs) {
if (new_cs->status == STATUS_MAP_WAIT) waiting++;
}
p = NetworkSend_Init(PACKET_SERVER_WAIT);
p->Send_uint8(waiting);
cs->Send_Packet(p);
}
/* This sends the map to the client */
DEF_SERVER_SEND_COMMAND(PACKET_SERVER_MAP)
{
/*
* Packet: SERVER_MAP
* Function: Sends the map to the client, or a part of it (it is splitted in
* a lot of multiple packets)
* Data:
* uint8: packet-type (MAP_PACKET_START, MAP_PACKET_NORMAL and MAP_PACKET_END)
* if MAP_PACKET_START:
* uint32: The current FrameCounter
* if MAP_PACKET_NORMAL:
* piece of the map (till max-size of packet)
* if MAP_PACKET_END:
* nothing
*/
static FILE *file_pointer;
static uint sent_packets; // How many packets we did send succecfully last time
if (cs->status < STATUS_AUTH) {
/* Illegal call, return error and ignore the packet */
SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_AUTHORIZED);
return;
}
if (cs->status == STATUS_AUTH) {
const char *filename = "network_server.tmp";
Packet *p;
/* Make a dump of the current game */
if (SaveOrLoad(filename, SL_SAVE, AUTOSAVE_DIR) != SL_OK) usererror("network savedump failed");
file_pointer = FioFOpenFile(filename, "rb", AUTOSAVE_DIR);
fseek(file_pointer, 0, SEEK_END);
if (ftell(file_pointer) == 0) usererror("network savedump failed - zero sized savegame?");
/* Now send the _frame_counter and how many packets are coming */
p = NetworkSend_Init(PACKET_SERVER_MAP);
p->Send_uint8 (MAP_PACKET_START);
p->Send_uint32(_frame_counter);
p->Send_uint32(ftell(file_pointer));
cs->Send_Packet(p);
fseek(file_pointer, 0, SEEK_SET);
sent_packets = 4; // We start with trying 4 packets
cs->status = STATUS_MAP;
/* Mark the start of download */
cs->last_frame = _frame_counter;
cs->last_frame_server = _frame_counter;
}
if (cs->status == STATUS_MAP) {
uint i;
int res;
for (i = 0; i < sent_packets; i++) {
Packet *p = NetworkSend_Init(PACKET_SERVER_MAP);
p->Send_uint8(MAP_PACKET_NORMAL);
res = (int)fread(p->buffer + p->size, 1, SEND_MTU - p->size, file_pointer);
if (ferror(file_pointer)) usererror("Error reading temporary network savegame!");
p->size += res;
cs->Send_Packet(p);
if (feof(file_pointer)) {
/* Done reading! */
Packet *p = NetworkSend_Init(PACKET_SERVER_MAP);
p->Send_uint8(MAP_PACKET_END);
cs->Send_Packet(p);
/* Set the status to DONE_MAP, no we will wait for the client
* to send it is ready (maybe that happens like never ;)) */
cs->status = STATUS_DONE_MAP;
fclose(file_pointer);
{
NetworkClientSocket *new_cs;
bool new_map_client = false;
/* Check if there is a client waiting for receiving the map
* and start sending him the map */
FOR_ALL_CLIENT_SOCKETS(new_cs) {
if (new_cs->status == STATUS_MAP_WAIT) {
/* Check if we already have a new client to send the map to */
if (!new_map_client) {
/* If not, this client will get the map */
new_cs->status = STATUS_AUTH;
new_map_client = true;
SEND_COMMAND(PACKET_SERVER_MAP)(new_cs);
} else {
/* Else, send the other clients how many clients are in front of them */
SEND_COMMAND(PACKET_SERVER_WAIT)(new_cs);
}
}
}
}
/* There is no more data, so break the for */
break;
}
}
/* Send all packets (forced) and check if we have send it all */
cs->Send_Packets();
if (cs->IsPacketQueueEmpty()) {
/* All are sent, increase the sent_packets */
sent_packets *= 2;
} else {
/* Not everything is sent, decrease the sent_packets */
if (sent_packets > 1) sent_packets /= 2;
}
}
}
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_JOIN)(NetworkClientSocket *cs, ClientID client_id)
{
/*
* Packet: SERVER_JOIN
* Function: A client is joined (all active clients receive this after a
* PACKET_CLIENT_MAP_OK) Mostly what directly follows is a
* PACKET_SERVER_CLIENT_INFO
* Data:
* uint32: Client-identifier
*/
Packet *p = NetworkSend_Init(PACKET_SERVER_JOIN);
p->Send_uint32(client_id);
cs->Send_Packet(p);
}
DEF_SERVER_SEND_COMMAND(PACKET_SERVER_FRAME)
{
/*
* Packet: SERVER_FRAME
* Function: Sends the current frame-counter to the client
* Data:
* uint32: Frame Counter
* uint32: Frame Counter Max (how far may the client walk before the server?)
* [uint32: general-seed-1]
* [uint32: general-seed-2]
* (last two depends on compile-settings, and are not default settings)
*/
Packet *p = NetworkSend_Init(PACKET_SERVER_FRAME);
p->Send_uint32(_frame_counter);
p->Send_uint32(_frame_counter_max);
#ifdef ENABLE_NETWORK_SYNC_EVERY_FRAME
p->Send_uint32(_sync_seed_1);
#ifdef NETWORK_SEND_DOUBLE_SEED
p->Send_uint32(_sync_seed_2);
#endif
#endif
cs->Send_Packet(p);
}
DEF_SERVER_SEND_COMMAND(PACKET_SERVER_SYNC)
{
/*
* Packet: SERVER_SYNC
* Function: Sends a sync-check to the client
* Data:
* uint32: Frame Counter
* uint32: General-seed-1
* [uint32: general-seed-2]
* (last one depends on compile-settings, and are not default settings)
*/
Packet *p = NetworkSend_Init(PACKET_SERVER_SYNC);
p->Send_uint32(_frame_counter);
p->Send_uint32(_sync_seed_1);
#ifdef NETWORK_SEND_DOUBLE_SEED
p->Send_uint32(_sync_seed_2);
#endif
cs->Send_Packet(p);
}
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_COMMAND)(NetworkClientSocket *cs, const CommandPacket *cp)
{
/*
* Packet: SERVER_COMMAND
* Function: Sends a DoCommand to the client
* Data:
* uint8: CompanyID (0..MAX_COMPANIES-1)
* uint32: CommandID (see command.h)
* uint32: P1 (free variables used in DoCommand)
* uint32: P2
* uint32: Tile
* string: text
* uint8: CallBackID (see callback_table.c)
* uint32: Frame of execution
*/
Packet *p = NetworkSend_Init(PACKET_SERVER_COMMAND);
cs->Send_Command(p, cp);
p->Send_uint32(cp->frame);
p->Send_bool (cp->my_cmd);
cs->Send_Packet(p);
}
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_CHAT)(NetworkClientSocket *cs, NetworkAction action, ClientID client_id, bool self_send, const char *msg, int64 data)
{
/*
* Packet: SERVER_CHAT
* Function: Sends a chat-packet to the client
* Data:
* uint8: ActionID (see network_data.h, NetworkAction)
* uint32: Client-identifier
* String: Message (max NETWORK_CHAT_LENGTH)
* uint64: Arbitrary data
*/
Packet *p = NetworkSend_Init(PACKET_SERVER_CHAT);
p->Send_uint8 (action);
p->Send_uint32(client_id);
p->Send_bool (self_send);
p->Send_string(msg);
p->Send_uint64(data);
cs->Send_Packet(p);
}
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_ERROR_QUIT)(NetworkClientSocket *cs, ClientID client_id, NetworkErrorCode errorno)
{
/*
* Packet: SERVER_ERROR_QUIT
* Function: One of the clients made an error and is quiting the game
* This packet informs the other clients of that.
* Data:
* uint32: Client-identifier
* uint8: ErrorID (see network_data.h, NetworkErrorCode)
*/
Packet *p = NetworkSend_Init(PACKET_SERVER_ERROR_QUIT);
p->Send_uint32(client_id);
p->Send_uint8 (errorno);
cs->Send_Packet(p);
}
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_QUIT)(NetworkClientSocket *cs, ClientID client_id)
{
/*
* Packet: SERVER_ERROR_QUIT
* Function: A client left the game, and this packets informs the other clients
* of that.
* Data:
* uint32: Client-identifier
*/
Packet *p = NetworkSend_Init(PACKET_SERVER_QUIT);
p->Send_uint32(client_id);
cs->Send_Packet(p);
}
DEF_SERVER_SEND_COMMAND(PACKET_SERVER_SHUTDOWN)
{
/*
* Packet: SERVER_SHUTDOWN
* Function: Let the clients know that the server is closing
* Data:
* <none>
*/
Packet *p = NetworkSend_Init(PACKET_SERVER_SHUTDOWN);
cs->Send_Packet(p);
}
DEF_SERVER_SEND_COMMAND(PACKET_SERVER_NEWGAME)
{
/*
* Packet: PACKET_SERVER_NEWGAME
* Function: Let the clients know that the server is loading a new map
* Data:
* <none>
*/
Packet *p = NetworkSend_Init(PACKET_SERVER_NEWGAME);
cs->Send_Packet(p);
}
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_RCON)(NetworkClientSocket *cs, uint16 colour, const char *command)
{
Packet *p = NetworkSend_Init(PACKET_SERVER_RCON);
p->Send_uint16(colour);
p->Send_string(command);
cs->Send_Packet(p);
}
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_MOVE)(NetworkClientSocket *cs, ClientID client_id, CompanyID company_id)
{
Packet *p = NetworkSend_Init(PACKET_SERVER_MOVE);
p->Send_uint32(client_id);
p->Send_uint8(company_id);
cs->Send_Packet(p);
}
DEF_SERVER_SEND_COMMAND_PARAM(PACKET_SERVER_COMPANY_UPDATE)(NetworkClientSocket *cs)
{
Packet *p = NetworkSend_Init(PACKET_SERVER_COMPANY_UPDATE);
p->Send_uint16(_network_company_passworded);
cs->Send_Packet(p);
}
DEF_SERVER_SEND_COMMAND(PACKET_SERVER_CONFIG_UPDATE)
{
Packet *p = NetworkSend_Init(PACKET_SERVER_CONFIG_UPDATE);
p->Send_uint8(_settings_client.network.max_companies);
p->Send_uint8(_settings_client.network.max_spectators);
cs->Send_Packet(p);
}
/***********
* Receiving functions
* DEF_SERVER_RECEIVE_COMMAND has parameter: NetworkClientSocket *cs, Packet *p
************/
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_COMPANY_INFO)
{
SEND_COMMAND(PACKET_SERVER_COMPANY_INFO)(cs);
}
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_NEWGRFS_CHECKED)
{
if (cs->status != STATUS_INACTIVE) {
/* Illegal call, return error and ignore the packet */
SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
return;
}
NetworkClientInfo *ci = cs->GetInfo();
/* We now want a password from the client else we do not allow him in! */
if (!StrEmpty(_settings_client.network.server_password)) {
SEND_COMMAND(PACKET_SERVER_NEED_PASSWORD)(cs, NETWORK_GAME_PASSWORD);
} else {
if (IsValidCompanyID(ci->client_playas) && !StrEmpty(_network_company_states[ci->client_playas].password)) {
SEND_COMMAND(PACKET_SERVER_NEED_PASSWORD)(cs, NETWORK_COMPANY_PASSWORD);
} else {
SEND_COMMAND(PACKET_SERVER_WELCOME)(cs);
}
}
}
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_JOIN)
{
if (cs->status != STATUS_INACTIVE) {
/* Illegal call, return error and ignore the packet */
SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
return;
}
char name[NETWORK_CLIENT_NAME_LENGTH];
char unique_id[NETWORK_UNIQUE_ID_LENGTH];
NetworkClientInfo *ci;
CompanyID playas;
NetworkLanguage client_lang;
char client_revision[NETWORK_REVISION_LENGTH];
p->Recv_string(client_revision, sizeof(client_revision));
/* Check if the client has revision control enabled */
if (!IsNetworkCompatibleVersion(client_revision)) {
/* Different revisions!! */
SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_WRONG_REVISION);
return;
}
p->Recv_string(name, sizeof(name));
playas = (Owner)p->Recv_uint8();
client_lang = (NetworkLanguage)p->Recv_uint8();
p->Recv_string(unique_id, sizeof(unique_id));
if (cs->has_quit) return;
/* join another company does not affect these values */
switch (playas) {
case COMPANY_NEW_COMPANY: // New company
if (ActiveCompanyCount() >= _settings_client.network.max_companies) {
SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_FULL);
return;
}
break;
case COMPANY_SPECTATOR: // Spectator
if (NetworkSpectatorCount() >= _settings_client.network.max_spectators) {
SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_FULL);
return;
}
break;
default: // Join another company (companies 1-8 (index 0-7))
if (!IsValidCompanyID(playas) || !IsHumanCompany(playas)) {
SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_COMPANY_MISMATCH);
return;
}
break;
}
/* We need a valid name.. make it Player */
if (StrEmpty(name)) strecpy(name, "Player", lastof(name));
if (!NetworkFindName(name)) { // Change name if duplicate
/* We could not create a name for this client */
SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NAME_IN_USE);
return;
}
ci = cs->GetInfo();
strecpy(ci->client_name, name, lastof(ci->client_name));
strecpy(ci->unique_id, unique_id, lastof(ci->unique_id));
ci->client_playas = playas;
ci->client_lang = client_lang;
/* Make sure companies to which people try to join are not autocleaned */
if (IsValidCompanyID(playas)) _network_company_states[playas].months_empty = 0;
if (_grfconfig == NULL) {
RECEIVE_COMMAND(PACKET_CLIENT_NEWGRFS_CHECKED)(cs, NULL);
} else {
SEND_COMMAND(PACKET_SERVER_CHECK_NEWGRFS)(cs);
}
}
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_PASSWORD)
{
NetworkPasswordType type;
char password[NETWORK_PASSWORD_LENGTH];
const NetworkClientInfo *ci;
type = (NetworkPasswordType)p->Recv_uint8();
p->Recv_string(password, sizeof(password));
if (cs->status == STATUS_AUTHORIZING && type == NETWORK_GAME_PASSWORD) {
/* Check game-password */
if (strcmp(password, _settings_client.network.server_password) != 0) {
/* Password is invalid */
SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_WRONG_PASSWORD);
return;
}
ci = cs->GetInfo();
if (IsValidCompanyID(ci->client_playas) && !StrEmpty(_network_company_states[ci->client_playas].password)) {
SEND_COMMAND(PACKET_SERVER_NEED_PASSWORD)(cs, NETWORK_COMPANY_PASSWORD);
return;
}
/* Valid password, allow user */
SEND_COMMAND(PACKET_SERVER_WELCOME)(cs);
return;
} else if (cs->status == STATUS_AUTHORIZING && type == NETWORK_COMPANY_PASSWORD) {
ci = cs->GetInfo();
if (strcmp(password, _network_company_states[ci->client_playas].password) != 0) {
/* Password is invalid */
SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_WRONG_PASSWORD);
return;
}
SEND_COMMAND(PACKET_SERVER_WELCOME)(cs);
return;
}
SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
return;
}
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_GETMAP)
{
NetworkClientSocket *new_cs;
/* The client was never joined.. so this is impossible, right?
* Ignore the packet, give the client a warning, and close his connection */
if (cs->status < STATUS_AUTH || cs->has_quit) {
SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_AUTHORIZED);
return;
}
/* Check if someone else is receiving the map */
FOR_ALL_CLIENT_SOCKETS(new_cs) {
if (new_cs->status == STATUS_MAP) {
/* Tell the new client to wait */
cs->status = STATUS_MAP_WAIT;
SEND_COMMAND(PACKET_SERVER_WAIT)(cs);
return;
}
}
/* We receive a request to upload the map.. give it to the client! */
SEND_COMMAND(PACKET_SERVER_MAP)(cs);
}
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_MAP_OK)
{
/* Client has the map, now start syncing */
if (cs->status == STATUS_DONE_MAP && !cs->has_quit) {
char client_name[NETWORK_CLIENT_NAME_LENGTH];
NetworkClientSocket *new_cs;
NetworkGetClientName(client_name, sizeof(client_name), cs);
NetworkTextMessage(NETWORK_ACTION_JOIN, CC_DEFAULT, false, client_name);
/* Mark the client as pre-active, and wait for an ACK
* so we know he is done loading and in sync with us */
cs->status = STATUS_PRE_ACTIVE;
NetworkHandleCommandQueue(cs);
SEND_COMMAND(PACKET_SERVER_FRAME)(cs);
SEND_COMMAND(PACKET_SERVER_SYNC)(cs);
/* This is the frame the client receives
* we need it later on to make sure the client is not too slow */
cs->last_frame = _frame_counter;
cs->last_frame_server = _frame_counter;
FOR_ALL_CLIENT_SOCKETS(new_cs) {
if (new_cs->status > STATUS_AUTH) {
SEND_COMMAND(PACKET_SERVER_CLIENT_INFO)(new_cs, cs->GetInfo());
SEND_COMMAND(PACKET_SERVER_JOIN)(new_cs, cs->client_id);
}
}
if (_settings_client.network.pause_on_join) {
/* Now pause the game till the client is in sync */
DoCommandP(0, 1, 0, CMD_PAUSE);
NetworkServerSendChat(NETWORK_ACTION_SERVER_MESSAGE, DESTTYPE_BROADCAST, 0, "", CLIENT_ID_SERVER, NETWORK_SERVER_MESSAGE_GAME_PAUSED_CONNECT);
}
/* also update the new client with our max values */
SEND_COMMAND(PACKET_SERVER_CONFIG_UPDATE)(cs);
/* quickly update the syncing client with company details */
SEND_COMMAND(PACKET_SERVER_COMPANY_UPDATE)(cs);
} else {
/* Wrong status for this packet, give a warning to client, and close connection */
SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
}
}
/** The client has done a command and wants us to handle it
* @param *cs the connected client that has sent the command
* @param *p the packet in which the command was sent
*/
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_COMMAND)
{
NetworkClientSocket *new_cs;
/* The client was never joined.. so this is impossible, right?
* Ignore the packet, give the client a warning, and close his connection */
if (cs->status < STATUS_DONE_MAP || cs->has_quit) {
SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
return;
}
CommandPacket cp;
const char *err = cs->Recv_Command(p, &cp);
if (cs->has_quit) return;
const NetworkClientInfo *ci = cs->GetInfo();
if (err != NULL) {
IConsolePrintF(CC_ERROR, "WARNING: %s from client %d (IP: %s).", err, ci->client_id, GetClientIP(ci));
SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
return;
}
if (GetCommandFlags(cp.cmd) & CMD_SERVER && ci->client_id != CLIENT_ID_SERVER) {
IConsolePrintF(CC_ERROR, "WARNING: server only command from client %d (IP: %s), kicking...", ci->client_id, GetClientIP(ci));
SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_KICKED);
return;
}
if ((GetCommandFlags(cp.cmd) & CMD_SPECTATOR) == 0 && !IsValidCompanyID(cp.company) && ci->client_id != CLIENT_ID_SERVER) {
IConsolePrintF(CC_ERROR, "WARNING: spectator issueing command from client %d (IP: %s), kicking...", ci->client_id, GetClientIP(ci));
SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_KICKED);
return;
}
/** Only CMD_COMPANY_CTRL is always allowed, for the rest, playas needs
* to match the company in the packet. If it doesn't, the client has done
* something pretty naughty (or a bug), and will be kicked
*/
if (!(cp.cmd == CMD_COMPANY_CTRL && cp.p1 == 0 && ci->client_playas == COMPANY_NEW_COMPANY) && ci->client_playas != cp.company) {
IConsolePrintF(CC_ERROR, "WARNING: client %d (IP: %s) tried to execute a command as company %d, kicking...",
ci->client_playas + 1, GetClientIP(ci), cp.company + 1);
SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_COMPANY_MISMATCH);
return;
}
/** @todo CMD_COMPANY_CTRL with p1 = 0 announces a new company to the server. To give the
* company the correct ID, the server injects p2 and executes the command. Any other p1
* is prohibited. Pretty ugly and should be redone together with its function.
* @see CmdCompanyCtrl()
*/
if (cp.cmd == CMD_COMPANY_CTRL) {
if (cp.p1 != 0) {
SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_CHEATER);
return;
}
/* Check if we are full - else it's possible for spectators to send a CMD_COMPANY_CTRL and the company is created regardless of max_companies! */
if (ActiveCompanyCount() >= _settings_client.network.max_companies) {
NetworkServerSendChat(NETWORK_ACTION_SERVER_MESSAGE, DESTTYPE_CLIENT, ci->client_id, "cannot create new company, server full", CLIENT_ID_SERVER);
return;
}
/* XXX - Execute the command as a valid company. Normally this would be done by a
* spectator, but that is not allowed any commands. So do an impersonation. The drawback
* of this is that the first company's last_built_tile is also updated... */
cp.company = OWNER_BEGIN;
cp.p2 = cs->client_id;
}
/* The frame can be executed in the same frame as the next frame-packet
* That frame just before that frame is saved in _frame_counter_max */
cp.frame = _frame_counter_max + 1;
cp.next = NULL;
CommandCallback *callback = cp.callback;
/* Queue the command for the clients (are send at the end of the frame
* if they can handle it ;)) */
FOR_ALL_CLIENT_SOCKETS(new_cs) {
if (new_cs->status >= STATUS_MAP) {
/* Callbacks are only send back to the client who sent them in the
* first place. This filters that out. */
cp.callback = (new_cs != cs) ? NULL : callback;
cp.my_cmd = (new_cs == cs);
NetworkAddCommandQueue(cp, new_cs);
}
}
cp.callback = NULL;
cp.my_cmd = false;
NetworkAddCommandQueue(cp);
}
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_ERROR)
{
/* This packets means a client noticed an error and is reporting this
* to us. Display the error and report it to the other clients */
NetworkClientSocket *new_cs;
char str[100];
char client_name[NETWORK_CLIENT_NAME_LENGTH];
NetworkErrorCode errorno = (NetworkErrorCode)p->Recv_uint8();
/* The client was never joined.. thank the client for the packet, but ignore it */
if (cs->status < STATUS_DONE_MAP || cs->has_quit) {
cs->has_quit = true;
return;
}
NetworkGetClientName(client_name, sizeof(client_name), cs);
StringID strid = GetNetworkErrorMsg(errorno);
GetString(str, strid, lastof(str));
DEBUG(net, 2, "'%s' reported an error and is closing its connection (%s)", client_name, str);
NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, NULL, strid);
FOR_ALL_CLIENT_SOCKETS(new_cs) {
if (new_cs->status > STATUS_AUTH) {
SEND_COMMAND(PACKET_SERVER_ERROR_QUIT)(new_cs, cs->client_id, errorno);
}
}
cs->has_quit = true;
}
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_QUIT)
{
/* The client wants to leave. Display this and report it to the other
* clients. */
NetworkClientSocket *new_cs;
char client_name[NETWORK_CLIENT_NAME_LENGTH];
/* The client was never joined.. thank the client for the packet, but ignore it */
if (cs->status < STATUS_DONE_MAP || cs->has_quit) {
cs->has_quit = true;
return;
}
NetworkGetClientName(client_name, sizeof(client_name), cs);
NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, NULL, STR_NETWORK_CLIENT_LEAVING);
FOR_ALL_CLIENT_SOCKETS(new_cs) {
if (new_cs->status > STATUS_AUTH) {
SEND_COMMAND(PACKET_SERVER_QUIT)(new_cs, cs->client_id);
}
}
cs->has_quit = true;
}
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_ACK)
{
if (cs->status < STATUS_AUTH) {
/* Illegal call, return error and ignore the packet */
SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_AUTHORIZED);
return;
}
uint32 frame = p->Recv_uint32();
/* The client is trying to catch up with the server */
if (cs->status == STATUS_PRE_ACTIVE) {
/* The client is not yet catched up? */
if (frame + DAY_TICKS < _frame_counter) return;
/* Now he is! Unpause the game */
cs->status = STATUS_ACTIVE;
if (_settings_client.network.pause_on_join) {
DoCommandP(0, 0, 0, CMD_PAUSE);
NetworkServerSendChat(NETWORK_ACTION_SERVER_MESSAGE, DESTTYPE_BROADCAST, 0, "", CLIENT_ID_SERVER, NETWORK_SERVER_MESSAGE_GAME_UNPAUSED_CONNECT);
}
/* Execute script for, e.g. MOTD */
IConsoleCmdExec("exec scripts/on_server_connect.scr 0");
}
/* The client received the frame, make note of it */
cs->last_frame = frame;
/* With those 2 values we can calculate the lag realtime */
cs->last_frame_server = _frame_counter;
}
void NetworkServerSendChat(NetworkAction action, DestType desttype, int dest, const char *msg, ClientID from_id, int64 data)
{
NetworkClientSocket *cs;
const NetworkClientInfo *ci, *ci_own, *ci_to;
switch (desttype) {
case DESTTYPE_CLIENT:
/* Are we sending to the server? */
if ((ClientID)dest == CLIENT_ID_SERVER) {
ci = NetworkFindClientInfoFromClientID(from_id);
/* Display the text locally, and that is it */
if (ci != NULL)
NetworkTextMessage(action, (ConsoleColour)GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
} else {
/* Else find the client to send the message to */
FOR_ALL_CLIENT_SOCKETS(cs) {
if (cs->client_id == (ClientID)dest) {
SEND_COMMAND(PACKET_SERVER_CHAT)(cs, action, from_id, false, msg, data);
break;
}
}
}
/* Display the message locally (so you know you have sent it) */
if (from_id != (ClientID)dest) {
if (from_id == CLIENT_ID_SERVER) {
ci = NetworkFindClientInfoFromClientID(from_id);
ci_to = NetworkFindClientInfoFromClientID((ClientID)dest);
if (ci != NULL && ci_to != NULL)
NetworkTextMessage(action, (ConsoleColour)GetDrawStringCompanyColour(ci->client_playas), true, ci_to->client_name, msg, data);
} else {
FOR_ALL_CLIENT_SOCKETS(cs) {
if (cs->client_id == from_id) {
SEND_COMMAND(PACKET_SERVER_CHAT)(cs, action, (ClientID)dest, true, msg, data);
break;
}
}
}
}
break;
case DESTTYPE_TEAM: {
bool show_local = true; // If this is false, the message is already displayed
/* on the client who did sent it.
* Find all clients that belong to this company */
ci_to = NULL;
FOR_ALL_CLIENT_SOCKETS(cs) {
ci = cs->GetInfo();
if (ci->client_playas == (CompanyID)dest) {
SEND_COMMAND(PACKET_SERVER_CHAT)(cs, action, from_id, false, msg, data);
if (cs->client_id == from_id) show_local = false;
ci_to = ci; // Remember a client that is in the company for company-name
}
}
ci = NetworkFindClientInfoFromClientID(from_id);
ci_own = NetworkFindClientInfoFromClientID(CLIENT_ID_SERVER);
if (ci != NULL && ci_own != NULL && ci_own->client_playas == dest) {
NetworkTextMessage(action, (ConsoleColour)GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
if (from_id == CLIENT_ID_SERVER) show_local = false;
ci_to = ci_own;
}
/* There is no such client */
if (ci_to == NULL) break;
/* Display the message locally (so you know you have sent it) */
if (ci != NULL && show_local) {
if (from_id == CLIENT_ID_SERVER) {
char name[NETWORK_NAME_LENGTH];
StringID str = IsValidCompanyID(ci_to->client_playas) ? STR_COMPANY_NAME : STR_NETWORK_SPECTATORS;
SetDParam(0, ci_to->client_playas);
GetString(name, str, lastof(name));
NetworkTextMessage(action, (ConsoleColour)GetDrawStringCompanyColour(ci_own->client_playas), true, name, msg, data);
} else {
FOR_ALL_CLIENT_SOCKETS(cs) {
if (cs->client_id == from_id) {
SEND_COMMAND(PACKET_SERVER_CHAT)(cs, action, ci_to->client_id, true, msg, data);
}
}
}
}
}
break;
default:
DEBUG(net, 0, "[server] received unknown chat destination type %d. Doing broadcast instead", desttype);
/* fall-through to next case */
case DESTTYPE_BROADCAST:
FOR_ALL_CLIENT_SOCKETS(cs) {
SEND_COMMAND(PACKET_SERVER_CHAT)(cs, action, from_id, false, msg, data);
}
ci = NetworkFindClientInfoFromClientID(from_id);
if (ci != NULL)
NetworkTextMessage(action, (ConsoleColour)GetDrawStringCompanyColour(ci->client_playas), false, ci->client_name, msg, data);
break;
}
}
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_CHAT)
{
if (cs->status < STATUS_AUTH) {
/* Illegal call, return error and ignore the packet */
SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_AUTHORIZED);
return;
}
NetworkAction action = (NetworkAction)p->Recv_uint8();
DestType desttype = (DestType)p->Recv_uint8();
int dest = p->Recv_uint32();
char msg[NETWORK_CHAT_LENGTH];
p->Recv_string(msg, NETWORK_CHAT_LENGTH);
int64 data = p->Recv_uint64();
const NetworkClientInfo *ci = cs->GetInfo();
switch (action) {
case NETWORK_ACTION_GIVE_MONEY:
if (!IsValidCompanyID(ci->client_playas)) break;
/* Fall-through */
case NETWORK_ACTION_CHAT:
case NETWORK_ACTION_CHAT_CLIENT:
case NETWORK_ACTION_CHAT_COMPANY:
NetworkServerSendChat(action, desttype, dest, msg, cs->client_id, data);
break;
default:
IConsolePrintF(CC_ERROR, "WARNING: invalid chat action from client %d (IP: %s).", ci->client_id, GetClientIP(ci));
SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
break;
}
}
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_SET_PASSWORD)
{
if (cs->status != STATUS_ACTIVE) {
/* Illegal call, return error and ignore the packet */
SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
return;
}
char password[NETWORK_PASSWORD_LENGTH];
const NetworkClientInfo *ci;
p->Recv_string(password, sizeof(password));
ci = cs->GetInfo();
if (IsValidCompanyID(ci->client_playas)) {
strecpy(_network_company_states[ci->client_playas].password, password, lastof(_network_company_states[ci->client_playas].password));
NetworkServerUpdateCompanyPassworded(ci->client_playas, !StrEmpty(_network_company_states[ci->client_playas].password));
}
}
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_SET_NAME)
{
if (cs->status != STATUS_ACTIVE) {
/* Illegal call, return error and ignore the packet */
SEND_COMMAND(PACKET_SERVER_ERROR)(cs, NETWORK_ERROR_NOT_EXPECTED);
return;
}
char client_name[NETWORK_CLIENT_NAME_LENGTH];
NetworkClientInfo *ci;
p->Recv_string(client_name, sizeof(client_name));
ci = cs->GetInfo();
if (cs->has_quit) return;
if (ci != NULL) {
/* Display change */
if (NetworkFindName(client_name)) {
NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, client_name);
strecpy(ci->client_name, client_name, lastof(ci->client_name));
NetworkUpdateClientInfo(ci->client_id);
}
}
}
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_RCON)
{
char pass[NETWORK_PASSWORD_LENGTH];
char command[NETWORK_RCONCOMMAND_LENGTH];
if (StrEmpty(_settings_client.network.rcon_password)) return;
p->Recv_string(pass, sizeof(pass));
p->Recv_string(command, sizeof(command));
if (strcmp(pass, _settings_client.network.rcon_password) != 0) {
DEBUG(net, 0, "[rcon] wrong password from client-id %d", cs->client_id);
return;
}
DEBUG(net, 0, "[rcon] client-id %d executed: '%s'", cs->client_id, command);
_redirect_console_to_client = cs->client_id;
IConsoleCmdExec(command);
_redirect_console_to_client = INVALID_CLIENT_ID;
return;
}
DEF_SERVER_RECEIVE_COMMAND(PACKET_CLIENT_MOVE)
{
CompanyID company_id = (Owner)p->Recv_uint8();
/* Check if the company is valid */
if (!IsValidCompanyID(company_id) && company_id != COMPANY_SPECTATOR) return;
/* Check if we require a password for this company */
if (company_id != COMPANY_SPECTATOR && !StrEmpty(_network_company_states[company_id].password)) {
/* we need a password from the client - should be in this packet */
char password[NETWORK_PASSWORD_LENGTH];
p->Recv_string(password, sizeof(password));
/* Incorrect password sent, return! */
if (strcmp(password, _network_company_states[company_id].password) != 0) {
DEBUG(net, 2, "[move] wrong password from client-id #%d for company #%d", cs->client_id, company_id + 1);
return;
}
}
/* if we get here we can move the client */
NetworkServerDoMove(cs->client_id, company_id);
}
/* The layout for the receive-functions by the server */
typedef void NetworkServerPacket(NetworkClientSocket *cs, Packet *p);
/* This array matches PacketType. At an incoming
* packet it is matches against this array
* and that way the right function to handle that
* packet is found. */
static NetworkServerPacket * const _network_server_packet[] = {
NULL, // PACKET_SERVER_FULL,
NULL, // PACKET_SERVER_BANNED,
RECEIVE_COMMAND(PACKET_CLIENT_JOIN),
NULL, // PACKET_SERVER_ERROR,
RECEIVE_COMMAND(PACKET_CLIENT_COMPANY_INFO),
NULL, // PACKET_SERVER_COMPANY_INFO,
NULL, // PACKET_SERVER_CLIENT_INFO,
NULL, // PACKET_SERVER_NEED_PASSWORD,
RECEIVE_COMMAND(PACKET_CLIENT_PASSWORD),
NULL, // PACKET_SERVER_WELCOME,
RECEIVE_COMMAND(PACKET_CLIENT_GETMAP),
NULL, // PACKET_SERVER_WAIT,
NULL, // PACKET_SERVER_MAP,
RECEIVE_COMMAND(PACKET_CLIENT_MAP_OK),
NULL, // PACKET_SERVER_JOIN,
NULL, // PACKET_SERVER_FRAME,
NULL, // PACKET_SERVER_SYNC,
RECEIVE_COMMAND(PACKET_CLIENT_ACK),
RECEIVE_COMMAND(PACKET_CLIENT_COMMAND),
NULL, // PACKET_SERVER_COMMAND,
RECEIVE_COMMAND(PACKET_CLIENT_CHAT),
NULL, // PACKET_SERVER_CHAT,
RECEIVE_COMMAND(PACKET_CLIENT_SET_PASSWORD),
RECEIVE_COMMAND(PACKET_CLIENT_SET_NAME),
RECEIVE_COMMAND(PACKET_CLIENT_QUIT),
RECEIVE_COMMAND(PACKET_CLIENT_ERROR),
NULL, // PACKET_SERVER_QUIT,
NULL, // PACKET_SERVER_ERROR_QUIT,
NULL, // PACKET_SERVER_SHUTDOWN,
NULL, // PACKET_SERVER_NEWGAME,
NULL, // PACKET_SERVER_RCON,
RECEIVE_COMMAND(PACKET_CLIENT_RCON),
NULL, // PACKET_CLIENT_CHECK_NEWGRFS,
RECEIVE_COMMAND(PACKET_CLIENT_NEWGRFS_CHECKED),
NULL, // PACKET_SERVER_MOVE,
RECEIVE_COMMAND(PACKET_CLIENT_MOVE),
NULL, // PACKET_SERVER_COMPANY_UPDATE,
NULL, // PACKET_SERVER_CONFIG_UPDATE,
};
/* If this fails, check the array above with network_data.h */
assert_compile(lengthof(_network_server_packet) == PACKET_END);
void NetworkSocketHandler::Send_CompanyInformation(Packet *p, const Company *c, const NetworkCompanyStats *stats)
{
/* Grab the company name */
char company_name[NETWORK_COMPANY_NAME_LENGTH];
SetDParam(0, c->index);
GetString(company_name, STR_COMPANY_NAME, lastof(company_name));
/* Get the income */
Money income = 0;
if (_cur_year - 1 == c->inaugurated_year) {
/* The company is here just 1 year, so display [2], else display[1] */
for (uint i = 0; i < lengthof(c->yearly_expenses[2]); i++) {
income -= c->yearly_expenses[2][i];
}
} else {
for (uint i = 0; i < lengthof(c->yearly_expenses[1]); i++) {
income -= c->yearly_expenses[1][i];
}
}
/* Send the information */
p->Send_uint8 (c->index);
p->Send_string(company_name);
p->Send_uint32(c->inaugurated_year);
p->Send_uint64(c->old_economy[0].company_value);
p->Send_uint64(c->money);
p->Send_uint64(income);
p->Send_uint16(c->old_economy[0].performance_history);
/* Send 1 if there is a passord for the company else send 0 */
p->Send_bool (!StrEmpty(_network_company_states[c->index].password));
for (int i = 0; i < NETWORK_VEHICLE_TYPES; i++) {
p->Send_uint16(stats->num_vehicle[i]);
}
for (int i = 0; i < NETWORK_STATION_TYPES; i++) {
p->Send_uint16(stats->num_station[i]);
}
}
/**
* Populate the company stats.
* @param stats the stats to update
*/
void NetworkPopulateCompanyStats(NetworkCompanyStats *stats)
{
const Vehicle *v;
const Station *s;
memset(stats, 0, sizeof(*stats) * MAX_COMPANIES);
/* Go through all vehicles and count the type of vehicles */
FOR_ALL_VEHICLES(v) {
if (!IsValidCompanyID(v->owner) || !v->IsPrimaryVehicle()) continue;
byte type = 0;
switch (v->type) {
case VEH_TRAIN: type = 0; break;
case VEH_ROAD: type = (v->cargo_type != CT_PASSENGERS) ? 1 : 2; break;
case VEH_AIRCRAFT: type = 3; break;
case VEH_SHIP: type = 4; break;
default: continue;
}
stats[v->owner].num_vehicle[type]++;
}
/* Go through all stations and count the types of stations */
FOR_ALL_STATIONS(s) {
if (IsValidCompanyID(s->owner)) {
NetworkCompanyStats *npi = &stats[s->owner];
if (s->facilities & FACIL_TRAIN) npi->num_station[0]++;
if (s->facilities & FACIL_TRUCK_STOP) npi->num_station[1]++;
if (s->facilities & FACIL_BUS_STOP) npi->num_station[2]++;
if (s->facilities & FACIL_AIRPORT) npi->num_station[3]++;
if (s->facilities & FACIL_DOCK) npi->num_station[4]++;
}
}
}
/* Send a packet to all clients with updated info about this client_id */
void NetworkUpdateClientInfo(ClientID client_id)
{
NetworkClientSocket *cs;
NetworkClientInfo *ci = NetworkFindClientInfoFromClientID(client_id);
if (ci == NULL) return;
FOR_ALL_CLIENT_SOCKETS(cs) {
SEND_COMMAND(PACKET_SERVER_CLIENT_INFO)(cs, ci);
}
}
/* Check if we want to restart the map */
static void NetworkCheckRestartMap()
{
if (_settings_client.network.restart_game_year != 0 && _cur_year >= _settings_client.network.restart_game_year) {
DEBUG(net, 0, "Auto-restarting map. Year %d reached", _cur_year);
StartNewGameWithoutGUI(GENERATE_NEW_SEED);
}
}
/* Check if the server has autoclean_companies activated
Two things happen:
1) If a company is not protected, it is closed after 1 year (for example)
2) If a company is protected, protection is disabled after 3 years (for example)
(and item 1. happens a year later) */
static void NetworkAutoCleanCompanies()
{
const NetworkClientInfo *ci;
const Company *c;
bool clients_in_company[MAX_COMPANIES];
int vehicles_in_company[MAX_COMPANIES];
if (!_settings_client.network.autoclean_companies) return;
memset(clients_in_company, 0, sizeof(clients_in_company));
/* Detect the active companies */
FOR_ALL_CLIENT_INFOS(ci) {
if (IsValidCompanyID(ci->client_playas)) clients_in_company[ci->client_playas] = true;
}
if (!_network_dedicated) {
ci = NetworkFindClientInfoFromClientID(CLIENT_ID_SERVER);
if (IsValidCompanyID(ci->client_playas)) clients_in_company[ci->client_playas] = true;
}
if (_settings_client.network.autoclean_novehicles != 0) {
memset(vehicles_in_company, 0, sizeof(vehicles_in_company));
const Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (!IsValidCompanyID(v->owner) || !v->IsPrimaryVehicle()) continue;
vehicles_in_company[v->owner]++;
}
}
/* Go through all the comapnies */
FOR_ALL_COMPANIES(c) {
/* Skip the non-active once */
if (c->is_ai) continue;
if (!clients_in_company[c->index]) {
/* The company is empty for one month more */
_network_company_states[c->index].months_empty++;
/* Is the company empty for autoclean_unprotected-months, and is there no protection? */
if (_settings_client.network.autoclean_unprotected != 0 && _network_company_states[c->index].months_empty > _settings_client.network.autoclean_unprotected && StrEmpty(_network_company_states[c->index].password)) {
/* Shut the company down */
DoCommandP(0, 2, c->index, CMD_COMPANY_CTRL);
IConsolePrintF(CC_DEFAULT, "Auto-cleaned company #%d with no password", c->index + 1);
}
/* Is the company empty for autoclean_protected-months, and there is a protection? */
if (_settings_client.network.autoclean_protected != 0 && _network_company_states[c->index].months_empty > _settings_client.network.autoclean_protected && !StrEmpty(_network_company_states[c->index].password)) {
/* Unprotect the company */
_network_company_states[c->index].password[0] = '\0';
IConsolePrintF(CC_DEFAULT, "Auto-removed protection from company #%d", c->index + 1);
_network_company_states[c->index].months_empty = 0;
NetworkServerUpdateCompanyPassworded(c->index, false);
}
/* Is the company empty for autoclean_novehicles-months, and has no vehicles? */
if (_settings_client.network.autoclean_novehicles != 0 && _network_company_states[c->index].months_empty > _settings_client.network.autoclean_novehicles && vehicles_in_company[c->index] == 0) {
/* Shut the company down */
DoCommandP(0, 2, c->index, CMD_COMPANY_CTRL);
IConsolePrintF(CC_DEFAULT, "Auto-cleaned company #%d with no vehicles", c->index + 1);
}
} else {
/* It is not empty, reset the date */
_network_company_states[c->index].months_empty = 0;
}
}
}
/* This function changes new_name to a name that is unique (by adding #1 ...)
* and it returns true if that succeeded. */
bool NetworkFindName(char new_name[NETWORK_CLIENT_NAME_LENGTH])
{
bool found_name = false;
uint number = 0;
char original_name[NETWORK_CLIENT_NAME_LENGTH];
/* We use NETWORK_CLIENT_NAME_LENGTH in here, because new_name is really a pointer */
ttd_strlcpy(original_name, new_name, NETWORK_CLIENT_NAME_LENGTH);
while (!found_name) {
const NetworkClientInfo *ci;
found_name = true;
FOR_ALL_CLIENT_INFOS(ci) {
if (strcmp(ci->client_name, new_name) == 0) {
/* Name already in use */
found_name = false;
break;
}
}
/* Check if it is the same as the server-name */
ci = NetworkFindClientInfoFromClientID(CLIENT_ID_SERVER);
if (ci != NULL) {
if (strcmp(ci->client_name, new_name) == 0) found_name = false; // name already in use
}
if (!found_name) {
/* Try a new name (<name> #1, <name> #2, and so on) */
/* Something's really wrong when there're more names than clients */
if (number++ > MAX_CLIENTS) break;
snprintf(new_name, NETWORK_CLIENT_NAME_LENGTH, "%s #%d", original_name, number);
}
}
return found_name;
}
/**
* Change the client name of the given client
* @param client_id the client to change the name of
* @param new_name the new name for the client
* @return true iff the name was changed
*/
bool NetworkServerChangeClientName(ClientID client_id, const char *new_name)
{
NetworkClientInfo *ci;
/* Check if the name's already in use */
FOR_ALL_CLIENT_INFOS(ci) {
if (strcmp(ci->client_name, new_name) == 0) return false;
}
ci = NetworkFindClientInfoFromClientID(client_id);
if (ci == NULL) return false;
NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, true, ci->client_name, new_name);
strecpy(ci->client_name, new_name, lastof(ci->client_name));
NetworkUpdateClientInfo(client_id);
return true;
}
/* Reads a packet from the stream */
bool NetworkServer_ReadPackets(NetworkClientSocket *cs)
{
Packet *p;
NetworkRecvStatus res;
while ((p = cs->Recv_Packet(&res)) != NULL) {
byte type = p->Recv_uint8();
if (type < PACKET_END && _network_server_packet[type] != NULL && !cs->has_quit) {
_network_server_packet[type](cs, p);
} else {
DEBUG(net, 0, "[server] received invalid packet type %d", type);
}
delete p;
}
return true;
}
/* Handle the local command-queue */
static void NetworkHandleCommandQueue(NetworkClientSocket *cs)
{
CommandPacket *cp;
while ( (cp = cs->command_queue) != NULL) {
SEND_COMMAND(PACKET_SERVER_COMMAND)(cs, cp);
cs->command_queue = cp->next;
free(cp);
}
}
/* This is called every tick if this is a _network_server */
void NetworkServer_Tick(bool send_frame)
{
NetworkClientSocket *cs;
#ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
bool send_sync = false;
#endif
#ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
if (_frame_counter >= _last_sync_frame + _settings_client.network.sync_freq) {
_last_sync_frame = _frame_counter;
send_sync = true;
}
#endif
/* Now we are done with the frame, inform the clients that they can
* do their frame! */
FOR_ALL_CLIENT_SOCKETS(cs) {
/* Check if the speed of the client is what we can expect from a client */
if (cs->status == STATUS_ACTIVE) {
/* 1 lag-point per day */
int lag = NetworkCalculateLag(cs) / DAY_TICKS;
if (lag > 0) {
if (lag > 3) {
/* Client did still not report in after 4 game-day, drop him
* (that is, the 3 of above, + 1 before any lag is counted) */
IConsolePrintF(CC_ERROR,"Client #%d is dropped because the client did not respond for more than 4 game-days", cs->client_id);
NetworkCloseClient(cs);
continue;
}
/* Report once per time we detect the lag */
if (cs->lag_test == 0) {
IConsolePrintF(CC_WARNING,"[%d] Client #%d is slow, try increasing *net_frame_freq to a higher value!", _frame_counter, cs->client_id);
cs->lag_test = 1;
}
} else {
cs->lag_test = 0;
}
} else if (cs->status == STATUS_PRE_ACTIVE) {
int lag = NetworkCalculateLag(cs);
if (lag > _settings_client.network.max_join_time) {
IConsolePrintF(CC_ERROR,"Client #%d is dropped because it took longer than %d ticks for him to join", cs->client_id, _settings_client.network.max_join_time);
NetworkCloseClient(cs);
}
} else if (cs->status == STATUS_INACTIVE) {
int lag = NetworkCalculateLag(cs);
if (lag > 4 * DAY_TICKS) {
IConsolePrintF(CC_ERROR,"Client #%d is dropped because it took longer than %d ticks to start the joining process", cs->client_id, 4 * DAY_TICKS);
NetworkCloseClient(cs);
}
}
if (cs->status >= STATUS_PRE_ACTIVE) {
/* Check if we can send command, and if we have anything in the queue */
NetworkHandleCommandQueue(cs);
/* Send an updated _frame_counter_max to the client */
if (send_frame) SEND_COMMAND(PACKET_SERVER_FRAME)(cs);
#ifndef ENABLE_NETWORK_SYNC_EVERY_FRAME
/* Send a sync-check packet */
if (send_sync) SEND_COMMAND(PACKET_SERVER_SYNC)(cs);
#endif
}
}
/* See if we need to advertise */
NetworkUDPAdvertise();
}
void NetworkServerYearlyLoop()
{
NetworkCheckRestartMap();
}
void NetworkServerMonthlyLoop()
{
NetworkAutoCleanCompanies();
}
void NetworkServerChangeOwner(Owner current_owner, Owner new_owner)
{
/* The server has to handle all administrative issues, for example
* updating and notifying all clients of what has happened */
NetworkClientInfo *ci = NetworkFindClientInfoFromClientID(CLIENT_ID_SERVER);
/* The server has just changed from owner */
if (current_owner == ci->client_playas) {
ci->client_playas = new_owner;
NetworkUpdateClientInfo(CLIENT_ID_SERVER);
}
/* Find all clients that were in control of this company, and mark them as new_owner */
FOR_ALL_CLIENT_INFOS(ci) {
if (current_owner == ci->client_playas) {
ci->client_playas = new_owner;
NetworkUpdateClientInfo(ci->client_id);
}
}
}
const char *GetClientIP(const NetworkClientInfo *ci)
{
struct in_addr addr;
addr.s_addr = ci->client_ip;
return inet_ntoa(addr);
}
void NetworkServerShowStatusToConsole()
{
static const char * const stat_str[] = {
"inactive",
"authorizing",
"authorized",
"waiting",
"loading map",
"map done",
"ready",
"active"
};
NetworkClientSocket *cs;
FOR_ALL_CLIENT_SOCKETS(cs) {
int lag = NetworkCalculateLag(cs);
const NetworkClientInfo *ci = cs->GetInfo();
const char *status;
status = (cs->status < (ptrdiff_t)lengthof(stat_str) ? stat_str[cs->status] : "unknown");
IConsolePrintF(CC_INFO, "Client #%1d name: '%s' status: '%s' frame-lag: %3d company: %1d IP: %s unique-id: '%s'",
cs->client_id, ci->client_name, status, lag,
ci->client_playas + (IsValidCompanyID(ci->client_playas) ? 1 : 0),
GetClientIP(ci), ci->unique_id);
}
}
/**
* Send Config Update
*/
void NetworkServerSendConfigUpdate()
{
NetworkClientSocket *cs;
FOR_ALL_CLIENT_SOCKETS(cs) {
SEND_COMMAND(PACKET_SERVER_CONFIG_UPDATE)(cs);
}
}
void NetworkServerUpdateCompanyPassworded(CompanyID company_id, bool passworded)
{
if (NetworkCompanyIsPassworded(company_id) == passworded) return;
SB(_network_company_passworded, company_id, 1, !!passworded);
InvalidateWindowClasses(WC_COMPANY);
NetworkClientSocket *cs;
FOR_ALL_CLIENT_SOCKETS(cs) {
SEND_COMMAND(PACKET_SERVER_COMPANY_UPDATE)(cs);
}
}
/**
* Handle the tid-bits of moving a client from one company to another.
* @param client_id id of the client we want to move.
* @param company_id id of the company we want to move the client to.
* @return void
**/
void NetworkServerDoMove(ClientID client_id, CompanyID company_id)
{
/* Only allow non-dedicated servers and normal clients to be moved */
if (client_id == CLIENT_ID_SERVER && _network_dedicated) return;
NetworkClientInfo *ci = NetworkFindClientInfoFromClientID(client_id);
/* No need to waste network resources if the client is in the company already! */
if (ci->client_playas == company_id) return;
ci->client_playas = company_id;
if (client_id == CLIENT_ID_SERVER) {
SetLocalCompany(company_id);
} else {
SEND_COMMAND(PACKET_SERVER_MOVE)(NetworkFindClientStateFromClientID(client_id), client_id, company_id);
}
/* announce the client's move */
NetworkUpdateClientInfo(client_id);
NetworkAction action = (company_id == COMPANY_SPECTATOR) ? NETWORK_ACTION_COMPANY_SPECTATOR : NETWORK_ACTION_COMPANY_JOIN;
NetworkServerSendChat(action, DESTTYPE_BROADCAST, 0, "", client_id, company_id + 1);
}
void NetworkServerSendRcon(ClientID client_id, ConsoleColour colour_code, const char *string)
{
SEND_COMMAND(PACKET_SERVER_RCON)(NetworkFindClientStateFromClientID(client_id), colour_code, string);
}
void NetworkServerSendError(ClientID client_id, NetworkErrorCode error)
{
SEND_COMMAND(PACKET_SERVER_ERROR)(NetworkFindClientStateFromClientID(client_id), error);
}
void NetworkServerKickClient(ClientID client_id)
{
if (client_id == CLIENT_ID_SERVER) return;
NetworkServerSendError(client_id, NETWORK_ERROR_KICKED);
}
void NetworkServerBanIP(const char *banip)
{
const NetworkClientInfo *ci;
uint32 ip_number = inet_addr(banip);
/* There can be multiple clients with the same IP, kick them all */
FOR_ALL_CLIENT_INFOS(ci) {
if (ci->client_ip == ip_number) {
NetworkServerKickClient(ci->client_id);
}
}
/* Add user to ban-list */
for (uint index = 0; index < lengthof(_network_ban_list); index++) {
if (_network_ban_list[index] == NULL) {
_network_ban_list[index] = strdup(banip);
break;
}
}
}
bool NetworkCompanyHasClients(CompanyID company)
{
const NetworkClientInfo *ci;
FOR_ALL_CLIENT_INFOS(ci) {
if (ci->client_playas == company) return true;
}
return false;
}
#endif /* ENABLE_NETWORK */
| 56,086
|
C++
|
.cpp
| 1,507
| 34.377571
| 216
| 0.711174
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,248
|
network_command.cpp
|
EnergeticBark_OpenTTD-3DS/src/network/network_command.cpp
|
/* $Id$ */
/** @file network_command.cpp Command handling over network connections. */
#ifdef ENABLE_NETWORK
#include "../stdafx.h"
#include "../debug.h"
#include "network_internal.h"
#include "network_client.h"
#include "../command_func.h"
#include "../callback_table.h"
#include "../core/alloc_func.hpp"
#include "../string_func.h"
#include "../company_func.h"
/** Local queue of packets */
static CommandPacket *_local_command_queue = NULL;
/**
* Add a command to the local or client socket command queue,
* based on the socket.
* @param cp the command packet to add
* @param cs the socket to send to (NULL = locally)
*/
void NetworkAddCommandQueue(CommandPacket cp, NetworkClientSocket *cs)
{
CommandPacket *new_cp = MallocT<CommandPacket>(1);
*new_cp = cp;
CommandPacket **begin = (cs == NULL ? &_local_command_queue : &cs->command_queue);
if (*begin == NULL) {
*begin = new_cp;
} else {
CommandPacket *c = *begin;
while (c->next != NULL) c = c->next;
c->next = new_cp;
}
}
/**
* Prepare a DoCommand to be send over the network
* @param tile The tile to perform a command on (see #CommandProc)
* @param p1 Additional data for the command (see #CommandProc)
* @param p2 Additional data for the command (see #CommandProc)
* @param cmd The command to execute (a CMD_* value)
* @param callback A callback function to call after the command is finished
* @param text The text to pass
*/
void NetworkSend_Command(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback, const char *text)
{
assert((cmd & CMD_FLAGS_MASK) == 0);
CommandPacket c;
c.company = _local_company;
c.next = NULL;
c.tile = tile;
c.p1 = p1;
c.p2 = p2;
c.cmd = cmd;
c.callback = callback;
strecpy(c.text, (text != NULL) ? text : "", lastof(c.text));
if (_network_server) {
/* If we are the server, we queue the command in our 'special' queue.
* In theory, we could execute the command right away, but then the
* client on the server can do everything 1 tick faster than others.
* So to keep the game fair, we delay the command with 1 tick
* which gives about the same speed as most clients.
*/
c.frame = _frame_counter_max + 1;
c.my_cmd = true;
NetworkAddCommandQueue(c);
/* Only the local client (in this case, the server) gets the callback */
c.callback = 0;
/* And we queue it for delivery to the clients */
NetworkClientSocket *cs;
FOR_ALL_CLIENT_SOCKETS(cs) {
if (cs->status > STATUS_MAP_WAIT) NetworkAddCommandQueue(c, cs);
}
return;
}
c.frame = 0; // The client can't tell which frame, so just make it 0
/* Clients send their command to the server and forget all about the packet */
SEND_COMMAND(PACKET_CLIENT_COMMAND)(&c);
}
/**
* Execute all commands on the local command queue that ought to be executed this frame.
*/
void NetworkExecuteLocalCommandQueue()
{
while (_local_command_queue != NULL) {
/* The queue is always in order, which means
* that the first element will be executed first. */
if (_frame_counter < _local_command_queue->frame) break;
if (_frame_counter > _local_command_queue->frame) {
/* If we reach here, it means for whatever reason, we've already executed
* past the command we need to execute. */
error("[net] Trying to execute a packet in the past!");
}
CommandPacket *cp = _local_command_queue;
/* We can execute this command */
_current_company = cp->company;
cp->cmd |= CMD_NETWORK_COMMAND;
DoCommandP(cp, cp->my_cmd);
_local_command_queue = _local_command_queue->next;
free(cp);
}
}
/**
* Free the local command queue.
*/
void NetworkFreeLocalCommandQueue()
{
/* Free all queued commands */
while (_local_command_queue != NULL) {
CommandPacket *p = _local_command_queue;
_local_command_queue = _local_command_queue->next;
free(p);
}
}
/**
* Receives a command from the network.
* @param p the packet to read from.
* @param cp the struct to write the data to.
* @return an error message. When NULL there has been no error.
*/
const char *NetworkClientSocket::Recv_Command(Packet *p, CommandPacket *cp)
{
cp->company = (CompanyID)p->Recv_uint8();
cp->cmd = p->Recv_uint32();
cp->p1 = p->Recv_uint32();
cp->p2 = p->Recv_uint32();
cp->tile = p->Recv_uint32();
p->Recv_string(cp->text, lengthof(cp->text));
byte callback = p->Recv_uint8();
if (!IsValidCommand(cp->cmd)) return "invalid command";
if (GetCommandFlags(cp->cmd) & CMD_OFFLINE) return "offline only command";
if ((cp->cmd & CMD_FLAGS_MASK) != 0) return "invalid command flag";
if (callback > _callback_table_count) return "invalid callback";
cp->callback = _callback_table[callback];
return NULL;
}
/**
* Sends a command over the network.
* @param p the packet to send it in.
* @param cp the packet to actually send.
*/
void NetworkClientSocket::Send_Command(Packet *p, const CommandPacket *cp)
{
p->Send_uint8 (cp->company);
p->Send_uint32(cp->cmd);
p->Send_uint32(cp->p1);
p->Send_uint32(cp->p2);
p->Send_uint32(cp->tile);
p->Send_string(cp->text);
byte callback = 0;
while (callback < _callback_table_count && _callback_table[callback] != cp->callback) {
callback++;
}
if (callback == _callback_table_count) {
DEBUG(net, 0, "Unknown callback. (Pointer: %p) No callback sent", callback);
callback = 0; // _callback_table[0] == NULL
}
p->Send_uint8 (callback);
}
#endif /* ENABLE_NETWORK */
| 5,457
|
C++
|
.cpp
| 158
| 32.259494
| 119
| 0.690074
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,249
|
host.cpp
|
EnergeticBark_OpenTTD-3DS/src/network/core/host.cpp
|
/* $Id$ */
/** @file host.cpp Functions related to getting host specific data (IPs). */
#ifdef ENABLE_NETWORK
#include "../../stdafx.h"
#include "../../debug.h"
#include "os_abstraction.h"
#include "../../core/alloc_func.hpp"
/**
* Internal implementation for finding the broadcast IPs.
* This function is implemented multiple times for multiple targets.
* @param broadcast the list of broadcasts to write into.
* @param limit the maximum number of items to add.
*/
static int NetworkFindBroadcastIPsInternal(uint32 *broadcast, int limit);
#if defined(PSP)
static int NetworkFindBroadcastIPsInternal(uint32 *broadcast, int limit) // PSP implementation
{
return 0;
}
#elif defined(BEOS_NET_SERVER) /* doesn't have neither getifaddrs or net/if.h */
/* Based on Andrew Bachmann's netstat+.c. Big thanks to him! */
int _netstat(int fd, char **output, int verbose);
int seek_past_header(char **pos, const char *header)
{
char *new_pos = strstr(*pos, header);
if (new_pos == 0) {
return B_ERROR;
}
*pos += strlen(header) + new_pos - *pos + 1;
return B_OK;
}
static int NetworkFindBroadcastIPsInternal(uint32 *broadcast, int limit) // BEOS implementation
{
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) {
DEBUG(net, 0, "[core] error creating socket");
return 0;
}
char *output_pointer = NULL;
int output_length = _netstat(sock, &output_pointer, 1);
if (output_length < 0) {
DEBUG(net, 0, "[core] error running _netstat");
return 0;
}
int index;
char **output = &output_pointer;
if (seek_past_header(output, "IP Interfaces:") == B_OK) {
while (index != limit) {
uint32 n, fields, read;
uint8 i1, i2, i3, i4, j1, j2, j3, j4;
struct in_addr inaddr;
uint32 ip;
uint32 netmask;
fields = sscanf(*output, "%u: %hhu.%hhu.%hhu.%hhu, netmask %hhu.%hhu.%hhu.%hhu%n",
&n, &i1, &i2, &i3, &i4, &j1, &j2, &j3, &j4, &read);
read += 1;
if (fields != 9) {
break;
}
ip = (uint32)i1 << 24 | (uint32)i2 << 16 | (uint32)i3 << 8 | (uint32)i4;
netmask = (uint32)j1 << 24 | (uint32)j2 << 16 | (uint32)j3 << 8 | (uint32)j4;
if (ip != INADDR_LOOPBACK && ip != INADDR_ANY) {
inaddr.s_addr = htonl(ip | ~netmask);
broadcast[index] = inaddr.s_addr;
index++;
}
if (read < 0) {
break;
}
*output += read;
}
closesocket(sock);
}
return index;
}
#elif defined(HAVE_GETIFADDRS)
static int NetworkFindBroadcastIPsInternal(uint32 *broadcast, int limit) // GETIFADDRS implementation
{
struct ifaddrs *ifap, *ifa;
if (getifaddrs(&ifap) != 0) return 0;
int index = 0;
for (ifa = ifap; ifa != NULL && index != limit; ifa = ifa->ifa_next) {
if (!(ifa->ifa_flags & IFF_BROADCAST)) continue;
if (ifa->ifa_broadaddr == NULL) continue;
if (ifa->ifa_broadaddr->sa_family != AF_INET) continue;
broadcast[index] = ((struct sockaddr_in*)ifa->ifa_broadaddr)->sin_addr.s_addr;
index++;
}
freeifaddrs(ifap);
return index;
}
#elif defined(WIN32)
static int NetworkFindBroadcastIPsInternal(uint32 *broadcast, int limit) // Win32 implementation
{
SOCKET sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock == INVALID_SOCKET) return 0;
DWORD len = 0;
INTERFACE_INFO *ifo = AllocaM(INTERFACE_INFO, limit);
memset(ifo, 0, limit * sizeof(*ifo));
if ((WSAIoctl(sock, SIO_GET_INTERFACE_LIST, NULL, 0, &ifo[0], limit * sizeof(*ifo), &len, NULL, NULL)) != 0) {
closesocket(sock);
return 0;
}
int index = 0;
for (uint j = 0; j < len / sizeof(*ifo) && index != limit; j++) {
if (ifo[j].iiFlags & IFF_LOOPBACK) continue;
if (!(ifo[j].iiFlags & IFF_BROADCAST)) continue;
/* iiBroadcast is unusable, because it always seems to be set to 255.255.255.255. */
broadcast[index++] = ifo[j].iiAddress.AddressIn.sin_addr.s_addr | ~ifo[j].iiNetmask.AddressIn.sin_addr.s_addr;
}
closesocket(sock);
return index;
}
#else /* not HAVE_GETIFADDRS */
#include "../../string_func.h"
static int NetworkFindBroadcastIPsInternal(uint32 *broadcast, int limit) // !GETIFADDRS implementation
{
SOCKET sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock == INVALID_SOCKET) return 0;
char buf[4 * 1024]; // Arbitrary buffer size
struct ifconf ifconf;
ifconf.ifc_len = sizeof(buf);
ifconf.ifc_buf = buf;
if (ioctl(sock, SIOCGIFCONF, &ifconf) == -1) {
closesocket(sock);
return 0;
}
const char *buf_end = buf + ifconf.ifc_len;
int index = 0;
for (const char *p = buf; p < buf_end && index != limit;) {
const struct ifreq *req = (const struct ifreq*)p;
if (req->ifr_addr.sa_family == AF_INET) {
struct ifreq r;
strecpy(r.ifr_name, req->ifr_name, lastof(r.ifr_name));
if (ioctl(sock, SIOCGIFFLAGS, &r) != -1 &&
r.ifr_flags & IFF_BROADCAST &&
ioctl(sock, SIOCGIFBRDADDR, &r) != -1) {
broadcast[index++] = ((struct sockaddr_in*)&r.ifr_broadaddr)->sin_addr.s_addr;
}
}
p += sizeof(struct ifreq);
#if defined(AF_LINK) && !defined(SUNOS)
p += req->ifr_addr.sa_len - sizeof(struct sockaddr);
#endif
}
closesocket(sock);
return index;
}
#endif /* all NetworkFindBroadcastIPsInternals */
/**
* Find the IPs to broadcast.
* @param broadcast the list of broadcasts to write into.
* @param limit the maximum number of items to add.
*/
void NetworkFindBroadcastIPs(uint32 *broadcast, int limit)
{
int count = NetworkFindBroadcastIPsInternal(broadcast, limit);
/* Make sure the list is terminated. */
broadcast[count] = 0;
/* Now display to the debug all the detected ips */
DEBUG(net, 3, "Detected broadcast addresses:");
for (int i = 0; broadcast[i] != 0; i++) {
DEBUG(net, 3, "%d) %s", i, inet_ntoa(*(struct in_addr *)&broadcast[i])); // inet_ntoa(inaddr));
}
}
/**
* Resolve a hostname to an ip.
* @param hsotname the hostname to resolve
* @return the IP belonging to that hostname, or 0 on failure.
*/
uint32 NetworkResolveHost(const char *hostname)
{
/* Is this an IP address? */
in_addr_t ip = inet_addr(hostname);
if (ip != INADDR_NONE) return ip;
/* No, try to resolve the name */
struct in_addr addr;
#if !defined(PSP)
struct hostent *he = gethostbyname(hostname);
if (he == NULL) {
DEBUG(net, 0, "[NET] Cannot resolve %s", hostname);
return 0;
}
addr = *(struct in_addr *)he->h_addr_list[0];
#else
int rid = -1;
char buf[1024];
/* Create a resolver */
if (sceNetResolverCreate(&rid, buf, sizeof(buf)) < 0) {
DEBUG(net, 0, "[NET] Error connecting resolver");
return 0;
}
/* Try to resolve the name */
if (sceNetResolverStartNtoA(rid, hostname, &addr, 2, 3) < 0) {
DEBUG(net, 0, "[NET] Cannot resolve %s", hostname);
sceNetResolverDelete(rid);
return 0;
}
sceNetResolverDelete(rid);
#endif /* PSP */
DEBUG(net, 1, "[NET] Resolved %s to %s", hostname, inet_ntoa(addr));
ip = addr.s_addr;
return ip;
}
#endif /* ENABLE_NETWORK */
| 6,750
|
C++
|
.cpp
| 205
| 30.395122
| 112
| 0.674157
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,250
|
tcp.cpp
|
EnergeticBark_OpenTTD-3DS/src/network/core/tcp.cpp
|
/* $Id$ */
/**
* @file tcp.cpp Basic functions to receive and send TCP packets.
*/
#ifdef ENABLE_NETWORK
#include "../../stdafx.h"
#include "../../debug.h"
#include "packet.h"
#include "tcp.h"
NetworkTCPSocketHandler::NetworkTCPSocketHandler(SOCKET s) :
NetworkSocketHandler(s),
packet_queue(NULL), packet_recv(NULL), writable(false)
{
}
NetworkTCPSocketHandler::~NetworkTCPSocketHandler()
{
this->CloseConnection();
if (this->sock != INVALID_SOCKET) closesocket(this->sock);
this->sock = INVALID_SOCKET;
}
NetworkRecvStatus NetworkTCPSocketHandler::CloseConnection()
{
this->writable = false;
this->has_quit = true;
/* Free all pending and partially received packets */
while (this->packet_queue != NULL) {
Packet *p = this->packet_queue->next;
delete this->packet_queue;
this->packet_queue = p;
}
delete this->packet_recv;
this->packet_recv = NULL;
return NETWORK_RECV_STATUS_OKAY;
}
/**
* This function puts the packet in the send-queue and it is send as
* soon as possible. This is the next tick, or maybe one tick later
* if the OS-network-buffer is full)
* @param packet the packet to send
*/
void NetworkTCPSocketHandler::Send_Packet(Packet *packet)
{
Packet *p;
assert(packet != NULL);
packet->PrepareToSend();
/* Locate last packet buffered for the client */
p = this->packet_queue;
if (p == NULL) {
/* No packets yet */
this->packet_queue = packet;
} else {
/* Skip to the last packet */
while (p->next != NULL) p = p->next;
p->next = packet;
}
}
/**
* Sends all the buffered packets out for this client. It stops when:
* 1) all packets are send (queue is empty)
* 2) the OS reports back that it can not send any more
* data right now (full network-buffer, it happens ;))
* 3) sending took too long
*/
bool NetworkTCPSocketHandler::Send_Packets()
{
ssize_t res;
Packet *p;
/* We can not write to this socket!! */
if (!this->writable) return false;
if (!this->IsConnected()) return false;
p = this->packet_queue;
while (p != NULL) {
res = send(this->sock, (const char*)p->buffer + p->pos, p->size - p->pos, 0);
if (res == -1) {
int err = GET_LAST_ERROR();
if (err != EWOULDBLOCK) {
/* Something went wrong.. close client! */
DEBUG(net, 0, "send failed with error %d", err);
this->CloseConnection();
return false;
}
return true;
}
if (res == 0) {
/* Client/server has left us :( */
this->CloseConnection();
return false;
}
p->pos += res;
/* Is this packet sent? */
if (p->pos == p->size) {
/* Go to the next packet */
this->packet_queue = p->next;
delete p;
p = this->packet_queue;
} else {
return true;
}
}
return true;
}
/**
* Receives a packet for the given client
* @param status the variable to store the status into
* @return the received packet (or NULL when it didn't receive one)
*/
Packet *NetworkTCPSocketHandler::Recv_Packet(NetworkRecvStatus *status)
{
ssize_t res;
Packet *p;
*status = NETWORK_RECV_STATUS_OKAY;
if (!this->IsConnected()) return NULL;
if (this->packet_recv == NULL) {
this->packet_recv = new Packet(this);
if (this->packet_recv == NULL) error("Failed to allocate packet");
}
p = this->packet_recv;
/* Read packet size */
if (p->pos < sizeof(PacketSize)) {
while (p->pos < sizeof(PacketSize)) {
/* Read the size of the packet */
res = recv(this->sock, (char*)p->buffer + p->pos, sizeof(PacketSize) - p->pos, 0);
if (res == -1) {
int err = GET_LAST_ERROR();
if (err != EWOULDBLOCK) {
/* Something went wrong... (104 is connection reset by peer) */
if (err != 104) DEBUG(net, 0, "recv failed with error %d", err);
*status = this->CloseConnection();
return NULL;
}
/* Connection would block, so stop for now */
return NULL;
}
if (res == 0) {
/* Client/server has left */
*status = this->CloseConnection();
return NULL;
}
p->pos += res;
}
/* Read the packet size from the received packet */
p->ReadRawPacketSize();
if (p->size > SEND_MTU) {
*status = this->CloseConnection();
return NULL;
}
}
/* Read rest of packet */
while (p->pos < p->size) {
res = recv(this->sock, (char*)p->buffer + p->pos, p->size - p->pos, 0);
if (res == -1) {
int err = GET_LAST_ERROR();
if (err != EWOULDBLOCK) {
/* Something went wrong... (104 is connection reset by peer) */
if (err != 104) DEBUG(net, 0, "recv failed with error %d", err);
*status = this->CloseConnection();
return NULL;
}
/* Connection would block */
return NULL;
}
if (res == 0) {
/* Client/server has left */
*status = this->CloseConnection();
return NULL;
}
p->pos += res;
}
/* Prepare for receiving a new packet */
this->packet_recv = NULL;
p->PrepareToRead();
return p;
}
bool NetworkTCPSocketHandler::IsPacketQueueEmpty()
{
return this->packet_queue == NULL;
}
#endif /* ENABLE_NETWORK */
| 4,919
|
C++
|
.cpp
| 178
| 24.758427
| 85
| 0.65633
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,251
|
tcp_game.cpp
|
EnergeticBark_OpenTTD-3DS/src/network/core/tcp_game.cpp
|
/* $Id$ */
/**
* @file tcp_game.cpp Basic functions to receive and send TCP packets for game purposes.
*/
#ifdef ENABLE_NETWORK
#include "../../stdafx.h"
#include "../../openttd.h"
#include "../../variables.h"
#include "../network_internal.h"
#include "packet.h"
#include "tcp_game.h"
#include "table/strings.h"
#include "../../oldpool_func.h"
/** Make very sure the preconditions given in network_type.h are actually followed */
assert_compile(MAX_CLIENT_SLOTS == (MAX_CLIENT_SLOTS >> NCI_BITS_PER_POOL_BLOCK) << NCI_BITS_PER_POOL_BLOCK);
assert_compile(MAX_CLIENT_SLOTS > MAX_CLIENTS);
typedef ClientIndex NetworkClientSocketID;
DEFINE_OLD_POOL_GENERIC(NetworkClientSocket, NetworkClientSocket);
NetworkClientSocket::NetworkClientSocket(ClientID client_id)
{
this->client_id = client_id;
this->status = STATUS_INACTIVE;
}
NetworkClientSocket::~NetworkClientSocket()
{
while (this->command_queue != NULL) {
CommandPacket *p = this->command_queue->next;
free(this->command_queue);
this->command_queue = p;
}
this->client_id = INVALID_CLIENT_ID;
this->status = STATUS_INACTIVE;
}
/**
* Functions to help NetworkRecv_Packet/NetworkSend_Packet a bit
* A socket can make errors. When that happens this handles what to do.
* For clients: close connection and drop back to main-menu
* For servers: close connection and that is it
* @return the new status
* TODO: needs to be splitted when using client and server socket packets
*/
NetworkRecvStatus NetworkClientSocket::CloseConnection()
{
/* Clients drop back to the main menu */
if (!_network_server && _networking) {
_switch_mode = SM_MENU;
_networking = false;
extern StringID _switch_mode_errorstr;
_switch_mode_errorstr = STR_NETWORK_ERR_LOSTCONNECTION;
return NETWORK_RECV_STATUS_CONN_LOST;
}
NetworkCloseClient(this);
return NETWORK_RECV_STATUS_OKAY;
}
#endif /* ENABLE_NETWORK */
| 1,903
|
C++
|
.cpp
| 55
| 32.690909
| 109
| 0.743184
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,252
|
core.cpp
|
EnergeticBark_OpenTTD-3DS/src/network/core/core.cpp
|
/* $Id$ */
/**
* @file core.cpp Functions used to initialize/shut down the core network
*/
#ifdef ENABLE_NETWORK
#include "../../stdafx.h"
#include "../../debug.h"
#include "os_abstraction.h"
#include "core.h"
#include "packet.h"
#ifdef __MORPHOS__
/* the library base is required here */
struct Library *SocketBase = NULL;
#endif
/**
* Initializes the network core (as that is needed for some platforms
* @return true if the core has been initialized, false otherwise
*/
bool NetworkCoreInitialize()
{
#if defined(__MORPHOS__) || defined(__AMIGA__)
/*
* IMPORTANT NOTE: SocketBase needs to be initialized before we use _any_
* network related function, else: crash.
*/
DEBUG(net, 3, "[core] loading bsd socket library");
SocketBase = OpenLibrary("bsdsocket.library", 4);
if (SocketBase == NULL) {
DEBUG(net, 0, "[core] can't open bsdsocket.library version 4, network unavailable");
return false;
}
#if defined(__AMIGA__)
/* for usleep() implementation (only required for legacy AmigaOS builds) */
TimerPort = CreateMsgPort();
if (TimerPort != NULL) {
TimerRequest = (struct timerequest*)CreateIORequest(TimerPort, sizeof(struct timerequest);
if (TimerRequest != NULL) {
if (OpenDevice("timer.device", UNIT_MICROHZ, (struct IORequest*)TimerRequest, 0) == 0) {
TimerBase = TimerRequest->tr_node.io_Device;
if (TimerBase == NULL) {
/* free ressources... */
DEBUG(net, 0, "[core] can't initialize timer, network unavailable");
return false;
}
}
}
}
#endif /* __AMIGA__ */
#endif /* __MORPHOS__ / __AMIGA__ */
/* Let's load the network in windows */
#ifdef WIN32
{
WSADATA wsa;
DEBUG(net, 3, "[core] loading windows socket library");
if (WSAStartup(MAKEWORD(2, 0), &wsa) != 0) {
DEBUG(net, 0, "[core] WSAStartup failed, network unavailable");
return false;
}
}
#endif /* WIN32 */
return true;
}
/**
* Shuts down the network core (as that is needed for some platforms
*/
void NetworkCoreShutdown()
{
#if defined(__MORPHOS__) || defined(__AMIGA__)
/* free allocated resources */
#if defined(__AMIGA__)
if (TimerBase != NULL) CloseDevice((struct IORequest*)TimerRequest); // XXX This smells wrong
if (TimerRequest != NULL) DeleteIORequest(TimerRequest);
if (TimerPort != NULL) DeleteMsgPort(TimerPort);
#endif
if (SocketBase != NULL) CloseLibrary(SocketBase);
#endif
#if defined(WIN32)
WSACleanup();
#endif
}
/**
* Serializes the GRFIdentifier (GRF ID and MD5 checksum) to the packet
* @param p the packet to write the data to
* @param grf the GRFIdentifier to serialize
*/
void NetworkSocketHandler::Send_GRFIdentifier(Packet *p, const GRFIdentifier *grf)
{
uint j;
p->Send_uint32(grf->grfid);
for (j = 0; j < sizeof(grf->md5sum); j++) {
p->Send_uint8 (grf->md5sum[j]);
}
}
/**
* Deserializes the GRFIdentifier (GRF ID and MD5 checksum) from the packet
* @param p the packet to read the data from
* @param grf the GRFIdentifier to deserialize
*/
void NetworkSocketHandler::Recv_GRFIdentifier(Packet *p, GRFIdentifier *grf)
{
uint j;
grf->grfid = p->Recv_uint32();
for (j = 0; j < sizeof(grf->md5sum); j++) {
grf->md5sum[j] = p->Recv_uint8();
}
}
#endif /* ENABLE_NETWORK */
| 3,204
|
C++
|
.cpp
| 107
| 27.785047
| 97
| 0.696852
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
1,539,253
|
udp.cpp
|
EnergeticBark_OpenTTD-3DS/src/network/core/udp.cpp
|
/* $Id$ */
/**
* @file core/udp.cpp Basic functions to receive and send UDP packets.
*/
#ifdef ENABLE_NETWORK
#include "../../stdafx.h"
#include "../../debug.h"
#include "../../core/bitmath_func.hpp"
#include "../../core/math_func.hpp"
#include "../../core/alloc_func.hpp"
#include "../../date_func.h"
#include "packet.h"
#include "udp.h"
/**
* Start listening on the given host and port.
* @param host the host (ip) to listen on
* @param port the port to listen on
* @param broadcast whether to allow broadcast sending/receiving
* @return true if the listening succeeded
*/
bool NetworkUDPSocketHandler::Listen(const uint32 host, const uint16 port, const bool broadcast)
{
struct sockaddr_in sin;
/* Make sure socket is closed */
this->Close();
this->sock = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
if (!this->IsConnected()) {
DEBUG(net, 0, "[udp] failed to start UDP listener");
return false;
}
SetNonBlocking(this->sock);
sin.sin_family = AF_INET;
/* Listen on all IPs */
sin.sin_addr.s_addr = host;
sin.sin_port = htons(port);
if (bind(this->sock, (struct sockaddr*)&sin, sizeof(sin)) != 0) {
DEBUG(net, 0, "[udp] bind failed on %s:%i", inet_ntoa(*(struct in_addr *)&host), port);
return false;
}
if (broadcast) {
/* Enable broadcast */
unsigned long val = 1;
#ifndef BEOS_NET_SERVER /* will work around this, some day; maybe. */
setsockopt(this->sock, SOL_SOCKET, SO_BROADCAST, (char *) &val , sizeof(val));
#endif
}
DEBUG(net, 1, "[udp] listening on port %s:%d", inet_ntoa(*(struct in_addr *)&host), port);
return true;
}
/**
* Close the given UDP socket
*/
void NetworkUDPSocketHandler::Close()
{
if (!this->IsConnected()) return;
closesocket(this->sock);
this->sock = INVALID_SOCKET;
}
NetworkRecvStatus NetworkUDPSocketHandler::CloseConnection()
{
this->has_quit = true;
return NETWORK_RECV_STATUS_OKAY;
}
/**
* Send a packet over UDP
* @param p the packet to send
* @param recv the receiver (target) of the packet
*/
void NetworkUDPSocketHandler::SendPacket(Packet *p, const struct sockaddr_in *recv)
{
int res;
p->PrepareToSend();
/* Send the buffer */
res = sendto(this->sock, (const char*)p->buffer, p->size, 0, (struct sockaddr *)recv, sizeof(*recv));
/* Check for any errors, but ignore it otherwise */
if (res == -1) DEBUG(net, 1, "[udp] sendto failed with: %i", GET_LAST_ERROR());
}
/**
* Receive a packet at UDP level
*/
void NetworkUDPSocketHandler::ReceivePackets()
{
struct sockaddr_in client_addr;
socklen_t client_len;
int nbytes;
Packet p(this);
int packet_len;
if (!this->IsConnected()) return;
packet_len = sizeof(p.buffer);
client_len = sizeof(client_addr);
/* Try to receive anything */
SetNonBlocking(this->sock); // Some OSes seem to lose the non-blocking status of the socket
nbytes = recvfrom(this->sock, (char*)p.buffer, packet_len, 0, (struct sockaddr *)&client_addr, &client_len);
/* We got some bytes for the base header of the packet. */
if (nbytes > 2) {
p.PrepareToRead();
/* If the size does not match the packet must be corrupted.
* Otherwise it will be marked as corrupted later on. */
if (nbytes != p.size) {
DEBUG(net, 1, "received a packet with mismatching size from %s:%d",
inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port));
return;
}
/* Handle the packet */
this->HandleUDPPacket(&p, &client_addr);
}
}
/**
* Serializes the NetworkGameInfo struct to the packet
* @param p the packet to write the data to
* @param info the NetworkGameInfo struct to serialize
*/
void NetworkUDPSocketHandler::Send_NetworkGameInfo(Packet *p, const NetworkGameInfo *info)
{
p->Send_uint8 (NETWORK_GAME_INFO_VERSION);
/*
* Please observe the order.
* The parts must be read in the same order as they are sent!
*/
/* Update the documentation in udp.h on changes
* to the NetworkGameInfo wire-protocol! */
/* NETWORK_GAME_INFO_VERSION = 4 */
{
/* Only send the GRF Identification (GRF_ID and MD5 checksum) of
* the GRFs that are needed, i.e. the ones that the server has
* selected in the NewGRF GUI and not the ones that are used due
* to the fact that they are in [newgrf-static] in openttd.cfg */
const GRFConfig *c;
uint count = 0;
/* Count number of GRFs to send information about */
for (c = info->grfconfig; c != NULL; c = c->next) {
if (!HasBit(c->flags, GCF_STATIC)) count++;
}
p->Send_uint8 (count); // Send number of GRFs
/* Send actual GRF Identifications */
for (c = info->grfconfig; c != NULL; c = c->next) {
if (!HasBit(c->flags, GCF_STATIC)) this->Send_GRFIdentifier(p, c);
}
}
/* NETWORK_GAME_INFO_VERSION = 3 */
p->Send_uint32(info->game_date);
p->Send_uint32(info->start_date);
/* NETWORK_GAME_INFO_VERSION = 2 */
p->Send_uint8 (info->companies_max);
p->Send_uint8 (info->companies_on);
p->Send_uint8 (info->spectators_max);
/* NETWORK_GAME_INFO_VERSION = 1 */
p->Send_string(info->server_name);
p->Send_string(info->server_revision);
p->Send_uint8 (info->server_lang);
p->Send_bool (info->use_password);
p->Send_uint8 (info->clients_max);
p->Send_uint8 (info->clients_on);
p->Send_uint8 (info->spectators_on);
p->Send_string(info->map_name);
p->Send_uint16(info->map_width);
p->Send_uint16(info->map_height);
p->Send_uint8 (info->map_set);
p->Send_bool (info->dedicated);
}
/**
* Deserializes the NetworkGameInfo struct from the packet
* @param p the packet to read the data from
* @param info the NetworkGameInfo to deserialize into
*/
void NetworkUDPSocketHandler::Recv_NetworkGameInfo(Packet *p, NetworkGameInfo *info)
{
static const Date MAX_DATE = ConvertYMDToDate(MAX_YEAR, 11, 31); // December is month 11
info->game_info_version = p->Recv_uint8();
/*
* Please observe the order.
* The parts must be read in the same order as they are sent!
*/
/* Update the documentation in udp.h on changes
* to the NetworkGameInfo wire-protocol! */
switch (info->game_info_version) {
case 4: {
GRFConfig **dst = &info->grfconfig;
uint i;
uint num_grfs = p->Recv_uint8();
/* Broken/bad data. It cannot have that many NewGRFs. */
if (num_grfs > NETWORK_MAX_GRF_COUNT) return;
for (i = 0; i < num_grfs; i++) {
GRFConfig *c = CallocT<GRFConfig>(1);
this->Recv_GRFIdentifier(p, c);
this->HandleIncomingNetworkGameInfoGRFConfig(c);
/* Append GRFConfig to the list */
*dst = c;
dst = &c->next;
}
} // Fallthrough
case 3:
info->game_date = Clamp(p->Recv_uint32(), 0, MAX_DATE);
info->start_date = Clamp(p->Recv_uint32(), 0, MAX_DATE);
/* Fallthrough */
case 2:
info->companies_max = p->Recv_uint8 ();
info->companies_on = p->Recv_uint8 ();
info->spectators_max = p->Recv_uint8 ();
/* Fallthrough */
case 1:
p->Recv_string(info->server_name, sizeof(info->server_name));
p->Recv_string(info->server_revision, sizeof(info->server_revision));
info->server_lang = p->Recv_uint8 ();
info->use_password = p->Recv_bool ();
info->clients_max = p->Recv_uint8 ();
info->clients_on = p->Recv_uint8 ();
info->spectators_on = p->Recv_uint8 ();
if (info->game_info_version < 3) { // 16 bits dates got scrapped and are read earlier
info->game_date = p->Recv_uint16() + DAYS_TILL_ORIGINAL_BASE_YEAR;
info->start_date = p->Recv_uint16() + DAYS_TILL_ORIGINAL_BASE_YEAR;
}
p->Recv_string(info->map_name, sizeof(info->map_name));
info->map_width = p->Recv_uint16();
info->map_height = p->Recv_uint16();
info->map_set = p->Recv_uint8 ();
info->dedicated = p->Recv_bool ();
if (info->server_lang >= NETWORK_NUM_LANGUAGES) info->server_lang = 0;
if (info->map_set >= NETWORK_NUM_LANDSCAPES) info->map_set = 0;
}
}
/**
* Defines a simple (switch) case for each network packet
* @param type the packet type to create the case for
*/
#define UDP_COMMAND(type) case type: this->NetworkPacketReceive_ ## type ## _command(p, client_addr); break;
/**
* Handle an incoming packets by sending it to the correct function.
* @param p the received packet
* @param client_addr the sender of the packet
*/
void NetworkUDPSocketHandler::HandleUDPPacket(Packet *p, const struct sockaddr_in *client_addr)
{
PacketUDPType type;
/* New packet == new client, which has not quit yet */
this->has_quit = false;
type = (PacketUDPType)p->Recv_uint8();
switch (this->HasClientQuit() ? PACKET_UDP_END : type) {
UDP_COMMAND(PACKET_UDP_CLIENT_FIND_SERVER);
UDP_COMMAND(PACKET_UDP_SERVER_RESPONSE);
UDP_COMMAND(PACKET_UDP_CLIENT_DETAIL_INFO);
UDP_COMMAND(PACKET_UDP_SERVER_DETAIL_INFO);
UDP_COMMAND(PACKET_UDP_SERVER_REGISTER);
UDP_COMMAND(PACKET_UDP_MASTER_ACK_REGISTER);
UDP_COMMAND(PACKET_UDP_CLIENT_GET_LIST);
UDP_COMMAND(PACKET_UDP_MASTER_RESPONSE_LIST);
UDP_COMMAND(PACKET_UDP_SERVER_UNREGISTER);
UDP_COMMAND(PACKET_UDP_CLIENT_GET_NEWGRFS);
UDP_COMMAND(PACKET_UDP_SERVER_NEWGRFS);
default:
if (this->HasClientQuit()) {
DEBUG(net, 0, "[udp] received invalid packet type %d from %s:%d", type, inet_ntoa(client_addr->sin_addr), ntohs(client_addr->sin_port));
} else {
DEBUG(net, 0, "[udp] received illegal packet from %s:%d", inet_ntoa(client_addr->sin_addr), ntohs(client_addr->sin_port));
}
break;
}
}
/**
* Create stub implementations for all receive commands that only
* show a warning that the given command is not available for the
* socket where the packet came from.
* @param type the packet type to create the stub for
*/
#define DEFINE_UNAVAILABLE_UDP_RECEIVE_COMMAND(type) \
void NetworkUDPSocketHandler::NetworkPacketReceive_## type ##_command(\
Packet *p, const struct sockaddr_in *client_addr) { \
DEBUG(net, 0, "[udp] received packet type %d on wrong port from %s:%d", \
type, inet_ntoa(client_addr->sin_addr), ntohs(client_addr->sin_port)); \
}
DEFINE_UNAVAILABLE_UDP_RECEIVE_COMMAND(PACKET_UDP_CLIENT_FIND_SERVER);
DEFINE_UNAVAILABLE_UDP_RECEIVE_COMMAND(PACKET_UDP_SERVER_RESPONSE);
DEFINE_UNAVAILABLE_UDP_RECEIVE_COMMAND(PACKET_UDP_CLIENT_DETAIL_INFO);
DEFINE_UNAVAILABLE_UDP_RECEIVE_COMMAND(PACKET_UDP_SERVER_DETAIL_INFO);
DEFINE_UNAVAILABLE_UDP_RECEIVE_COMMAND(PACKET_UDP_SERVER_REGISTER);
DEFINE_UNAVAILABLE_UDP_RECEIVE_COMMAND(PACKET_UDP_MASTER_ACK_REGISTER);
DEFINE_UNAVAILABLE_UDP_RECEIVE_COMMAND(PACKET_UDP_CLIENT_GET_LIST);
DEFINE_UNAVAILABLE_UDP_RECEIVE_COMMAND(PACKET_UDP_MASTER_RESPONSE_LIST);
DEFINE_UNAVAILABLE_UDP_RECEIVE_COMMAND(PACKET_UDP_SERVER_UNREGISTER);
DEFINE_UNAVAILABLE_UDP_RECEIVE_COMMAND(PACKET_UDP_CLIENT_GET_NEWGRFS);
DEFINE_UNAVAILABLE_UDP_RECEIVE_COMMAND(PACKET_UDP_SERVER_NEWGRFS);
#endif /* ENABLE_NETWORK */
| 10,709
|
C++
|
.cpp
| 282
| 35.400709
| 141
| 0.698997
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,254
|
tcp_content.cpp
|
EnergeticBark_OpenTTD-3DS/src/network/core/tcp_content.cpp
|
/* $Id$ */
/**
* @file tcp_content.cpp Basic functions to receive and send Content packets.
*/
#ifdef ENABLE_NETWORK
#include "../../stdafx.h"
#include "../../debug.h"
#include "tcp_content.h"
ContentInfo::ContentInfo()
{
memset(this, 0, sizeof(*this));
}
ContentInfo::~ContentInfo()
{
free(this->dependencies);
free(this->tags);
}
size_t ContentInfo::Size() const
{
size_t len = 0;
for (uint i = 0; i < this->tag_count; i++) len += strlen(this->tags[i]) + 1;
/* The size is never larger than the content info size plus the size of the
* tags and dependencies */
return sizeof(*this) +
sizeof(this->dependency_count) +
sizeof(*this->dependencies) * this->dependency_count;
}
bool ContentInfo::IsSelected() const
{
switch (this->state) {
case ContentInfo::SELECTED:
case ContentInfo::AUTOSELECTED:
return true;
default:
return false;
}
}
bool ContentInfo::IsValid() const
{
return this->state < ContentInfo::INVALID && this->type >= CONTENT_TYPE_BEGIN && this->type < CONTENT_TYPE_END;
}
void NetworkContentSocketHandler::Close()
{
CloseConnection();
if (this->sock == INVALID_SOCKET) return;
closesocket(this->sock);
this->sock = INVALID_SOCKET;
}
/**
* Defines a simple (switch) case for each network packet
* @param type the packet type to create the case for
*/
#define CONTENT_COMMAND(type) case type: return this->NetworkPacketReceive_ ## type ## _command(p); break;
/**
* Handle an incoming packets by sending it to the correct function.
* @param p the received packet
*/
bool NetworkContentSocketHandler::HandlePacket(Packet *p)
{
PacketContentType type = (PacketContentType)p->Recv_uint8();
switch (this->HasClientQuit() ? PACKET_CONTENT_END : type) {
CONTENT_COMMAND(PACKET_CONTENT_CLIENT_INFO_LIST);
CONTENT_COMMAND(PACKET_CONTENT_CLIENT_INFO_ID);
CONTENT_COMMAND(PACKET_CONTENT_CLIENT_INFO_EXTID);
CONTENT_COMMAND(PACKET_CONTENT_CLIENT_INFO_EXTID_MD5);
CONTENT_COMMAND(PACKET_CONTENT_SERVER_INFO);
CONTENT_COMMAND(PACKET_CONTENT_CLIENT_CONTENT);
CONTENT_COMMAND(PACKET_CONTENT_SERVER_CONTENT);
default:
if (this->HasClientQuit()) {
DEBUG(net, 0, "[tcp/content] received invalid packet type %d from %s:%d", type, inet_ntoa(this->client_addr.sin_addr), ntohs(this->client_addr.sin_port));
} else {
DEBUG(net, 0, "[tcp/content] received illegal packet from %s:%d", inet_ntoa(this->client_addr.sin_addr), ntohs(this->client_addr.sin_port));
}
return false;
}
}
/**
* Receive a packet at UDP level
*/
void NetworkContentSocketHandler::Recv_Packets()
{
Packet *p;
NetworkRecvStatus res;
while ((p = this->Recv_Packet(&res)) != NULL) {
bool cont = HandlePacket(p);
delete p;
if (!cont) return;
}
}
/**
* Create stub implementations for all receive commands that only
* show a warning that the given command is not available for the
* socket where the packet came from.
* @param type the packet type to create the stub for
*/
#define DEFINE_UNAVAILABLE_CONTENT_RECEIVE_COMMAND(type) \
bool NetworkContentSocketHandler::NetworkPacketReceive_## type ##_command(Packet *p) { \
DEBUG(net, 0, "[tcp/content] received illegal packet type %d from %s:%d", \
type, inet_ntoa(this->client_addr.sin_addr), ntohs(this->client_addr.sin_port)); \
return false; \
}
DEFINE_UNAVAILABLE_CONTENT_RECEIVE_COMMAND(PACKET_CONTENT_CLIENT_INFO_LIST);
DEFINE_UNAVAILABLE_CONTENT_RECEIVE_COMMAND(PACKET_CONTENT_CLIENT_INFO_ID);
DEFINE_UNAVAILABLE_CONTENT_RECEIVE_COMMAND(PACKET_CONTENT_CLIENT_INFO_EXTID);
DEFINE_UNAVAILABLE_CONTENT_RECEIVE_COMMAND(PACKET_CONTENT_CLIENT_INFO_EXTID_MD5);
DEFINE_UNAVAILABLE_CONTENT_RECEIVE_COMMAND(PACKET_CONTENT_SERVER_INFO);
DEFINE_UNAVAILABLE_CONTENT_RECEIVE_COMMAND(PACKET_CONTENT_CLIENT_CONTENT);
DEFINE_UNAVAILABLE_CONTENT_RECEIVE_COMMAND(PACKET_CONTENT_SERVER_CONTENT);
#endif /* ENABLE_NETWORK */
| 3,840
|
C++
|
.cpp
| 110
| 32.790909
| 159
| 0.745283
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,255
|
tcp_connect.cpp
|
EnergeticBark_OpenTTD-3DS/src/network/core/tcp_connect.cpp
|
/* $Id$ */
/**
* @file tcp_connect.cpp Basic functions to create connections without blocking.
*/
#ifdef ENABLE_NETWORK
#include "../../stdafx.h"
#include "../../debug.h"
#include "../../core/smallvec_type.hpp"
#include "../../thread.h"
#include "tcp.h"
/** List of connections that are currently being created */
static SmallVector<TCPConnecter *, 1> _tcp_connecters;
TCPConnecter::TCPConnecter(const NetworkAddress &address) :
connected(false),
aborted(false),
killed(false),
sock(INVALID_SOCKET),
address(address)
{
*_tcp_connecters.Append() = this;
if (!ThreadObject::New(TCPConnecter::ThreadEntry, this, &this->thread)) {
this->Connect();
}
}
void TCPConnecter::Connect()
{
DEBUG(net, 1, "Connecting to %s %d", address.GetHostname(), address.GetPort());
this->sock = socket(AF_INET, SOCK_STREAM, 0);
if (this->sock == INVALID_SOCKET) {
this->aborted = true;
return;
}
if (!SetNoDelay(this->sock)) DEBUG(net, 1, "Setting TCP_NODELAY failed");
struct sockaddr_in sin;
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = address.GetIP();
sin.sin_port = htons(address.GetPort());
/* We failed to connect for which reason what so ever */
if (connect(this->sock, (struct sockaddr*) &sin, sizeof(sin)) != 0) {
closesocket(this->sock);
this->sock = INVALID_SOCKET;
this->aborted = true;
return;
}
if (!SetNonBlocking(this->sock)) DEBUG(net, 0, "Setting non-blocking mode failed");
this->connected = true;
}
/* static */ void TCPConnecter::ThreadEntry(void *param)
{
static_cast<TCPConnecter*>(param)->Connect();
}
/* static */ void TCPConnecter::CheckCallbacks()
{
for (TCPConnecter **iter = _tcp_connecters.Begin(); iter < _tcp_connecters.End(); /* nothing */) {
TCPConnecter *cur = *iter;
if ((cur->connected || cur->aborted) && cur->killed) {
_tcp_connecters.Erase(iter);
if (cur->sock != INVALID_SOCKET) closesocket(cur->sock);
delete cur;
continue;
}
if (cur->connected) {
_tcp_connecters.Erase(iter);
cur->OnConnect(cur->sock);
delete cur;
continue;
}
if (cur->aborted) {
_tcp_connecters.Erase(iter);
cur->OnFailure();
delete cur;
continue;
}
iter++;
}
}
/* static */ void TCPConnecter::KillAll()
{
for (TCPConnecter **iter = _tcp_connecters.Begin(); iter != _tcp_connecters.End(); iter++) (*iter)->killed = true;
}
#endif /* ENABLE_NETWORK */
| 2,356
|
C++
|
.cpp
| 81
| 26.703704
| 115
| 0.685423
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,257
|
address.cpp
|
EnergeticBark_OpenTTD-3DS/src/network/core/address.cpp
|
/* $Id$ */
/** @file core/address.cpp Implementation of the address. */
#include "../../stdafx.h"
#ifdef ENABLE_NETWORK
#include "address.h"
#include "host.h"
const char *NetworkAddress::GetHostname() const
{
if (this->hostname != NULL) return this->hostname;
in_addr addr;
addr.s_addr = this->ip;
return inet_ntoa(addr);
}
uint32 NetworkAddress::GetIP()
{
if (!this->resolved) {
this->ip = NetworkResolveHost(this->hostname);
this->resolved = true;
}
return this->ip;
}
#endif /* ENABLE_NETWORK */
| 518
|
C++
|
.cpp
| 22
| 21.681818
| 60
| 0.704918
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,260
|
ai_instance.cpp
|
EnergeticBark_OpenTTD-3DS/src/ai/ai_instance.cpp
|
/* $Id$ */
/** @file ai_instance.cpp Implementation of AIInstance. */
#include "../stdafx.h"
#include "../debug.h"
#include "../settings_type.h"
#include "../vehicle_base.h"
#include "../saveload/saveload.h"
#include "../gui.h"
#include "table/strings.h"
#include <squirrel.h>
#include "../script/squirrel.hpp"
#include "../script/squirrel_helper.hpp"
#include "../script/squirrel_class.hpp"
#include "../script/squirrel_std.hpp"
#define DEFINE_SCRIPT_FILES
#include "ai_info.hpp"
#include "ai_storage.hpp"
#include "ai_instance.hpp"
#include "ai_gui.hpp"
/* Convert all AI related classes to Squirrel data.
* Note: this line a marker in squirrel_export.sh. Do not change! */
#include "api/ai_abstractlist.hpp.sq"
#include "api/ai_accounting.hpp.sq"
#include "api/ai_airport.hpp.sq"
#include "api/ai_base.hpp.sq"
#include "api/ai_bridge.hpp.sq"
#include "api/ai_bridgelist.hpp.sq"
#include "api/ai_cargo.hpp.sq"
#include "api/ai_cargolist.hpp.sq"
#include "api/ai_company.hpp.sq"
#include "api/ai_controller.hpp.sq"
#include "api/ai_date.hpp.sq"
#include "api/ai_depotlist.hpp.sq"
#include "api/ai_engine.hpp.sq"
#include "api/ai_enginelist.hpp.sq"
#include "api/ai_error.hpp.sq"
#include "api/ai_event.hpp.sq"
#include "api/ai_event_types.hpp.sq"
#include "api/ai_execmode.hpp.sq"
#include "api/ai_gamesettings.hpp.sq"
#include "api/ai_group.hpp.sq"
#include "api/ai_grouplist.hpp.sq"
#include "api/ai_industry.hpp.sq"
#include "api/ai_industrylist.hpp.sq"
#include "api/ai_industrytype.hpp.sq"
#include "api/ai_industrytypelist.hpp.sq"
#include "api/ai_list.hpp.sq"
#include "api/ai_log.hpp.sq"
#include "api/ai_map.hpp.sq"
#include "api/ai_marine.hpp.sq"
#include "api/ai_order.hpp.sq"
#include "api/ai_rail.hpp.sq"
#include "api/ai_railtypelist.hpp.sq"
#include "api/ai_road.hpp.sq"
#include "api/ai_sign.hpp.sq"
#include "api/ai_station.hpp.sq"
#include "api/ai_stationlist.hpp.sq"
#include "api/ai_subsidy.hpp.sq"
#include "api/ai_subsidylist.hpp.sq"
#include "api/ai_testmode.hpp.sq"
#include "api/ai_tile.hpp.sq"
#include "api/ai_tilelist.hpp.sq"
#include "api/ai_town.hpp.sq"
#include "api/ai_townlist.hpp.sq"
#include "api/ai_tunnel.hpp.sq"
#include "api/ai_vehicle.hpp.sq"
#include "api/ai_vehiclelist.hpp.sq"
#include "api/ai_waypoint.hpp.sq"
#include "api/ai_waypointlist.hpp.sq"
#undef DEFINE_SCRIPT_FILES
/* static */ AIInstance *AIInstance::current_instance = NULL;
AIStorage::~AIStorage()
{
/* Free our pointers */
if (event_data != NULL) AIEventController::FreeEventPointer();
if (log_data != NULL) AILog::FreeLogPointer();
}
static void PrintFunc(bool error_msg, const SQChar *message)
{
/* Convert to OpenTTD internal capable string */
AIController::Print(error_msg, FS2OTTD(message));
}
AIInstance::AIInstance(AIInfo *info) :
controller(NULL),
storage(NULL),
engine(NULL),
instance(NULL),
is_started(false),
is_dead(false),
suspend(0),
callback(NULL)
{
/* Set the instance already, so we can use AIObject::Set commands */
GetCompany(_current_company)->ai_instance = this;
AIInstance::current_instance = this;
this->controller = new AIController();
this->storage = new AIStorage();
this->engine = new Squirrel();
this->engine->SetPrintFunction(&PrintFunc);
/* The import method is available at a very early stage */
this->engine->AddMethod("import", &AILibrary::Import, 4, ".ssi");
/* Register the AIController */
SQAIController_Register(this->engine);
/* Load and execute the script for this AI */
const char *main_script = info->GetMainScript();
if (strcmp(main_script, "%_dummy") == 0) {
extern void AI_CreateAIDummy(HSQUIRRELVM vm);
AI_CreateAIDummy(this->engine->GetVM());
} else if (!this->engine->LoadScript(main_script)) {
this->Died();
return;
}
/* Create the main-class */
this->instance = MallocT<SQObject>(1);
if (!this->engine->CreateClassInstance(info->GetInstanceName(), this->controller, this->instance)) {
this->Died();
return;
}
/* Register the API functions and classes */
this->RegisterAPI();
/* The topmost stack item is true if there is data from a savegame
* and false otherwise. */
sq_pushbool(this->engine->vm, false);
}
AIInstance::~AIInstance()
{
if (instance != NULL) this->engine->ReleaseObject(this->instance);
if (engine != NULL) delete this->engine;
delete this->storage;
delete this->controller;
free(this->instance);
}
void AIInstance::RegisterAPI()
{
/* Register all classes */
squirrel_register_std(this->engine);
SQAIAbstractList_Register(this->engine);
SQAIAccounting_Register(this->engine);
SQAIAirport_Register(this->engine);
SQAIBase_Register(this->engine);
SQAIBridge_Register(this->engine);
SQAIBridgeList_Register(this->engine);
SQAIBridgeList_Length_Register(this->engine);
SQAICargo_Register(this->engine);
SQAICargoList_Register(this->engine);
SQAICargoList_IndustryAccepting_Register(this->engine);
SQAICargoList_IndustryProducing_Register(this->engine);
SQAICompany_Register(this->engine);
SQAIDate_Register(this->engine);
SQAIDepotList_Register(this->engine);
SQAIEngine_Register(this->engine);
SQAIEngineList_Register(this->engine);
SQAIError_Register(this->engine);
SQAIEvent_Register(this->engine);
SQAIEventCompanyBankrupt_Register(this->engine);
SQAIEventCompanyInTrouble_Register(this->engine);
SQAIEventCompanyMerger_Register(this->engine);
SQAIEventCompanyNew_Register(this->engine);
SQAIEventController_Register(this->engine);
SQAIEventDisasterZeppelinerCleared_Register(this->engine);
SQAIEventDisasterZeppelinerCrashed_Register(this->engine);
SQAIEventEngineAvailable_Register(this->engine);
SQAIEventEnginePreview_Register(this->engine);
SQAIEventIndustryClose_Register(this->engine);
SQAIEventIndustryOpen_Register(this->engine);
SQAIEventStationFirstVehicle_Register(this->engine);
SQAIEventSubsidyAwarded_Register(this->engine);
SQAIEventSubsidyExpired_Register(this->engine);
SQAIEventSubsidyOffer_Register(this->engine);
SQAIEventSubsidyOfferExpired_Register(this->engine);
SQAIEventVehicleCrashed_Register(this->engine);
SQAIEventVehicleLost_Register(this->engine);
SQAIEventVehicleUnprofitable_Register(this->engine);
SQAIEventVehicleWaitingInDepot_Register(this->engine);
SQAIExecMode_Register(this->engine);
SQAIGameSettings_Register(this->engine);
SQAIGroup_Register(this->engine);
SQAIGroupList_Register(this->engine);
SQAIIndustry_Register(this->engine);
SQAIIndustryList_Register(this->engine);
SQAIIndustryList_CargoAccepting_Register(this->engine);
SQAIIndustryList_CargoProducing_Register(this->engine);
SQAIIndustryType_Register(this->engine);
SQAIIndustryTypeList_Register(this->engine);
SQAIList_Register(this->engine);
SQAILog_Register(this->engine);
SQAIMap_Register(this->engine);
SQAIMarine_Register(this->engine);
SQAIOrder_Register(this->engine);
SQAIRail_Register(this->engine);
SQAIRailTypeList_Register(this->engine);
SQAIRoad_Register(this->engine);
SQAISign_Register(this->engine);
SQAIStation_Register(this->engine);
SQAIStationList_Register(this->engine);
SQAIStationList_Vehicle_Register(this->engine);
SQAISubsidy_Register(this->engine);
SQAISubsidyList_Register(this->engine);
SQAITestMode_Register(this->engine);
SQAITile_Register(this->engine);
SQAITileList_Register(this->engine);
SQAITileList_IndustryAccepting_Register(this->engine);
SQAITileList_IndustryProducing_Register(this->engine);
SQAITileList_StationType_Register(this->engine);
SQAITown_Register(this->engine);
SQAITownList_Register(this->engine);
SQAITunnel_Register(this->engine);
SQAIVehicle_Register(this->engine);
SQAIVehicleList_Register(this->engine);
SQAIVehicleList_DefaultGroup_Register(this->engine);
SQAIVehicleList_Group_Register(this->engine);
SQAIVehicleList_SharedOrders_Register(this->engine);
SQAIVehicleList_Station_Register(this->engine);
SQAIWaypoint_Register(this->engine);
SQAIWaypointList_Register(this->engine);
SQAIWaypointList_Vehicle_Register(this->engine);
this->engine->SetGlobalPointer(this->engine);
}
void AIInstance::Continue()
{
assert(this->suspend < 0);
this->suspend = -this->suspend - 1;
}
void AIInstance::Died()
{
DEBUG(ai, 0, "The AI died unexpectedly.");
this->is_dead = true;
if (this->instance != NULL) this->engine->ReleaseObject(this->instance);
delete this->engine;
this->instance = NULL;
this->engine = NULL;
ShowAIDebugWindow(_current_company);
if (strcmp(GetCompany(_current_company)->ai_info->GetMainScript(), "%_dummy") != 0) {
ShowErrorMessage(INVALID_STRING_ID, STR_AI_PLEASE_REPORT_CRASH, 0, 0);
}
}
void AIInstance::GameLoop()
{
if (this->is_dead) return;
if (this->engine->HasScriptCrashed()) {
/* The script crashed during saving, kill it here. */
this->Died();
return;
}
this->controller->ticks++;
if (this->suspend < -1) this->suspend++; // Multiplayer suspend, increase up to -1.
if (this->suspend < 0) return; // Multiplayer suspend, wait for Continue().
if (--this->suspend > 0) return; // Singleplayer suspend, decrease to 0.
/* If there is a callback to call, call that first */
if (this->callback != NULL) {
try {
this->callback(this);
} catch (AI_VMSuspend e) {
this->suspend = e.GetSuspendTime();
this->callback = e.GetSuspendCallback();
return;
}
}
this->suspend = 0;
this->callback = NULL;
if (!this->is_started) {
try {
AIObject::SetAllowDoCommand(false);
/* Run the constructor if it exists. Don't allow any DoCommands in it. */
if (this->engine->MethodExists(*this->instance, "constructor")) {
if (!this->engine->CallMethod(*this->instance, "constructor")) { this->Died(); return; }
}
if (!this->CallLoad()) { this->Died(); return; }
AIObject::SetAllowDoCommand(true);
/* Start the AI by calling Start() */
if (!this->engine->CallMethod(*this->instance, "Start", _settings_game.ai.ai_max_opcode_till_suspend) || !this->engine->IsSuspended()) this->Died();
} catch (AI_VMSuspend e) {
this->suspend = e.GetSuspendTime();
this->callback = e.GetSuspendCallback();
}
this->is_started = true;
return;
}
/* Continue the VM */
try {
if (!this->engine->Resume(_settings_game.ai.ai_max_opcode_till_suspend)) this->Died();
} catch (AI_VMSuspend e) {
this->suspend = e.GetSuspendTime();
this->callback = e.GetSuspendCallback();
}
}
void AIInstance::CollectGarbage()
{
if (this->is_started && !this->is_dead) this->engine->CollectGarbage();
}
/* static */ void AIInstance::DoCommandReturn(AIInstance *instance)
{
instance->engine->InsertResult(AIObject::GetLastCommandRes());
}
/* static */ void AIInstance::DoCommandReturnVehicleID(AIInstance *instance)
{
instance->engine->InsertResult(AIObject::GetNewVehicleID());
}
/* static */ void AIInstance::DoCommandReturnSignID(AIInstance *instance)
{
instance->engine->InsertResult(AIObject::GetNewSignID());
}
/* static */ void AIInstance::DoCommandReturnGroupID(AIInstance *instance)
{
instance->engine->InsertResult(AIObject::GetNewGroupID());
}
/* static */ AIStorage *AIInstance::GetStorage()
{
assert(IsValidCompanyID(_current_company) && !IsHumanCompany(_current_company));
return GetCompany(_current_company)->ai_instance->storage;
}
/*
* All data is stored in the following format:
* First 1 byte indicating if there is a data blob at all.
* 1 byte indicating the type of data.
* The data itself, this differs per type:
* - integer: a binary representation of the integer (int32).
* - string: First one byte with the string length, then a 0-terminated char
* array. The string can't be longer then 255 bytes (including
* terminating '\0').
* - array: All data-elements of the array are saved recursive in this
* format, and ended with an element of the type
* SQSL_ARRAY_TABLE_END.
* - table: All key/value pairs are saved in this format (first key 1, then
* value 1, then key 2, etc.). All keys and values can have an
* arbitrary type (as long as it is supported by the save function
* of course). The table is ended with an element of the type
* SQSL_ARRAY_TABLE_END.
* - bool: A single byte with value 1 representing true and 0 false.
* - null: No data.
*/
/** The type of the data that follows in the savegame. */
enum SQSaveLoadType {
SQSL_INT = 0x00, ///< The following data is an integer.
SQSL_STRING = 0x01, ///< The following data is an string.
SQSL_ARRAY = 0x02, ///< The following data is an array.
SQSL_TABLE = 0x03, ///< The following data is an table.
SQSL_BOOL = 0x04, ///< The following data is a boolean.
SQSL_NULL = 0x05, ///< A null variable.
SQSL_ARRAY_TABLE_END = 0xFF, ///< Marks the end of an array or table, no data follows.
};
static byte _ai_sl_byte;
static const SaveLoad _ai_byte[] = {
SLEG_VAR(_ai_sl_byte, SLE_UINT8),
SLE_END()
};
enum {
AISAVE_MAX_DEPTH = 25, ///< The maximum recursive depth for items stored in the savegame.
};
/* static */ bool AIInstance::SaveObject(HSQUIRRELVM vm, SQInteger index, int max_depth, bool test)
{
if (max_depth == 0) {
AILog::Error("Savedata can only be nested to 25 deep. No data saved.");
return false;
}
switch (sq_gettype(vm, index)) {
case OT_INTEGER: {
if (!test) {
_ai_sl_byte = SQSL_INT;
SlObject(NULL, _ai_byte);
}
SQInteger res;
sq_getinteger(vm, index, &res);
if (!test) {
int value = (int)res;
SlArray(&value, 1, SLE_INT32);
}
return true;
}
case OT_STRING: {
if (!test) {
_ai_sl_byte = SQSL_STRING;
SlObject(NULL, _ai_byte);
}
const SQChar *res;
sq_getstring(vm, index, &res);
/* @bug if a string longer than 512 characters is given to FS2OTTD, the
* internal buffer overflows. */
const char *buf = FS2OTTD(res);
size_t len = strlen(buf) + 1;
if (len >= 255) {
AILog::Error("Maximum string length is 254 chars. No data saved.");
return false;
}
if (!test) {
_ai_sl_byte = (byte)len;
SlObject(NULL, _ai_byte);
SlArray((void*)buf, len, SLE_CHAR);
}
return true;
}
case OT_ARRAY: {
if (!test) {
_ai_sl_byte = SQSL_ARRAY;
SlObject(NULL, _ai_byte);
}
sq_pushnull(vm);
while (SQ_SUCCEEDED(sq_next(vm, index - 1))) {
/* Store the value */
bool res = SaveObject(vm, -1, max_depth - 1, test);
sq_pop(vm, 2);
if (!res) {
sq_pop(vm, 1);
return false;
}
}
sq_pop(vm, 1);
if (!test) {
_ai_sl_byte = SQSL_ARRAY_TABLE_END;
SlObject(NULL, _ai_byte);
}
return true;
}
case OT_TABLE: {
if (!test) {
_ai_sl_byte = SQSL_TABLE;
SlObject(NULL, _ai_byte);
}
sq_pushnull(vm);
while (SQ_SUCCEEDED(sq_next(vm, index - 1))) {
/* Store the key + value */
bool res = SaveObject(vm, -2, max_depth - 1, test) && SaveObject(vm, -1, max_depth - 1, test);
sq_pop(vm, 2);
if (!res) {
sq_pop(vm, 1);
return false;
}
}
sq_pop(vm, 1);
if (!test) {
_ai_sl_byte = SQSL_ARRAY_TABLE_END;
SlObject(NULL, _ai_byte);
}
return true;
}
case OT_BOOL: {
if (!test) {
_ai_sl_byte = SQSL_BOOL;
SlObject(NULL, _ai_byte);
}
SQBool res;
sq_getbool(vm, index, &res);
if (!test) {
_ai_sl_byte = res ? 1 : 0;
SlObject(NULL, _ai_byte);
}
return true;
}
case OT_NULL: {
if (!test) {
_ai_sl_byte = SQSL_NULL;
SlObject(NULL, _ai_byte);
}
return true;
}
default:
AILog::Error("You tried to save an unsupported type. No data saved.");
return false;
}
}
/* static */ void AIInstance::SaveEmpty()
{
_ai_sl_byte = 0;
SlObject(NULL, _ai_byte);
}
void AIInstance::Save()
{
/* Don't save data if the AI didn't start yet or if it crashed. */
if (this->engine == NULL || this->engine->HasScriptCrashed()) {
SaveEmpty();
return;
}
HSQUIRRELVM vm = this->engine->GetVM();
if (!this->is_started) {
SQBool res;
sq_getbool(vm, -1, &res);
if (!res) {
SaveEmpty();
return;
}
/* Push the loaded savegame data to the top of the stack. */
sq_push(vm, -2);
_ai_sl_byte = 1;
SlObject(NULL, _ai_byte);
/* Save the data that was just loaded. */
SaveObject(vm, -1, AISAVE_MAX_DEPTH, false);
sq_poptop(vm);
} else if (this->engine->MethodExists(*this->instance, "Save")) {
HSQOBJECT savedata;
/* We don't want to be interrupted during the save function. */
bool backup_allow = AIObject::GetAllowDoCommand();
AIObject::SetAllowDoCommand(false);
if (!this->engine->CallMethod(*this->instance, "Save", &savedata)) {
/* The script crashed in the Save function. We can't kill
* it here, but do so in the next AI tick. */
SaveEmpty();
return;
}
AIObject::SetAllowDoCommand(backup_allow);
if (!sq_istable(savedata)) {
AILog::Error("Save function should return a table.");
SaveEmpty();
return;
}
sq_pushobject(vm, savedata);
if (SaveObject(vm, -1, AISAVE_MAX_DEPTH, true)) {
_ai_sl_byte = 1;
SlObject(NULL, _ai_byte);
SaveObject(vm, -1, AISAVE_MAX_DEPTH, false);
} else {
_ai_sl_byte = 0;
SlObject(NULL, _ai_byte);
}
sq_pop(vm, 1);
} else {
AILog::Warning("Save function is not implemented");
_ai_sl_byte = 0;
SlObject(NULL, _ai_byte);
}
}
/* static */ bool AIInstance::LoadObjects(HSQUIRRELVM vm)
{
SlObject(NULL, _ai_byte);
switch (_ai_sl_byte) {
case SQSL_INT: {
int value;
SlArray(&value, 1, SLE_INT32);
if (vm != NULL) sq_pushinteger(vm, (SQInteger)value);
return true;
}
case SQSL_STRING: {
SlObject(NULL, _ai_byte);
static char buf[256];
SlArray(buf, _ai_sl_byte, SLE_CHAR);
if (vm != NULL) sq_pushstring(vm, OTTD2FS(buf), -1);
return true;
}
case SQSL_ARRAY: {
if (vm != NULL) sq_newarray(vm, 0);
while (LoadObjects(vm)) {
if (vm != NULL) sq_arrayappend(vm, -2);
/* The value is popped from the stack by squirrel. */
}
return true;
}
case SQSL_TABLE: {
if (vm != NULL) sq_newtable(vm);
while (LoadObjects(vm)) {
LoadObjects(vm);
if (vm != NULL) sq_rawset(vm, -3);
/* The key (-2) and value (-1) are popped from the stack by squirrel. */
}
return true;
}
case SQSL_BOOL: {
SlObject(NULL, _ai_byte);
if (vm != NULL) sq_pushinteger(vm, (SQBool)(_ai_sl_byte != 0));
return true;
}
case SQSL_NULL: {
if (vm != NULL) sq_pushnull(vm);
return true;
}
case SQSL_ARRAY_TABLE_END: {
return false;
}
default: NOT_REACHED();
}
}
/* static */ void AIInstance::LoadEmpty()
{
SlObject(NULL, _ai_byte);
/* Check if there was anything saved at all. */
if (_ai_sl_byte == 0) return;
LoadObjects(NULL);
}
void AIInstance::Load(int version)
{
if (this->engine == NULL || version == -1) {
LoadEmpty();
return;
}
HSQUIRRELVM vm = this->engine->GetVM();
SlObject(NULL, _ai_byte);
/* Check if there was anything saved at all. */
if (_ai_sl_byte == 0) return;
/* First remove the value "false" since we have data to load. */
sq_poptop(vm);
sq_pushinteger(vm, version);
LoadObjects(vm);
sq_pushbool(vm, true);
}
bool AIInstance::CallLoad()
{
HSQUIRRELVM vm = this->engine->GetVM();
/* Is there save data that we should load? */
SQBool res;
sq_getbool(vm, -1, &res);
sq_poptop(vm);
if (!res) return true;
if (!this->engine->MethodExists(*this->instance, "Load")) {
AILog::Warning("Loading failed: there was data for the AI to load, but the AI does not have a Load() function.");
/* Pop the savegame data and version. */
sq_pop(vm, 2);
return true;
}
/* Go to the instance-root */
sq_pushobject(vm, *this->instance);
/* Find the function-name inside the script */
sq_pushstring(vm, OTTD2FS("Load"), -1);
/* Change the "Load" string in a function pointer */
sq_get(vm, -2);
/* Push the main instance as "this" object */
sq_pushobject(vm, *this->instance);
/* Push the version data and savegame data as arguments */
sq_push(vm, -5);
sq_push(vm, -5);
/* Call the AI load function. sq_call removes the arguments (but not the
* function pointer) from the stack. */
if (SQ_FAILED(sq_call(vm, 3, SQFalse, SQFalse))) return false;
/* Pop 1) The version, 2) the savegame data, 3) the object instance, 4) the function pointer. */
sq_pop(vm, 4);
return true;
}
| 20,212
|
C++
|
.cpp
| 624
| 29.80609
| 152
| 0.699928
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,261
|
ai_scanner.cpp
|
EnergeticBark_OpenTTD-3DS/src/ai/ai_scanner.cpp
|
/* $Id$ */
/** @file ai_scanner.cpp allows scanning AI scripts */
#include "../stdafx.h"
#include "../debug.h"
#include "../string_func.h"
#include "../fileio_func.h"
#include "../fios.h"
#include "../network/network.h"
#include "../core/random_func.hpp"
#include <sys/stat.h>
#include <squirrel.h>
#include "../script/squirrel.hpp"
#include "../script/squirrel_helper.hpp"
#include "../script/squirrel_class.hpp"
#include "ai.hpp"
#include "ai_info.hpp"
#include "ai_scanner.hpp"
#include "api/ai_controller.hpp"
void AIScanner::ScanDir(const char *dirname, bool library_scan)
{
extern bool FiosIsValidFile(const char *path, const struct dirent *ent, struct stat *sb);
extern bool FiosIsHiddenFile(const struct dirent *ent);
char d_name[MAX_PATH];
char temp_script[1024];
struct stat sb;
struct dirent *dirent;
DIR *dir;
dir = ttd_opendir(dirname);
/* Dir not found, so do nothing */
if (dir == NULL) return;
/* Walk all dirs trying to find a dir in which 'main.nut' exists */
while ((dirent = readdir(dir)) != NULL) {
ttd_strlcpy(d_name, FS2OTTD(dirent->d_name), sizeof(d_name));
/* Valid file, not '.' or '..', not hidden */
if (!FiosIsValidFile(dirname, dirent, &sb)) continue;
if (strcmp(d_name, ".") == 0 || strcmp(d_name, "..") == 0) continue;
if (FiosIsHiddenFile(dirent) && strncasecmp(d_name, PERSONAL_DIR, strlen(d_name)) != 0) continue;
/* Create the full length dirname */
ttd_strlcpy(temp_script, dirname, sizeof(temp_script));
ttd_strlcat(temp_script, d_name, sizeof(temp_script));
if (S_ISREG(sb.st_mode)) {
/* Only .tar files are allowed */
char *ext = strrchr(d_name, '.');
if (ext == NULL || strcasecmp(ext, ".tar") != 0) continue;
/* We always expect a directory in the TAR */
const char *first_dir = FioTarFirstDir(temp_script);
if (first_dir == NULL) continue;
ttd_strlcat(temp_script, PATHSEP, sizeof(temp_script));
ttd_strlcat(temp_script, first_dir, sizeof(temp_script));
FioTarAddLink(temp_script, first_dir);
} else if (!S_ISDIR(sb.st_mode)) {
/* Skip any other type of file */
continue;
}
/* Add an additional / where needed */
if (temp_script[strlen(temp_script) - 1] != PATHSEPCHAR) ttd_strlcat(temp_script, PATHSEP, sizeof(temp_script));
if (!library_scan) {
char info_script[MAX_PATH];
ttd_strlcpy(info_script, temp_script, sizeof(info_script));
ttd_strlcpy(main_script, temp_script, sizeof(main_script));
/* Every AI should contain an 'info.nut' and 'main.nut' file; else it is not a valid AI */
ttd_strlcat(info_script, "info.nut", sizeof(info_script));
ttd_strlcat(main_script, "main.nut", sizeof(main_script));
if (!FioCheckFileExists(info_script, AI_DIR) || !FioCheckFileExists(main_script, AI_DIR)) continue;
DEBUG(ai, 6, "Loading AI at location '%s'", main_script);
/* We don't care if one of the other scripts failed to load. */
this->engine->ResetCrashed();
this->engine->LoadScript(info_script);
} else {
char library_script[MAX_PATH];
ttd_strlcpy(library_script, temp_script, sizeof(library_script));
ttd_strlcpy(main_script, temp_script, sizeof(main_script));
/* Every library should contain an 'library.nut' and 'main.nut' file; else it is not a valid library */
ttd_strlcat(library_script, "library.nut", sizeof(library_script));
ttd_strlcat(main_script, "main.nut", sizeof(main_script));
if (!FioCheckFileExists(library_script, AI_LIBRARY_DIR) || !FioCheckFileExists(main_script, AI_LIBRARY_DIR)) continue;
DEBUG(ai, 6, "Loading AI Library at location '%s'", main_script);
/* We don't care if one of the other scripst failed to load. */
this->engine->ResetCrashed();
this->engine->LoadScript(library_script);
}
}
closedir(dir);
}
void AIScanner::ScanAIDir()
{
char buf[MAX_PATH];
Searchpath sp;
extern void ScanForTarFiles();
ScanForTarFiles();
FOR_ALL_SEARCHPATHS(sp) {
FioAppendDirectory(buf, MAX_PATH, sp, AI_DIR);
if (FileExists(buf)) this->ScanDir(buf, false);
FioAppendDirectory(buf, MAX_PATH, sp, AI_LIBRARY_DIR);
if (FileExists(buf)) this->ScanDir(buf, true);
}
}
void AIScanner::RescanAIDir()
{
this->ScanAIDir();
}
AIScanner::AIScanner() :
info_dummy(NULL)
{
this->engine = new Squirrel();
this->main_script[0] = '\0';
/* Create the AIInfo class, and add the RegisterAI function */
DefSQClass <AIInfo> SQAIInfo("AIInfo");
SQAIInfo.PreRegister(engine);
SQAIInfo.AddConstructor<void (AIInfo::*)(), 1>(engine, "x");
SQAIInfo.DefSQAdvancedMethod(this->engine, &AIInfo::AddSetting, "AddSetting");
SQAIInfo.DefSQAdvancedMethod(this->engine, &AIInfo::AddLabels, "AddLabels");
SQAIInfo.DefSQConst(engine, AICONFIG_RANDOM, "AICONFIG_RANDOM");
SQAIInfo.DefSQConst(engine, AICONFIG_BOOLEAN, "AICONFIG_BOOLEAN");
SQAIInfo.PostRegister(engine);
this->engine->AddMethod("RegisterAI", &AIInfo::Constructor, 2, "tx");
this->engine->AddMethod("RegisterDummyAI", &AIInfo::DummyConstructor, 2, "tx");
/* Create the AILibrary class, and add the RegisterLibrary function */
this->engine->AddClassBegin("AILibrary");
this->engine->AddClassEnd();
this->engine->AddMethod("RegisterLibrary", &AILibrary::Constructor, 2, "tx");
/* Mark this class as global pointer */
this->engine->SetGlobalPointer(this);
/* Scan the AI dir for scripts */
this->ScanAIDir();
/* Create the dummy AI */
this->engine->ResetCrashed();
strcpy(this->main_script, "%_dummy");
extern void AI_CreateAIInfoDummy(HSQUIRRELVM vm);
AI_CreateAIInfoDummy(this->engine->GetVM());
}
AIScanner::~AIScanner()
{
AIInfoList::iterator it = this->info_list.begin();
for (; it != this->info_list.end(); it++) {
free((void *)(*it).first);
delete (*it).second;
}
it = this->info_single_list.begin();
for (; it != this->info_single_list.end(); it++) {
free((void *)(*it).first);
}
AILibraryList::iterator lit = this->library_list.begin();
for (; lit != this->library_list.end(); lit++) {
free((void *)(*lit).first);
delete (*lit).second;
}
delete this->info_dummy;
delete this->engine;
}
bool AIScanner::ImportLibrary(const char *library, const char *class_name, int version, HSQUIRRELVM vm, AIController *controller)
{
/* Internally we store libraries as 'library.version' */
char library_name[1024];
snprintf(library_name, sizeof(library_name), "%s.%d", library, version);
strtolower(library_name);
/* Check if the library + version exists */
AILibraryList::iterator iter = this->library_list.find(library_name);
if (iter == this->library_list.end()) {
char error[1024];
/* Now see if the version doesn't exist, or the library */
iter = this->library_list.find(library);
if (iter == this->library_list.end()) {
snprintf(error, sizeof(error), "couldn't find library '%s'", library);
} else {
snprintf(error, sizeof(error), "couldn't find library '%s' version %d. The latest version available is %d", library, version, (*iter).second->GetVersion());
}
sq_throwerror(vm, OTTD2FS(error));
return false;
}
/* Get the current table/class we belong to */
HSQOBJECT parent;
sq_getstackobj(vm, 1, &parent);
char fake_class[1024];
int next_number;
if (!controller->LoadedLibrary(library_name, &next_number, &fake_class[0], sizeof(fake_class))) {
/* Create a new fake internal name */
snprintf(fake_class, sizeof(fake_class), "_internalNA%d", next_number);
/* Load the library in a 'fake' namespace, so we can link it to the name the user requested */
sq_pushroottable(vm);
sq_pushstring(vm, OTTD2FS(fake_class), -1);
sq_newclass(vm, SQFalse);
/* Load the library */
if (!Squirrel::LoadScript(vm, (*iter).second->GetMainScript(), false)) {
char error[1024];
snprintf(error, sizeof(error), "there was a compile error when importing '%s' version %d", library, version);
sq_throwerror(vm, OTTD2FS(error));
return false;
}
/* Create the fake class */
sq_newslot(vm, -3, SQFalse);
sq_pop(vm, 1);
controller->AddLoadedLibrary(library_name, fake_class);
}
/* Find the real class inside the fake class (like 'sets.Vector') */
sq_pushroottable(vm);
sq_pushstring(vm, OTTD2FS(fake_class), -1);
if (SQ_FAILED(sq_get(vm, -2))) {
sq_throwerror(vm, _SC("internal error assigning library class"));
return false;
}
sq_pushstring(vm, OTTD2FS((*iter).second->GetInstanceName()), -1);
if (SQ_FAILED(sq_get(vm, -2))) {
char error[1024];
snprintf(error, sizeof(error), "unable to find class '%s' in the library '%s' version %d", (*iter).second->GetInstanceName(), library, version);
sq_throwerror(vm, OTTD2FS(error));
return false;
}
HSQOBJECT obj;
sq_getstackobj(vm, -1, &obj);
sq_pop(vm, 3);
if (StrEmpty(class_name)) {
sq_pushobject(vm, obj);
return true;
}
/* Now link the name the user wanted to our 'fake' class */
sq_pushobject(vm, parent);
sq_pushstring(vm, OTTD2FS(class_name), -1);
sq_pushobject(vm, obj);
sq_newclass(vm, SQTrue);
sq_newslot(vm, -3, SQFalse);
sq_pop(vm, 1);
sq_pushobject(vm, obj);
return true;
}
void AIScanner::RegisterLibrary(AILibrary *library)
{
char library_name[1024];
snprintf(library_name, sizeof(library_name), "%s.%s.%d", library->GetCategory(), library->GetInstanceName(), library->GetVersion());
strtolower(library_name);
if (this->library_list.find(library_name) != this->library_list.end()) {
/* This AI was already registered */
#ifdef WIN32
/* Windows doesn't care about the case */
if (strcasecmp(this->library_list[library_name]->GetMainScript(), library->GetMainScript()) == 0) {
#else
if (strcmp(this->library_list[library_name]->GetMainScript(), library->GetMainScript()) == 0) {
#endif
delete library;
return;
}
DEBUG(ai, 0, "Registering two libraries with the same name and version");
DEBUG(ai, 0, " 1: %s", this->library_list[library_name]->GetMainScript());
DEBUG(ai, 0, " 2: %s", library->GetMainScript());
DEBUG(ai, 0, "The first is taking precedence.");
delete library;
return;
}
this->library_list[strdup(library_name)] = library;
}
void AIScanner::RegisterAI(AIInfo *info)
{
char ai_name[1024];
snprintf(ai_name, sizeof(ai_name), "%s.%d", info->GetName(), info->GetVersion());
strtolower(ai_name);
/* Check if GetShortName follows the rules */
if (strlen(info->GetShortName()) != 4) {
DEBUG(ai, 0, "The AI '%s' returned a string from GetShortName() which is not four characaters. Unable to load the AI.", info->GetName());
delete info;
return;
}
if (this->info_list.find(ai_name) != this->info_list.end()) {
/* This AI was already registered */
#ifdef WIN32
/* Windows doesn't care about the case */
if (strcasecmp(this->info_list[ai_name]->GetMainScript(), info->GetMainScript()) == 0) {
#else
if (strcmp(this->info_list[ai_name]->GetMainScript(), info->GetMainScript()) == 0) {
#endif
delete info;
return;
}
DEBUG(ai, 0, "Registering two AIs with the same name and version");
DEBUG(ai, 0, " 1: %s", this->info_list[ai_name]->GetMainScript());
DEBUG(ai, 0, " 2: %s", info->GetMainScript());
DEBUG(ai, 0, "The first is taking precedence.");
delete info;
return;
}
this->info_list[strdup(ai_name)] = info;
/* Add the AI to the 'unique' AI list, where only the highest version of the
* AI is registered. */
snprintf(ai_name, sizeof(ai_name), "%s", info->GetName());
strtolower(ai_name);
if (this->info_single_list.find(ai_name) == this->info_single_list.end()) {
this->info_single_list[strdup(ai_name)] = info;
} else if (this->info_single_list[ai_name]->GetVersion() < info->GetVersion()) {
this->info_single_list[ai_name] = info;
}
}
AIInfo *AIScanner::SelectRandomAI()
{
if (this->info_single_list.size() == 0) {
DEBUG(ai, 0, "No suitable AI found, loading 'dummy' AI.");
return this->info_dummy;
}
/* Find a random AI */
uint pos;
if (_networking) pos = InteractiveRandomRange((uint16)this->info_single_list.size());
else pos = RandomRange((uint16)this->info_single_list.size());
/* Find the Nth item from the array */
AIInfoList::iterator it = this->info_single_list.begin();
for (; pos > 0; pos--) it++;
AIInfoList::iterator first_it = it;
return (*it).second;
}
AIInfo *AIScanner::FindInfo(const char *nameParam, int versionParam)
{
if (this->info_list.size() == 0) return NULL;
if (nameParam == NULL) return NULL;
char ai_name[1024];
ttd_strlcpy(ai_name, nameParam, sizeof(ai_name));
strtolower(ai_name);
AIInfo *info = NULL;
int version = -1;
if (versionParam == -1) {
/* We want to load the latest version of this AI; so find it */
if (this->info_single_list.find(ai_name) != this->info_single_list.end()) return this->info_single_list[ai_name];
/* If we didn't find a match AI, maybe the user included a version */
char *e = strrchr(ai_name, '.');
if (e == NULL) return NULL;
*e = '\0';
e++;
versionParam = atoi(e);
/* Fall-through, like we were calling this function with a version */
}
/* Try to find a direct 'name.version' match */
char ai_name_tmp[1024];
snprintf(ai_name_tmp, sizeof(ai_name_tmp), "%s.%d", ai_name, versionParam);
strtolower(ai_name_tmp);
if (this->info_list.find(ai_name_tmp) != this->info_list.end()) return this->info_list[ai_name_tmp];
/* See if there is a compatible AI which goes by that name, with the highest
* version which allows loading the requested version */
AIInfoList::iterator it = this->info_list.begin();
for (; it != this->info_list.end(); it++) {
char ai_name_compare[1024];
snprintf(ai_name_compare, sizeof(ai_name_compare), "%s", (*it).second->GetName());
strtolower(ai_name_compare);
if (strcasecmp(ai_name, ai_name_compare) == 0 && (*it).second->CanLoadFromVersion(versionParam)) {
version = (*it).second->GetVersion();
info = (*it).second;
}
}
return info;
}
char *AIScanner::GetAIConsoleList(char *p, const char *last)
{
p += seprintf(p, last, "List of AIs:\n");
AIInfoList::iterator it = this->info_list.begin();
for (; it != this->info_list.end(); it++) {
AIInfo *i = (*it).second;
p += seprintf(p, last, "%10s (v%d): %s\n", i->GetName(), i->GetVersion(), i->GetDescription());
}
p += seprintf(p, last, "\n");
return p;
}
#if defined(ENABLE_NETWORK)
#include "../network/network_content.h"
#include "../md5.h"
#include "../tar_type.h"
/** Helper for creating a MD5sum of all files within of an AI. */
struct AIFileChecksumCreator : FileScanner {
byte md5sum[16]; ///< The final md5sum
/**
* Initialise the md5sum to be all zeroes,
* so we can easily xor the data.
*/
AIFileChecksumCreator()
{
memset(this->md5sum, 0, sizeof(this->md5sum));
}
/* Add the file and calculate the md5 sum. */
virtual bool AddFile(const char *filename, size_t basepath_length)
{
Md5 checksum;
uint8 buffer[1024];
size_t len, size;
byte tmp_md5sum[16];
/* Open the file ... */
FILE *f = FioFOpenFile(filename, "rb", DATA_DIR, &size);
if (f == NULL) return false;
/* ... calculate md5sum... */
while ((len = fread(buffer, 1, (size > sizeof(buffer)) ? sizeof(buffer) : size, f)) != 0 && size != 0) {
size -= len;
checksum.Append(buffer, len);
}
checksum.Finish(tmp_md5sum);
FioFCloseFile(f);
/* ... and xor it to the overall md5sum. */
for (uint i = 0; i < sizeof(md5sum); i++) this->md5sum[i] ^= tmp_md5sum[i];
return true;
}
};
/**
* Check whether the AI given in info is the same as in ci based
* on the shortname and md5 sum.
* @param ci the information to compare to
* @param md5sum whether to check the MD5 checksum
* @param info the AI to get the shortname and md5 sum from
* @return true iff they're the same
*/
static bool IsSameAI(const ContentInfo *ci, bool md5sum, AIFileInfo *info)
{
uint32 id = 0;
const char *str = info->GetShortName();
for (int j = 0; j < 4 && *str != '\0'; j++, str++) id |= *str << (8 * j);
if (id != ci->unique_id) return false;
if (!md5sum) return true;
AIFileChecksumCreator checksum;
char path[MAX_PATH];
strecpy(path, info->GetMainScript(), lastof(path));
/* There'll always be at least 2 path separator characters in an AI's
* main script name as the search algorithm requires the main script to
* be in a subdirectory of the AI directory; so ai/<path>/main.nut. */
*strrchr(path, PATHSEPCHAR) = '\0';
*strrchr(path, PATHSEPCHAR) = '\0';
TarList::iterator iter = _tar_list.find(path);
if (iter != _tar_list.end()) {
/* The main script is in a tar file, so find all files that
* are in the same tar and add them to the MD5 checksumming. */
TarFileList::iterator tar;
FOR_ALL_TARS(tar) {
/* Not in the same tar. */
if (tar->second.tar_filename != iter->first) continue;
/* Check the extension. */
const char *ext = strrchr(tar->first.c_str(), '.');
if (ext == NULL || strcasecmp(ext, ".nut") != 0) continue;
/* Create the full path name, */
seprintf(path, lastof(path), "%s%c%s", tar->second.tar_filename, PATHSEPCHAR, tar->first.c_str());
checksum.AddFile(path, 0);
}
} else {
/* Add the path sep char back when searching a directory, so we are
* in the actual directory. */
path[strlen(path)] = PATHSEPCHAR;
checksum.Scan(".nut", path);
}
return memcmp(ci->md5sum, checksum.md5sum, sizeof(ci->md5sum)) == 0;
}
/**
* Check whether we have an AI (library) with the exact characteristics as ci.
* @param ci the characteristics to search on (shortname and md5sum)
* @param md5sum whether to check the MD5 checksum
* @return true iff we have an AI (library) matching.
*/
bool AIScanner::HasAI(const ContentInfo *ci, bool md5sum)
{
switch (ci->type) {
case CONTENT_TYPE_AI:
for (AIInfoList::iterator it = this->info_list.begin(); it != this->info_list.end(); it++) {
if (IsSameAI(ci, md5sum, (*it).second)) return true;
}
return false;
case CONTENT_TYPE_AI_LIBRARY:
for (AILibraryList::iterator it = this->library_list.begin(); it != this->library_list.end(); it++) {
if (IsSameAI(ci, md5sum, (*it).second)) return true;
}
return false;
default:
NOT_REACHED();
}
}
/**
* Check whether we have an AI (library) with the exact characteristics as ci.
* @param ci the characteristics to search on (shortname and md5sum)
* @param md5sum whether to check the MD5 checksum
* @return true iff we have an AI (library) matching.
*/
/* static */ bool AI::HasAI(const ContentInfo *ci, bool md5sum)
{
return AI::ai_scanner->HasAI(ci, md5sum);
}
#endif /* ENABLE_NETWORK */
| 18,328
|
C++
|
.cpp
| 473
| 36.160677
| 159
| 0.688506
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,262
|
ai_info_dummy.cpp
|
EnergeticBark_OpenTTD-3DS/src/ai/ai_info_dummy.cpp
|
/* $Id$ */
#include <squirrel.h>
#include "../stdafx.h"
/* The reason this exists in C++, is that a user can trash his ai/ dir,
* leaving no AIs available. The complexity to solve this is insane, and
* therefor the alternative is used, and make sure there is always an AI
* available, no matter what the situation is. By defining it in C++, there
* is simply now way a user can delete it, and therefor safe to use. It has
* to be noted that this AI is complete invisible for the user, and impossible
* to select manual. It is a fail-over in case no AIs are available.
*/
const SQChar dummy_script_info[] = _SC(" \n\
class DummyAI extends AIInfo { \n\
function GetAuthor() { return \"OpenTTD NoAI Developers Team\"; } \n\
function GetName() { return \"DummyAI\"; } \n\
function GetShortName() { return \"DUMM\"; } \n\
function GetDescription() { return \"A Dummy AI that is loaded when your ai/ dir is empty\"; }\n\
function GetVersion() { return 1; } \n\
function GetDate() { return \"2008-07-26\"; } \n\
function CreateInstance() { return \"DummyAI\"; } \n\
} \n\
\n\
RegisterDummyAI(DummyAI()); \n\
");
const SQChar dummy_script[] = _SC(" \n\
class DummyAI extends AIController { \n\
function Start() { \n\
AILog.Error(\"No suitable AI found to load.\"); \n\
AILog.Error(\"This AI is a dummy AI and won't do anything.\"); \n\
AILog.Error(\"You can download several AIs via the 'Online Content' system.\"); \n\
} \n\
} \n\
");
void AI_CreateAIInfoDummy(HSQUIRRELVM vm)
{
sq_pushroottable(vm);
/* Load and run the script */
if (SQ_SUCCEEDED(sq_compilebuffer(vm, dummy_script_info, scstrlen(dummy_script_info), _SC("dummy"), SQTrue))) {
sq_push(vm, -2);
if (SQ_SUCCEEDED(sq_call(vm, 1, SQFalse, SQTrue))) {
sq_pop(vm, 1);
return;
}
}
NOT_REACHED();
}
void AI_CreateAIDummy(HSQUIRRELVM vm)
{
sq_pushroottable(vm);
/* Load and run the script */
if (SQ_SUCCEEDED(sq_compilebuffer(vm, dummy_script, scstrlen(dummy_script), _SC("dummy"), SQTrue))) {
sq_push(vm, -2);
if (SQ_SUCCEEDED(sq_call(vm, 1, SQFalse, SQTrue))) {
sq_pop(vm, 1);
return;
}
}
NOT_REACHED();
}
| 3,264
|
C++
|
.cpp
| 59
| 51.355932
| 112
| 0.439475
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,263
|
ai_gui.cpp
|
EnergeticBark_OpenTTD-3DS/src/ai/ai_gui.cpp
|
/* $Id$ */
/** @file ai_gui.cpp Window for configuring the AIs */
#include "../stdafx.h"
#include "../gui.h"
#include "../window_gui.h"
#include "../company_func.h"
#include "../company_base.h"
#include "../company_gui.h"
#include "../strings_func.h"
#include "../window_func.h"
#include "../gfx_func.h"
#include "../command_func.h"
#include "../network/network.h"
#include "../string_func.h"
#include "../textbuf_gui.h"
#include "../settings_type.h"
#include "../settings_func.h"
#include "../network/network_content.h"
#include "ai.hpp"
#include "api/ai_log.hpp"
#include "ai_config.hpp"
#include "table/strings.h"
/**
* Window that let you choose an available AI.
*/
struct AIListWindow : public Window {
/** Enum referring to the widgets of the AI list window */
enum AIListWindowWidgets {
AIL_WIDGET_CLOSEBOX = 0, ///< Close window button
AIL_WIDGET_CAPTION, ///< Window caption
AIL_WIDGET_LIST, ///< The matrix with all available AIs
AIL_WIDGET_SCROLLBAR, ///< Scrollbar next to the AI list
AIL_WIDGET_INFO_BG, ///< Panel to draw some AI information on
AIL_WIDGET_ACCEPT, ///< Accept button
AIL_WIDGET_CANCEL, ///< Cancel button
AIL_WIDGET_CONTENT_DOWNLOAD, ///< Download content button
AIL_WIDGET_RESIZE, ///< Resize button
};
const AIInfoList *ai_info_list;
int selected;
CompanyID slot;
AIListWindow(const WindowDesc *desc, CompanyID slot) : Window(desc, 0),
slot(slot)
{
this->ai_info_list = AI::GetUniqueInfoList();
this->resize.step_height = 14;
this->vscroll.cap = (this->widget[AIL_WIDGET_LIST].bottom - this->widget[AIL_WIDGET_LIST].top) / 14 + 1;
this->widget[AIL_WIDGET_LIST].data = (this->vscroll.cap << 8) + 1;
SetVScrollCount(this, (int)this->ai_info_list->size() + 1);
/* Try if we can find the currently selected AI */
this->selected = -1;
if (AIConfig::GetConfig(slot)->HasAI()) {
AIInfo *info = AIConfig::GetConfig(slot)->GetInfo();
int i = 0;
for (AIInfoList::const_iterator it = this->ai_info_list->begin(); it != this->ai_info_list->end(); it++, i++) {
if ((*it).second == info) {
this->selected = i;
break;
}
}
}
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
this->DrawWidgets();
/* Draw a list of all available AIs. */
int y = this->widget[AIL_WIDGET_LIST].top;
/* First AI in the list is hardcoded to random */
if (this->vscroll.pos == 0) {
DrawStringTruncated(4, y + 3, STR_AI_RANDOM_AI, this->selected == -1 ? TC_WHITE : TC_BLACK, this->width - 8);
y += 14;
}
AIInfo *selected_info = NULL;
AIInfoList::const_iterator it = this->ai_info_list->begin();
for (int i = 1; it != this->ai_info_list->end(); i++, it++) {
if (this->selected == i - 1) selected_info = (*it).second;
if (IsInsideBS(i, this->vscroll.pos, this->vscroll.cap)) {
DoDrawStringTruncated((*it).second->GetName(), 4, y + 3, (this->selected == i - 1) ? TC_WHITE : TC_BLACK, this->width - 8);
y += 14;
}
}
/* Some info about the currently selected AI. */
if (selected_info != NULL) {
int y = this->widget[AIL_WIDGET_INFO_BG].top + 6;
int x = DrawString(4, y, STR_AI_AUTHOR, TC_BLACK);
DoDrawStringTruncated(selected_info->GetAuthor(), x + 5, y, TC_BLACK, this->width - x - 8);
y += 13;
x = DrawString(4, y, STR_AI_VERSION, TC_BLACK);
static char buf[8];
sprintf(buf, "%d", selected_info->GetVersion());
DoDrawStringTruncated(buf, x + 5, y, TC_BLACK, this->width - x - 8);
y += 13;
SetDParamStr(0, selected_info->GetDescription());
DrawStringMultiLine(4, y, STR_JUST_RAW_STRING, this->width - 8, this->widget[AIL_WIDGET_INFO_BG].bottom - y);
}
}
void ChangeAI()
{
if (this->selected == -1) {
AIConfig::GetConfig(slot)->ChangeAI(NULL);
} else {
AIInfoList::const_iterator it = this->ai_info_list->begin();
for (int i = 0; i < this->selected; i++) it++;
AIConfig::GetConfig(slot)->ChangeAI((*it).second->GetName(), (*it).second->GetVersion());
}
InvalidateWindow(WC_GAME_OPTIONS, 0);
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case AIL_WIDGET_LIST: { // Select one of the AIs
int sel = (pt.y - this->widget[AIL_WIDGET_LIST].top) / 14 + this->vscroll.pos - 1;
if (sel < (int)this->ai_info_list->size()) {
this->selected = sel;
this->SetDirty();
}
break;
}
case AIL_WIDGET_ACCEPT: {
this->ChangeAI();
delete this;
break;
}
case AIL_WIDGET_CANCEL:
delete this;
break;
case AIL_WIDGET_CONTENT_DOWNLOAD:
if (!_network_available) {
ShowErrorMessage(INVALID_STRING_ID, STR_NETWORK_ERR_NOTAVAILABLE, 0, 0);
} else {
#if defined(ENABLE_NETWORK)
ShowNetworkContentListWindow(NULL, CONTENT_TYPE_AI);
#endif
}
break;
}
}
virtual void OnDoubleClick(Point pt, int widget)
{
switch (widget) {
case AIL_WIDGET_LIST: {
int sel = (pt.y - this->widget[AIL_WIDGET_LIST].top) / 14 + this->vscroll.pos - 1;
if (sel < (int)this->ai_info_list->size()) {
this->selected = sel;
this->ChangeAI();
delete this;
}
break;
}
}
}
virtual void OnResize(Point new_size, Point delta)
{
if (delta.x != 0) {
ResizeButtons(this, AIL_WIDGET_ACCEPT, AIL_WIDGET_CANCEL);
}
this->vscroll.cap += delta.y / 14;
this->widget[AIL_WIDGET_LIST].data = (this->vscroll.cap << 8) + 1;
}
};
/* Widget definition for the ai list window. */
static const Widget _ai_list_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_MAUVE, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // AIL_WIDGET_CLOSEBOX
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_MAUVE, 11, 199, 0, 13, STR_AI_LIST_CAPTION, STR_018C_WINDOW_TITLE_DRAG_THIS}, // AIL_WIDGET_CAPTION
{ WWT_MATRIX, RESIZE_RB, COLOUR_MAUVE, 0, 187, 14, 125, 0x501, STR_AI_AILIST_TIP}, // AIL_WIDGET_LIST
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_MAUVE, 188, 199, 14, 125, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST }, // AIL_WIDGET_SCROLLBAR
{ WWT_PANEL, RESIZE_RTB, COLOUR_MAUVE, 0, 199, 126, 209, 0x0, STR_NULL}, // AIL_WIDGET_INFO_BG
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_MAUVE, 0, 99, 210, 221, STR_AI_ACCEPT, STR_AI_ACCEPT_TIP}, // AIL_WIDGET_ACCEPT
{ WWT_PUSHTXTBTN, RESIZE_RTB, COLOUR_MAUVE, 100, 199, 210, 221, STR_AI_CANCEL, STR_AI_CANCEL_TIP}, // AIL_WIDGET_CANCEL
{ WWT_PUSHTXTBTN, RESIZE_RTB, COLOUR_MAUVE, 0, 187, 222, 233, STR_CONTENT_INTRO_BUTTON, STR_CONTENT_INTRO_BUTTON_TIP}, // AIL_WIDGET_DOWNLOAD_CONTENT
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_MAUVE, 188, 199, 222, 233, STR_NULL, STR_RESIZE_BUTTON}, // AIL_WIDGET_RESIZE
{ WIDGETS_END},
};
/* Window definition for the ai list window. */
static const WindowDesc _ai_list_desc(
WDP_CENTER, WDP_CENTER, 200, 234, 200, 234,
WC_AI_LIST, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_RESIZABLE,
_ai_list_widgets
);
void ShowAIListWindow(CompanyID slot)
{
DeleteWindowByClass(WC_AI_LIST);
new AIListWindow(&_ai_list_desc, slot);
}
/**
* Window for settings the parameters of an AI.
*/
struct AISettingsWindow : public Window {
/** Enum referring to the widgets of the AI settings window */
enum AISettingsWindowWidgest {
AIS_WIDGET_CLOSEBOX = 0, ///< Close window button
AIS_WIDGET_CAPTION, ///< Window caption
AIS_WIDGET_BACKGROUND, ///< Panel to draw the settings on
AIS_WIDGET_SCROLLBAR, ///< Scrollbar to scroll through all settings
AIS_WIDGET_ACCEPT, ///< Accept button
AIS_WIDGET_RESET, ///< Reset button
AIS_WIDGET_RESIZE, ///< Resize button
};
CompanyID slot;
AIConfig *ai_config;
int clicked_button;
bool clicked_increase;
int timeout;
int clicked_row;
AISettingsWindow(const WindowDesc *desc, CompanyID slot) : Window(desc, 0),
slot(slot),
clicked_button(-1),
timeout(0)
{
this->FindWindowPlacementAndResize(desc);
this->ai_config = AIConfig::GetConfig(slot);
this->resize.step_height = 14;
this->vscroll.cap = (this->widget[AIS_WIDGET_BACKGROUND].bottom - this->widget[AIS_WIDGET_BACKGROUND].top) / 14 + 1;
this->widget[AIS_WIDGET_BACKGROUND].data = (this->vscroll.cap << 8) + 1;
SetVScrollCount(this, (int)this->ai_config->GetConfigList()->size());
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
this->DrawWidgets();
AIConfig *config = this->ai_config;
AIConfigItemList::const_iterator it = config->GetConfigList()->begin();
int i = 0;
for (; i < this->vscroll.pos; i++) it++;
int y = this->widget[AIS_WIDGET_BACKGROUND].top;
for (; i < this->vscroll.pos + this->vscroll.cap && it != config->GetConfigList()->end(); i++, it++) {
int current_value = config->GetSetting((*it).name);
int x = 0;
if (((*it).flags & AICONFIG_BOOLEAN) != 0) {
DrawFrameRect(4, y + 2, 23, y + 10, (current_value != 0) ? COLOUR_GREEN : COLOUR_RED, (current_value != 0) ? FR_LOWERED : FR_NONE);
} else {
DrawArrowButtons(4, y + 2, COLOUR_YELLOW, (this->clicked_button == i) ? 1 + !!this->clicked_increase : 0, current_value > (*it).min_value, current_value < (*it).max_value);
if (it->labels != NULL && it->labels->Find(current_value) != it->labels->End()) {
x = DoDrawStringTruncated(it->labels->Find(current_value)->second, 28, y + 3, TC_ORANGE, this->width - 32);
} else {
SetDParam(0, current_value);
x = DrawStringTruncated(28, y + 3, STR_JUST_INT, TC_ORANGE, this->width - 32);
}
}
DoDrawStringTruncated((*it).description, max(x + 3, 54), y + 3, TC_LIGHT_BLUE, this->width - (4 + max(x + 3, 54)));
y += 14;
}
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case AIS_WIDGET_BACKGROUND: {
int num = (pt.y - this->widget[AIS_WIDGET_BACKGROUND].top) / 14 + this->vscroll.pos;
if (num >= (int)this->ai_config->GetConfigList()->size()) break;
AIConfigItemList::const_iterator it = this->ai_config->GetConfigList()->begin();
for (int i = 0; i < num; i++) it++;
AIConfigItem config_item = *it;
bool bool_item = (config_item.flags & AICONFIG_BOOLEAN) != 0;
const int x = pt.x - 4;
/* One of the arrows is clicked (or green/red rect in case of bool value) */
if (IsInsideMM(x, 0, 21)) {
int new_val = this->ai_config->GetSetting(config_item.name);
if (bool_item) {
new_val = !new_val;
} else if (x >= 10) {
/* Increase button clicked */
new_val += config_item.step_size;
if (new_val > config_item.max_value) new_val = config_item.max_value;
this->clicked_increase = true;
} else {
/* Decrease button clicked */
new_val -= config_item.step_size;
if (new_val < config_item.min_value) new_val = config_item.min_value;
this->clicked_increase = false;
}
this->ai_config->SetSetting(config_item.name, new_val);
this->clicked_button = num;
this->timeout = 5;
if (_settings_newgame.difficulty.diff_level != 3) {
_settings_newgame.difficulty.diff_level = 3;
ShowErrorMessage(INVALID_STRING_ID, STR_DIFFICULTY_TO_CUSTOM, 0, 0);
}
} else if (!bool_item) {
/* Display a query box so users can enter a custom value. */
this->clicked_row = num;
SetDParam(0, this->ai_config->GetSetting(config_item.name));
ShowQueryString(STR_CONFIG_SETTING_INT32, STR_CONFIG_SETTING_QUERY_CAPT, 10, 100, this, CS_NUMERAL, QSF_NONE);
}
this->SetDirty();
break;
}
case AIS_WIDGET_ACCEPT:
delete this;
break;
case AIS_WIDGET_RESET:
this->ai_config->ResetSettings();
this->SetDirty();
break;
}
}
virtual void OnQueryTextFinished(char *str)
{
if (StrEmpty(str)) return;
AIConfigItemList::const_iterator it = this->ai_config->GetConfigList()->begin();
for (int i = 0; i < this->clicked_row; i++) it++;
int32 value = atoi(str);
this->ai_config->SetSetting((*it).name, value);
this->SetDirty();
}
virtual void OnResize(Point new_size, Point delta)
{
if (delta.x != 0) {
ResizeButtons(this, AIS_WIDGET_ACCEPT, AIS_WIDGET_RESET);
}
this->vscroll.cap += delta.y / 14;
this->widget[AIS_WIDGET_BACKGROUND].data = (this->vscroll.cap << 8) + 1;
}
virtual void OnTick()
{
if (--this->timeout == 0) {
this->clicked_button = -1;
this->SetDirty();
}
}
};
/* Widget definition for the AI settings window. */
static const Widget _ai_settings_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_MAUVE, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // AIS_WIDGET_CLOSEBOX
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_MAUVE, 11, 199, 0, 13, STR_AI_SETTINGS_CAPTION, STR_018C_WINDOW_TITLE_DRAG_THIS}, // AIS_WIDGET_CAPTION
{ WWT_MATRIX, RESIZE_RB, COLOUR_MAUVE, 0, 187, 14, 195, 0x501, STR_NULL}, // AIS_WIDGET_BACKGROUND
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_MAUVE, 188, 199, 14, 195, 0x0, STR_0190_SCROLL_BAR_SCROLLS_LIST }, // AIS_WIDGET_SCROLLBAR
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_MAUVE, 0, 93, 196, 207, STR_AI_CLOSE, STR_NULL}, // AIS_WIDGET_ACCEPT
{ WWT_PUSHTXTBTN, RESIZE_RTB, COLOUR_MAUVE, 94, 187, 196, 207, STR_AI_RESET, STR_NULL}, // AIS_WIDGET_RESET
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_MAUVE, 188, 199, 196, 207, STR_NULL, STR_RESIZE_BUTTON}, // AIS_WIDGET_RESIZE
{ WIDGETS_END},
};
/* Window definition for the AI settings window. */
static const WindowDesc _ai_settings_desc(
WDP_CENTER, WDP_CENTER, 200, 208, 500, 208,
WC_AI_SETTINGS, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS | WDF_RESIZABLE,
_ai_settings_widgets
);
void ShowAISettingsWindow(CompanyID slot)
{
DeleteWindowByClass(WC_AI_LIST);
DeleteWindowByClass(WC_AI_SETTINGS);
new AISettingsWindow(&_ai_settings_desc, slot);
}
/* Widget definition for the configure AI window. */
static const Widget _ai_config_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_MAUVE, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // AIC_WIDGET_CLOSEBOX
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_MAUVE, 11, 299, 0, 13, STR_AI_CONFIG_CAPTION, STR_018C_WINDOW_TITLE_DRAG_THIS}, // AIC_WIDGET_CAPTION
{ WWT_PANEL, RESIZE_RB, COLOUR_MAUVE, 0, 299, 14, 171, 0x0, STR_NULL}, // AIC_WIDGET_BACKGROUND
{ WWT_MATRIX, RESIZE_RB, COLOUR_MAUVE, 0, 287, 30, 141, 0x501, STR_AI_LIST_TIP}, // AIC_WIDGET_LIST
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_MAUVE, 288, 299, 30, 141, STR_NULL, STR_0190_SCROLL_BAR_SCROLLS_LIST}, // AIC_WIDGET_SCROLLBAR
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_YELLOW, 10, 102, 151, 162, STR_AI_CHANGE, STR_AI_CHANGE_TIP}, // AIC_WIDGET_CHANGE
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_YELLOW, 103, 195, 151, 162, STR_AI_CONFIGURE, STR_AI_CONFIGURE_TIP}, // AIC_WIDGET_CONFIGURE
{ WWT_PUSHTXTBTN, RESIZE_TB, COLOUR_YELLOW, 196, 289, 151, 162, STR_AI_CLOSE, STR_NULL}, // AIC_WIDGET_CLOSE
{ WIDGETS_END},
};
/* Window definition for the configure AI window. */
static const WindowDesc _ai_config_desc(
WDP_CENTER, WDP_CENTER, 300, 172, 300, 172,
WC_GAME_OPTIONS, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_UNCLICK_BUTTONS,
_ai_config_widgets
);
/**
* Window to configure which AIs will start.
*/
struct AIConfigWindow : public Window {
/** Enum referring to the widgets of the AI config window */
enum AIConfigWindowWidgets {
AIC_WIDGET_CLOSEBOX = 0, ///< Close window button
AIC_WIDGET_CAPTION, ///< Window caption
AIC_WIDGET_BACKGROUND, ///< Window background
AIC_WIDGET_LIST, ///< List with currently selected AIs
AIC_WIDGET_SCROLLBAR, ///< Scrollbar to scroll through the selected AIs
AIC_WIDGET_CHANGE, ///< Select another AI button
AIC_WIDGET_CONFIGURE, ///< Change AI settings button
AIC_WIDGET_CLOSE, ///< Close window button
AIC_WIDGET_RESIZE, ///< Resize button
};
CompanyID selected_slot;
bool clicked_button;
bool clicked_increase;
int timeout;
AIConfigWindow() : Window(&_ai_config_desc),
clicked_button(false),
timeout(0)
{
selected_slot = INVALID_COMPANY;
this->resize.step_height = 14;
this->vscroll.cap = (this->widget[AIC_WIDGET_LIST].bottom - this->widget[AIC_WIDGET_LIST].top) / 14 + 1;
this->widget[AIC_WIDGET_LIST].data = (this->vscroll.cap << 8) + 1;
SetVScrollCount(this, MAX_COMPANIES);
this->FindWindowPlacementAndResize(&_ai_config_desc);
}
~AIConfigWindow()
{
DeleteWindowByClass(WC_AI_LIST);
DeleteWindowByClass(WC_AI_SETTINGS);
}
virtual void OnPaint()
{
this->SetWidgetDisabledState(AIC_WIDGET_CHANGE, selected_slot == INVALID_COMPANY);
this->SetWidgetDisabledState(AIC_WIDGET_CONFIGURE, selected_slot == INVALID_COMPANY);
this->DrawWidgets();
byte max_competitors = _settings_newgame.difficulty.max_no_competitors;
DrawArrowButtons(10, 18, COLOUR_YELLOW, this->clicked_button ? 1 + !!this->clicked_increase : 0, max_competitors > 0, max_competitors < MAX_COMPANIES - 1);
SetDParam(0, _settings_newgame.difficulty.max_no_competitors);
DrawString(36, 18, STR_6805_MAXIMUM_NO_COMPETITORS, TC_FROMSTRING);
int y = this->widget[AIC_WIDGET_LIST].top;
for (int i = this->vscroll.pos; i < this->vscroll.pos + this->vscroll.cap && i < MAX_COMPANIES; i++) {
StringID text;
if (AIConfig::GetConfig((CompanyID)i)->GetInfo() != NULL) {
SetDParamStr(0, AIConfig::GetConfig((CompanyID)i)->GetInfo()->GetName());
text = STR_JUST_RAW_STRING;
} else if (i == 0) {
text = STR_AI_HUMAN_PLAYER;
} else {
text = STR_AI_RANDOM_AI;
}
DrawStringTruncated(10, y + 3, text, (this->selected_slot == i) ? TC_WHITE : ((i > _settings_newgame.difficulty.max_no_competitors || i == 0) ? TC_SILVER : TC_ORANGE), this->width - 20);
y += 14;
}
}
virtual void OnClick(Point pt, int widget)
{
switch (widget) {
case AIC_WIDGET_BACKGROUND: {
/* Check if the user clicked on one of the arrows to configure the number of AIs */
if (IsInsideBS(pt.x, 10, 20) && IsInsideBS(pt.y, 18, 10)) {
int new_value;
if (pt.x <= 20) {
new_value = max(0, _settings_newgame.difficulty.max_no_competitors - 1);
} else {
new_value = min(MAX_COMPANIES - 1, _settings_newgame.difficulty.max_no_competitors + 1);
}
IConsoleSetSetting("difficulty.max_no_competitors", new_value);
this->SetDirty();
}
break;
}
case AIC_WIDGET_LIST: { // Select a slot
uint slot = (pt.y - this->widget[AIC_WIDGET_LIST].top) / 14 + this->vscroll.pos;
if (slot == 0 || slot > _settings_newgame.difficulty.max_no_competitors) slot = INVALID_COMPANY;
this->selected_slot = (CompanyID)slot;
this->SetDirty();
break;
}
case AIC_WIDGET_CHANGE: // choose other AI
ShowAIListWindow((CompanyID)this->selected_slot);
break;
case AIC_WIDGET_CONFIGURE: // change the settings for an AI
ShowAISettingsWindow((CompanyID)this->selected_slot);
break;
case AIC_WIDGET_CLOSE:
delete this;
break;
}
}
virtual void OnDoubleClick(Point pt, int widget)
{
switch (widget) {
case AIC_WIDGET_LIST:
this->OnClick(pt, widget);
if (this->selected_slot != INVALID_COMPANY) ShowAIListWindow((CompanyID)this->selected_slot);
break;
}
}
virtual void OnResize(Point new_size, Point delta)
{
this->vscroll.cap += delta.y / 14;
this->widget[AIC_WIDGET_LIST].data = (this->vscroll.cap << 8) + 1;
}
virtual void OnTick()
{
if (--this->timeout == 0) {
this->clicked_button = false;
this->SetDirty();
}
}
};
void ShowAIConfigWindow()
{
DeleteWindowById(WC_GAME_OPTIONS, 0);
new AIConfigWindow();
}
struct AIDebugWindow : public Window {
enum AIDebugWindowWidgets {
AID_WIDGET_CLOSEBOX = 0,
AID_WIDGET_CAPTION,
AID_WIDGET_VIEW,
AID_WIDGET_NAME_TEXT,
AID_WIDGET_RELOAD_TOGGLE,
AID_WIDGET_LOG_PANEL,
AID_WIDGET_SCROLLBAR,
AID_WIDGET_UNUSED_1,
AID_WIDGET_UNUSED_2,
AID_WIDGET_UNUSED_3,
AID_WIDGET_UNUSED_4,
AID_WIDGET_UNUSED_5,
AID_WIDGET_UNUSED_6,
AID_WIDGET_UNUSED_7,
AID_WIDGET_COMPANY_BUTTON_START,
AID_WIDGET_COMPANY_BUTTON_END = AID_WIDGET_COMPANY_BUTTON_START + 14,
};
static CompanyID ai_debug_company;
int redraw_timer;
AIDebugWindow(const WindowDesc *desc, WindowNumber number) : Window(desc, number)
{
/* Disable the companies who are not active or not an AI */
for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) {
this->SetWidgetDisabledState(i + AID_WIDGET_COMPANY_BUTTON_START, !IsValidCompanyID(i) || !GetCompany(i)->is_ai);
}
this->DisableWidget(AID_WIDGET_RELOAD_TOGGLE);
this->vscroll.cap = 14;
this->vscroll.pos = 0;
this->resize.step_height = 12;
if (ai_debug_company != INVALID_COMPANY) this->LowerWidget(ai_debug_company + AID_WIDGET_COMPANY_BUTTON_START);
this->FindWindowPlacementAndResize(desc);
}
virtual void OnPaint()
{
/* Check if the currently selected company is still active. */
if (ai_debug_company == INVALID_COMPANY || !IsValidCompanyID(ai_debug_company)) {
if (ai_debug_company != INVALID_COMPANY) {
/* Raise and disable the widget for the previous selection. */
this->RaiseWidget(ai_debug_company + AID_WIDGET_COMPANY_BUTTON_START);
this->DisableWidget(ai_debug_company + AID_WIDGET_COMPANY_BUTTON_START);
ai_debug_company = INVALID_COMPANY;
}
for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) {
if (IsValidCompanyID(i) && GetCompany(i)->is_ai) {
/* Lower the widget corresponding to this company. */
this->LowerWidget(i + AID_WIDGET_COMPANY_BUTTON_START);
ai_debug_company = i;
break;
}
}
}
/* Update "Reload AI" button */
this->SetWidgetDisabledState(AID_WIDGET_RELOAD_TOGGLE, ai_debug_company == INVALID_COMPANY);
/* Draw standard stuff */
this->DrawWidgets();
/* If there are no active companies, don't display anything else. */
if (ai_debug_company == INVALID_COMPANY) return;
/* Paint the company icons */
for (CompanyID i = COMPANY_FIRST; i < MAX_COMPANIES; i++) {
if (!IsValidCompanyID(i) || !GetCompany(i)->is_ai) {
/* Check if we have the company as an active company */
if (!this->IsWidgetDisabled(i + AID_WIDGET_COMPANY_BUTTON_START)) {
/* Bah, company gone :( */
this->DisableWidget(i + AID_WIDGET_COMPANY_BUTTON_START);
/* We need a repaint */
this->SetDirty();
}
continue;
}
/* Check if we have the company marked as inactive */
if (this->IsWidgetDisabled(i + AID_WIDGET_COMPANY_BUTTON_START)) {
/* New AI! Yippie :p */
this->EnableWidget(i + AID_WIDGET_COMPANY_BUTTON_START);
/* We need a repaint */
this->SetDirty();
}
byte x = (i == ai_debug_company) ? 1 : 0;
DrawCompanyIcon(i, (i % 8) * 37 + 13 + x, (i < 8 ? 0 : 13) + 16 + x);
}
/* Draw the AI name */
AIInfo *info = GetCompany(ai_debug_company)->ai_info;
assert(info != NULL);
char name[1024];
snprintf(name, sizeof(name), "%s (v%d)", info->GetName(), info->GetVersion());
DoDrawString(name, 7, 47, TC_BLACK);
CompanyID old_company = _current_company;
_current_company = ai_debug_company;
AILog::LogData *log = (AILog::LogData *)AIObject::GetLogPointer();
_current_company = old_company;
SetVScrollCount(this, (log == NULL) ? 0 : log->used);
this->InvalidateWidget(AID_WIDGET_SCROLLBAR);
if (log == NULL) return;
int y = 6;
for (int i = this->vscroll.pos; i < (this->vscroll.cap + this->vscroll.pos); i++) {
uint pos = (log->count + log->pos - i) % log->count;
if (log->lines[pos] == NULL) break;
TextColour colour;
switch (log->type[pos]) {
case AILog::LOG_SQ_INFO: colour = TC_BLACK; break;
case AILog::LOG_SQ_ERROR: colour = TC_RED; break;
case AILog::LOG_INFO: colour = TC_BLACK; break;
case AILog::LOG_WARNING: colour = TC_YELLOW; break;
case AILog::LOG_ERROR: colour = TC_RED; break;
default: colour = TC_BLACK; break;
}
DoDrawStringTruncated(log->lines[pos], 7, this->widget[AID_WIDGET_LOG_PANEL].top + y, colour, this->widget[AID_WIDGET_LOG_PANEL].right - this->widget[AID_WIDGET_LOG_PANEL].left - 14);
y += 12;
}
}
void ChangeToAI(CompanyID show_ai)
{
this->RaiseWidget(ai_debug_company + AID_WIDGET_COMPANY_BUTTON_START);
ai_debug_company = show_ai;
this->LowerWidget(ai_debug_company + AID_WIDGET_COMPANY_BUTTON_START);
this->SetDirty();
}
virtual void OnClick(Point pt, int widget)
{
/* Check which button is clicked */
if (IsInsideMM(widget, AID_WIDGET_COMPANY_BUTTON_START, AID_WIDGET_COMPANY_BUTTON_END + 1)) {
/* Is it no on disable? */
if (!this->IsWidgetDisabled(widget)) {
ChangeToAI((CompanyID)(widget - AID_WIDGET_COMPANY_BUTTON_START));
}
}
if (widget == AID_WIDGET_RELOAD_TOGGLE && !this->IsWidgetDisabled(widget)) {
/* First kill the company of the AI, then start a new one. This should start the current AI again */
DoCommandP(0, 2, ai_debug_company, CMD_COMPANY_CTRL);
DoCommandP(0, 1, 0, CMD_COMPANY_CTRL);
}
}
virtual void OnTimeout()
{
this->RaiseWidget(AID_WIDGET_RELOAD_TOGGLE);
this->SetDirty();
}
virtual void OnInvalidateData(int data = 0)
{
if (data == -1 || ai_debug_company == data) this->SetDirty();
}
virtual void OnResize(Point new_size, Point delta)
{
this->vscroll.cap += delta.y / (int)this->resize.step_height;
}
};
CompanyID AIDebugWindow::ai_debug_company = INVALID_COMPANY;
static const Widget _ai_debug_widgets[] = {
{ WWT_CLOSEBOX, RESIZE_NONE, COLOUR_GREY, 0, 10, 0, 13, STR_00C5, STR_018B_CLOSE_WINDOW}, // AID_WIDGET_CLOSEBOX
{ WWT_CAPTION, RESIZE_RIGHT, COLOUR_GREY, 11, 298, 0, 13, STR_AI_DEBUG, STR_018C_WINDOW_TITLE_DRAG_THIS}, // AID_WIDGET_CAPTION
{ WWT_PANEL, RESIZE_RIGHT, COLOUR_GREY, 0, 298, 14, 40, 0x0, STR_NULL}, // AID_WIDGET_VIEW
{ WWT_PANEL, RESIZE_RIGHT, COLOUR_GREY, 0, 149, 41, 60, 0x0, STR_AI_DEBUG_NAME_TIP}, // AID_WIDGET_NAME_TEXT
{ WWT_PUSHTXTBTN, RESIZE_LR, COLOUR_GREY, 150, 298, 41, 60, STR_AI_DEBUG_RELOAD, STR_AI_DEBUG_RELOAD_TIP}, // AID_WIDGET_RELOAD_TOGGLE
{ WWT_PANEL, RESIZE_RB, COLOUR_GREY, 0, 286, 61, 240, 0x0, STR_NULL}, // AID_WIDGET_LOG_PANEL
{ WWT_SCROLLBAR, RESIZE_LRB, COLOUR_GREY, 287, 298, 61, 228, STR_NULL, STR_0190_SCROLL_BAR_SCROLLS_LIST}, // AID_WIDGET_SCROLLBAR
/* As this is WIP, leave the next few so we can work a bit with the GUI */
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 298, 101, 120, 0x0, STR_NULL}, // AID_WIDGET_UNUSED_1
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 298, 121, 140, 0x0, STR_NULL}, // AID_WIDGET_UNUSED_2
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 298, 141, 160, 0x0, STR_NULL}, // AID_WIDGET_UNUSED_3
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 298, 161, 180, 0x0, STR_NULL}, // AID_WIDGET_UNUSED_4
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 298, 181, 200, 0x0, STR_NULL}, // AID_WIDGET_UNUSED_5
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 298, 201, 220, 0x0, STR_NULL}, // AID_WIDGET_UNUSED_6
{ WWT_EMPTY, RESIZE_NONE, COLOUR_GREY, 0, 298, 221, 240, 0x0, STR_NULL}, // AID_WIDGET_UNUSED_7
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 2, 38, 14, 26, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY}, // AID_WIDGET_COMPANY_BUTTON_START
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 39, 75, 14, 26, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 76, 112, 14, 26, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 113, 149, 14, 26, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 150, 186, 14, 26, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 187, 223, 14, 26, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 224, 260, 14, 26, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 261, 297, 14, 26, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 2, 38, 27, 39, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 39, 75, 27, 39, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 76, 112, 27, 39, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 113, 149, 27, 39, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 150, 186, 27, 39, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 187, 223, 27, 39, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY},
{ WWT_PANEL, RESIZE_NONE, COLOUR_GREY, 224, 260, 27, 39, 0x0, STR_704F_CLICK_HERE_TO_TOGGLE_COMPANY}, // AID_WIDGET_COMPANY_BUTTON_END
{ WWT_RESIZEBOX, RESIZE_LRTB, COLOUR_GREY, 287, 298, 229, 240, STR_NULL, STR_RESIZE_BUTTON},
{ WIDGETS_END},
};
static const WindowDesc _ai_debug_desc(
WDP_AUTO, WDP_AUTO, 299, 241, 299, 241,
WC_AI_DEBUG, WC_NONE,
WDF_STD_TOOLTIPS | WDF_STD_BTN | WDF_DEF_WIDGET | WDF_RESIZABLE,
_ai_debug_widgets
);
void ShowAIDebugWindow(CompanyID show_company)
{
if (!_networking || _network_server) {
AIDebugWindow *w = (AIDebugWindow *)BringWindowToFrontById(WC_AI_DEBUG, 0);
if (w == NULL) w = new AIDebugWindow(&_ai_debug_desc, 0);
if (show_company != INVALID_COMPANY) w->ChangeToAI(show_company);
} else {
ShowErrorMessage(INVALID_STRING_ID, STR_AI_DEBUG_SERVER_ONLY, 0, 0);
}
}
| 31,403
|
C++
|
.cpp
| 685
| 42.635036
| 189
| 0.624575
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,264
|
ai_core.cpp
|
EnergeticBark_OpenTTD-3DS/src/ai/ai_core.cpp
|
/* $Id$ */
/** @file ai_core.cpp Implementation of AI. */
#include "../stdafx.h"
#include "../core/bitmath_func.hpp"
#include "../company_base.h"
#include "../company_func.h"
#include "../debug.h"
#include "../network/network.h"
#include "../settings_type.h"
#include "../window_func.h"
#include "../command_func.h"
#include "ai.hpp"
#include "ai_scanner.hpp"
#include "ai_instance.hpp"
#include "ai_config.hpp"
/* static */ uint AI::frame_counter = 0;
/* static */ AIScanner *AI::ai_scanner = NULL;
/* static */ bool AI::CanStartNew()
{
/* Only allow new AIs on the server and only when that is allowed in multiplayer */
return !_networking || (_network_server && _settings_game.ai.ai_in_multiplayer);
}
/* static */ void AI::StartNew(CompanyID company)
{
assert(IsValidCompanyID(company));
/* Clients shouldn't start AIs */
if (_networking && !_network_server) return;
AIInfo *info = AIConfig::GetConfig(company)->GetInfo();
if (info == NULL) {
info = AI::ai_scanner->SelectRandomAI();
assert(info != NULL);
/* Load default data and store the name in the settings */
AIConfig::GetConfig(company)->ChangeAI(info->GetName());
}
_current_company = company;
Company *c = GetCompany(company);
c->ai_info = info;
assert(c->ai_instance == NULL);
c->ai_instance = new AIInstance(info);
InvalidateWindowData(WC_AI_DEBUG, 0, -1);
return;
}
/* static */ void AI::GameLoop()
{
/* If we are in networking, only servers run this function, and that only if it is allowed */
if (_networking && (!_network_server || !_settings_game.ai.ai_in_multiplayer)) return;
/* The speed with which AIs go, is limited by the 'competitor_speed' */
AI::frame_counter++;
assert(_settings_game.difficulty.competitor_speed <= 4);
if ((AI::frame_counter & ((1 << (4 - _settings_game.difficulty.competitor_speed)) - 1)) != 0) return;
const Company *c;
FOR_ALL_COMPANIES(c) {
if (!IsHumanCompany(c->index)) {
_current_company = c->index;
c->ai_instance->GameLoop();
}
}
/* Occasionally collect garbage; every 255 ticks do one company.
* Effectively collecting garbage once every two months per AI. */
if ((AI::frame_counter & 255) == 0) {
CompanyID cid = (CompanyID)GB(AI::frame_counter, 8, 4);
if (IsValidCompanyID(cid) && !IsHumanCompany(cid)) GetCompany(cid)->ai_instance->CollectGarbage();
}
_current_company = OWNER_NONE;
}
/* static */ uint AI::GetTick()
{
return AI::frame_counter;
}
/* static */ void AI::Stop(CompanyID company)
{
if (_networking && !_network_server) return;
CompanyID old_company = _current_company;
_current_company = company;
Company *c = GetCompany(company);
delete c->ai_instance;
c->ai_instance = NULL;
_current_company = old_company;
InvalidateWindowData(WC_AI_DEBUG, 0, -1);
}
/* static */ void AI::KillAll()
{
/* It might happen there are no companies .. than we have nothing to loop */
if (GetCompanyPoolSize() == 0) return;
const Company *c;
FOR_ALL_COMPANIES(c) {
if (!IsHumanCompany(c->index)) AI::Stop(c->index);
}
}
/* static */ void AI::Initialize()
{
if (AI::ai_scanner != NULL) AI::Uninitialize(true);
AI::frame_counter = 0;
if (AI::ai_scanner == NULL) AI::ai_scanner = new AIScanner();
}
/* static */ void AI::Uninitialize(bool keepConfig)
{
AI::KillAll();
if (keepConfig) {
/* Run a rescan, which indexes all AIInfos again, and check if we can
* still load all the AIS, while keeping the configs in place */
Rescan();
} else {
delete AI::ai_scanner;
AI::ai_scanner = NULL;
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
if (_settings_game.ai_config[c] != NULL) {
delete _settings_game.ai_config[c];
_settings_game.ai_config[c] = NULL;
}
if (_settings_newgame.ai_config[c] != NULL) {
delete _settings_newgame.ai_config[c];
_settings_newgame.ai_config[c] = NULL;
}
}
}
}
/* static */ void AI::ResetConfig()
{
/* Check for both newgame as current game if we can reload the AIInfo insde
* the AIConfig. If not, remove the AI from the list (which will assign
* a random new AI on reload). */
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
if (_settings_game.ai_config[c] != NULL && _settings_game.ai_config[c]->HasAI()) {
if (!_settings_game.ai_config[c]->ResetInfo()) {
DEBUG(ai, 0, "After a reload, the AI by the name '%s' was no longer found, and removed from the list.", _settings_game.ai_config[c]->GetName());
_settings_game.ai_config[c]->ChangeAI(NULL);
}
}
if (_settings_newgame.ai_config[c] != NULL && _settings_newgame.ai_config[c]->HasAI()) {
if (!_settings_newgame.ai_config[c]->ResetInfo()) {
DEBUG(ai, 0, "After a reload, the AI by the name '%s' was no longer found, and removed from the list.", _settings_newgame.ai_config[c]->GetName());
_settings_newgame.ai_config[c]->ChangeAI(NULL);
}
}
}
}
/* static */ void AI::NewEvent(CompanyID company, AIEvent *event)
{
/* AddRef() and Release() need to be called at least once, so do it here */
event->AddRef();
/* Clients should ignore events */
if (_networking && !_network_server) {
event->Release();
return;
}
/* Only AIs can have an event-queue */
if (!IsValidCompanyID(company) || IsHumanCompany(company)) {
event->Release();
return;
}
/* Queue the event */
CompanyID old_company = _current_company;
_current_company = company;
AIEventController::InsertEvent(event);
_current_company = old_company;
event->Release();
}
/* static */ void AI::BroadcastNewEvent(AIEvent *event, CompanyID skip_company)
{
/* AddRef() and Release() need to be called at least once, so do it here */
event->AddRef();
/* Clients should ignore events */
if (_networking && !_network_server) {
event->Release();
return;
}
/* Try to send the event to all AIs */
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
if (c != skip_company) AI::NewEvent(c, event);
}
event->Release();
}
void CcAI(bool success, TileIndex tile, uint32 p1, uint32 p2)
{
AIObject::SetLastCommandRes(success);
if (!success) {
AIObject::SetLastError(AIError::StringToError(_error_message));
} else {
AIObject::IncreaseDoCommandCosts(AIObject::GetLastCost());
}
GetCompany(_current_company)->ai_instance->Continue();
}
/* static */ void AI::Save(CompanyID company)
{
if (!_networking || _network_server) {
assert(IsValidCompanyID(company));
assert(GetCompany(company)->ai_instance != NULL);
CompanyID old_company = _current_company;
_current_company = company;
GetCompany(company)->ai_instance->Save();
_current_company = old_company;
} else {
AIInstance::SaveEmpty();
}
}
/* static */ void AI::Load(CompanyID company, int version)
{
if (!_networking || _network_server) {
assert(IsValidCompanyID(company));
assert(GetCompany(company)->ai_instance != NULL);
CompanyID old_company = _current_company;
_current_company = company;
GetCompany(company)->ai_instance->Load(version);
_current_company = old_company;
} else {
/* Read, but ignore, the load data */
AIInstance::LoadEmpty();
}
}
/* static */ int AI::GetStartNextTime()
{
/* Find the first company which doesn't exist yet */
for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
if (!IsValidCompanyID(c)) return AIConfig::GetConfig(c)->GetSetting("start_date");
}
/* Currently no AI can be started, check again in a year. */
return DAYS_IN_YEAR;
}
/* static */ char *AI::GetConsoleList(char *p, const char *last)
{
return AI::ai_scanner->GetAIConsoleList(p, last);
}
/* static */ const AIInfoList *AI::GetInfoList()
{
return AI::ai_scanner->GetAIInfoList();
}
/* static */ const AIInfoList *AI::GetUniqueInfoList()
{
return AI::ai_scanner->GetUniqueAIInfoList();
}
/* static */ AIInfo *AI::FindInfo(const char *name, int version)
{
return AI::ai_scanner->FindInfo(name, version);
}
/* static */ bool AI::ImportLibrary(const char *library, const char *class_name, int version, HSQUIRRELVM vm)
{
return AI::ai_scanner->ImportLibrary(library, class_name, version, vm, GetCompany(_current_company)->ai_instance->GetController());
}
/* static */ void AI::Rescan()
{
AI::ai_scanner->RescanAIDir();
ResetConfig();
}
| 8,133
|
C++
|
.cpp
| 244
| 31.061475
| 151
| 0.692573
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,265
|
ai_waypointlist.cpp
|
EnergeticBark_OpenTTD-3DS/src/ai/api/ai_waypointlist.cpp
|
/* $Id$ */
/** @file ai_waypointlist.cpp Implementation of AIWaypointList and friends. */
#include "ai_waypointlist.hpp"
#include "ai_vehicle.hpp"
#include "ai_waypoint.hpp"
#include "../../company_func.h"
#include "../../vehicle_base.h"
#include "../../waypoint.h"
AIWaypointList::AIWaypointList()
{
const Waypoint *wp;
FOR_ALL_WAYPOINTS(wp) {
if (wp->owner == _current_company) this->AddItem(wp->index);
}
}
AIWaypointList_Vehicle::AIWaypointList_Vehicle(VehicleID vehicle_id)
{
if (!AIVehicle::IsValidVehicle(vehicle_id)) return;
const Vehicle *v = ::GetVehicle(vehicle_id);
for (const Order *o = v->GetFirstOrder(); o != NULL; o = o->next) {
if (o->IsType(OT_GOTO_WAYPOINT)) this->AddItem(o->GetDestination());
}
}
| 736
|
C++
|
.cpp
| 23
| 30.26087
| 78
| 0.708628
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,266
|
ai_vehicle.cpp
|
EnergeticBark_OpenTTD-3DS/src/ai/api/ai_vehicle.cpp
|
/* $Id$ */
/** @file ai_vehicle.cpp Implementation of AIVehicle. */
#include "ai_engine.hpp"
#include "ai_cargo.hpp"
#include "ai_gamesettings.hpp"
#include "ai_group.hpp"
#include "../ai_instance.hpp"
#include "../../company_func.h"
#include "../../aircraft.h"
#include "../../string_func.h"
#include "../../strings_func.h"
#include "../../command_func.h"
#include "../../roadveh.h"
#include "../../train.h"
#include "../../vehicle_func.h"
#include "table/strings.h"
/* static */ bool AIVehicle::IsValidVehicle(VehicleID vehicle_id)
{
if (!::IsValidVehicleID(vehicle_id)) return false;
const Vehicle *v = ::GetVehicle(vehicle_id);
return v->owner == _current_company && (v->IsPrimaryVehicle() || (v->type == VEH_TRAIN && ::IsFreeWagon(v)));
}
/* static */ int32 AIVehicle::GetNumWagons(VehicleID vehicle_id)
{
if (!IsValidVehicle(vehicle_id)) return -1;
int num = 1;
if (::GetVehicle(vehicle_id)->type == VEH_TRAIN) {
const Vehicle *v = ::GetVehicle(vehicle_id);
while ((v = GetNextUnit(v)) != NULL) num++;
}
return num;
}
/* static */ int AIVehicle::GetLength(VehicleID vehicle_id)
{
if (!IsValidVehicle(vehicle_id)) return -1;
const Vehicle *v = ::GetVehicle(vehicle_id);
switch (v->type) {
case VEH_ROAD: {
uint total_length = 0;
for (const Vehicle *u = v; u != NULL; u = u->Next()) {
total_length += u->u.road.cached_veh_length;
}
return total_length;
}
case VEH_TRAIN: return v->u.rail.cached_total_length;
default: return -1;
}
}
/* static */ VehicleID AIVehicle::BuildVehicle(TileIndex depot, EngineID engine_id)
{
EnforcePrecondition(INVALID_VEHICLE, AIEngine::IsValidEngine(engine_id));
::VehicleType type = ::GetEngine(engine_id)->type;
EnforcePreconditionCustomError(INVALID_VEHICLE, !AIGameSettings::IsDisabledVehicleType((AIVehicle::VehicleType)type), AIVehicle::ERR_VEHICLE_BUILD_DISABLED);
if (!AIObject::DoCommand(depot, engine_id, 0, ::GetCmdBuildVeh(type), NULL, &AIInstance::DoCommandReturnVehicleID)) return INVALID_VEHICLE;
/* In case of test-mode, we return VehicleID 0 */
return 0;
}
/* static */ VehicleID AIVehicle::CloneVehicle(TileIndex depot, VehicleID vehicle_id, bool share_orders)
{
EnforcePrecondition(false, IsValidVehicle(vehicle_id));
if (!AIObject::DoCommand(depot, vehicle_id, share_orders, CMD_CLONE_VEHICLE, NULL, &AIInstance::DoCommandReturnVehicleID)) return INVALID_VEHICLE;
/* In case of test-mode, we return VehicleID 0 */
return 0;
}
/* static */ bool AIVehicle::_MoveWagonInternal(VehicleID source_vehicle_id, int source_wagon, bool move_attached_wagons, int dest_vehicle_id, int dest_wagon)
{
EnforcePrecondition(false, IsValidVehicle(source_vehicle_id) && source_wagon < GetNumWagons(source_vehicle_id));
EnforcePrecondition(false, dest_vehicle_id == -1 || (IsValidVehicle(dest_vehicle_id) && dest_wagon < GetNumWagons(dest_vehicle_id)));
EnforcePrecondition(false, ::GetVehicle(source_vehicle_id)->type == VEH_TRAIN);
EnforcePrecondition(false, dest_vehicle_id == -1 || ::GetVehicle(dest_vehicle_id)->type == VEH_TRAIN);
const Vehicle *v = ::GetVehicle(source_vehicle_id);
while (source_wagon-- > 0) v = GetNextUnit(v);
const Vehicle *w = NULL;
if (dest_vehicle_id != -1) {
w = ::GetVehicle(dest_vehicle_id);
while (dest_wagon-- > 0) w = GetNextUnit(w);
}
return AIObject::DoCommand(0, v->index | ((w == NULL ? INVALID_VEHICLE : w->index) << 16), move_attached_wagons ? 1 : 0, CMD_MOVE_RAIL_VEHICLE);
}
/* static */ bool AIVehicle::MoveWagon(VehicleID source_vehicle_id, int source_wagon, int dest_vehicle_id, int dest_wagon)
{
return _MoveWagonInternal(source_vehicle_id, source_wagon, false, dest_vehicle_id, dest_wagon);
}
/* static */ bool AIVehicle::MoveWagonChain(VehicleID source_vehicle_id, int source_wagon, int dest_vehicle_id, int dest_wagon)
{
return _MoveWagonInternal(source_vehicle_id, source_wagon, true, dest_vehicle_id, dest_wagon);
}
/* static */ int AIVehicle::GetRefitCapacity(VehicleID vehicle_id, CargoID cargo)
{
if (!IsValidVehicle(vehicle_id)) return -1;
if (!AICargo::IsValidCargo(cargo)) return -1;
CommandCost res = ::DoCommand(0, vehicle_id, cargo, DC_QUERY_COST, GetCmdRefitVeh(::GetVehicle(vehicle_id)));
return CmdSucceeded(res) ? _returned_refit_capacity : -1;
}
/* static */ bool AIVehicle::RefitVehicle(VehicleID vehicle_id, CargoID cargo)
{
EnforcePrecondition(false, IsValidVehicle(vehicle_id) && AICargo::IsValidCargo(cargo));
return AIObject::DoCommand(0, vehicle_id, cargo, GetCmdRefitVeh(::GetVehicle(vehicle_id)));
}
/* static */ bool AIVehicle::SellVehicle(VehicleID vehicle_id)
{
EnforcePrecondition(false, IsValidVehicle(vehicle_id));
const Vehicle *v = ::GetVehicle(vehicle_id);
return AIObject::DoCommand(0, vehicle_id, v->type == VEH_TRAIN ? 1 : 0, GetCmdSellVeh(v));
}
/* static */ bool AIVehicle::_SellWagonInternal(VehicleID vehicle_id, int wagon, bool sell_attached_wagons)
{
EnforcePrecondition(false, IsValidVehicle(vehicle_id) && wagon < GetNumWagons(vehicle_id));
EnforcePrecondition(false, ::GetVehicle(vehicle_id)->type == VEH_TRAIN);
const Vehicle *v = ::GetVehicle(vehicle_id);
while (wagon-- > 0) v = GetNextUnit(v);
return AIObject::DoCommand(0, v->index, sell_attached_wagons ? 1 : 0, CMD_SELL_RAIL_WAGON);
}
/* static */ bool AIVehicle::SellWagon(VehicleID vehicle_id, int wagon)
{
return _SellWagonInternal(vehicle_id, wagon, false);
}
/* static */ bool AIVehicle::SellWagonChain(VehicleID vehicle_id, int wagon)
{
return _SellWagonInternal(vehicle_id, wagon, true);
}
/* static */ bool AIVehicle::SendVehicleToDepot(VehicleID vehicle_id)
{
EnforcePrecondition(false, IsValidVehicle(vehicle_id));
return AIObject::DoCommand(0, vehicle_id, 0, GetCmdSendToDepot(::GetVehicle(vehicle_id)));
}
/* static */ bool AIVehicle::IsInDepot(VehicleID vehicle_id)
{
if (!IsValidVehicle(vehicle_id)) return false;
return ::GetVehicle(vehicle_id)->IsInDepot();
}
/* static */ bool AIVehicle::IsStoppedInDepot(VehicleID vehicle_id)
{
if (!IsValidVehicle(vehicle_id)) return false;
return ::GetVehicle(vehicle_id)->IsStoppedInDepot();
}
/* static */ bool AIVehicle::StartStopVehicle(VehicleID vehicle_id)
{
EnforcePrecondition(false, IsValidVehicle(vehicle_id));
return AIObject::DoCommand(0, vehicle_id, 0, CMD_START_STOP_VEHICLE);
}
/* static */ bool AIVehicle::SkipToVehicleOrder(VehicleID vehicle_id, AIOrder::OrderPosition order_position)
{
order_position = AIOrder::ResolveOrderPosition(vehicle_id, order_position);
EnforcePrecondition(false, AIOrder::IsValidVehicleOrder(vehicle_id, order_position));
return AIObject::DoCommand(0, vehicle_id, order_position, CMD_SKIP_TO_ORDER);
}
/* static */ bool AIVehicle::ReverseVehicle(VehicleID vehicle_id)
{
EnforcePrecondition(false, IsValidVehicle(vehicle_id));
EnforcePrecondition(false, ::GetVehicle(vehicle_id)->type == VEH_ROAD || ::GetVehicle(vehicle_id)->type == VEH_TRAIN);
switch (::GetVehicle(vehicle_id)->type) {
case VEH_ROAD: return AIObject::DoCommand(0, vehicle_id, 0, CMD_TURN_ROADVEH);
case VEH_TRAIN: return AIObject::DoCommand(0, vehicle_id, 0, CMD_REVERSE_TRAIN_DIRECTION);
default: NOT_REACHED();
}
}
/* static */ bool AIVehicle::SetName(VehicleID vehicle_id, const char *name)
{
EnforcePrecondition(false, IsValidVehicle(vehicle_id));
EnforcePrecondition(false, !::StrEmpty(name));
EnforcePreconditionCustomError(false, ::strlen(name) < MAX_LENGTH_VEHICLE_NAME_BYTES, AIError::ERR_PRECONDITION_STRING_TOO_LONG);
return AIObject::DoCommand(0, vehicle_id, 0, CMD_RENAME_VEHICLE, name);
}
/* static */ TileIndex AIVehicle::GetLocation(VehicleID vehicle_id)
{
if (!IsValidVehicle(vehicle_id)) return INVALID_TILE;
const Vehicle *v = ::GetVehicle(vehicle_id);
if (v->type == VEH_AIRCRAFT) {
uint x = Clamp(v->x_pos / TILE_SIZE, 0, ::MapSizeX() - 2);
uint y = Clamp(v->y_pos / TILE_SIZE, 0, ::MapSizeY() - 2);
return ::TileXY(x, y);
}
return v->tile;
}
/* static */ EngineID AIVehicle::GetEngineType(VehicleID vehicle_id)
{
if (!IsValidVehicle(vehicle_id)) return INVALID_ENGINE;
return ::GetVehicle(vehicle_id)->engine_type;
}
/* static */ EngineID AIVehicle::GetWagonEngineType(VehicleID vehicle_id, int wagon)
{
if (!IsValidVehicle(vehicle_id)) return INVALID_ENGINE;
if (wagon >= GetNumWagons(vehicle_id)) return INVALID_ENGINE;
const Vehicle *v = ::GetVehicle(vehicle_id);
if (v->type == VEH_TRAIN) {
while (wagon-- > 0) v = GetNextUnit(v);
}
return v->engine_type;
}
/* static */ int32 AIVehicle::GetUnitNumber(VehicleID vehicle_id)
{
if (!IsValidVehicle(vehicle_id)) return -1;
return ::GetVehicle(vehicle_id)->unitnumber;
}
/* static */ char *AIVehicle::GetName(VehicleID vehicle_id)
{
if (!IsValidVehicle(vehicle_id)) return NULL;
static const int len = 64;
char *vehicle_name = MallocT<char>(len);
::SetDParam(0, vehicle_id);
::GetString(vehicle_name, STR_VEHICLE_NAME, &vehicle_name[len - 1]);
return vehicle_name;
}
/* static */ int32 AIVehicle::GetAge(VehicleID vehicle_id)
{
if (!IsValidVehicle(vehicle_id)) return -1;
return ::GetVehicle(vehicle_id)->age;
}
/* static */ int32 AIVehicle::GetWagonAge(VehicleID vehicle_id, int wagon)
{
if (!IsValidVehicle(vehicle_id)) return -1;
if (wagon >= GetNumWagons(vehicle_id)) return -1;
const Vehicle *v = ::GetVehicle(vehicle_id);
if (v->type == VEH_TRAIN) {
while (wagon-- > 0) v = GetNextUnit(v);
}
return v->age;
}
/* static */ int32 AIVehicle::GetMaxAge(VehicleID vehicle_id)
{
if (!IsValidVehicle(vehicle_id)) return -1;
return ::GetVehicle(vehicle_id)->max_age;
}
/* static */ int32 AIVehicle::GetAgeLeft(VehicleID vehicle_id)
{
if (!IsValidVehicle(vehicle_id)) return -1;
return ::GetVehicle(vehicle_id)->max_age - ::GetVehicle(vehicle_id)->age;
}
/* static */ int32 AIVehicle::GetCurrentSpeed(VehicleID vehicle_id)
{
if (!IsValidVehicle(vehicle_id)) return -1;
return ::GetVehicle(vehicle_id)->GetDisplaySpeed(); // km-ish/h
}
/* static */ AIVehicle::VehicleState AIVehicle::GetState(VehicleID vehicle_id)
{
if (!IsValidVehicle(vehicle_id)) return AIVehicle::VS_INVALID;
const Vehicle *v = ::GetVehicle(vehicle_id);
byte vehstatus = v->vehstatus;
if (vehstatus & ::VS_CRASHED) return AIVehicle::VS_CRASHED;
if (v->breakdown_ctr != 0) return AIVehicle::VS_BROKEN;
if (v->IsStoppedInDepot()) return AIVehicle::VS_IN_DEPOT;
if (vehstatus & ::VS_STOPPED) return AIVehicle::VS_STOPPED;
if (v->current_order.IsType(OT_LOADING)) return AIVehicle::VS_AT_STATION;
return AIVehicle::VS_RUNNING;
}
/* static */ Money AIVehicle::GetRunningCost(VehicleID vehicle_id)
{
if (!IsValidVehicle(vehicle_id)) return -1;
return ::GetVehicle(vehicle_id)->GetRunningCost() >> 8;
}
/* static */ Money AIVehicle::GetProfitThisYear(VehicleID vehicle_id)
{
if (!IsValidVehicle(vehicle_id)) return -1;
return ::GetVehicle(vehicle_id)->GetDisplayProfitThisYear();
}
/* static */ Money AIVehicle::GetProfitLastYear(VehicleID vehicle_id)
{
if (!IsValidVehicle(vehicle_id)) return -1;
return ::GetVehicle(vehicle_id)->GetDisplayProfitLastYear();
}
/* static */ Money AIVehicle::GetCurrentValue(VehicleID vehicle_id)
{
if (!IsValidVehicle(vehicle_id)) return -1;
return ::GetVehicle(vehicle_id)->value;
}
/* static */ AIVehicle::VehicleType AIVehicle::GetVehicleType(VehicleID vehicle_id)
{
if (!IsValidVehicle(vehicle_id)) return VT_INVALID;
switch (::GetVehicle(vehicle_id)->type) {
case VEH_ROAD: return VT_ROAD;
case VEH_TRAIN: return VT_RAIL;
case VEH_SHIP: return VT_WATER;
case VEH_AIRCRAFT: return VT_AIR;
default: return VT_INVALID;
}
}
/* static */ AIRoad::RoadType AIVehicle::GetRoadType(VehicleID vehicle_id)
{
if (!IsValidVehicle(vehicle_id)) return AIRoad::ROADTYPE_INVALID;
if (GetVehicleType(vehicle_id) != VT_ROAD) return AIRoad::ROADTYPE_INVALID;
return (AIRoad::RoadType)::GetVehicle(vehicle_id)->u.road.roadtype;
}
/* static */ int32 AIVehicle::GetCapacity(VehicleID vehicle_id, CargoID cargo)
{
if (!IsValidVehicle(vehicle_id)) return -1;
if (!AICargo::IsValidCargo(cargo)) return -1;
uint32 amount = 0;
for (const Vehicle *v = ::GetVehicle(vehicle_id); v != NULL; v = v->Next()) {
if (v->cargo_type == cargo) amount += v->cargo_cap;
}
return amount;
}
/* static */ int32 AIVehicle::GetCargoLoad(VehicleID vehicle_id, CargoID cargo)
{
if (!IsValidVehicle(vehicle_id)) return -1;
if (!AICargo::IsValidCargo(cargo)) return -1;
uint32 amount = 0;
for (const Vehicle *v = ::GetVehicle(vehicle_id); v != NULL; v = v->Next()) {
if (v->cargo_type == cargo) amount += v->cargo.Count();
}
return amount;
}
/* static */ GroupID AIVehicle::GetGroupID(VehicleID vehicle_id)
{
if (!IsValidVehicle(vehicle_id)) return AIGroup::GROUP_INVALID;
return ::GetVehicle(vehicle_id)->group_id;
}
/* static */ bool AIVehicle::IsArticulated(VehicleID vehicle_id)
{
if (!IsValidVehicle(vehicle_id)) return false;
if (GetVehicleType(vehicle_id) != VT_ROAD && GetVehicleType(vehicle_id) != VT_RAIL) return false;
const Vehicle *v = ::GetVehicle(vehicle_id);
switch (v->type) {
case VEH_ROAD: return RoadVehHasArticPart(v);
case VEH_TRAIN: return EngineHasArticPart(v);
default: NOT_REACHED();
}
}
/* static */ bool AIVehicle::HasSharedOrders(VehicleID vehicle_id)
{
if (!IsValidVehicle(vehicle_id)) return false;
Vehicle *v = ::GetVehicle(vehicle_id);
return v->orders.list != NULL && v->orders.list->GetNumVehicles() > 1;
}
| 13,348
|
C++
|
.cpp
| 325
| 39.110769
| 158
| 0.73422
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,267
|
ai_cargolist.cpp
|
EnergeticBark_OpenTTD-3DS/src/ai/api/ai_cargolist.cpp
|
/* $Id$ */
/** @file ai_cargolist.cpp Implementation of AICargoList and friends. */
#include "ai_cargolist.hpp"
#include "ai_industry.hpp"
#include "../../cargotype.h"
#include "../../tile_type.h"
#include "../../industry.h"
AICargoList::AICargoList()
{
for (byte i = 0; i < NUM_CARGO; i++) {
const CargoSpec *c = ::GetCargo(i);
if (c->IsValid()) {
this->AddItem(i);
}
}
}
AICargoList_IndustryAccepting::AICargoList_IndustryAccepting(IndustryID industry_id)
{
if (!AIIndustry::IsValidIndustry(industry_id)) return;
Industry *ind = ::GetIndustry(industry_id);
for (uint i = 0; i < lengthof(ind->accepts_cargo); i++) {
CargoID cargo_id = ind->accepts_cargo[i];
if (cargo_id != CT_INVALID) {
this->AddItem(cargo_id);
}
}
}
AICargoList_IndustryProducing::AICargoList_IndustryProducing(IndustryID industry_id)
{
if (!AIIndustry::IsValidIndustry(industry_id)) return;
Industry *ind = ::GetIndustry(industry_id);
for (uint i = 0; i < lengthof(ind->produced_cargo); i++) {
CargoID cargo_id = ind->produced_cargo[i];
if (cargo_id != CT_INVALID) {
this->AddItem(cargo_id);
}
}
}
| 1,113
|
C++
|
.cpp
| 38
| 27.131579
| 84
| 0.691011
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,270
|
ai_object.cpp
|
EnergeticBark_OpenTTD-3DS/src/ai/api/ai_object.cpp
|
/* $Id$ */
/** @file ai_object.cpp Implementation of AIObject. */
#include "ai_log.hpp"
#include "table/strings.h"
#include "../ai.hpp"
#include "../ai_storage.hpp"
#include "../ai_instance.hpp"
static AIStorage *GetStorage()
{
return AIInstance::GetStorage();
}
void AIObject::SetDoCommandDelay(uint ticks)
{
assert(ticks > 0);
GetStorage()->delay = ticks;
}
uint AIObject::GetDoCommandDelay()
{
return GetStorage()->delay;
}
void AIObject::SetDoCommandMode(AIModeProc *proc, AIObject *instance)
{
GetStorage()->mode = proc;
GetStorage()->mode_instance = instance;
}
AIModeProc *AIObject::GetDoCommandMode()
{
return GetStorage()->mode;
}
AIObject *AIObject::GetDoCommandModeInstance()
{
return GetStorage()->mode_instance;
}
void AIObject::SetDoCommandCosts(Money value)
{
GetStorage()->costs = CommandCost(value);
}
void AIObject::IncreaseDoCommandCosts(Money value)
{
GetStorage()->costs.AddCost(value);
}
Money AIObject::GetDoCommandCosts()
{
return GetStorage()->costs.GetCost();
}
void AIObject::SetLastError(AIErrorType last_error)
{
GetStorage()->last_error = last_error;
}
AIErrorType AIObject::GetLastError()
{
return GetStorage()->last_error;
}
void AIObject::SetLastCost(Money last_cost)
{
GetStorage()->last_cost = last_cost;
}
Money AIObject::GetLastCost()
{
return GetStorage()->last_cost;
}
void AIObject::SetRoadType(RoadType road_type)
{
GetStorage()->road_type = road_type;
}
RoadType AIObject::GetRoadType()
{
return GetStorage()->road_type;
}
void AIObject::SetRailType(RailType rail_type)
{
GetStorage()->rail_type = rail_type;
}
RailType AIObject::GetRailType()
{
return GetStorage()->rail_type;
}
void AIObject::SetLastCommandRes(bool res)
{
GetStorage()->last_command_res = res;
/* Also store the results of various global variables */
SetNewVehicleID(_new_vehicle_id);
SetNewSignID(_new_sign_id);
SetNewTunnelEndtile(_build_tunnel_endtile);
SetNewGroupID(_new_group_id);
}
bool AIObject::GetLastCommandRes()
{
return GetStorage()->last_command_res;
}
void AIObject::SetNewVehicleID(VehicleID vehicle_id)
{
GetStorage()->new_vehicle_id = vehicle_id;
}
VehicleID AIObject::GetNewVehicleID()
{
return GetStorage()->new_vehicle_id;
}
void AIObject::SetNewSignID(SignID sign_id)
{
GetStorage()->new_sign_id = sign_id;
}
SignID AIObject::GetNewSignID()
{
return GetStorage()->new_sign_id;
}
void AIObject::SetNewTunnelEndtile(TileIndex tile)
{
GetStorage()->new_tunnel_endtile = tile;
}
TileIndex AIObject::GetNewTunnelEndtile()
{
return GetStorage()->new_tunnel_endtile;
}
void AIObject::SetNewGroupID(GroupID group_id)
{
GetStorage()->new_group_id = group_id;
}
GroupID AIObject::GetNewGroupID()
{
return GetStorage()->new_group_id;
}
void AIObject::SetAllowDoCommand(bool allow)
{
GetStorage()->allow_do_command = allow;
}
bool AIObject::GetAllowDoCommand()
{
return GetStorage()->allow_do_command;
}
void *&AIObject::GetEventPointer()
{
return GetStorage()->event_data;
}
void *&AIObject::GetLogPointer()
{
return GetStorage()->log_data;
}
void AIObject::SetCallbackVariable(int index, int value)
{
if ((size_t)index >= GetStorage()->callback_value.size()) GetStorage()->callback_value.resize(index + 1);
GetStorage()->callback_value[index] = value;
}
int AIObject::GetCallbackVariable(int index)
{
return GetStorage()->callback_value[index];
}
bool AIObject::DoCommand(TileIndex tile, uint32 p1, uint32 p2, uint cmd, const char *text, AISuspendCallbackProc *callback)
{
if (AIObject::GetAllowDoCommand() == false) {
AILog::Error("You are not allowed to execute any DoCommand (even indirect) in your constructor, Save(), Load(), and any valuator.\n");
return false;
}
CommandCost res;
/* Set the default callback to return a true/false result of the DoCommand */
if (callback == NULL) callback = &AIInstance::DoCommandReturn;
/* Make sure the last error is reset, so we don't give faulty warnings */
SetLastError(AIError::ERR_NONE);
/* First, do a test-run to see if we can do this */
res = ::DoCommand(tile, p1, p2, CommandFlagsToDCFlags(GetCommandFlags(cmd)), cmd, text);
/* The command failed, so return */
if (::CmdFailed(res)) {
SetLastError(AIError::StringToError(_error_message));
return false;
}
/* Check what the callback wants us to do */
if (GetDoCommandMode() != NULL && !GetDoCommandMode()(tile, p1, p2, cmd, res)) {
IncreaseDoCommandCosts(res.GetCost());
return true;
}
#ifdef ENABLE_NETWORK
/* Send the command */
if (_networking) {
/* NetworkSend_Command needs _local_company to be set correctly, so
* adjust it, and put it back right after the function */
CompanyID old_company = _local_company;
_local_company = _current_company;
::NetworkSend_Command(tile, p1, p2, cmd, CcAI, text);
_local_company = old_company;
SetLastCost(res.GetCost());
/* Suspend the AI till the command is really executed */
throw AI_VMSuspend(-(int)GetDoCommandDelay(), callback);
} else {
#else
{
#endif
/* For SinglePlayer we execute the command immediatly */
if (!::DoCommandP(tile, p1, p2, cmd, NULL, text)) res = CMD_ERROR;
SetLastCommandRes(!::CmdFailed(res));
if (::CmdFailed(res)) {
SetLastError(AIError::StringToError(_error_message));
return false;
}
SetLastCost(res.GetCost());
IncreaseDoCommandCosts(res.GetCost());
/* Suspend the AI player for 1+ ticks, so it simulates multiplayer. This
* both avoids confusion when a developer launched his AI in a
* multiplayer game, but also gives time for the GUI and human player
* to interact with the game. */
throw AI_VMSuspend(GetDoCommandDelay(), callback);
}
NOT_REACHED();
}
| 5,627
|
C++
|
.cpp
| 203
| 25.871921
| 136
| 0.748977
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,277
|
ai_subsidy.cpp
|
EnergeticBark_OpenTTD-3DS/src/ai/api/ai_subsidy.cpp
|
/* $Id$ */
/** @file ai_subsidy.cpp Implementation of AISubsidy. */
#include "ai_subsidy.hpp"
#include "ai_date.hpp"
#include "../../economy_func.h"
#include "../../station_base.h"
#include "../../cargotype.h"
/* static */ bool AISubsidy::IsValidSubsidy(SubsidyID subsidy_id)
{
return subsidy_id < lengthof(_subsidies) && _subsidies[subsidy_id].cargo_type != CT_INVALID;
}
/* static */ bool AISubsidy::IsAwarded(SubsidyID subsidy_id)
{
if (!IsValidSubsidy(subsidy_id)) return false;
return _subsidies[subsidy_id].age >= 12;
}
/* static */ AICompany::CompanyID AISubsidy::GetAwardedTo(SubsidyID subsidy_id)
{
if (!IsAwarded(subsidy_id)) return AICompany::COMPANY_INVALID;
return (AICompany::CompanyID)((byte)GetStation(_subsidies[subsidy_id].from)->owner);
}
/* static */ int32 AISubsidy::GetExpireDate(SubsidyID subsidy_id)
{
if (!IsValidSubsidy(subsidy_id)) return -1;
int year = AIDate::GetYear(AIDate::GetCurrentDate());
int month = AIDate::GetMonth(AIDate::GetCurrentDate());
if (IsAwarded(subsidy_id)) {
month += 24 - _subsidies[subsidy_id].age;
} else {
month += 12 - _subsidies[subsidy_id].age;
}
year += (month - 1) / 12;
month = ((month - 1) % 12) + 1;
return AIDate::GetDate(year, month, 1);
}
/* static */ CargoID AISubsidy::GetCargoType(SubsidyID subsidy_id)
{
if (!IsValidSubsidy(subsidy_id)) return CT_INVALID;
return _subsidies[subsidy_id].cargo_type;
}
/* static */ bool AISubsidy::SourceIsTown(SubsidyID subsidy_id)
{
if (!IsValidSubsidy(subsidy_id) || IsAwarded(subsidy_id)) return false;
return GetCargo(GetCargoType(subsidy_id))->town_effect == TE_PASSENGERS ||
GetCargo(GetCargoType(subsidy_id))->town_effect == TE_MAIL;
}
/* static */ int32 AISubsidy::GetSource(SubsidyID subsidy_id)
{
if (!IsValidSubsidy(subsidy_id)) return INVALID_STATION;
return _subsidies[subsidy_id].from;
}
/* static */ bool AISubsidy::DestinationIsTown(SubsidyID subsidy_id)
{
if (!IsValidSubsidy(subsidy_id) || IsAwarded(subsidy_id)) return false;
switch (GetCargo(GetCargoType(subsidy_id))->town_effect) {
case TE_PASSENGERS:
case TE_MAIL:
case TE_GOODS:
case TE_FOOD:
return true;
default:
return false;
}
}
/* static */ int32 AISubsidy::GetDestination(SubsidyID subsidy_id)
{
if (!IsValidSubsidy(subsidy_id)) return INVALID_STATION;
return _subsidies[subsidy_id].to;
}
| 2,345
|
C++
|
.cpp
| 69
| 31.898551
| 93
| 0.728039
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,279
|
ai_station.cpp
|
EnergeticBark_OpenTTD-3DS/src/ai/api/ai_station.cpp
|
/* $Id$ */
/** @file ai_station.cpp Implementation of AIStation. */
#include "ai_station.hpp"
#include "ai_cargo.hpp"
#include "ai_map.hpp"
#include "ai_town.hpp"
#include "../../command_func.h"
#include "../../debug.h"
#include "../../station_map.h"
#include "../../string_func.h"
#include "../../strings_func.h"
#include "../../company_func.h"
#include "../../town.h"
#include "table/strings.h"
/* static */ bool AIStation::IsValidStation(StationID station_id)
{
return ::IsValidStationID(station_id) && ::GetStation(station_id)->owner == _current_company;
}
/* static */ StationID AIStation::GetStationID(TileIndex tile)
{
if (!::IsValidTile(tile) || !::IsTileType(tile, MP_STATION)) return INVALID_STATION;
return ::GetStationIndex(tile);
}
/* static */ char *AIStation::GetName(StationID station_id)
{
if (!IsValidStation(station_id)) return NULL;
static const int len = 64;
char *station_name = MallocT<char>(len);
::SetDParam(0, GetStation(station_id)->index);
::GetString(station_name, STR_STATION, &station_name[len - 1]);
return station_name;
}
/* static */ bool AIStation::SetName(StationID station_id, const char *name)
{
EnforcePrecondition(false, IsValidStation(station_id));
EnforcePrecondition(false, !::StrEmpty(name));
EnforcePreconditionCustomError(false, ::strlen(name) < MAX_LENGTH_STATION_NAME_BYTES, AIError::ERR_PRECONDITION_STRING_TOO_LONG);
return AIObject::DoCommand(0, station_id, 0, CMD_RENAME_STATION, name);
}
/* static */ TileIndex AIStation::GetLocation(StationID station_id)
{
if (!IsValidStation(station_id)) return INVALID_TILE;
return ::GetStation(station_id)->xy;
}
/* static */ int32 AIStation::GetCargoWaiting(StationID station_id, CargoID cargo_id)
{
if (!IsValidStation(station_id)) return -1;
if (!AICargo::IsValidCargo(cargo_id)) return -1;
return ::GetStation(station_id)->goods[cargo_id].cargo.Count();
}
/* static */ int32 AIStation::GetCargoRating(StationID station_id, CargoID cargo_id)
{
if (!IsValidStation(station_id)) return -1;
if (!AICargo::IsValidCargo(cargo_id)) return -1;
return ::GetStation(station_id)->goods[cargo_id].rating * 101 >> 8;
}
/* static */ int32 AIStation::GetCoverageRadius(AIStation::StationType station_type)
{
if (station_type == STATION_AIRPORT) {
DEBUG(ai, 0, "GetCoverageRadius(): coverage radius of airports needs to be requested via AIAirport::GetAirportCoverageRadius(), as it requires AirportType");
return -1;
}
if (CountBits(station_type) != 1) return -1;
if (!_settings_game.station.modified_catchment) return CA_UNMODIFIED;
switch (station_type) {
case STATION_TRAIN: return CA_TRAIN;
case STATION_TRUCK_STOP: return CA_TRUCK;
case STATION_BUS_STOP: return CA_BUS;
case STATION_DOCK: return CA_DOCK;
default: return CA_NONE;
}
}
/* static */ int32 AIStation::GetDistanceManhattanToTile(StationID station_id, TileIndex tile)
{
if (!IsValidStation(station_id)) return -1;
return AIMap::DistanceManhattan(tile, GetLocation(station_id));
}
/* static */ int32 AIStation::GetDistanceSquareToTile(StationID station_id, TileIndex tile)
{
if (!IsValidStation(station_id)) return -1;
return AIMap::DistanceSquare(tile, GetLocation(station_id));
}
/* static */ bool AIStation::IsWithinTownInfluence(StationID station_id, TownID town_id)
{
if (!IsValidStation(station_id)) return false;
return AITown::IsWithinTownInfluence(town_id, GetLocation(station_id));
}
/* static */ bool AIStation::HasStationType(StationID station_id, StationType station_type)
{
if (!IsValidStation(station_id)) return false;
if (CountBits(station_type) != 1) return false;
return (::GetStation(station_id)->facilities & station_type) != 0;
}
/* static */ bool AIStation::HasRoadType(StationID station_id, AIRoad::RoadType road_type)
{
if (!IsValidStation(station_id)) return false;
if (!AIRoad::IsRoadTypeAvailable(road_type)) return false;
::RoadTypes r = RoadTypeToRoadTypes((::RoadType)road_type);
for (const RoadStop *rs = ::GetStation(station_id)->GetPrimaryRoadStop(ROADSTOP_BUS); rs != NULL; rs = rs->next) {
if ((::GetRoadTypes(rs->xy) & r) != 0) return true;
}
for (const RoadStop *rs = ::GetStation(station_id)->GetPrimaryRoadStop(ROADSTOP_TRUCK); rs != NULL; rs = rs->next) {
if ((::GetRoadTypes(rs->xy) & r) != 0) return true;
}
return false;
}
/* static */ TownID AIStation::GetNearestTown(StationID station_id)
{
if (!IsValidStation(station_id)) return INVALID_TOWN;
return ::GetStation(station_id)->town->index;
}
| 4,507
|
C++
|
.cpp
| 111
| 38.747748
| 159
| 0.73425
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,281
|
ai_vehiclelist.cpp
|
EnergeticBark_OpenTTD-3DS/src/ai/api/ai_vehiclelist.cpp
|
/* $Id$ */
/** @file ai_vehiclelist.cpp Implementation of AIVehicleList and friends. */
#include "ai_vehiclelist.hpp"
#include "ai_group.hpp"
#include "ai_station.hpp"
#include "ai_vehicle.hpp"
#include "../../company_func.h"
#include "../../vehicle_base.h"
AIVehicleList::AIVehicleList()
{
const Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->owner == _current_company && v->IsPrimaryVehicle()) this->AddItem(v->index);
}
}
AIVehicleList_Station::AIVehicleList_Station(StationID station_id)
{
if (!AIStation::IsValidStation(station_id)) return;
const Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->owner == _current_company && v->IsPrimaryVehicle()) {
const Order *order;
FOR_VEHICLE_ORDERS(v, order) {
if (order->IsType(OT_GOTO_STATION) && order->GetDestination() == station_id) {
this->AddItem(v->index);
break;
}
}
}
}
}
AIVehicleList_SharedOrders::AIVehicleList_SharedOrders(VehicleID vehicle_id)
{
if (!AIVehicle::IsValidVehicle(vehicle_id)) return;
for (const Vehicle *v = GetVehicle(vehicle_id)->FirstShared(); v != NULL; v = v->NextShared()) {
this->AddItem(v->index);
}
}
AIVehicleList_Group::AIVehicleList_Group(GroupID group_id)
{
if (!AIGroup::IsValidGroup((AIGroup::GroupID)group_id)) return;
const Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->owner == _current_company && v->IsPrimaryVehicle()) {
if (v->group_id == group_id) this->AddItem(v->index);
}
}
}
AIVehicleList_DefaultGroup::AIVehicleList_DefaultGroup(AIVehicle::VehicleType vehicle_type)
{
if (vehicle_type < AIVehicle::VT_RAIL || vehicle_type > AIVehicle::VT_AIR) return;
const Vehicle *v;
FOR_ALL_VEHICLES(v) {
if (v->owner == _current_company && v->IsPrimaryVehicle()) {
if (v->type == vehicle_type && v->group_id == AIGroup::GROUP_DEFAULT) this->AddItem(v->index);
}
}
}
| 1,814
|
C++
|
.cpp
| 58
| 28.913793
| 97
| 0.700115
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,282
|
ai_order.cpp
|
EnergeticBark_OpenTTD-3DS/src/ai/api/ai_order.cpp
|
/* $Id$ */
/** @file ai_order.cpp Implementation of AIOrder. */
#include "ai_order.hpp"
#include "ai_vehicle.hpp"
#include "ai_log.hpp"
#include "../ai_instance.hpp"
#include "../../debug.h"
#include "../../vehicle_base.h"
#include "../../depot_base.h"
#include "../../station_map.h"
#include "../../waypoint.h"
/**
* Gets the order type given a tile
* @param t the tile to get the order from
* @return the order type, or OT_END when there is no order
*/
static OrderType GetOrderTypeByTile(TileIndex t)
{
if (!::IsValidTile(t)) return OT_END;
switch (::GetTileType(t)) {
default: break;
case MP_STATION: return OT_GOTO_STATION; break;
case MP_WATER: if (::IsShipDepot(t)) return OT_GOTO_DEPOT; break;
case MP_ROAD: if (::GetRoadTileType(t) == ROAD_TILE_DEPOT) return OT_GOTO_DEPOT; break;
case MP_RAILWAY:
switch (::GetRailTileType(t)) {
case RAIL_TILE_DEPOT: return OT_GOTO_DEPOT;
case RAIL_TILE_WAYPOINT: return OT_GOTO_WAYPOINT;
default: break;
}
break;
}
return OT_END;
}
/* static */ bool AIOrder::IsValidVehicleOrder(VehicleID vehicle_id, OrderPosition order_position)
{
return AIVehicle::IsValidVehicle(vehicle_id) && order_position >= 0 && (order_position < ::GetVehicle(vehicle_id)->GetNumOrders() || order_position == ORDER_CURRENT);
}
/* static */ bool AIOrder::IsConditionalOrder(VehicleID vehicle_id, OrderPosition order_position)
{
if (order_position == ORDER_CURRENT) return false;
if (!IsValidVehicleOrder(vehicle_id, order_position)) return false;
const Order *order = ::GetVehicleOrder(GetVehicle(vehicle_id), order_position);
return order->GetType() == OT_CONDITIONAL;
}
/* static */ AIOrder::OrderPosition AIOrder::ResolveOrderPosition(VehicleID vehicle_id, OrderPosition order_position)
{
if (!AIVehicle::IsValidVehicle(vehicle_id)) return ORDER_INVALID;
if (order_position == ORDER_CURRENT) return (AIOrder::OrderPosition)::GetVehicle(vehicle_id)->cur_order_index;
return (order_position >= 0 && order_position < ::GetVehicle(vehicle_id)->GetNumOrders()) ? order_position : ORDER_INVALID;
}
/* static */ bool AIOrder::AreOrderFlagsValid(TileIndex destination, AIOrderFlags order_flags)
{
switch (::GetOrderTypeByTile(destination)) {
case OT_GOTO_STATION:
return ((order_flags & ~(AIOF_NON_STOP_FLAGS | AIOF_UNLOAD_FLAGS | AIOF_LOAD_FLAGS)) == 0) &&
/* Test the different mutual exclusive flags. */
(((order_flags & AIOF_TRANSFER) == 0) || ((order_flags & AIOF_UNLOAD) == 0)) &&
(((order_flags & AIOF_TRANSFER) == 0) || ((order_flags & AIOF_NO_UNLOAD) == 0)) &&
(((order_flags & AIOF_UNLOAD) == 0) || ((order_flags & AIOF_NO_UNLOAD) == 0)) &&
(((order_flags & AIOF_UNLOAD) == 0) || ((order_flags & AIOF_NO_UNLOAD) == 0)) &&
(((order_flags & AIOF_NO_UNLOAD) == 0) || ((order_flags & AIOF_NO_LOAD) == 0)) &&
(((order_flags & AIOF_FULL_LOAD_ANY) == 0) || ((order_flags & AIOF_NO_LOAD) == 0));
case OT_GOTO_DEPOT: return (order_flags & ~(AIOF_NON_STOP_FLAGS | AIOF_SERVICE_IF_NEEDED)) == 0;
case OT_GOTO_WAYPOINT: return (order_flags & ~(AIOF_NON_STOP_FLAGS)) == 0;
default: return false;
}
}
/* static */ bool AIOrder::IsValidConditionalOrder(OrderCondition condition, CompareFunction compare)
{
switch (condition) {
case OC_LOAD_PERCENTAGE:
case OC_RELIABILITY:
case OC_MAX_SPEED:
case OC_AGE:
return compare >= CF_EQUALS && compare <= CF_MORE_EQUALS;
case OC_REQUIRES_SERVICE:
return compare == CF_IS_TRUE || compare == CF_IS_FALSE;
case OC_UNCONDITIONALLY:
return true;
default: return false;
}
}
/* static */ int32 AIOrder::GetOrderCount(VehicleID vehicle_id)
{
return AIVehicle::IsValidVehicle(vehicle_id) ? ::GetVehicle(vehicle_id)->GetNumOrders() : -1;
}
/* static */ TileIndex AIOrder::GetOrderDestination(VehicleID vehicle_id, OrderPosition order_position)
{
if (!IsValidVehicleOrder(vehicle_id, order_position)) return INVALID_TILE;
const Order *order;
const Vehicle *v = ::GetVehicle(vehicle_id);
if (order_position == ORDER_CURRENT) {
order = &v->current_order;
} else {
order = ::GetVehicleOrder(GetVehicle(vehicle_id), order_position);
if (order->GetType() == OT_CONDITIONAL) return INVALID_TILE;
}
switch (order->GetType()) {
case OT_GOTO_DEPOT:
if (v->type != VEH_AIRCRAFT) return ::GetDepot(order->GetDestination())->xy;
/* FALL THROUGH: aircraft's hangars are referenced by StationID, not DepotID */
case OT_GOTO_STATION: return ::GetStation(order->GetDestination())->xy;
case OT_GOTO_WAYPOINT: return ::GetWaypoint(order->GetDestination())->xy;
default: return INVALID_TILE;
}
}
/* static */ AIOrder::AIOrderFlags AIOrder::GetOrderFlags(VehicleID vehicle_id, OrderPosition order_position)
{
if (!IsValidVehicleOrder(vehicle_id, order_position)) return AIOF_INVALID;
const Order *order;
if (order_position == ORDER_CURRENT) {
order = &::GetVehicle(vehicle_id)->current_order;
} else {
order = ::GetVehicleOrder(GetVehicle(vehicle_id), order_position);
if (order->GetType() == OT_CONDITIONAL) return AIOF_INVALID;
}
AIOrderFlags order_flags = AIOF_NONE;
order_flags |= (AIOrderFlags)order->GetNonStopType();
switch (order->GetType()) {
case OT_GOTO_DEPOT:
if (order->GetDepotOrderType() & ODTFB_SERVICE) order_flags |= AIOF_SERVICE_IF_NEEDED;
break;
case OT_GOTO_STATION:
order_flags |= (AIOrderFlags)(order->GetLoadType() << 5);
order_flags |= (AIOrderFlags)(order->GetUnloadType() << 2);
break;
default: break;
}
return order_flags;
}
/* static */ AIOrder::OrderPosition AIOrder::GetOrderJumpTo(VehicleID vehicle_id, OrderPosition order_position)
{
if (!IsValidVehicleOrder(vehicle_id, order_position)) return ORDER_INVALID;
if (order_position == ORDER_CURRENT || !IsConditionalOrder(vehicle_id, order_position)) return ORDER_INVALID;
const Order *order = ::GetVehicleOrder(GetVehicle(vehicle_id), order_position);
return (OrderPosition)order->GetConditionSkipToOrder();
}
/* static */ AIOrder::OrderCondition AIOrder::GetOrderCondition(VehicleID vehicle_id, OrderPosition order_position)
{
if (!IsValidVehicleOrder(vehicle_id, order_position)) return OC_INVALID;
if (order_position == ORDER_CURRENT || !IsConditionalOrder(vehicle_id, order_position)) return OC_INVALID;
const Order *order = ::GetVehicleOrder(GetVehicle(vehicle_id), order_position);
return (OrderCondition)order->GetConditionVariable();
}
/* static */ AIOrder::CompareFunction AIOrder::GetOrderCompareFunction(VehicleID vehicle_id, OrderPosition order_position)
{
if (!IsValidVehicleOrder(vehicle_id, order_position)) return CF_INVALID;
if (order_position == ORDER_CURRENT || !IsConditionalOrder(vehicle_id, order_position)) return CF_INVALID;
const Order *order = ::GetVehicleOrder(GetVehicle(vehicle_id), order_position);
return (CompareFunction)order->GetConditionComparator();
}
/* static */ int32 AIOrder::GetOrderCompareValue(VehicleID vehicle_id, OrderPosition order_position)
{
if (!IsValidVehicleOrder(vehicle_id, order_position)) return -1;
if (order_position == ORDER_CURRENT || !IsConditionalOrder(vehicle_id, order_position)) return -1;
const Order *order = ::GetVehicleOrder(GetVehicle(vehicle_id), order_position);
int32 value = order->GetConditionValue();
if (order->GetConditionVariable() == OCV_MAX_SPEED) value = value * 16 / 10;
return value;
}
/* static */ bool AIOrder::SetOrderJumpTo(VehicleID vehicle_id, OrderPosition order_position, OrderPosition jump_to)
{
EnforcePrecondition(false, IsValidVehicleOrder(vehicle_id, order_position));
EnforcePrecondition(false, order_position != ORDER_CURRENT && IsConditionalOrder(vehicle_id, order_position));
EnforcePrecondition(false, IsValidVehicleOrder(vehicle_id, jump_to) && jump_to != ORDER_CURRENT);
return AIObject::DoCommand(0, vehicle_id | (order_position << 16), MOF_COND_DESTINATION | (jump_to << 4), CMD_MODIFY_ORDER);
}
/* static */ bool AIOrder::SetOrderCondition(VehicleID vehicle_id, OrderPosition order_position, OrderCondition condition)
{
EnforcePrecondition(false, IsValidVehicleOrder(vehicle_id, order_position));
EnforcePrecondition(false, order_position != ORDER_CURRENT && IsConditionalOrder(vehicle_id, order_position));
EnforcePrecondition(false, condition >= OC_LOAD_PERCENTAGE && condition <= OC_UNCONDITIONALLY);
return AIObject::DoCommand(0, vehicle_id | (order_position << 16), MOF_COND_VARIABLE | (condition << 4), CMD_MODIFY_ORDER);
}
/* static */ bool AIOrder::SetOrderCompareFunction(VehicleID vehicle_id, OrderPosition order_position, CompareFunction compare)
{
EnforcePrecondition(false, IsValidVehicleOrder(vehicle_id, order_position));
EnforcePrecondition(false, order_position != ORDER_CURRENT && IsConditionalOrder(vehicle_id, order_position));
EnforcePrecondition(false, compare >= CF_EQUALS && compare <= CF_IS_FALSE);
return AIObject::DoCommand(0, vehicle_id | (order_position << 16), MOF_COND_COMPARATOR | (compare << 4), CMD_MODIFY_ORDER);
}
/* static */ bool AIOrder::SetOrderCompareValue(VehicleID vehicle_id, OrderPosition order_position, int32 value)
{
EnforcePrecondition(false, IsValidVehicleOrder(vehicle_id, order_position));
EnforcePrecondition(false, order_position != ORDER_CURRENT && IsConditionalOrder(vehicle_id, order_position));
EnforcePrecondition(false, value >= 0 && value < 2048);
if (GetOrderCondition(vehicle_id, order_position) == OC_MAX_SPEED) value = value * 10 / 16;
return AIObject::DoCommand(0, vehicle_id | (order_position << 16), MOF_COND_VALUE | (value << 4), CMD_MODIFY_ORDER);
}
/* static */ bool AIOrder::AppendOrder(VehicleID vehicle_id, TileIndex destination, AIOrderFlags order_flags)
{
EnforcePrecondition(false, AIVehicle::IsValidVehicle(vehicle_id));
EnforcePrecondition(false, AreOrderFlagsValid(destination, order_flags));
return InsertOrder(vehicle_id, (AIOrder::OrderPosition)::GetVehicle(vehicle_id)->GetNumOrders(), destination, order_flags);
}
/* static */ bool AIOrder::AppendConditionalOrder(VehicleID vehicle_id, OrderPosition jump_to)
{
EnforcePrecondition(false, AIVehicle::IsValidVehicle(vehicle_id));
EnforcePrecondition(false, IsValidVehicleOrder(vehicle_id, jump_to));
return InsertConditionalOrder(vehicle_id, (AIOrder::OrderPosition)::GetVehicle(vehicle_id)->GetNumOrders(), jump_to);
}
/* static */ bool AIOrder::InsertOrder(VehicleID vehicle_id, OrderPosition order_position, TileIndex destination, AIOrder::AIOrderFlags order_flags)
{
/* IsValidVehicleOrder is not good enough because it does not allow appending. */
if (order_position == ORDER_CURRENT) order_position = AIOrder::ResolveOrderPosition(vehicle_id, order_position);
EnforcePrecondition(false, AIVehicle::IsValidVehicle(vehicle_id));
EnforcePrecondition(false, order_position >= 0 && order_position <= ::GetVehicle(vehicle_id)->GetNumOrders());
EnforcePrecondition(false, AreOrderFlagsValid(destination, order_flags));
Order order;
switch (::GetOrderTypeByTile(destination)) {
case OT_GOTO_DEPOT:
order.MakeGoToDepot(::GetDepotByTile(destination)->index, (OrderDepotTypeFlags)(ODTFB_PART_OF_ORDERS | ((order_flags & AIOF_SERVICE_IF_NEEDED) ? ODTFB_SERVICE : 0)));
break;
case OT_GOTO_STATION:
order.MakeGoToStation(::GetStationIndex(destination));
order.SetLoadType((OrderLoadFlags)GB(order_flags, 5, 3));
order.SetUnloadType((OrderUnloadFlags)GB(order_flags, 2, 3));
break;
case OT_GOTO_WAYPOINT:
order.MakeGoToWaypoint(::GetWaypointIndex(destination));
break;
default:
return false;
}
order.SetNonStopType((OrderNonStopFlags)GB(order_flags, 0, 2));
return AIObject::DoCommand(0, vehicle_id | (order_position << 16), order.Pack(), CMD_INSERT_ORDER);
}
/* static */ bool AIOrder::InsertConditionalOrder(VehicleID vehicle_id, OrderPosition order_position, OrderPosition jump_to)
{
/* IsValidVehicleOrder is not good enough because it does not allow appending. */
if (order_position == ORDER_CURRENT) order_position = AIOrder::ResolveOrderPosition(vehicle_id, order_position);
EnforcePrecondition(false, AIVehicle::IsValidVehicle(vehicle_id));
EnforcePrecondition(false, IsValidVehicleOrder(vehicle_id, jump_to));
Order order;
order.MakeConditional(jump_to);
return AIObject::DoCommand(0, vehicle_id | (order_position << 16), order.Pack(), CMD_INSERT_ORDER);
}
/* static */ bool AIOrder::RemoveOrder(VehicleID vehicle_id, OrderPosition order_position)
{
order_position = AIOrder::ResolveOrderPosition(vehicle_id, order_position);
EnforcePrecondition(false, IsValidVehicleOrder(vehicle_id, order_position));
return AIObject::DoCommand(0, vehicle_id, order_position, CMD_DELETE_ORDER);
}
/* static */ bool AIOrder::SkipToOrder(VehicleID vehicle_id, OrderPosition next_order)
{
EnforcePrecondition(false, IsValidVehicleOrder(vehicle_id, next_order));
return AIObject::DoCommand(0, vehicle_id, next_order, CMD_SKIP_TO_ORDER);
}
/**
* Callback handler as SetOrderFlags possibly needs multiple DoCommand calls
* to be able to set all order flags correctly. As we need to wait till the
* command has completed before we know the next bits to change we need to
* call the function multiple times. Each time it'll reduce the difference
* between the wanted and the current order.
* @param instance The AI we are doing the callback for.
*/
static void _DoCommandReturnSetOrderFlags(class AIInstance *instance)
{
AIObject::SetLastCommandRes(AIOrder::_SetOrderFlags());
AIInstance::DoCommandReturn(instance);
}
/* static */ bool AIOrder::_SetOrderFlags()
{
/* Make sure we don't go into an infinite loop */
int retry = AIObject::GetCallbackVariable(3) - 1;
if (retry < 0) {
DEBUG(ai, 0, "Possible infinite loop in SetOrderFlags() detected");
return false;
}
AIObject::SetCallbackVariable(3, retry);
VehicleID vehicle_id = (VehicleID)AIObject::GetCallbackVariable(0);
OrderPosition order_position = (OrderPosition)AIObject::GetCallbackVariable(1);
AIOrderFlags order_flags = (AIOrderFlags)AIObject::GetCallbackVariable(2);
order_position = AIOrder::ResolveOrderPosition(vehicle_id, order_position);
EnforcePrecondition(false, IsValidVehicleOrder(vehicle_id, order_position));
EnforcePrecondition(false, AreOrderFlagsValid(GetOrderDestination(vehicle_id, order_position), order_flags));
const Order *order = ::GetVehicleOrder(GetVehicle(vehicle_id), order_position);
AIOrderFlags current = GetOrderFlags(vehicle_id, order_position);
if ((current & AIOF_NON_STOP_FLAGS) != (order_flags & AIOF_NON_STOP_FLAGS)) {
return AIObject::DoCommand(0, vehicle_id | (order_position << 16), (order_flags & AIOF_NON_STOP_FLAGS) << 4 | MOF_NON_STOP, CMD_MODIFY_ORDER, NULL, &_DoCommandReturnSetOrderFlags);
}
switch (order->GetType()) {
case OT_GOTO_DEPOT:
if ((current & AIOF_SERVICE_IF_NEEDED) != (order_flags & AIOF_SERVICE_IF_NEEDED)) {
return AIObject::DoCommand(0, vehicle_id | (order_position << 16), MOF_DEPOT_ACTION, CMD_MODIFY_ORDER, NULL, &_DoCommandReturnSetOrderFlags);
}
break;
case OT_GOTO_STATION:
if ((current & AIOF_UNLOAD_FLAGS) != (order_flags & AIOF_UNLOAD_FLAGS)) {
return AIObject::DoCommand(0, vehicle_id | (order_position << 16), (order_flags & AIOF_UNLOAD_FLAGS) << 2 | MOF_UNLOAD, CMD_MODIFY_ORDER, NULL, &_DoCommandReturnSetOrderFlags);
}
if ((current & AIOF_LOAD_FLAGS) != (order_flags & AIOF_LOAD_FLAGS)) {
return AIObject::DoCommand(0, vehicle_id | (order_position << 16), (order_flags & AIOF_LOAD_FLAGS) >> 1 | MOF_LOAD, CMD_MODIFY_ORDER, NULL, &_DoCommandReturnSetOrderFlags);
}
break;
default: break;
}
assert(GetOrderFlags(vehicle_id, order_position) == order_flags);
return true;
}
/* static */ bool AIOrder::SetOrderFlags(VehicleID vehicle_id, OrderPosition order_position, AIOrder::AIOrderFlags order_flags)
{
AIObject::SetCallbackVariable(0, vehicle_id);
AIObject::SetCallbackVariable(1, order_position);
AIObject::SetCallbackVariable(2, order_flags);
/* In case another client(s) change orders at the same time we could
* end in an infinite loop. This stops that from happening ever. */
AIObject::SetCallbackVariable(3, 8);
return AIOrder::_SetOrderFlags();
}
/* static */ bool AIOrder::ChangeOrder(VehicleID vehicle_id, OrderPosition order_position, AIOrder::AIOrderFlags order_flags)
{
AILog::Warning("AIOrder::ChangeOrder is deprecated and will be removed soon, please use AIOrder::SetOrderFlags instead.");
return SetOrderFlags(vehicle_id, order_position, order_flags);
}
/* static */ bool AIOrder::MoveOrder(VehicleID vehicle_id, OrderPosition order_position_move, OrderPosition order_position_target)
{
order_position_move = AIOrder::ResolveOrderPosition(vehicle_id, order_position_move);
order_position_target = AIOrder::ResolveOrderPosition(vehicle_id, order_position_target);
EnforcePrecondition(false, IsValidVehicleOrder(vehicle_id, order_position_move));
EnforcePrecondition(false, IsValidVehicleOrder(vehicle_id, order_position_target));
return AIObject::DoCommand(0, vehicle_id, order_position_move | (order_position_target << 16), CMD_MOVE_ORDER);
}
/* static */ bool AIOrder::CopyOrders(VehicleID vehicle_id, VehicleID main_vehicle_id)
{
EnforcePrecondition(false, AIVehicle::IsValidVehicle(vehicle_id));
EnforcePrecondition(false, AIVehicle::IsValidVehicle(main_vehicle_id));
return AIObject::DoCommand(0, vehicle_id | (main_vehicle_id << 16), CO_COPY, CMD_CLONE_ORDER);
}
/* static */ bool AIOrder::ShareOrders(VehicleID vehicle_id, VehicleID main_vehicle_id)
{
EnforcePrecondition(false, AIVehicle::IsValidVehicle(vehicle_id));
EnforcePrecondition(false, AIVehicle::IsValidVehicle(main_vehicle_id));
return AIObject::DoCommand(0, vehicle_id | (main_vehicle_id << 16), CO_SHARE, CMD_CLONE_ORDER);
}
/* static */ bool AIOrder::UnshareOrders(VehicleID vehicle_id)
{
EnforcePrecondition(false, AIVehicle::IsValidVehicle(vehicle_id));
return AIObject::DoCommand(0, vehicle_id, CO_UNSHARE, CMD_CLONE_ORDER);
}
| 17,923
|
C++
|
.cpp
| 341
| 50.175953
| 182
| 0.7511
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,283
|
ai_execmode.cpp
|
EnergeticBark_OpenTTD-3DS/src/ai/api/ai_execmode.cpp
|
/* $Id$ */
/** @file ai_execmode.cpp Implementation of AIExecMode. */
#include "ai_execmode.hpp"
#include "../../command_type.h"
bool AIExecMode::ModeProc(TileIndex tile, uint32 p1, uint32 p2, uint procc, CommandCost costs)
{
/* In execution mode we only return 'true', telling the DoCommand it
* should continue with the real execution of the command. */
return true;
}
AIExecMode::AIExecMode()
{
this->last_mode = this->GetDoCommandMode();
this->last_instance = this->GetDoCommandModeInstance();
this->SetDoCommandMode(&AIExecMode::ModeProc, this);
}
AIExecMode::~AIExecMode()
{
assert(this->GetDoCommandModeInstance() == this);
this->SetDoCommandMode(this->last_mode, this->last_instance);
}
| 714
|
C++
|
.cpp
| 21
| 32.333333
| 94
| 0.744186
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,284
|
ai_list.cpp
|
EnergeticBark_OpenTTD-3DS/src/ai/api/ai_list.cpp
|
/* $Id$ */
/** @file ai_list.cpp Implementation of AIList. */
#include <squirrel.h>
#include "ai_list.hpp"
void AIList::AddItem(int32 item, int32 value)
{
AIAbstractList::AddItem(item);
this->SetValue(item, value);
}
void AIList::ChangeItem(int32 item, int32 value)
{
this->SetValue(item, value);
}
void AIList::RemoveItem(int32 item)
{
AIAbstractList::RemoveItem(item);
}
SQInteger AIList::_set(HSQUIRRELVM vm) {
if (sq_gettype(vm, 2) != OT_INTEGER) return SQ_ERROR;
if (sq_gettype(vm, 3) != OT_INTEGER || sq_gettype(vm, 3) == OT_NULL) {
return sq_throwerror(vm, _SC("you can only assign integers to this list"));
}
SQInteger idx, val;
sq_getinteger(vm, 2, &idx);
if (sq_gettype(vm, 3) == OT_NULL) {
this->RemoveItem(idx);
return 0;
}
sq_getinteger(vm, 3, &val);
if (!this->HasItem(idx)) {
this->AddItem(idx, val);
return 0;
}
this->ChangeItem(idx, val);
return 0;
}
| 903
|
C++
|
.cpp
| 36
| 23.111111
| 77
| 0.692308
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,287
|
ai_waypoint.cpp
|
EnergeticBark_OpenTTD-3DS/src/ai/api/ai_waypoint.cpp
|
/* $Id$ */
/** @file ai_waypoint.cpp Implementation of AIWaypoint. */
#include "ai_waypoint.hpp"
#include "ai_rail.hpp"
#include "../../command_func.h"
#include "../../string_func.h"
#include "../../strings_func.h"
#include "../../company_func.h"
#include "../../waypoint.h"
#include "../../core/alloc_func.hpp"
#include "table/strings.h"
/* static */ bool AIWaypoint::IsValidWaypoint(WaypointID waypoint_id)
{
return ::IsValidWaypointID(waypoint_id) && ::GetWaypoint(waypoint_id)->owner == _current_company;
}
/* static */ WaypointID AIWaypoint::GetWaypointID(TileIndex tile)
{
if (!AIRail::IsRailWaypointTile(tile)) return WAYPOINT_INVALID;
return ::GetWaypointIndex(tile);
}
/* static */ char *AIWaypoint::GetName(WaypointID waypoint_id)
{
if (!IsValidWaypoint(waypoint_id)) return NULL;
static const int len = 64;
char *waypoint_name = MallocT<char>(len);
::SetDParam(0, waypoint_id);
::GetString(waypoint_name, STR_WAYPOINT_RAW, &waypoint_name[len - 1]);
return waypoint_name;
}
/* static */ bool AIWaypoint::SetName(WaypointID waypoint_id, const char *name)
{
EnforcePrecondition(false, IsValidWaypoint(waypoint_id));
EnforcePrecondition(false, !::StrEmpty(name));
EnforcePreconditionCustomError(false, ::strlen(name) < MAX_LENGTH_WAYPOINT_NAME_BYTES, AIError::ERR_PRECONDITION_STRING_TOO_LONG);
return AIObject::DoCommand(0, waypoint_id, 0, CMD_RENAME_WAYPOINT, name);
}
/* static */ TileIndex AIWaypoint::GetLocation(WaypointID waypoint_id)
{
if (!IsValidWaypoint(waypoint_id)) return INVALID_TILE;
return ::GetWaypoint(waypoint_id)->xy;
}
| 1,575
|
C++
|
.cpp
| 41
| 36.756098
| 131
| 0.742444
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,295
|
ai_subsidylist.cpp
|
EnergeticBark_OpenTTD-3DS/src/ai/api/ai_subsidylist.cpp
|
/* $Id$ */
/** @file ai_subsidylist.cpp Implementation of AISubsidyList. */
#include "ai_subsidylist.hpp"
#include "ai_subsidy.hpp"
#include "../../economy_func.h"
AISubsidyList::AISubsidyList()
{
for (uint i = 0; i < lengthof(_subsidies); i++) {
if (AISubsidy::IsValidSubsidy(i)) this->AddItem(i);
}
}
| 310
|
C++
|
.cpp
| 11
| 26.545455
| 64
| 0.689189
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,299
|
ai_company.cpp
|
EnergeticBark_OpenTTD-3DS/src/ai/api/ai_company.cpp
|
/* $Id$ */
/** @file ai_company.cpp Implementation of AICompany. */
#include "ai_company.hpp"
#include "ai_error.hpp"
#include "ai_log.hpp"
#include "../../command_func.h"
#include "../../company_func.h"
#include "../../company_base.h"
#include "../../economy_func.h"
#include "../../strings_func.h"
#include "../../tile_map.h"
#include "../../core/alloc_func.hpp"
#include "../../string_func.h"
#include "table/strings.h"
/* static */ AICompany::CompanyID AICompany::ResolveCompanyID(AICompany::CompanyID company)
{
if (company == COMPANY_SELF) return (CompanyID)((byte)_current_company);
return ::IsValidCompanyID((::CompanyID)company) ? company : COMPANY_INVALID;
}
/* static */ bool AICompany::IsMine(AICompany::CompanyID company)
{
return ResolveCompanyID(company) == ResolveCompanyID(COMPANY_SELF);
}
/* static */ bool AICompany::SetName(const char *name)
{
EnforcePrecondition(false, !::StrEmpty(name));
EnforcePreconditionCustomError(false, ::strlen(name) < MAX_LENGTH_COMPANY_NAME_BYTES, AIError::ERR_PRECONDITION_STRING_TOO_LONG);
return AIObject::DoCommand(0, 0, 0, CMD_RENAME_COMPANY, name);
}
/* static */ char *AICompany::GetName(AICompany::CompanyID company)
{
company = ResolveCompanyID(company);
if (company == COMPANY_INVALID) return NULL;
static const int len = 64;
char *company_name = MallocT<char>(len);
::SetDParam(0, company);
::GetString(company_name, STR_COMPANY_NAME, &company_name[len - 1]);
return company_name;
}
/* static */ bool AICompany::SetPresidentName(const char *name)
{
EnforcePrecondition(false, !::StrEmpty(name));
return AIObject::DoCommand(0, 0, 0, CMD_RENAME_PRESIDENT, name);
}
/* static */ char *AICompany::GetPresidentName(AICompany::CompanyID company)
{
company = ResolveCompanyID(company);
static const int len = 64;
char *president_name = MallocT<char>(len);
if (company != COMPANY_INVALID) {
::SetDParam(0, company);
::GetString(president_name, STR_PRESIDENT_NAME, &president_name[len - 1]);
} else {
*president_name = '\0';
}
return president_name;
}
/* static */ Money AICompany::GetCompanyValue(AICompany::CompanyID company)
{
company = ResolveCompanyID(company);
if (company == COMPANY_INVALID) return -1;
return ::CalculateCompanyValue(::GetCompany((CompanyID)company));
}
/* static */ Money AICompany::GetBankBalance(AICompany::CompanyID company)
{
company = ResolveCompanyID(company);
if (company == COMPANY_INVALID) return -1;
return ::GetCompany((CompanyID)company)->money;
}
/* static */ Money AICompany::GetLoanAmount()
{
return ::GetCompany(_current_company)->current_loan;
}
/* static */ Money AICompany::GetMaxLoanAmount()
{
return _economy.max_loan;
}
/* static */ Money AICompany::GetLoanInterval()
{
return LOAN_INTERVAL;
}
/* static */ bool AICompany::SetLoanAmount(int32 loan)
{
EnforcePrecondition(false, loan >= 0);
EnforcePrecondition(false, (loan % GetLoanInterval()) == 0);
EnforcePrecondition(false, loan <= GetMaxLoanAmount());
EnforcePrecondition(false, (loan - GetLoanAmount() + GetBankBalance(COMPANY_SELF)) >= 0);
if (loan == GetLoanAmount()) return true;
return AIObject::DoCommand(0,
abs(loan - GetLoanAmount()), 2,
(loan > GetLoanAmount()) ? CMD_INCREASE_LOAN : CMD_DECREASE_LOAN);
}
/* static */ bool AICompany::SetMinimumLoanAmount(int32 loan)
{
EnforcePrecondition(false, loan >= 0);
int32 over_interval = loan % GetLoanInterval();
if (over_interval != 0) loan += GetLoanInterval() - over_interval;
EnforcePrecondition(false, loan <= GetMaxLoanAmount());
SetLoanAmount(loan);
return GetLoanAmount() == loan;
}
/* static */ bool AICompany::BuildCompanyHQ(TileIndex tile)
{
EnforcePrecondition(false, ::IsValidTile(tile));
return AIObject::DoCommand(tile, 0, 0, CMD_BUILD_COMPANY_HQ);
}
/* static */ TileIndex AICompany::GetCompanyHQ(CompanyID company)
{
company = ResolveCompanyID(company);
if (company == COMPANY_INVALID) return INVALID_TILE;
TileIndex loc = ::GetCompany((CompanyID)company)->location_of_HQ;
return (loc == 0) ? INVALID_TILE : loc;
}
/* static */ bool AICompany::SetAutoRenewStatus(bool autorenew)
{
return AIObject::DoCommand(0, 0, autorenew ? 1 : 0, CMD_SET_AUTOREPLACE);
}
/* static */ bool AICompany::GetAutoRenewStatus(CompanyID company)
{
company = ResolveCompanyID(company);
if (company == COMPANY_INVALID) return false;
return ::GetCompany((CompanyID)company)->engine_renew;
}
/* static */ bool AICompany::SetAutoRenewMonths(int16 months)
{
return AIObject::DoCommand(0, 1, months, CMD_SET_AUTOREPLACE);
}
/* static */ int16 AICompany::GetAutoRenewMonths(CompanyID company)
{
company = ResolveCompanyID(company);
if (company == COMPANY_INVALID) return 0;
return ::GetCompany((CompanyID)company)->engine_renew_months;
}
/* static */ bool AICompany::SetAutoRenewMoney(uint32 money)
{
return AIObject::DoCommand(0, 2, money, CMD_SET_AUTOREPLACE);
}
/* static */ uint32 AICompany::GetAutoRenewMoney(CompanyID company)
{
company = ResolveCompanyID(company);
if (company == COMPANY_INVALID) return 0;
return ::GetCompany((CompanyID)company)->engine_renew_money;
}
| 5,086
|
C++
|
.cpp
| 143
| 33.755245
| 130
| 0.742449
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,303
|
ai_tilelist.cpp
|
EnergeticBark_OpenTTD-3DS/src/ai/api/ai_tilelist.cpp
|
/* $Id$ */
/** @file ai_tilelist.cpp Implementation of AITileList and friends. */
#include "ai_tilelist.hpp"
#include "ai_industry.hpp"
#include "../../tile_map.h"
#include "../../industry_map.h"
#include "../../station_map.h"
#include "../../settings_type.h"
void AITileList::FixRectangleSpan(TileIndex &t1, TileIndex &t2)
{
uint x1 = ::TileX(t1);
uint x2 = ::TileX(t2);
uint y1 = ::TileY(t1);
uint y2 = ::TileY(t2);
if (x1 >= x2) ::Swap(x1, x2);
if (y1 >= y2) ::Swap(y1, y2);
t1 = ::TileXY(x1, y1);
t2 = ::TileXY(x2, y2);
}
void AITileList::AddRectangle(TileIndex t1, TileIndex t2)
{
if (!::IsValidTile(t1)) return;
if (!::IsValidTile(t2)) return;
this->FixRectangleSpan(t1, t2);
uint w = TileX(t2) - TileX(t1) + 1;
uint h = TileY(t2) - TileY(t1) + 1;
BEGIN_TILE_LOOP(t, w, h, t1) {
this->AddItem(t);
} END_TILE_LOOP(t, w, h, t1)
}
void AITileList::AddTile(TileIndex tile)
{
if (!::IsValidTile(tile)) return;
this->AddItem(tile);
}
void AITileList::RemoveRectangle(TileIndex t1, TileIndex t2)
{
if (!::IsValidTile(t1)) return;
if (!::IsValidTile(t2)) return;
this->FixRectangleSpan(t1, t2);
uint w = TileX(t2) - TileX(t1) + 1;
uint h = TileY(t2) - TileY(t1) + 1;
BEGIN_TILE_LOOP(t, w, h, t1) {
this->RemoveItem(t);
} END_TILE_LOOP(t, w, h, t1)
}
void AITileList::RemoveTile(TileIndex tile)
{
if (!::IsValidTile(tile)) return;
this->RemoveItem(tile);
}
AITileList_IndustryAccepting::AITileList_IndustryAccepting(IndustryID industry_id, uint radius)
{
if (!AIIndustry::IsValidIndustry(industry_id)) return;
const Industry *i = ::GetIndustry(industry_id);
/* Check if this industry accepts anything */
{
bool cargo_accepts = false;
for (byte j = 0; j < lengthof(i->accepts_cargo); j++) {
if (i->accepts_cargo[j] != CT_INVALID) cargo_accepts = true;
}
if (!cargo_accepts) return;
}
if (!_settings_game.station.modified_catchment) radius = CA_UNMODIFIED;
BEGIN_TILE_LOOP(cur_tile, i->width + radius * 2, i->height + radius * 2, i->xy - ::TileDiffXY(radius, radius)) {
if (!::IsValidTile(cur_tile)) continue;
/* Exclude all tiles that belong to this industry */
if (::IsTileType(cur_tile, MP_INDUSTRY) && ::GetIndustryIndex(cur_tile) == industry_id) continue;
/* Only add the tile if it accepts the cargo (sometimes just 1 tile of an
* industry triggers the acceptance). */
AcceptedCargo accepts;
::GetAcceptanceAroundTiles(accepts, cur_tile, 1, 1, radius);
{
bool cargo_accepts = false;
for (byte j = 0; j < lengthof(i->accepts_cargo); j++) {
if (i->accepts_cargo[j] != CT_INVALID && accepts[i->accepts_cargo[j]] != 0) cargo_accepts = true;
}
if (!cargo_accepts) continue;
}
this->AddTile(cur_tile);
} END_TILE_LOOP(cur_tile, i->width + radius * 2, i->height + radius * 2, i->xy - ::TileDiffXY(radius, radius))
}
AITileList_IndustryProducing::AITileList_IndustryProducing(IndustryID industry_id, uint radius)
{
if (!AIIndustry::IsValidIndustry(industry_id)) return;
const Industry *i = ::GetIndustry(industry_id);
/* Check if this industry produces anything */
{
bool cargo_produces = false;
for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
if (i->produced_cargo[j] != CT_INVALID) cargo_produces = true;
}
if (!cargo_produces) return;
}
if (!_settings_game.station.modified_catchment) radius = CA_UNMODIFIED;
BEGIN_TILE_LOOP(cur_tile, i->width + radius * 2, i->height + radius * 2, i->xy - ::TileDiffXY(radius, radius)) {
if (!::IsValidTile(cur_tile)) continue;
/* Exclude all tiles that belong to this industry */
if (::IsTileType(cur_tile, MP_INDUSTRY) && ::GetIndustryIndex(cur_tile) == industry_id) continue;
/* Only add the tile if it produces the cargo (a bug in OpenTTD makes this
* inconsitance). */
AcceptedCargo produces;
::GetProductionAroundTiles(produces, cur_tile, 1, 1, radius);
{
bool cargo_produces = false;
for (byte j = 0; j < lengthof(i->produced_cargo); j++) {
if (i->produced_cargo[j] != CT_INVALID && produces[i->produced_cargo[j]] != 0) cargo_produces = true;
}
if (!cargo_produces) continue;
}
this->AddTile(cur_tile);
} END_TILE_LOOP(cur_tile, i->width + radius * 2, i->height + radius * 2, i->xy - ::TileDiffXY(radius, radius))
}
AITileList_StationType::AITileList_StationType(StationID station_id, AIStation::StationType station_type)
{
if (!AIStation::IsValidStation(station_id)) return;
const StationRect *rect = &::GetStation(station_id)->rect;
uint station_type_value = 0;
/* Convert AIStation::StationType to ::StationType, but do it in a
* bitmask, so we can scan for multiple entries at the same time. */
if ((station_type & AIStation::STATION_TRAIN) != 0) station_type_value |= (1 << ::STATION_RAIL);
if ((station_type & AIStation::STATION_TRUCK_STOP) != 0) station_type_value |= (1 << ::STATION_TRUCK);
if ((station_type & AIStation::STATION_BUS_STOP) != 0) station_type_value |= (1 << ::STATION_BUS);
if ((station_type & AIStation::STATION_AIRPORT) != 0) station_type_value |= (1 << ::STATION_AIRPORT) | (1 << ::STATION_OILRIG);
if ((station_type & AIStation::STATION_DOCK) != 0) station_type_value |= (1 << ::STATION_DOCK) | (1 << ::STATION_OILRIG);
BEGIN_TILE_LOOP(cur_tile, rect->right - rect->left + 1, rect->bottom - rect->top + 1, ::TileXY(rect->left, rect->top)) {
if (!::IsTileType(cur_tile, MP_STATION)) continue;
if (::GetStationIndex(cur_tile) != station_id) continue;
if (!HasBit(station_type_value, ::GetStationType(cur_tile))) continue;
this->AddTile(cur_tile);
} END_TILE_LOOP(cur_tile, rect->right - rect->left + 1, rect->bottom - rect->top + 1, ::TileXY(rect->left, rect->top))
}
| 5,661
|
C++
|
.cpp
| 132
| 40.378788
| 131
| 0.6785
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,310
|
ai_testmode.cpp
|
EnergeticBark_OpenTTD-3DS/src/ai/api/ai_testmode.cpp
|
/* $Id$ */
/** @file ai_testmode.cpp Implementation of AITestMode. */
#include "ai_testmode.hpp"
#include "../../command_type.h"
bool AITestMode::ModeProc(TileIndex tile, uint32 p1, uint32 p2, uint procc, CommandCost costs)
{
/* In test mode we only return 'false', telling the DoCommand it
* should stop after testing the command and return with that result. */
return false;
}
AITestMode::AITestMode()
{
this->last_mode = this->GetDoCommandMode();
this->last_instance = this->GetDoCommandModeInstance();
this->SetDoCommandMode(&AITestMode::ModeProc, this);
}
AITestMode::~AITestMode()
{
assert(this->GetDoCommandModeInstance() == this);
this->SetDoCommandMode(this->last_mode, this->last_instance);
}
| 722
|
C++
|
.cpp
| 21
| 32.714286
| 94
| 0.744253
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,313
|
ai_event_types.cpp
|
EnergeticBark_OpenTTD-3DS/src/ai/api/ai_event_types.cpp
|
/* $Id$ */
/** @file ai_event_types.cpp Implementation of all EventTypes. */
#include "ai_event_types.hpp"
#include "../../command_type.h"
#include "../../strings_func.h"
#include "../../settings_type.h"
#include "../../rail.h"
#include "../../engine_base.h"
#include "../../articulated_vehicles.h"
#include "table/strings.h"
char *AIEventEnginePreview::GetName()
{
static const int len = 64;
char *engine_name = MallocT<char>(len);
::SetDParam(0, engine);
::GetString(engine_name, STR_ENGINE_NAME, &engine_name[len - 1]);
return engine_name;
}
CargoID AIEventEnginePreview::GetCargoType()
{
const Engine *e = ::GetEngine(engine);
if (!e->CanCarryCargo()) return CT_INVALID;
return e->GetDefaultCargoType();
}
int32 AIEventEnginePreview::GetCapacity()
{
const Engine *e = ::GetEngine(engine);
switch (e->type) {
case VEH_ROAD:
case VEH_TRAIN: {
uint16 *capacities = GetCapacityOfArticulatedParts(engine, e->type);
for (CargoID c = 0; c < NUM_CARGO; c++) {
if (capacities[c] == 0) continue;
return capacities[c];
}
return -1;
} break;
case VEH_SHIP:
case VEH_AIRCRAFT:
return e->GetDisplayDefaultCapacity();
break;
default: NOT_REACHED();
}
}
int32 AIEventEnginePreview::GetMaxSpeed()
{
const Engine *e = ::GetEngine(engine);
int32 max_speed = e->GetDisplayMaxSpeed(); // km-ish/h
if (e->type == VEH_AIRCRAFT) max_speed /= _settings_game.vehicle.plane_speed;
return max_speed;
}
Money AIEventEnginePreview::GetPrice()
{
return ::GetEngine(engine)->GetCost();
}
Money AIEventEnginePreview::GetRunningCost()
{
return ::GetEngine(engine)->GetRunningCost();
}
AIVehicle::VehicleType AIEventEnginePreview::GetVehicleType()
{
switch (::GetEngine(engine)->type) {
case VEH_ROAD: return AIVehicle::VT_ROAD;
case VEH_TRAIN: return AIVehicle::VT_RAIL;
case VEH_SHIP: return AIVehicle::VT_WATER;
case VEH_AIRCRAFT: return AIVehicle::VT_AIR;
default: NOT_REACHED();
}
}
bool AIEventEnginePreview::AcceptPreview()
{
return AIObject::DoCommand(0, engine, 0, CMD_WANT_ENGINE_PREVIEW);
}
| 2,063
|
C++
|
.cpp
| 73
| 26.150685
| 78
| 0.715225
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,316
|
G5_detector.cpp
|
EnergeticBark_OpenTTD-3DS/src/os/macosx/G5_detector.cpp
|
/* $Id$ */
/** @file G5_detector.cpp Detection for G5 machines (PowerPC). */
#include <mach/mach.h>
#include <mach/mach_host.h>
#include <mach/host_info.h>
#include <mach/machine.h>
#include <stdio.h>
#ifndef CPU_SUBTYPE_POWERPC_970
#define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
#endif
/* this function is a lightly modified version of some code from Apple's developer homepage to detect G5 CPUs at runtime */
main()
{
host_basic_info_data_t hostInfo;
mach_msg_type_number_t infoCount;
boolean_t is_G5;
infoCount = HOST_BASIC_INFO_COUNT;
host_info(mach_host_self(), HOST_BASIC_INFO,
(host_info_t)&hostInfo, &infoCount);
is_G5 = ((hostInfo.cpu_type == CPU_TYPE_POWERPC) &&
(hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970));
if (is_G5)
printf("1");
}
| 785
|
C++
|
.cpp
| 24
| 30.583333
| 123
| 0.720159
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
1,539,317
|
splash.cpp
|
EnergeticBark_OpenTTD-3DS/src/os/macosx/splash.cpp
|
/* $Id$ */
/** @file splash.cpp Splash screen support for OSX. */
#include "../../stdafx.h"
#include "../../openttd.h"
#include "../../variables.h"
#include "../../debug.h"
#include "../../gfx_func.h"
#include "../../fileio_func.h"
#include "../../blitter/factory.hpp"
#include "splash.h"
#ifdef WITH_PNG
#include <png.h>
static void PNGAPI png_my_error(png_structp png_ptr, png_const_charp message)
{
DEBUG(misc, 0, "[libpng] error: %s - %s", message, (char *)png_get_error_ptr(png_ptr));
longjmp(png_ptr->jmpbuf, 1);
}
static void PNGAPI png_my_warning(png_structp png_ptr, png_const_charp message)
{
DEBUG(misc, 1, "[libpng] warning: %s - %s", message, (char *)png_get_error_ptr(png_ptr));
}
void DisplaySplashImage()
{
png_byte header[8];
FILE *f;
png_structp png_ptr;
png_infop info_ptr, end_info;
uint width, height, bit_depth, color_type;
png_colorp palette;
int num_palette;
png_bytep *row_pointers;
uint8 *src;
uint y;
uint xoff, yoff;
int i;
f = FioFOpenFile(SPLASH_IMAGE_FILE);
if (f == NULL) return;
fread(header, 1, 8, f);
if (png_sig_cmp(header, 0, 8) != 0) {
fclose(f);
return;
}
png_ptr = png_create_read_struct (PNG_LIBPNG_VER_STRING, (png_voidp) NULL, png_my_error, png_my_warning);
if (png_ptr == NULL) {
fclose(f);
return;
}
info_ptr = png_create_info_struct(png_ptr);
if (info_ptr == NULL) {
png_destroy_read_struct(&png_ptr, (png_infopp)NULL, (png_infopp)NULL);
fclose(f);
return;
}
end_info = png_create_info_struct(png_ptr);
if (end_info == NULL) {
png_destroy_read_struct(&png_ptr, &info_ptr, (png_infopp)NULL);
fclose(f);
return;
}
if (setjmp(png_jmpbuf(png_ptr))) {
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
fclose(f);
return;
}
png_init_io(png_ptr, f);
png_set_sig_bytes(png_ptr, 8);
png_read_png(png_ptr, info_ptr, PNG_TRANSFORM_IDENTITY, NULL);
width = png_get_image_width(png_ptr, info_ptr);
height = png_get_image_height(png_ptr, info_ptr);
bit_depth = png_get_bit_depth(png_ptr, info_ptr);
color_type = png_get_color_type(png_ptr, info_ptr);
if (color_type != PNG_COLOR_TYPE_PALETTE || bit_depth != 8) {
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
fclose(f);
return;
}
if (!png_get_valid(png_ptr, info_ptr, PNG_INFO_PLTE)) {
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
fclose(f);
return;
}
png_get_PLTE(png_ptr, info_ptr, &palette, &num_palette);
row_pointers = png_get_rows(png_ptr, info_ptr);
if (width > (uint) _screen.width) width = _screen.width;
if (height > (uint) _screen.height) height = _screen.height;
xoff = (_screen.width - width) / 2;
yoff = (_screen.height - height) / 2;
switch (BlitterFactoryBase::GetCurrentBlitter()->GetScreenDepth()) {
case 8: {
uint8 *dst;
memset(_screen.dst_ptr, 0xff, _screen.pitch * _screen.height);
for (y = 0; y < height; y++) {
src = row_pointers[y];
dst = ((uint8 *) _screen.dst_ptr) + (yoff + y) * _screen.pitch + xoff;
memcpy(dst, src, width);
}
for (i = 0; i < num_palette; i++) {
_cur_palette[i].a = i == 0 ? 0 : 0xff;
_cur_palette[i].r = palette[i].red;
_cur_palette[i].g = palette[i].green;
_cur_palette[i].b = palette[i].blue;
}
_cur_palette[0xff].a = 0xff;
_cur_palette[0xff].r = 0;
_cur_palette[0xff].g = 0;
_cur_palette[0xff].b = 0;
_pal_first_dirty = 0;
_pal_count_dirty = 256;
}
break;
case 32: {
uint32 *dst;
uint x;
memset(_screen.dst_ptr, 0xff000000, _screen.pitch * _screen.height * 4);
for (y = 0; y < height; y++) {
src = row_pointers[y];
dst = ((uint32 *) _screen.dst_ptr) + (yoff + y) * _screen.pitch + xoff;
for (x = 0; x < width; x++)
dst[x] = palette[src[x]].blue | (palette[src[x]].green << 8) | (palette[src[x]].red << 16) | 0xff000000;
}
}
break;
}
png_destroy_read_struct(&png_ptr, &info_ptr, &end_info);
fclose(f);
return;
}
#else /* WITH_PNG */
void DisplaySplashImage() {}
#endif /* WITH_PNG */
| 4,049
|
C++
|
.cpp
| 130
| 28.061538
| 110
| 0.631348
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
1,539,318
|
win32_m.cpp
|
EnergeticBark_OpenTTD-3DS/src/music/win32_m.cpp
|
/* $Id$ */
/** @file win32_m.cpp Music playback for Windows. */
#include "../stdafx.h"
#include "win32_m.h"
#include <windows.h>
#include <mmsystem.h>
static struct {
bool stop_song;
bool terminate;
bool playing;
int new_vol;
HANDLE wait_obj;
HANDLE thread;
UINT_PTR devid;
char start_song[MAX_PATH];
} _midi;
static FMusicDriver_Win32 iFMusicDriver_Win32;
void MusicDriver_Win32::PlaySong(const char *filename)
{
assert(filename != NULL);
strcpy(_midi.start_song, filename);
_midi.playing = true;
_midi.stop_song = false;
SetEvent(_midi.wait_obj);
}
void MusicDriver_Win32::StopSong()
{
if (_midi.playing) {
_midi.stop_song = true;
_midi.start_song[0] = '\0';
SetEvent(_midi.wait_obj);
}
}
bool MusicDriver_Win32::IsSongPlaying()
{
return _midi.playing;
}
void MusicDriver_Win32::SetVolume(byte vol)
{
_midi.new_vol = vol;
SetEvent(_midi.wait_obj);
}
static MCIERROR CDECL MidiSendCommand(const TCHAR *cmd, ...)
{
va_list va;
TCHAR buf[512];
va_start(va, cmd);
_vsntprintf(buf, lengthof(buf), cmd, va);
va_end(va);
return mciSendString(buf, NULL, 0, 0);
}
static bool MidiIntPlaySong(const char *filename)
{
MidiSendCommand(_T("close all"));
if (MidiSendCommand(_T("open \"%s\" type sequencer alias song"), OTTD2FS(filename)) != 0) {
/* Let's try the "short name" */
TCHAR buf[MAX_PATH];
if (GetShortPathName(OTTD2FS(filename), buf, MAX_PATH) == 0) return false;
if (MidiSendCommand(_T("open \"%s\" type sequencer alias song"), buf) != 0) return false;
}
return MidiSendCommand(_T("play song from 0")) == 0;
}
static void MidiIntStopSong()
{
MidiSendCommand(_T("close all"));
}
static void MidiIntSetVolume(int vol)
{
DWORD v = (vol * 65535 / 127);
midiOutSetVolume((HMIDIOUT)_midi.devid, v + (v << 16));
}
static bool MidiIntIsSongPlaying()
{
char buf[16];
mciSendStringA("status song mode", buf, sizeof(buf), 0);
return strcmp(buf, "playing") == 0 || strcmp(buf, "seeking") == 0;
}
static DWORD WINAPI MidiThread(LPVOID arg)
{
do {
char *s;
int vol;
vol = _midi.new_vol;
if (vol != -1) {
_midi.new_vol = -1;
MidiIntSetVolume(vol);
}
s = _midi.start_song;
if (s[0] != '\0') {
_midi.playing = MidiIntPlaySong(s);
s[0] = '\0';
/* Delay somewhat in case we don't manage to play. */
if (!_midi.playing) WaitForMultipleObjects(1, &_midi.wait_obj, FALSE, 5000);
}
if (_midi.stop_song && _midi.playing) {
_midi.stop_song = false;
_midi.playing = false;
MidiIntStopSong();
}
if (_midi.playing && !MidiIntIsSongPlaying()) _midi.playing = false;
WaitForMultipleObjects(1, &_midi.wait_obj, FALSE, 1000);
} while (!_midi.terminate);
MidiIntStopSong();
return 0;
}
const char *MusicDriver_Win32::Start(const char * const *parm)
{
MIDIOUTCAPS midicaps;
UINT nbdev;
UINT_PTR dev;
char buf[16];
mciSendStringA("capability sequencer has audio", buf, lengthof(buf), 0);
if (strcmp(buf, "true") != 0) return "MCI sequencer can't play audio";
memset(&_midi, 0, sizeof(_midi));
_midi.new_vol = -1;
/* Get midi device */
_midi.devid = MIDI_MAPPER;
for (dev = 0, nbdev = midiOutGetNumDevs(); dev < nbdev; dev++) {
if (midiOutGetDevCaps(dev, &midicaps, sizeof(midicaps)) == 0 && (midicaps.dwSupport & MIDICAPS_VOLUME)) {
_midi.devid = dev;
break;
}
}
if (NULL == (_midi.wait_obj = CreateEvent(NULL, FALSE, FALSE, NULL))) return "Failed to create event";
/* The lpThreadId parameter of CreateThread (the last parameter)
* may NOT be NULL on Windows 95, 98 and ME. */
DWORD threadId;
if (NULL == (_midi.thread = CreateThread(NULL, 8192, MidiThread, 0, 0, &threadId))) return "Failed to create thread";
return NULL;
}
void MusicDriver_Win32::Stop()
{
_midi.terminate = true;
SetEvent(_midi.wait_obj);
WaitForMultipleObjects(1, &_midi.thread, true, INFINITE);
CloseHandle(_midi.wait_obj);
CloseHandle(_midi.thread);
}
| 3,861
|
C++
|
.cpp
| 138
| 25.753623
| 118
| 0.69385
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
1,539,319
|
extmidi.cpp
|
EnergeticBark_OpenTTD-3DS/src/music/extmidi.cpp
|
/* $Id$ */
/** @file extmidi.cpp Playing music via an external player. */
#ifndef __MORPHOS__
#include "../stdafx.h"
#include "../debug.h"
#include "extmidi.h"
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <signal.h>
#include <sys/stat.h>
#include <errno.h>
#ifndef EXTERNAL_PLAYER
#define EXTERNAL_PLAYER "timidity"
#endif
static FMusicDriver_ExtMidi iFMusicDriver_ExtMidi;
const char *MusicDriver_ExtMidi::Start(const char * const * parm)
{
const char *command = GetDriverParam(parm, "cmd");
if (StrEmpty(command)) command = EXTERNAL_PLAYER;
this->command = strdup(command);
this->song[0] = '\0';
this->pid = -1;
return NULL;
}
void MusicDriver_ExtMidi::Stop()
{
free(command);
this->song[0] = '\0';
this->DoStop();
}
void MusicDriver_ExtMidi::PlaySong(const char *filename)
{
strecpy(this->song, filename, lastof(this->song));
this->DoStop();
}
void MusicDriver_ExtMidi::StopSong()
{
this->song[0] = '\0';
this->DoStop();
}
bool MusicDriver_ExtMidi::IsSongPlaying()
{
#ifndef N3DS
if (this->pid != -1 && waitpid(this->pid, NULL, WNOHANG) == this->pid)
this->pid = -1;
if (this->pid == -1 && this->song[0] != '\0') this->DoPlay();
return this->pid != -1;
#endif
}
void MusicDriver_ExtMidi::SetVolume(byte vol)
{
DEBUG(driver, 1, "extmidi: set volume not implemented");
}
void MusicDriver_ExtMidi::DoPlay()
{
#ifndef N3DS
this->pid = fork();
switch (this->pid) {
case 0: {
int d;
close(0);
d = open("/dev/null", O_RDONLY);
if (d != -1 && dup2(d, 1) != -1 && dup2(d, 2) != -1) {
#if defined(MIDI_ARG)
execlp(this->command, "extmidi", MIDI_ARG, this->song, (char*)0);
#else
execlp(this->command, "extmidi", this->song, (char*)0);
#endif
}
_exit(1);
}
case -1:
DEBUG(driver, 0, "extmidi: couldn't fork: %s", strerror(errno));
/* FALLTHROUGH */
default:
this->song[0] = '\0';
break;
}
#endif
}
void MusicDriver_ExtMidi::DoStop()
{
if (this->pid != -1) kill(this->pid, SIGTERM);
}
#endif /* __MORPHOS__ */
| 2,053
|
C++
|
.cpp
| 87
| 21.402299
| 71
| 0.657773
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
1,539,320
|
null_m.cpp
|
EnergeticBark_OpenTTD-3DS/src/music/null_m.cpp
|
/* $Id$ */
/** @file null_m.cpp The music playback that is silent. */
#include "../stdafx.h"
#include "null_m.h"
static FMusicDriver_Null iFMusicDriver_Null;
| 162
|
C++
|
.cpp
| 5
| 30.6
| 58
| 0.705882
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| true
| false
| true
| true
| true
| false
|
1,539,321
|
allegro_m.cpp
|
EnergeticBark_OpenTTD-3DS/src/music/allegro_m.cpp
|
/* $Id$ */
/** @file allegro_m.cpp Playing music via allegro. */
#ifdef WITH_ALLEGRO
#include "../stdafx.h"
#include "../debug.h"
#include "allegro_m.h"
#include <allegro.h>
static FMusicDriver_Allegro iFMusicDriver_Allegro;
static MIDI *_midi = NULL;
/** There are multiple modules that might be using Allegro and
* Allegro can only be initiated once. */
extern int _allegro_instance_count;
const char *MusicDriver_Allegro::Start(const char * const *param)
{
if (_allegro_instance_count == 0 && install_allegro(SYSTEM_AUTODETECT, &errno, NULL)) return NULL;
_allegro_instance_count++;
/* Initialise the sound */
if (install_sound(DIGI_AUTODETECT, MIDI_AUTODETECT, NULL) != 0) return NULL;
/* Okay, there's no soundcard */
if (midi_card == MIDI_NONE) {
DEBUG(driver, 0, "allegro: no midi card found");
}
return NULL;
}
void MusicDriver_Allegro::Stop()
{
if (_midi != NULL) destroy_midi(_midi);
_midi = NULL;
if (--_allegro_instance_count == 0) allegro_exit();
}
void MusicDriver_Allegro::PlaySong(const char *filename)
{
if (_midi != NULL) destroy_midi(_midi);
_midi = load_midi(filename);
play_midi(_midi, false);
}
void MusicDriver_Allegro::StopSong()
{
stop_midi();
}
bool MusicDriver_Allegro::IsSongPlaying()
{
return midi_pos >= 0;
}
void MusicDriver_Allegro::SetVolume(byte vol)
{
set_volume(-1, vol);
}
#endif /* WITH_ALLEGRO */
| 1,372
|
C++
|
.cpp
| 49
| 26.265306
| 99
| 0.719204
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
1,539,322
|
qtmidi.cpp
|
EnergeticBark_OpenTTD-3DS/src/music/qtmidi.cpp
|
/* $Id$ */
/**
* @file qtmidi.cpp
* @brief MIDI music player for MacOS X using QuickTime.
*
* This music player should work in all MacOS X releases starting from 10.0,
* as QuickTime is an integral part of the system since the old days of the
* Motorola 68k-based Macintoshes. The only extra dependency apart from
* QuickTime itself is Carbon, which is included since 10.0 as well.
*
* QuickTime gets fooled with the MIDI files from Transport Tycoon Deluxe
* because of the @c .gm suffix. To force QuickTime to load the MIDI files
* without the need of dealing with the individual QuickTime components
* needed to play music (data source, MIDI parser, note allocators,
* synthesizers and the like) some Carbon functions are used to set the file
* type as seen by QuickTime, using @c FSpSetFInfo() (which modifies the
* file's resource fork).
*/
#define MAC_OS_X_VERSION_MIN_REQUIRED MAC_OS_X_VERSION_10_3
#include <AvailabilityMacros.h>
/*
* OpenTTD includes.
*/
#define WindowClass OSX_WindowClass
#include <QuickTime/QuickTime.h>
#undef WindowClass
#include "../stdafx.h"
#include "qtmidi.h"
/*
* System includes. We need to workaround with some defines because there's
* stuff already defined in QuickTime headers.
*/
#define OTTD_Random OSX_OTTD_Random
#undef OTTD_Random
#undef WindowClass
#undef SL_ERROR
#undef bool
#include <assert.h>
#include <unistd.h>
#include <fcntl.h>
/* we need to include debug.h after CoreServices because defining DEBUG will break CoreServices in OSX 10.2 */
#include "../debug.h"
static FMusicDriver_QtMidi iFMusicDriver_QtMidi;
enum {
midiType = 'Midi' ///< OSType code for MIDI songs.
};
/**
* Sets the @c OSType of a given file to @c 'Midi', but only if it's not
* already set.
*
* @param *spec A @c FSSpec structure referencing a file.
*/
static void SetMIDITypeIfNeeded(const FSRef *ref)
{
FSCatalogInfo catalogInfo;
assert(ref);
if (noErr != FSGetCatalogInfo(ref, kFSCatInfoNodeFlags | kFSCatInfoFinderInfo, &catalogInfo, NULL, NULL, NULL)) return;
if (!(catalogInfo.nodeFlags & kFSNodeIsDirectoryMask)) {
FileInfo * const info = (FileInfo *) catalogInfo.finderInfo;
if (info->fileType != midiType && !(info->finderFlags & kIsAlias)) {
OSErr e;
info->fileType = midiType;
e = FSSetCatalogInfo(ref, kFSCatInfoFinderInfo, &catalogInfo);
if (e == noErr) {
DEBUG(driver, 3, "qtmidi: changed filetype to 'Midi'");
} else {
DEBUG(driver, 0, "qtmidi: changing filetype to 'Midi' failed - error %d", e);
}
}
}
}
/**
* Loads a MIDI file and returns it as a QuickTime Movie structure.
*
* @param *path String with the path of an existing MIDI file.
* @param *moov Pointer to a @c Movie where the result will be stored.
* @return Wether the file was loaded and the @c Movie successfully created.
*/
static bool LoadMovieForMIDIFile(const char *path, Movie *moov)
{
int fd;
int ret;
char magic[4];
FSRef fsref;
FSSpec fsspec;
short refnum = 0;
short resid = 0;
assert(path != NULL);
assert(moov != NULL);
DEBUG(driver, 2, "qtmidi: start loading '%s'...", path);
/*
* XXX Manual check for MIDI header ('MThd'), as I don't know how to make
* QuickTime load MIDI files without a .mid suffix without knowing it's
* a MIDI file and setting the OSType of the file to the 'Midi' value.
* Perhahaps ugly, but it seems that it does the Right Thing(tm).
*/
fd = open(path, O_RDONLY, 0);
if (fd == -1) return false;
ret = read(fd, magic, 4);
close(fd);
if (ret < 4) return false;
DEBUG(driver, 3, "qtmidi: header is '%.4s'", magic);
if (magic[0] != 'M' || magic[1] != 'T' || magic[2] != 'h' || magic[3] != 'd')
return false;
if (noErr != FSPathMakeRef((const UInt8 *) path, &fsref, NULL)) return false;
SetMIDITypeIfNeeded(&fsref);
if (noErr != FSGetCatalogInfo(&fsref, kFSCatInfoNone, NULL, NULL, &fsspec, NULL)) return false;
if (OpenMovieFile(&fsspec, &refnum, fsRdPerm) != noErr) return false;
DEBUG(driver, 3, "qtmidi: '%s' successfully opened", path);
if (noErr != NewMovieFromFile(moov, refnum, &resid, NULL,
newMovieActive | newMovieDontAskUnresolvedDataRefs, NULL)) {
CloseMovieFile(refnum);
return false;
}
DEBUG(driver, 3, "qtmidi: movie container created");
CloseMovieFile(refnum);
return true;
}
/**
* Flag which has the @c true value when QuickTime is available and
* initialized.
*/
static bool _quicktime_started = false;
/**
* Initialize QuickTime if needed. This function sets the
* #_quicktime_started flag to @c true if QuickTime is present in the system
* and it was initialized properly.
*/
static void InitQuickTimeIfNeeded()
{
OSStatus dummy;
if (_quicktime_started) return;
DEBUG(driver, 2, "qtmidi: initializing Quicktime");
/* Be polite: check wether QuickTime is available and initialize it. */
_quicktime_started =
(noErr == Gestalt(gestaltQuickTime, &dummy)) &&
(noErr == EnterMovies());
if (!_quicktime_started) DEBUG(driver, 0, "qtmidi: Quicktime initialization failed!");
}
/** Possible states of the QuickTime music driver. */
enum {
QT_STATE_IDLE, ///< No file loaded.
QT_STATE_PLAY, ///< File loaded, playing.
QT_STATE_STOP, ///< File loaded, stopped.
};
static Movie _quicktime_movie; ///< Current QuickTime @c Movie.
static byte _quicktime_volume = 127; ///< Current volume.
static int _quicktime_state = QT_STATE_IDLE; ///< Current player state.
/**
* Maps OpenTTD volume to QuickTime notion of volume.
*/
#define VOLUME ((short)((0x00FF & _quicktime_volume) << 1))
/**
* Initialized the MIDI player, including QuickTime initialization.
*
* @todo Give better error messages by inspecting error codes returned by
* @c Gestalt() and @c EnterMovies(). Needs changes in
* #InitQuickTimeIfNeeded.
*/
const char *MusicDriver_QtMidi::Start(const char * const *parm)
{
InitQuickTimeIfNeeded();
return (_quicktime_started) ? NULL : "can't initialize QuickTime";
}
/**
* Checks wether the player is active.
*
* This function is called at regular intervals from OpenTTD's main loop, so
* we call @c MoviesTask() from here to let QuickTime do its work.
*/
bool MusicDriver_QtMidi::IsSongPlaying()
{
if (!_quicktime_started) return true;
switch (_quicktime_state) {
case QT_STATE_IDLE:
case QT_STATE_STOP:
/* Do nothing. */
break;
case QT_STATE_PLAY:
MoviesTask(_quicktime_movie, 0);
/* Check wether movie ended. */
if (IsMovieDone(_quicktime_movie) ||
(GetMovieTime(_quicktime_movie, NULL) >=
GetMovieDuration(_quicktime_movie)))
_quicktime_state = QT_STATE_STOP;
}
return _quicktime_state == QT_STATE_PLAY;
}
/**
* Stops the MIDI player.
*
* Stops playing and frees any used resources before returning. As it
* deinitilizes QuickTime, the #_quicktime_started flag is set to @c false.
*/
void MusicDriver_QtMidi::Stop()
{
if (!_quicktime_started) return;
DEBUG(driver, 2, "qtmidi: stopping driver...");
switch (_quicktime_state) {
case QT_STATE_IDLE:
DEBUG(driver, 3, "qtmidi: stopping not needed, already idle");
/* Do nothing. */
break;
case QT_STATE_PLAY:
StopSong();
case QT_STATE_STOP:
DisposeMovie(_quicktime_movie);
}
ExitMovies();
_quicktime_started = false;
}
/**
* Starts playing a new song.
*
* @param filename Path to a MIDI file.
*/
void MusicDriver_QtMidi::PlaySong(const char *filename)
{
if (!_quicktime_started) return;
DEBUG(driver, 2, "qtmidi: trying to play '%s'", filename);
switch (_quicktime_state) {
case QT_STATE_PLAY:
StopSong();
DEBUG(driver, 3, "qtmidi: previous tune stopped");
/* XXX Fall-through -- no break needed. */
case QT_STATE_STOP:
DisposeMovie(_quicktime_movie);
DEBUG(driver, 3, "qtmidi: previous tune disposed");
_quicktime_state = QT_STATE_IDLE;
/* XXX Fall-through -- no break needed. */
case QT_STATE_IDLE:
LoadMovieForMIDIFile(filename, &_quicktime_movie);
SetMovieVolume(_quicktime_movie, VOLUME);
StartMovie(_quicktime_movie);
_quicktime_state = QT_STATE_PLAY;
}
DEBUG(driver, 3, "qtmidi: playing '%s'", filename);
}
/**
* Stops playing the current song, if the player is active.
*/
void MusicDriver_QtMidi::StopSong()
{
if (!_quicktime_started) return;
switch (_quicktime_state) {
case QT_STATE_IDLE:
/* XXX Fall-through -- no break needed. */
case QT_STATE_STOP:
DEBUG(driver, 3, "qtmidi: stop requested, but already idle");
/* Do nothing. */
break;
case QT_STATE_PLAY:
StopMovie(_quicktime_movie);
_quicktime_state = QT_STATE_STOP;
DEBUG(driver, 3, "qtmidi: player stopped");
}
}
/**
* Changes the playing volume of the MIDI player.
*
* As QuickTime controls volume in a per-movie basis, the desired volume is
* stored in #_quicktime_volume, and the volume is set here using the
* #VOLUME macro, @b and when loading new song in #PlaySong.
*
* @param vol The desired volume, range of the value is @c 0-127
*/
void MusicDriver_QtMidi::SetVolume(byte vol)
{
if (!_quicktime_started) return;
_quicktime_volume = vol;
DEBUG(driver, 2, "qtmidi: set volume to %u (%hi)", vol, VOLUME);
switch (_quicktime_state) {
case QT_STATE_IDLE:
/* Do nothing. */
break;
case QT_STATE_PLAY:
case QT_STATE_STOP:
SetMovieVolume(_quicktime_movie, VOLUME);
}
}
| 9,271
|
C++
|
.cpp
| 280
| 30.714286
| 120
| 0.713982
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
1,539,323
|
bemidi.cpp
|
EnergeticBark_OpenTTD-3DS/src/music/bemidi.cpp
|
/* $Id$ */
/** @file bemidi.cpp Support for BeOS midi. */
#include "../stdafx.h"
#include "../openttd.h"
#include "bemidi.h"
/* BeOS System Includes */
#include <MidiSynthFile.h>
static BMidiSynthFile midiSynthFile;
static FMusicDriver_BeMidi iFMusicDriver_BeMidi;
const char *MusicDriver_BeMidi::Start(const char * const *parm)
{
return NULL;
}
void MusicDriver_BeMidi::Stop()
{
midiSynthFile.UnloadFile();
}
void MusicDriver_BeMidi::PlaySong(const char *filename)
{
bemidi_stop();
entry_ref midiRef;
get_ref_for_path(filename, &midiRef);
midiSynthFile.LoadFile(&midiRef);
midiSynthFile.Start();
}
void MusicDriver_BeMidi::StopSong()
{
midiSynthFile.UnloadFile();
}
bool MusicDriver_BeMidi::IsSongPlaying()
{
return !midiSynthFile.IsFinished();
}
void MusicDriver_BeMidi::SetVolume(byte vol)
{
fprintf(stderr, "BeMidi: Set volume not implemented\n");
}
| 875
|
C++
|
.cpp
| 37
| 22.081081
| 63
| 0.771463
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
1,539,324
|
dmusic.cpp
|
EnergeticBark_OpenTTD-3DS/src/music/dmusic.cpp
|
/* $Id$ */
/** @file dmusic.cpp Playing music via DirectMusic. */
#ifdef WIN32_ENABLE_DIRECTMUSIC_SUPPORT
#include "../stdafx.h"
#ifdef WIN32_LEAN_AND_MEAN
#undef WIN32_LEAN_AND_MEAN // Don't exclude rarely-used stuff from Windows headers
#endif
#include "../debug.h"
#include "../win32.h"
#include "dmusic.h"
#include <windows.h>
#include <dmksctrl.h>
#include <dmusici.h>
#include <dmusicc.h>
#include <dmusicf.h>
static FMusicDriver_DMusic iFMusicDriver_DMusic;
/** the performance object controls manipulation of the segments */
static IDirectMusicPerformance *performance = NULL;
/** the loader object can load many types of DMusic related files */
static IDirectMusicLoader *loader = NULL;
/** the segment object is where the MIDI data is stored for playback */
static IDirectMusicSegment *segment = NULL;
static bool seeking = false;
#define M(x) x "\0"
static const char ole_files[] =
M("ole32.dll")
M("CoCreateInstance")
M("CoInitialize")
M("CoUninitialize")
M("")
;
#undef M
struct ProcPtrs {
unsigned long (WINAPI * CoCreateInstance)(REFCLSID rclsid, LPUNKNOWN pUnkOuter, DWORD dwClsContext, REFIID riid, LPVOID *ppv);
HRESULT (WINAPI * CoInitialize)(LPVOID pvReserved);
void (WINAPI * CoUninitialize)();
};
static ProcPtrs proc;
const char *MusicDriver_DMusic::Start(const char * const *parm)
{
if (performance != NULL) return NULL;
if (proc.CoCreateInstance == NULL) {
if (!LoadLibraryList((Function*)&proc, ole_files))
return "ole32.dll load failed";
}
/* Initialize COM */
if (FAILED(proc.CoInitialize(NULL))) {
return "COM initialization failed";
}
/* create the performance object */
if (FAILED(proc.CoCreateInstance(
CLSID_DirectMusicPerformance,
NULL,
CLSCTX_INPROC,
IID_IDirectMusicPerformance,
(LPVOID*)&performance
))) {
proc.CoUninitialize();
return "Failed to create the performance object";
}
/* initialize it */
if (FAILED(performance->Init(NULL, NULL, NULL))) {
performance->Release();
performance = NULL;
proc.CoUninitialize();
return "Failed to initialize performance object";
}
/* choose default Windows synth */
if (FAILED(performance->AddPort(NULL))) {
performance->CloseDown();
performance->Release();
performance = NULL;
proc.CoUninitialize();
return "AddPort failed";
}
/* create the loader object; this will be used to load the MIDI file */
if (FAILED(proc.CoCreateInstance(
CLSID_DirectMusicLoader,
NULL,
CLSCTX_INPROC,
IID_IDirectMusicLoader,
(LPVOID*)&loader
))) {
performance->CloseDown();
performance->Release();
performance = NULL;
proc.CoUninitialize();
return "Failed to create loader object";
}
return NULL;
}
void MusicDriver_DMusic::Stop()
{
seeking = false;
if (performance != NULL) performance->Stop(NULL, NULL, 0, 0);
if (segment != NULL) {
segment->SetParam(GUID_Unload, 0xFFFFFFFF, 0, 0, performance);
segment->Release();
segment = NULL;
}
if (performance != NULL) {
performance->CloseDown();
performance->Release();
performance = NULL;
}
if (loader != NULL) {
loader->Release();
loader = NULL;
}
proc.CoUninitialize();
}
void MusicDriver_DMusic::PlaySong(const char *filename)
{
/* set up the loader object info */
DMUS_OBJECTDESC obj_desc;
ZeroMemory(&obj_desc, sizeof(obj_desc));
obj_desc.dwSize = sizeof(obj_desc);
obj_desc.guidClass = CLSID_DirectMusicSegment;
obj_desc.dwValidData = DMUS_OBJ_CLASS | DMUS_OBJ_FILENAME | DMUS_OBJ_FULLPATH;
MultiByteToWideChar(
CP_ACP, MB_PRECOMPOSED,
filename, -1,
obj_desc.wszFileName, lengthof(obj_desc.wszFileName)
);
/* release the existing segment if we have any */
if (segment != NULL) {
segment->Release();
segment = NULL;
}
/* make a new segment */
if (FAILED(loader->GetObject(
&obj_desc, IID_IDirectMusicSegment, (LPVOID*)&segment
))) {
DEBUG(driver, 0, "DirectMusic: GetObject failed");
return;
}
/* tell the segment what kind of data it contains */
if (FAILED(segment->SetParam(
GUID_StandardMIDIFile, 0xFFFFFFFF, 0, 0, performance
))) {
DEBUG(driver, 0, "DirectMusic: SetParam (MIDI file) failed");
return;
}
/* tell the segment to 'download' the instruments */
if (FAILED(segment->SetParam(GUID_Download, 0xFFFFFFFF, 0, 0, performance))) {
DEBUG(driver, 0, "DirectMusic: failed to download instruments");
return;
}
/* start playing the MIDI file */
if (FAILED(performance->PlaySegment(segment, 0, 0, NULL))) {
DEBUG(driver, 0, "DirectMusic: PlaySegment failed");
return;
}
seeking = true;
}
void MusicDriver_DMusic::StopSong()
{
if (FAILED(performance->Stop(segment, NULL, 0, 0))) {
DEBUG(driver, 0, "DirectMusic: StopSegment failed");
}
seeking = false;
}
bool MusicDriver_DMusic::IsSongPlaying()
{
/* Not the nicest code, but there is a short delay before playing actually
* starts. OpenTTD makes no provision for this. */
if (performance->IsPlaying(segment, NULL) == S_OK) {
seeking = false;
return true;
} else {
return seeking;
}
}
void MusicDriver_DMusic::SetVolume(byte vol)
{
long db = vol * 2000 / 127 - 2000; ///< 0 - 127 -> -2000 - 0
performance->SetGlobalParam(GUID_PerfMasterVolume, &db, sizeof(db));
}
#endif /* WIN32_ENABLE_DIRECTMUSIC_SUPPORT */
| 5,233
|
C++
|
.cpp
| 179
| 26.748603
| 127
| 0.724895
|
EnergeticBark/OpenTTD-3DS
| 34
| 1
| 4
|
GPL-2.0
|
9/20/2024, 10:44:59 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| true
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.