Compare commits

...

189 Commits

Author SHA1 Message Date
Jonathan G Rennison 2b539a2d37 Fix water infrastructure total when changing owner of object on water 3 days ago
Jonathan G Rennison 1e9fb74451 Merge branch 'master' into jgrpp
# Conflicts:
#	.github/workflows/release-windows.yml
#	src/autoreplace_gui.cpp
#	src/cargotype.cpp
#	src/company_base.h
#	src/company_cmd.cpp
#	src/company_gui.cpp
#	src/currency.h
#	src/date_gui.cpp
#	src/dropdown.cpp
#	src/dropdown_func.h
#	src/dropdown_type.h
#	src/game/game_gui.cpp
#	src/genworld.cpp
#	src/genworld_gui.cpp
#	src/ground_vehicle.hpp
#	src/group_gui.cpp
#	src/house.h
#	src/industry_gui.cpp
#	src/network/network_client.cpp
#	src/network/network_server.cpp
#	src/network/network_type.h
#	src/newgrf_class_func.h
#	src/newgrf_house.cpp
#	src/newgrf_roadstop.h
#	src/openttd.cpp
#	src/order_gui.cpp
#	src/saveload/saveload.cpp
#	src/saveload/saveload.h
#	src/screenshot_gui.cpp
#	src/settings_gui.cpp
#	src/settings_type.h
#	src/slider.cpp
#	src/smallmap_gui.cpp
#	src/station_cmd.cpp
#	src/stdafx.h
#	src/survey.cpp
#	src/tile_map.h
#	src/town_cmd.cpp
#	src/town_gui.cpp
#	src/vehicle.cpp
#	src/vehicle_gui.cpp
#	src/vehicle_gui_base.h
3 days ago
Jonathan G Rennison cbea3b8b46 Add console command to merge two companies 3 days ago
Jonathan G Rennison f2f8692fb2 Add setting to allow track editing to ignore realistic braking restrictions 3 days ago
Jonathan G Rennison 7874fb7a12 Add public key auth support for settings_access console command 4 days ago
Jonathan G Rennison 84a0dd326f Merge branch 'master' into jgrpp
# Conflicts:
#	src/console_cmds.cpp
#	src/network/core/config.h
#	src/network/core/packet.h
#	src/network/core/tcp.cpp
#	src/network/core/tcp_game.cpp
#	src/network/core/tcp_game.h
#	src/network/network_client.cpp
#	src/network/network_client.h
#	src/network/network_gui.h
#	src/network/network_server.cpp
#	src/network/network_server.h
#	src/table/settings/network_secrets_settings.ini
4 days ago
Jonathan G Rennison effaf6acc4 Allow removing reservation boundary signal in realistic braking
All other operations were permitted so only disallowing removal
was not useful and could be trivially bypassed
6 days ago
Jonathan G Rennison 431a6a1262 Allow sorting by average order occupancy in shared order group mode
See: #698
6 days ago
Jonathan G Rennison d39bdd352b Merge PR #700 into jgrpp 6 days ago
pvillaverde dc465000f7 🌐 Update Galician Translations 2024-05-26 6 days ago
Jonathan G Rennison 1d70c781c6 Fix vehicle window showing profit last year in wallclock timekeeping mode 1 week ago
Qwest8K 6dfe5c4da9
Update: Russian translation (#695)
Russian localization update
1 week ago
Jonathan G Rennison a8d830aa3e Fix signal side when using both sides signal style with no-entry signals 1 week ago
Jonathan G Rennison a24d72f0d7 Fix flag values in CustomSignalSpriteContextFlags 1 week ago
Jonathan G Rennison 8907b9aa31 Reduce diff with upstream for console command functionality 2 weeks ago
Jonathan G Rennison 88d7be1d99 Change FormatArrayAsHex to be uppercase by default
To match upstream
2 weeks ago
Jonathan G Rennison 48910a8b7d Version: Committing version data for tag: jgrpp-0.59.1 2 weeks ago
Jonathan G Rennison 5e971bfc02 Fix abstract filetype not being set for network client join savegames 2 weeks ago
Jonathan G Rennison fc5b3b90b4 Remove incorrect assertion as temporary fix for #692
See: https://github.com/OpenTTD/OpenTTD/issues/12651
2 weeks ago
Rubidium 1d13ac7280 Fix #12655, 4f6d75f: inconsistent state in client list and potential crash after client leaves
(cherry picked from commit f939e81bf0)
2 weeks ago
Peter Nelson f62eb72fcb Fix #12685: nullptr dereference when checking for equal loaded/loading groups. (#12686)
Always treat empty groups as non-equal. Given that the case of both being empty is handled earlier, they cannot both be equal and empty.

Additionally if a loaded or loading set are all the same, only add one reference.

(cherry picked from commit 856ec901ca)
2 weeks ago
Jonathan G Rennison 3df3ed6690 Reduce frequency of brake overheating breakdowns
Decay overheat state more quickly
Avoid double-triggering overheating
Make overheating speed-dependent
2 weeks ago
Jonathan G Rennison 66d03530dc Adjust handling of vehicle subspeed with realistic braking
In particular when descending a steep slope with insufficient braking
2 weeks ago
Jonathan G Rennison 6d1f3b673e Fix non-percentage servicing interval when using wallclock mode 2 weeks ago
Jonathan G Rennison 89902c8ab1 Fix advisory max speed being higher than strict max for reservation end
In GetCurrentMaxSpeedInfoInternal
2 weeks ago
Jonathan G Rennison 242e87652b Fix setting display for industry cargo scaling 2 weeks ago
Jonathan G Rennison b81da24a64 Fix setting default value for industry cargo scaling mode in old saves 2 weeks ago
Jonathan G Rennison bdd1d36bd9 Fix road vehicle restart loading at same station when using implicit orders 3 weeks ago
TELK b1faf3d39f Update: Korean translation 3 weeks ago
TELK d3fc9997d1
Update: Korean translation up to 0.59.0 (#689)
* Update: Korean translation up to 0.59.0

* Update: Korean translation up to fc4ea241

* Update: Korean translation / missing ones
3 weeks ago
Peter Nelson d7f029344f Codechange: Don't delete news items or NewGRF window when EffectVehicle is deleted. (#12334)
EffectVehicles never create news and can't be debugged, so searching for news items and windows to delete just wastes time.

(cherry picked from commit 737e3feaf0)
3 weeks ago
Jonathan G Rennison fc4ea241b0 Merge branch 'master' into jgrpp 3 weeks ago
Jonathan G Rennison 6d4f616706 Fix crash when sorting by capacity in autoreplace window
Move capacity cache into GUIList sort parameter

See: #690
3 weeks ago
Jonathan G Rennison 5e24882c18 Use template specialisation for GUIList parameter reference/init behaviour 3 weeks ago
Jonathan G Rennison 18a42664fc Merge branch 'master' into jgrpp
Remove 'byte' typedef
3 weeks ago
Jonathan G Rennison f1c0f864f5 Add setting to shorten vehicle view status text 4 weeks ago
Jonathan G Rennison 0a0b42a931 Bump OpenTTD content version to 14.1 4 weeks ago
Jonathan G Rennison 3e57319c0b Fix SDL keycode to vkey mapping 4 weeks ago
Jonathan G Rennison eccffec758 Version: Committing version data for tag: jgrpp-0.59.0 4 weeks ago
Peter Nelson 6de4fa921c Change: Use standard padding for company password window.
Also use now-established OnResize pattern for setting height of password warning widget.

(cherry picked from commit 0090431e99b8301c9e3ee14fb3435075708294d5)
4 weeks ago
Jonathan G Rennison f993e30850 Take cargo refit into account in build vehicle window capacity sort modes 4 weeks ago
Jonathan G Rennison 1e5c96ef87 De-duplicate filling TestedEngineDetails in build vehicle windows 4 weeks ago
Jonathan G Rennison fe374a1db0 Allow sorting by cargo capacity/running cost in dual pane train purchase window 4 weeks ago
Jonathan G Rennison 126173a839 Fix text filter in dual-pane purchase window with GRF custom names 4 weeks ago
Jonathan G Rennison 6dab30f928 Documentation: Remove random_bits variable from road stops (NML) 4 weeks ago
Jonathan G Rennison 6ef682cf44 Documentation: Fix typo 4 weeks ago
Jonathan G Rennison a413ddfd82 Readme: Expand introduction section a bit 4 weeks ago
Jonathan G Rennison 4f7fa73140 Readme: Remove various things which have been upstreamed 4 weeks ago
Jonathan G Rennison e89a40994a Reduce diff with upstream for fileio.cpp 4 weeks ago
Peter Nelson a2bd2efec1 Codechange: Remove support for links in tar files. (#12571)
This was a feature to support the original 32bpp sprite system and is no longer relevant.

(cherry picked from commit ef55cc7979)

# Conflicts:
#	src/fileio.cpp
4 weeks ago
Loïc Guilloux 716ba5fd2a Fix #12584: Improved error handling during tar scan (#12586)
(cherry picked from commit 99b74c1064)

# Conflicts:
#	src/fileio.cpp
4 weeks ago
Peter Nelson 8769318653 Codechange: Ensure SDLK mappings stay in the expected order. (#12608)
Add a constexpr constructor that ensures at compile-time that the source SDLK range matches the target range.

(cherry picked from commit 90029beb49)

# Conflicts:
#	src/video/sdl2_v.cpp
#	src/video/sdl_v.cpp
4 weeks ago
Fen fd183914c8 Fix 2d27e8e: Update numpad keycodes for SDL2, making it usable (#12596)
* Fix 2d27e8e: Update numpad keycodes for SDL2, making it usable

* Cleanup: List sdl2 numpad mappings individually

(cherry picked from commit 2559bdfa6f)
4 weeks ago
Jonathan G Rennison f1334b9854 Documentation: Fix typo 1 month ago
Calvin Sykes 69cb68a3e2 Override remain at station behaviour for road vehicles with explicit stop direction set
(cherry picked from commit 8f8d635baf3dc1506de206a3378498bedfd020bf)

See: #686
1 month ago
Jonathan G Rennison 247b40c95b Adjust setting texts for show running costs per year setting 1 month ago
Jonathan G Rennison d90c540f9e Enable economy day length scaling in wallclock timekeeping mode 1 month ago
Jonathan G Rennison 9a07f14f56 Show running costs in calendar years by default 1 month ago
Jonathan G Rennison c5cd598217 Debug: Log number of GRFs at level sl=2 when loading a game
Add helper to get the number of non-static GRFs in a GRF config
1 month ago
Jonathan G Rennison adc7840f01 Scheduled dispatch: Caveat text for number of vehicles required 1 month ago
Jonathan G Rennison a14f850f33 Debug: Show unreachable error groups in sprite dump when show details enabled 1 month ago
Peter Nelson 96ddabb30c Codechange: Remove write-only spec_id from RoadStopSpec. (#12582)
Comment is incorrect about its value too.

(cherry picked from commit 72c55128d2)
1 month ago
Jonathan G Rennison 991b7a958e Do not reset lateness on auto-timetable congestion detection, when using scheduled dispatch 1 month ago
TELK b39bd33c1c
Update: Korean translation up to 980de73 (#688)
* Update: ko-KR / Colouring some setting

* Update: Korean translation - time

* Update: Korean translation up to 980de735
1 month ago
Jonathan G Rennison 29871e412c Fix 69e7c1697: Add missing include for MSVC 1 month ago
Jonathan G Rennison ce40e85ccc Fix ROADSTOP_DRAW_MODE_WAYP_GROUND when used with RSF_DRAW_MODE_REGISTER 1 month ago
Jonathan G Rennison 07cfa5f602 Fix documentation comment for RSF_DRAW_MODE_REGISTER 1 month ago
Jonathan G Rennison 980de7353d TBTR: Fix replacement servicing condition when using infinite money 1 month ago
Jonathan G Rennison 69e7c1697e Win32: Increase buffer size and count in wave out sound driver
Ensure that wave structs are zero-inited and buffers are freed
1 month ago
Jonathan G Rennison 3136f08b86 Debug: Fix display of engine cargo age period and reliability decay speed 1 month ago
Jonathan G Rennison 33baceaef7 Maintain timer sort invariants when changing period
See: https://github.com/OpenTTD/OpenTTD/issues/12509
1 month ago
Jonathan G Rennison 674642f9cc Add a priority field to TimerGameTick::TPeriod
Use this as the primary sort key for TimerGameTick::TPeriod,
to avoid container sort order changes on timer period saveload.
1 month ago
Jonathan G Rennison d5b8f51bf9 Rename variable to fix Windows header name collision 1 month ago
Jonathan G Rennison 71227f61d8 Use MoveFileExW to implement FioRenameFile on Windows
This is to allow renaming over an existing file
1 month ago
Jonathan G Rennison 083d91a582 Remove use of shell API function for rename 1 month ago
Peter Nelson 653e217bb1 Fix: Signature validation did not close its file. (#12479)
(cherry picked from commit 3316b27496)
1 month ago
Peter Nelson 8fdc91bd9f Fix a29766d: Wrong scrolling dropdown list position with RTL. (#12412)
(cherry picked from commit 9750826590)
1 month ago
Loïc Guilloux 54093fb8b2 Fix: [Win32] Force font mapper to only use TrueType fonts (#12406)
(cherry picked from commit 11aa3694fa)
1 month ago
Jonathan G Rennison 98dc6c3c81 Fix NewGRF byte order when using -q 1 month ago
Peter Nelson ae16df2d61 Fix #12497: Add workaround for motion_counter being implemented correctly.
#12229 stopped updating motion_counter for non-engine parts of trains, and in doing so accidentally followed the spec for NewGRF var 46, which breaks NewGRFs that used to... accidentally work.

Make var 46 return motion_counter of the first engine, regardless of self or parent scope. This means var 46 is always in sync with the head engine, and avoids further changes to when motion_counter is updated.

(cherry picked from commit 9539b02455f672e11f3ac32302a00cffa5507770)
1 month ago
Jonathan G Rennison 6056a00222 Fix incorrect train weight used for infrastructure sharing track fees 1 month ago
Jonathan G Rennison 0150f8f570 Merge branch 'master' into jgrpp
# Conflicts:
#	src/network/network_server.cpp
1 month ago
Jonathan G Rennison e17c6da46a Fix industry cargoes when loading newer vanilla savegames 1 month ago
Jonathan G Rennison d70c824056 Linkgraph: Increase effect strength of distance scaling setting
Updates: 3d049895
1 month ago
Jonathan G Rennison d52d447603 Update station/industry nearby lists in BuildOilRig
See: https://github.com/OpenTTD/OpenTTD/issues/12506
1 month ago
Jonathan G Rennison 41543498f4 Fix ships leaving dots behind in viewport map mode
Fixes: 57db9a41
2 months ago
Jonathan G Rennison 1e38e513ae Fix EnginesDailyLoop being called on new economy day instead of calendar 2 months ago
Jonathan G Rennison 0dcbcedbac Fix ScriptRail::BuildSignal when using realistic braking with block signals 2 months ago
FedelloKirfed 46d71463d9 🌐 Update Galician Translations 2024-04-14 2 months ago
Peter Nelson f79ec7955a Codechange: Explicitly reset old industry data before loading games. 2 months ago
Peter Nelson bd2a92331b Codechange: Use inline and std::array for old industry structures.
This avoids separate declaration/definition, and less C-style arrays.
2 months ago
Peter Nelson f6b38e8e06 Codechange: Remove optional MakeCargo() parameters that are never changed.
Default values are always used, so don't need to be parameters.
2 months ago
Peter Nelson e4fc8ef595 Codechange: Use std::span for industry cargo window instead of pointer + length. 2 months ago
merni-ns 6f36f3d714
Fix #11055: Make saveload failure error messages consistent with others (#12247)
The save/load error messages were combined using string parameters, rather than using the built-in functionality of error dialogs.
2 months ago
merni-ns 92a171c3e0
Doc: Improve the output and documentation of the font command. (#12392)
Now that the default font =/= sprite font, there is a different way to invoke the sprite font, and default size applies to default (not sprite).
Also, interface scaling now affects the font size.
2 months ago
Peter Nelson d68e5159e1
Feature: Allow base sounds set to be changed mid-game. (#12399) 2 months ago
translators 3d2a8fb60c Update: Translations from eints
welsh: 5 changes by Ansbaradigeidfran
ukrainian: 11 changes by StepanIvasyn
catalan: 1 change by J0anJosep
portuguese (brazilian): 69 changes by pasantoro
2 months ago
Peter Nelson d683ec0183
Codechange: Move dropdown and slider out of widgets directory. (#12403)
Also shuffle headers to place widget includes near end.

This leaves the widgets directory solely for defining Widget IDs.
2 months ago
Rubidium d5e28a904d Fix fb9d4af: use different nonces for key exchange and stream encryption 2 months ago
translators 9954187680 Update: Translations from eints
greek: 172 changes by gh658804
ukrainian: 18 changes by StepanIvasyn
portuguese (brazilian): 9 changes by pasantoro
2 months ago
Patric Stout 77f02faf15
Codefix 977aba73be: also update comment about removal of is_random (#12400) 2 months ago
translators 340c2802da Update: Translations from eints
ukrainian: 14 changes by StepanIvasyn
dutch: 3 changes by Afoklala
portuguese (brazilian): 34 changes by pasantoro
2 months ago
Patric Stout e866ca8adc
Cleanup 69d5b9d3: actually clean up all remnants of "no-thread" builds (#12398) 2 months ago
Patric Stout c0308acb03
Fix: "-q" displays NewGRF IDs in the wrong byte-order (#12397) 2 months ago
Peter Nelson 8d312b305b
Codechange: Replace currency macros with functions. (#12396) 2 months ago
translators e21c12afeb Update: Translations from eints
finnish: 39 changes by hpiirai
ukrainian: 23 changes by StepanIvasyn
danish: 1 change by bscargo
french: 1 change by Lishouuu
portuguese: 1 change by azulcosta
portuguese (brazilian): 100 changes by pasantoro
2 months ago
Peter Nelson e16b982b6a Codechange: Use iteration when dealing with all HouseSpecs. 2 months ago
Peter Nelson 3e83dcedfd Codechange: Allocate houses dynamically instead of from a fixed array.
This uses vectors for HouseSpecs and global/town building counts.
2 months ago
Peter Nelson 8746be8bf2
Codechange: Use FindVehiclesWithOrder when removing a road stop. (#12144) 2 months ago
frosch 907cb4fc53
Fix: [Script] ScriptSubsidy::GetExpireDate should return an economy-date (#12372) 2 months ago
Michael Lutz 8fb7d74dfe Fix eabb9db: Drag building of road stops should not allow mixing z levels. 2 months ago
Michael Lutz 69acc132ca Fix #12387, eabb9db: [NewGRF] Wrong tile offset passed to rail station CB 149 (slope check) 2 months ago
Loïc Guilloux 71087bb6d3
Change: [CI] Always use latest stable Xcode (#12390) 2 months ago
translators ca53e134be Update: Translations from eints
swedish: 14 changes by sereneavatar
finnish: 2 changes by hpiirai
ukrainian: 18 changes by StepanIvasyn
latvian: 4 changes by lexuslatvia
portuguese (brazilian): 13 changes by pasantoro
2 months ago
Jonathan G Rennison 433484cda3
Fix #12388: Vehicle::CopyVehicleConfigAndStatistics not releasing unit number (#12389) 2 months ago
translators b8b01818ca Update: Translations from eints
english (au): 1 change by krysclarke
norwegian (bokmal): 1 change by eriksorngard
spanish (mexican): 32 changes by rgonzalez-py
english (us): 3 changes by 2TallTyler
russian: 3 changes by Ln-Wolf
ukrainian: 18 changes by StepanIvasyn
lithuanian: 6 changes by dziugas1959
portuguese (brazilian): 11 changes by pasantoro
2 months ago
translators 575336ef43 Update: Translations from eints
swedish: 20 changes by joeax910
greek: 182 changes by gh658804
ukrainian: 11 changes by StepanIvasyn
slovak: 45 changes by puco
lithuanian: 14 changes by dziugas1959
portuguese (brazilian): 11 changes by pasantoro
2 months ago
Rubidium 8e12bd35ae Fix: server shutdown and newgame packets should be stable
The server sends shutdown and newgame (reboot) packets to any connected client.
This can be useful, so you can tell clients that are trying to join that the
server is restarting. However, that means that packets can be sent before a
version check has been done.
So, these packets should be in the stable packet range instead of the one that
is unstable and guarded by a version check.
2 months ago
Peter Nelson 4751179dc5
Codefix: Remove unused class member and extraneous spaces. (#12378) 2 months ago
Rubidium 9aa6669266 Fix: inconsistent check for client authorized status 2 months ago
Rubidium 84bbe235e4 Fix: do not send chat to clients that have not authorized yet 2 months ago
Tyler Trahan f71ada4f30
Fix #12268: Capitalize "Wait to unbunch" order string (#12375) 2 months ago
SamuXarick f845b4bbc3
Fix: Changing NPF max search nodes while in-game had no effect (#12194) 2 months ago
translators 40a75e0b8d Update: Translations from eints
swedish: 19 changes by joeax910
norwegian (bokmal): 2 changes by eriksorngard
ukrainian: 6 changes by StepanIvasyn
french: 3 changes by ottdfevr
portuguese (brazilian): 23 changes by pasantoro
polish: 1 change by pAter-exe
2 months ago
Peter Nelson 97c1738541
Fix #12368: Incorrect offset for click position within industry chain window. (#12370) 2 months ago
Peter Nelson eebfb83aa2
Fix 2fd9096: Label for fruit incorrectly changed to `FRUI` from `FRUT`. (#12367) 2 months ago
Tyler Trahan 8928f4979a
Change: Add dividers in vehicle group action dropdown (#12284) 2 months ago
Rubidium caa7c44052 Cleanup: remove checks for old MSVC versions 2 months ago
Rubidium d09b5aaeba Codechange: use int32_t instead of uint16_t for scroll bar position/size/capacity 2 months ago
Rubidium c01bf06ee1 Codefix: some minor errors in tcp-game protocol documentation 2 months ago
translators 018944dc20 Update: Translations from eints
english (au): 2 changes by krysclarke
vietnamese: 1 change by KhoiCanDev
chinese (simplified): 9 changes by WenSimEHRP
greek: 152 changes by gh658804
russian: 3 changes by Ln-Wolf
finnish: 2 changes by hpiirai
ukrainian: 9 changes by StepanIvasyn
danish: 2 changes by bscargo
portuguese: 5 changes by azulcosta
portuguese (brazilian): 35 changes by pasantoro
2 months ago
Peter Nelson 668186ca5b
Codechange: Remove macros involved with NewGRFClass. (#12363)
Use direct class instantiation instead.
2 months ago
Peter Nelson ff35288ddf
Fix: Don't let CT_INVALID map to valid cargo type. (#12364) 2 months ago
glx22 02c00f3e3e Change: [Script] Use economy time for ScriptDate 2 months ago
glx22 704e871a0e Revert bbdbf9a: ScriptTimeMode was not the best solution for economy/calendar support 2 months ago
frosch 603154899a
Add: [SDL2] Driver parameter 'no_mouse_capture' to ease interactive debugging (#12336) 2 months ago
Rubidium 0f25eaa271 Fix: crash to desktop when attempting to join a company while not joined (yet) 2 months ago
Jonathan G Rennison 515303b8be Fix #12092: Incorrect x-axis in cargo payment graph window 2 months ago
Tyler Trahan 2732b3d6c6
Change: Show unbunching action in timetable window (#12351) 2 months ago
Peter Nelson ea74ca0a76
Fix #12347: Crash attempting to find catchment tiles of a station with no catchment area. (#12348) 2 months ago
Rubidium f599108c16 Codechange: move 'months_empty' to CompanyProperties 2 months ago
translators 4321cca5fb Update: Translations from eints
vietnamese: 1 change by KhoiCanDev
chinese (simplified): 1 change by WenSimEHRP
ukrainian: 11 changes by StepanIvasyn
catalan: 1 change by J0anJosep
danish: 1 change by bscargo
dutch: 3 changes by Afoklala
portuguese (brazilian): 58 changes by pasantoro
2 months ago
Peter Nelson df2ee7b06c
Cleanup: Remove old SaveLoad workarounds for MS VS 2017. (#12355) 2 months ago
Rubidium e904122441 Codefix: follow coding style 2 months ago
merni-ns 7457f8d0ff
Codefix: Incorrect pluralisation in last service/service interval texts (#12352) 2 months ago
raddari 5751da7809
Fix #7982: Show existing coverage with unambiguous adjacent station (#12346)
When hovering a tile containing a station, show existing coverage for
that station even when adjacent to a different station.

Co-authored-by: Peter Nelson <peter@fuzzle.org>
2 months ago
translators e141734e54 Update: Translations from eints
english (au): 1 change by krysclarke
norwegian (bokmal): 1 change by eriksorngard
english (us): 1 change by 2TallTyler
korean: 3 changes by telk5093
german: 1 change by Wuzzy2
finnish: 3 changes by hpiirai
ukrainian: 12 changes by StepanIvasyn
portuguese (brazilian): 81 changes by pasantoro
polish: 1 change by pAter-exe
2 months ago
Jonathan G Rennison 2189607c34 Codechange: Reduce size of class WaterRegion
The tile patch array is 256 bytes and is not needed for the majority
of water regions, change it to be optional via std::unique_ptr
2 months ago
Jonathan G Rennison e42aec5a89 Fix #12305: Crash with large positive sprite x offset in engine preview window 2 months ago
translators 0eaeeaabb6 Update: Translations from eints
russian: 2 changes by Ln-Wolf
catalan: 2 changes by J0anJosep
portuguese (brazilian): 23 changes by pasantoro
2 months ago
Tyler Trahan 704d3b8a9b
Fix #12342: Add missing ellipsis to town generation error string (#12343) 2 months ago
translators 00a09af1fd Update: Translations from eints
english (us): 2 changes by 2TallTyler
vietnamese: 2 changes by KhoiCanDev
german: 2 changes by Wuzzy2
ukrainian: 2 changes by StepanIvasyn
portuguese (brazilian): 9 changes by pasantoro
2 months ago
Owen Rudge d4a6ee9554 Change: [CI] Use Azure Code Signing for Windows build 2 months ago
translators 3a3d8f3b53 Update: Translations from eints
english (au): 2 changes by krysclarke
norwegian (bokmal): 2 changes by eriksorngard
chinese (simplified): 31 changes by lysinelai
greek: 7 changes by Xertoveizer
ukrainian: 14 changes by StepanIvasyn
danish: 2 changes by bscargo
lithuanian: 15 changes by dziugas1959
spanish: 2 changes by MontyMontana
french: 2 changes by glx22
portuguese (brazilian): 52 changes by pasantoro
polish: 2 changes by pAter-exe
2 months ago
Peter Nelson 737e3feaf0
Codechange: Don't delete news items or NewGRF window when EffectVehicle is deleted. (#12334)
EffectVehicles never create news and can't be debugged, so searching for news items and windows to delete just wastes time.
2 months ago
Rubidium 7580eac2d5 Codechange: create helper class for useful NetworkAuthorizedKeys functions 2 months ago
Peter Nelson 2485de9462
Codefix: Widget should be passed as WidgetID type. (#12332) 2 months ago
Peter Nelson 107c208d87
Codechange: Use single list for hierarchical group lists. (#12330)
Replace both group list implementations (vehicle group list and company colour group list) with a single implementation, using a struct to hold the group and indentation level instead of two separate lists. Parts that were previously duplicated are now shared.
2 months ago
translators ec3c8d3462 Update: Translations from eints
ukrainian: 12 changes by StepanIvasyn
portuguese (brazilian): 21 changes by pasantoro
polish: 52 changes by pAter-exe
2 months ago
Rubidium 4af089b9be Feature: console command to change authorized keys 3 months ago
Rubidium b7dfa3eb90 Feature: authorized key authentication for rcon 3 months ago
Rubidium 1cf8799810 Feature: encrypt the connection between game server and client 3 months ago
Rubidium d26629c15b Codechange: make encoded length of packet size and type more explicit 3 months ago
Rubidium 5706801ea7 Feature: authenticate to the server without sending the password
Either using password-authentication key exchange or via authorized keys
3 months ago
Rubidium dd532cbc77 Codechange: add setting for authorized/secret/public keys 3 months ago
Rubidium fb9d4afa5c Codechange: add set of classes providing authentication and encryption 3 months ago
Peter Nelson 88cf99017a
Fix #12302: Allow empty train engines to use an invalid cargo type. (#12325)
The cargo type will be forced to the first available type (usually passengers) instead of the engine being disabled.
3 months ago
Peter Nelson 322ca6ef54 Codechange: Shuffle members of Vehicle to reduce size.
This reduces space wasted due to member alignment.
3 months ago
Peter Nelson 3fc7b3b9a0 Codechange: Cache train curve speed limit can be stored in 16 bits.
Cache curve speed modifier and max curve speed are both 16 bit values so can be stored in 16 bit types instead of 32 bit types.
3 months ago
Patric Stout f08da1d373
Codechange: the "no revision detected" string is with four zeros (norev0000) (#12328) 3 months ago
Peter Nelson ab94c8b511
Codechange: Iterate order lists instead of vehicles to find if any vehicle visits a station. (#12315)
This reduces the search time as shared orders are only searched once and non-front vehicles are skipped.
3 months ago
translators 6c5a8f55df Update: Translations from eints
norwegian (bokmal): 58 changes by eriksorngard
vietnamese: 45 changes by KhoiCanDev
greek: 21 changes by Xertoveizer
ukrainian: 5 changes by StepanIvasyn
tamil: 24 changes by merni-ns
lithuanian: 7 changes by dziugas1959
portuguese (brazilian): 61 changes by pasantoro
polish: 21 changes by aefoes
3 months ago
frosch a886bd9666
Fix #12319, 3a676a5: Some SSE blitters were broken due to ODR violations (#12322) 3 months ago
Patric Stout a3cfd23cf9
Codechange: rename byte to uint8_t (#12308) 3 months ago
Loïc Guilloux bd7120bae4
Fix #12316, 268e512: Support for enum storage type in GenerateWidget.cmake (#12321) 3 months ago
merni-ns af1bd43b30
Codefix 4c0dca1: [CI] Fix typo in workflow file (#12318) 3 months ago
Peter Nelson 0058ebe472
Codechange: Check cheap station-facility-filter before expensive in-use-filter. (#12317) 3 months ago
Loïc Guilloux 818a57c9af
Codechange: Actually use LIT_NONE (#12314) 3 months ago
SamuXarick d7c5e9e8ab Codechange: Where the ship comes from is already known
This simplifies the handling of variables.

`ChooseShipTrack` is called upon entering `tile`, and looking further back to the caller, it can be deduced that `v->tile` matches `src_tile`. With that said, `enterdir` can also be removed, as it's not used anywhere else.

`CreateRandomPath` and `GetRandomFollowUpTrackdir` is being fed `src_tile` as it's 2nd parameter. This could be eliminated, as `v` is also being passed to it. Just use `v->tile` in those functions.
3 months ago
Patric Stout 7f49b6f25a
Codefix: allow preview label on PRs against release branches too (#12310) 3 months ago
Patric Stout 5f4f9334ce
Codefix f1e999ec: use RandomRange(l) instead of _random.Next(l) (#12274) 3 months ago
merni-ns 4c0dca1411
Codechange: [CI] Move Release CI build to MacOS runner (#12309) 3 months ago
Rubidium fe12d38024 Codechange: split initiating of joining and identification of the client 3 months ago
Rubidium 15d02f51ed Codechange: use span to send bytes to Packet and add span recv function 3 months ago
Rubidium b6c75dec3a Codechange: explicitly allow only one state in initial handshake/authorization 3 months ago
Rubidium 26d1d5d6e7 Codechange: move decision whether to check NewGRFs to SendNewGRFCheck, just like for sending game/company passwords 3 months ago
Rubidium 6eff879e49 Codechange: pass the socket handler that is going to send the packet into the packet 3 months ago
Rubidium 3c488e1eb8 Codechange: don't check things outside the lock, that could change while waiting on the lock 3 months ago
Rubidium ec4104ec6c Codechange: do not pass the socket when the receiver already knows it 3 months ago

@ -30,15 +30,10 @@ jobs:
fail-fast: false
matrix:
include:
- name: Clang - Debug
- name: Clang
compiler: clang-15
cxxcompiler: clang++-15
libraries: libsdl2-dev
- name: Clang - Release
compiler: clang-15
cxxcompiler: clang++-15
libraries: libsdl2-dev
extra-cmake-parameters: -DCMAKE_BUILD_TYPE=RelWithDebInfo -DOPTION_USE_ASSERTS=OFF
- name: GCC - SDL2
compiler: gcc
cxxcompiler: g++
@ -66,10 +61,16 @@ jobs:
fail-fast: false
matrix:
include:
- arch: arm64
- name: arm64 - Debug
arch: arm64
full_arch: arm64
extra-cmake-parameters: -DCMAKE_BUILD_TYPE=Debug
- name: arm64 - Release
arch: arm64
full_arch: arm64
extra-cmake-parameters: -DCMAKE_BUILD_TYPE=RelWithDebInfo -DOPTION_USE_ASSERTS=OFF
name: Mac OS (${{ matrix.arch }})
name: Mac OS (${{ matrix.name }})
uses: ./.github/workflows/ci-macos.yml
secrets: inherit
@ -77,6 +78,7 @@ jobs:
with:
arch: ${{ matrix.arch }}
full_arch: ${{ matrix.full_arch }}
extra-cmake-parameters: ${{ matrix.extra-cmake-parameters }}
windows:
strategy:

@ -9,6 +9,10 @@ on:
full_arch:
required: true
type: string
extra-cmake-parameters:
required: false
type: string
default: ""
env:
CTEST_OUTPUT_ON_FAILURE: 1
@ -78,6 +82,7 @@ jobs:
-DCMAKE_OSX_ARCHITECTURES=${{ inputs.full_arch }} \
-DVCPKG_TARGET_TRIPLET=${{ inputs.arch }}-osx \
-DCMAKE_TOOLCHAIN_FILE=${{ runner.temp }}/vcpkg/scripts/buildsystems/vcpkg.cmake \
${{ inputs.extra-cmake-parameters }} \
# EOF
echo "::endgroup::"

@ -7,6 +7,7 @@ on:
- synchronize
branches:
- master
- release/**
concurrency:
group: ${{ github.workflow }}-${{ github.event.pull_request.number }}

@ -94,22 +94,6 @@ jobs:
with:
arch: ${{ matrix.host }}
- name: Import code signing certificate
if: ${{ false }} # Disabled
shell: powershell
# If this is run on a fork, there may not be a certificate set up - continue in this case
continue-on-error: true
run: |
$tempFile = [System.IO.Path]::GetTempFileName()
$bytes = [System.Convert]::FromBase64String($env:WINDOWS_CERTIFICATE_P12)
[IO.File]::WriteAllBytes($tempFile, $bytes)
$pwd = ConvertTo-SecureString $env:WINDOWS_CERTIFICATE_PASSWORD -AsPlainText -Force
Import-PfxCertificate -FilePath $tempFile -CertStoreLocation Cert:\CurrentUser\My -Password $pwd
Remove-Item $tempFile
env:
WINDOWS_CERTIFICATE_P12: ${{ secrets.WINDOWS_CERTIFICATE_P12 }}
WINDOWS_CERTIFICATE_PASSWORD: ${{ secrets.WINDOWS_CERTIFICATE_PASSWORD }}
- name: Build (with installer)
if: inputs.is_tag == 'true'
shell: bash
@ -126,7 +110,6 @@ jobs:
-DHOST_BINARY_DIR=${GITHUB_WORKSPACE}/build-host \
-DCMAKE_BUILD_TYPE=RelWithDebInfo \
-DOPTION_SURVEY_KEY=${{ inputs.survey_key }} \
-DWINDOWS_CERTIFICATE_COMMON_NAME="${WINDOWS_CERTIFICATE_COMMON_NAME}" \
# EOF
echo "::endgroup::"
@ -134,7 +117,12 @@ jobs:
cmake --build . --target openttd
echo "::endgroup::"
env:
WINDOWS_CERTIFICATE_COMMON_NAME: ${{ secrets.WINDOWS_CERTIFICATE_COMMON_NAME }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_CODESIGN_ACCOUNT_NAME: ${{ secrets.AZURE_CODESIGN_ACCOUNT_NAME }}
AZURE_CODESIGN_ENDPOINT: ${{ secrets.AZURE_CODESIGN_ENDPOINT }}
AZURE_CODESIGN_PROFILE_NAME: ${{ secrets.AZURE_CODESIGN_PROFILE_NAME }}
- name: Build (without installer)
if: inputs.is_tag != 'true'
@ -151,7 +139,6 @@ jobs:
-DHOST_BINARY_DIR=${GITHUB_WORKSPACE}/build-host \
-DCMAKE_BUILD_TYPE=RelWithDebInfo \
-DOPTION_SURVEY_KEY=${{ inputs.survey_key }} \
-DWINDOWS_CERTIFICATE_COMMON_NAME="${WINDOWS_CERTIFICATE_COMMON_NAME}" \
# EOF
echo "::endgroup::"
@ -159,7 +146,12 @@ jobs:
cmake --build . --target openttd
echo "::endgroup::"
env:
WINDOWS_CERTIFICATE_COMMON_NAME: ${{ secrets.WINDOWS_CERTIFICATE_COMMON_NAME }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_CODESIGN_ACCOUNT_NAME: ${{ secrets.AZURE_CODESIGN_ACCOUNT_NAME }}
AZURE_CODESIGN_ENDPOINT: ${{ secrets.AZURE_CODESIGN_ENDPOINT }}
AZURE_CODESIGN_PROFILE_NAME: ${{ secrets.AZURE_CODESIGN_PROFILE_NAME }}
- name: Create bundles
shell: bash
@ -184,13 +176,15 @@ jobs:
- name: Sign installer
if: ${{ false }} # inputs.is_tag == 'true'
shell: bash
# If this is run on a fork, there may not be a certificate set up - continue in this case
continue-on-error: true
run: |
cd ${GITHUB_WORKSPACE}/build/bundles
../../os/windows/sign.bat *.exe "${WINDOWS_CERTIFICATE_COMMON_NAME}"
${GITHUB_WORKSPACE}/os/windows/sign.bat "${GITHUB_WORKSPACE}/build/bundles"
env:
WINDOWS_CERTIFICATE_COMMON_NAME: ${{ secrets.WINDOWS_CERTIFICATE_COMMON_NAME }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_CODESIGN_ACCOUNT_NAME: ${{ secrets.AZURE_CODESIGN_ACCOUNT_NAME }}
AZURE_CODESIGN_ENDPOINT: ${{ secrets.AZURE_CODESIGN_ENDPOINT }}
AZURE_CODESIGN_PROFILE_NAME: ${{ secrets.AZURE_CODESIGN_PROFILE_NAME }}
- name: Store bundles
uses: actions/upload-artifact@v4

@ -1,2 +1,2 @@
jgrpp-0.58.3 20240410 0 6642b7e12c203cba63246d57db760bf9c521769e 1 0 2024
ec66ffa6cab681f8f7d8bc388aaaac7e772591a41201d4854d07dcd7378ecac3 -
jgrpp-0.59.1 20240519 0 5e971bfc026aa9a58773d89c583e78765156b9e4 1 0 2024
f0d82005ae0e64dc0f833d5cbd6776afb06c9a513cc83119ce8fd0a2e5be097b -

@ -248,7 +248,7 @@ Templates are a very powerful C++ tool, but they can easily confuse beginners. T
* Templates are to be documented in a very clear and verbose manner. Never assume anything in the documentation.
* the template keyword and the template layout get a separate line. typenames are either "T" or preceded by a "T", integers get a single capital letter or a descriptive name preceded by "T".
```c++
template <typename T, typename Tsomething, int N, byte Tnumber_of_something>
template <typename T, typename Tsomething, int N, uint8_t Tnumber_of_something>
int Func();
```

@ -110,9 +110,6 @@ builds.
- `-DOPTION_USE_ASSERTS=OFF`: disable asserts. Use with care, as assert
statements capture early signs of trouble. Release builds have them
disabled by default.
- `-DOPTION_USE_THREADS=OFF`: disable the use of threads. This will block
the interface in many places, and in general gives a worse experience of
the game. Use with care.
- `-DOPTION_TOOLS_ONLY=ON`: only build tools like `strgen`. Does not build
the game itself. Useful for cross-compiling.

@ -1,6 +1,10 @@
## JGR's Patchpack version 0.58.3
## JGR's Patchpack version 0.59.1
This is a collection of patches applied to [OpenTTD](http://www.openttd.org/)
This is a collection of features and other modifications applied to [OpenTTD](http://www.openttd.org/).
It's a separate version of the game which can be installed and played alongside the standard game, not a loadable mod (NewGRF, script, or so on).
This is mainly intended to be used by players who are already familiar with the standard game and how to play it.
It is not aimed at beginner/novice players. Some features and settings are there for very experienced players and so may have a steep learning curve.
* * *
@ -16,14 +20,14 @@ section "Licensing" below for details,
See [below](#openttd) for the original OpenTTD readme.
The thread for this patchpack can be found [here](http://www.tt-forums.net/viewtopic.php?f=33&t=73469).
See [jgrpp-changelog.md](jgrpp-changelog.md) for the changelog.
See the [wiki](https://github.com/JGRennison/OpenTTD-patches/wiki) for guides on how to use some of the included features.
See [installation.md](/installation.md) for instructions on how to install.
The TT-Forums thread for this patchpack can be found [here](http://www.tt-forums.net/viewtopic.php?f=33&t=73469).
(Nearly all of the patches which are listed below have been modified, fixed or extended in some way, and so are not the same as the originals which are linked).
#### Railways and Trains
@ -116,7 +120,6 @@ See [installation.md](/installation.md) for instructions on how to install.
* Open train vehicle details window on total cargo tab if shift pressed.
* Add news/advice setting to warn if no depot order in vehicle schedule.
* [Add buttons to collapse/expand all groups](http://www.tt-forums.net/viewtopic.php?f=33&t=74365).
* Add a menu item to the vehicle list to assign all listed vehicles to a new group.
* Add a setting to include the train length and group name in the vehicle details window.
* Add a setting for whether to open the new vehicle GUI when share-cloning.
* Add setting to disable mass action buttons for top-level vehicle lists.
@ -132,7 +135,6 @@ See [installation.md](/installation.md) for instructions on how to install.
* [Automated timetables and separation](http://www.tt-forums.net/viewtopic.php?f=33&t=46391).
* Allow clearing of timetable time fields which are at 0. Allow explicitly setting timetable time fields to 0 without clearing them.
* Allow changing/clearing the timetabled waiting time and max speed of all of a vehicle's orders at once.
* Add client setting to show the remainder ticks in timetable, after dividing to days or minutes.
* Add a company setting to control the number of ticks used in auto-fill timetable rounding.
* [Cargo type orders](https://www.tt-forums.net/viewtopic.php?p=1047749).
@ -167,7 +169,6 @@ See [installation.md](/installation.md) for instructions on how to install.
* [Departure boards](https://www.tt-forums.net/viewtopic.php?f=33&t=49956).
* Add road waypoints.
* Add NewGRF road stops.
* Add a setting to increase the station catchment radius.
* Station rating: track "last visited vehicle type" separately per cargo.
* Add setting to scale station cargo capacity and rating tolerance by size.
@ -188,7 +189,6 @@ See [installation.md](/installation.md) for instructions on how to install.
#### Towns
* [Town cargo generation factor](http://www.tt-forums.net/viewtopic.php?t=46399).
* [Rating in town label](http://www.tt-forums.net/viewtopic.php?f=33&t=42598).
* [Random town road reconstruction](https://www.tt-forums.net/viewtopic.php?f=33&t=36438). This defaults to off.
* Add very and extremely slow options to town growth rate setting.
@ -205,7 +205,6 @@ See [installation.md](/installation.md) for instructions on how to install.
#### Industries
* Industry cargo generation factor.
* Allow linking only inputs or outputs to the smallmap and map mode viewports in the industry chain window.
#### Map and Landscaping
@ -215,7 +214,6 @@ See [installation.md](/installation.md) for instructions on how to install.
* Add a new tree placement mode (perfect).
* [Minimum town distance](https://www.tt-forums.net/viewtopic.php?f=33&t=33625).
* Add map generation settings to control river/lake, rocky patch, and tropic zone generation.
* Add generation of wide rivers.
* Add settings to customise the size of town zones, and city zones.
* Add setting to show purchased land using clear tile ground sprites (dirt, grass, snow, desert, etc).
@ -223,7 +221,6 @@ See [installation.md](/installation.md) for instructions on how to install.
* Enable building rivers in game. Off by default.
* Add a setting to disable removing sea/rivers.
* Allow building objects by area (1x1 objects only).
* Allow purchasing a region of tiles at once, by dragging.
* Add setting to control if and how land purchasing is permitted.
* Add a company rate limit for land purchasing.
@ -305,7 +302,6 @@ See [installation.md](/installation.md) for instructions on how to install.
* Add setting to allow non server admins to use the money cheat in multiplayer.
* Allow clicking the money text in the cheats window to enter a quantity.
* Add cheats to set inflation income and cost factors.
* Add cheat to set all station ratings to 100%.
* Add cheat to set all town local authority ratings to Outstanding.
#### Cargo Distribution and Link Graph
@ -324,7 +320,6 @@ See [installation.md](/installation.md) for instructions on how to install.
#### Console and Scripts
* Add basic tab-completion to the console window.
* Add console commands for conditional execution from game date.
* [Daily/monthly/yearly scripts](http://www.tt-forums.net/viewtopic.php?f=33&t=49595)

@ -171,10 +171,10 @@ elseif(WIN32)
set(CPACK_PACKAGE_FILE_NAME "openttd-#CPACK_PACKAGE_VERSION#-windows-${CPACK_SYSTEM_NAME}")
if(WINDOWS_CERTIFICATE_COMMON_NAME)
if(DEFINED ENV{AZURE_CODESIGN_PROFILE_NAME})
add_custom_command(TARGET openttd
POST_BUILD
COMMAND "${CMAKE_SOURCE_DIR}/os/windows/sign.bat" "$<TARGET_FILE:openttd>" "${WINDOWS_CERTIFICATE_COMMON_NAME}"
COMMAND "${CMAKE_SOURCE_DIR}/os/windows/sign.bat" "${BINARY_DESTINATION_DIR}"
)
endif()
elseif(UNIX)

@ -57,13 +57,6 @@ function(set_options)
option(OPTION_DEDICATED "Build dedicated server only (no GUI)" OFF)
option(OPTION_INSTALL_FHS "Install with Filesystem Hierarchy Standard folders" ${DEFAULT_OPTION_INSTALL_FHS})
option(OPTION_USE_ASSERTS "Use assertions; leave enabled for nightlies, betas, and RCs" ON)
if(EMSCRIPTEN)
# Although pthreads is supported, it is not in a way yet that is
# useful for us.
option(OPTION_USE_THREADS "Use threads" OFF)
else()
option(OPTION_USE_THREADS "Use threads" ON)
endif()
option(OPTION_USE_NSIS "Use NSIS to create windows installer; enable only for stable releases" OFF)
option(OPTION_TOOLS_ONLY "Build only tools target" OFF)
option(OPTION_DOCS_ONLY "Build only docs target" OFF)
@ -85,7 +78,6 @@ function(show_options)
message(STATUS "Option Dedicated - ${OPTION_DEDICATED}")
message(STATUS "Option Install FHS - ${OPTION_INSTALL_FHS}")
message(STATUS "Option Use assert - ${OPTION_USE_ASSERTS}")
message(STATUS "Option Use threads - ${OPTION_USE_THREADS}")
message(STATUS "Option Use NSIS - ${OPTION_USE_NSIS}")
if(OPTION_SURVEY_KEY)
@ -109,10 +101,6 @@ function(add_definitions_based_on_options)
add_definitions(-DDEDICATED)
endif()
if(NOT OPTION_USE_THREADS)
add_definitions(-DNO_THREADS)
endif()
if(OPTION_USE_ASSERTS)
add_definitions(-DWITH_ASSERT)
else()

@ -56,11 +56,14 @@ foreach(ENUM IN LISTS ENUM_LINES)
endif()
# Check for enum match
if("${LINE}" MATCHES "^ *enum *${ENUM_PATTERN} *\{")
if("${LINE}" MATCHES "^ *enum *${ENUM_PATTERN}( *: *[^ ]*)? *\{")
# REGEX REPLACE does a REGEX MATCHALL and fails if an empty string is matched
string(REGEX MATCH "[^ ]*" RESULT "${LINE}")
string(REPLACE "${RESULT}" "" RM_INDENT "${LINE}")
string(REGEX MATCH " *: *[^ ]*" RESULT "${LINE}")
string(REPLACE "${RESULT}" "" LINE "${LINE}")
set(ACTIVE 1)
if(ACTIVE_COMMENT GREATER 0)
string(APPEND ${PLACE_HOLDER} "\n${COMMENT}")

@ -129,8 +129,8 @@
<tr><td>stop_type</td><td>RST_TYPE_XXX</td><td>XXX = BUS | TRUCK | WAYPOINT (<b>Not in standard specification</b>)</td></tr>
<tr><td>terrain_type</td><td>TILETYPE_XXX</td><td>XXX = NORMAL | DESERT | RAIN_FOREST | SNOW</td></tr>
<tr><td>tile_slope</td><td>SLOPE_XXX</td><td>See <a href="https://newgrf-specs.tt-wiki.net/wiki/NML:List_of_tile_slopes">tile slopes</a> for an overview of possible values</td></tr>
<tr><td>has_road</td><td>0 | 1</td><td>1 is this road stop has road</td></tr>
<tr><td>has_tram</td><td>0 | 1</td><td>1 is this road stop has tram</td></tr>
<tr><td>has_road</td><td>0 | 1</td><td>1 if this road stop has road</td></tr>
<tr><td>has_tram</td><td>0 | 1</td><td>1 if this road stop has tram</td></tr>
<tr><td>road_type</td><td>road type | 0xFF</td><td>Road type. If there is no road the value will be 0xFF. If the roadtype has no entry in the roadtype translation table of the GRF, this value will be 0xFF. If no translation table is present, the raw value will be returned.</td></tr>
<tr><td>tram_type</td><td>tram type | 0xFF</td><td>Tram type. If there is no tram the value will be 0xFF. If the tramtype has no entry in the tramtype translation table of the GRF, this value will be 0xFF. If no translation table is present, the raw value will be returned.</td></tr>
<tr><td>town_manhattan_dist</td><td></td><td>Manhattan distance to the associated town</td></tr>
@ -142,7 +142,6 @@
<tr><td>company_colour2</td><td>COLOUR_XXX</td><td></td></tr>
<tr><td>animation_frame</td><td>0..255</td><td>Animation frame of the current tile</td></tr>
<tr><td>waiting_triggers</td><td>0..255</td><td>Waiting triggers</td></tr>
<tr><td>random_bits</td><td>0..16777215</td><td>All random bits</td></tr>
<tr><td>random_bits_tile</td><td>0..255</td><td>Random bits (per tile), see also <a href="https://newgrf-specs.tt-wiki.net/wiki/NML:Stations#Base_station_variables">random_bits_station</a></td></tr>
<tr><td>one_way_info<br /><b>Not in standard specification</b></td><td>RST_OWI_XXX</td><td>One-way road information of drive-through stop tile<br />XXX = TWO_WAY | WEST_BOUND | EAST_BOUND | NO_ENTRY</td></tr>
<tr><td>one_way_info_inferred<br /><b>Not in standard specification</b></td><td>RST_OWI_XXX</td><td>Inferred one-way road information of drive-through stop tile<br />XXX = TWO_WAY | WEST_BOUND | EAST_BOUND | NO_ENTRY</td></tr>

@ -74,7 +74,7 @@
<ul>
<li>The number of houses in the town changes</li>
<li>When the game is loaded</li>
<li>When settings, NewGRFs or other relavant game configuration is changed</li>
<li>When settings, NewGRFs or other relevant game configuration is changed</li>
</ul>
</p>

@ -105,7 +105,7 @@
<ul>
<li>The number of houses in the town changes</li>
<li>When the game is loaded</li>
<li>When settings, NewGRFs or other relavant game configuration is changed</li>
<li>When settings, NewGRFs or other relevant game configuration is changed</li>
</ul>
</p>

@ -2,6 +2,44 @@
* * *
### v0.59.1 (2024-05-20)
* Fix crash when sorting by capacity in autoreplace window.
* Fix non-percentage servicing interval when using wallclock mode.
* Fix road vehicles skipping orders when using implicit orders.
* Fix setting default value for industry cargo scaling mode when loading old savegames.
* Fix setting display for industry cargo scaling.
* Fix crash which could occur when using autorenew/autoreplace wagon removal with leading engines longer than the train length limit.
* Fix crash which could occur with loading certain GRFs.
* Fix multiplayer desync when joining a server after previously loading a scenario.
* Fix keyboard input issues on Linux/SDL.
* Realistic braking:
* Fix accuracy issues with realistic acceleration and braking when a train is underpowered for ascending or descending a steep slope.
* Reduce sensitivity of train brakes overheated breakdown.
* Add setting to shorten vehicle view status text.
* Bump trunk base from commit bd7120bae41b6e7ac86c664c8220b59cd57242bb to commit 88cf99017a26f887230d2c14d057a97bbf077f7c.
### v0.59.0 (2024-05-05)
* Fix loading recent vanilla savegame versions resulting in incorrect industry cargoes.
* Fix incorrect station catchment/acceptance which could occur when an oil rig/water industry completed construction, which could cause multiplayer desyncs.
* Fix AI construction of block signals when using realistic braking.
* Fix incorrect train weights being used for calculating infrastructure sharing track fees.
* Fix vehicles leaving dots behind in viewport map mode in some cases.
* Fix NewGRF train motion animations for some NewGRFs which use articulated engines.
* Fix template-based train replacement not triggering replacements for companies nominally in debt when using the infinite money setting.
* Fix text filters in dual-pane train purchase window when using NewGRFs with variable vehicle names.
* Road vehicles no longer remaining loading when the next order is for the same station if the next order has a different required direction.
* Enable the cargo capacity/running cost sort mode in the dual pane train purchase window.
* The vehicle capacity sort modes in the build vehicle windows now take into account the selected refit cargo.
* Timekeeping:
* The day length factor setting is now enabled in wallclock timekeeping mode. This scales the economy speed, but not the calendar speed.
* Fix timing of engine preview offers in wallclock timekeeping mode.
* Scheduled dispatch:
* When using scheduled dispatch and timetable automation at the same time, vehicle lateness values are no longer reset when congestion is detected.
* The number of vehicles required text is now clarified to be an estimate.
* Further increase effect size of cargo dist effect of distance on demand setting for values greater than 100%.
* Further reduce the possibility of stuttering when playing sound effects on Windows.
* Bump trunk base from commit 3e625b5b1a81b00f774ca87b48d3e4f4e9d014c3 to commit bd7120bae41b6e7ac86c664c8220b59cd57242bb.
### v0.58.3 (2024-04-10)
* Fix stuttering when playing sound effects on Windows.
* Fix incorrect cargo payment calculations for cargo in the mail compartment of aircraft and in non-first parts of multi-part ships.

@ -1,18 +1,2 @@
@echo off
REM Signing script
REM Arguments: sign.bat exe_to_sign certificate_subject_name
REM This is a loose wrapper around the Microsoft signtool application (included in the Windows SDK).
REM See https://docs.microsoft.com/en-us/dotnet/framework/tools/signtool-exe for more details.
REM Path to signtool.exe
IF NOT DEFINED SIGNTOOL_PATH (SET SIGNTOOL_PATH=signtool)
REM URL of the timestamp server
IF NOT DEFINED SIGNTOOL_TIMESTAMP_URL (SET SIGNTOOL_TIMESTAMP_URL=http://timestamp.digicert.com)
REM Sign with SHA-1 for Windows 7 and below
"%SIGNTOOL_PATH%" sign -v -n %2 -t %SIGNTOOL_TIMESTAMP_URL% -fd sha1 %1
REM Sign with SHA-256 for Windows 8 and above
"%SIGNTOOL_PATH%" sign -v -n %2 -tr %SIGNTOOL_TIMESTAMP_URL% -fd sha256 -td sha256 -as %1
pwsh -File "%~dp0sign_azure.ps1" %1

@ -0,0 +1,40 @@
# Signing script for Azure Code Signing
# Arguments: sign_azure.ps1 path_to_sign
#
# Environment variables must be set up before use:
#
# AZURE_TENANT_ID
# AZURE_CLIENT_ID
# AZURE_CLIENT_SECRET
# AZURE_CODESIGN_ACCOUNT_NAME
# AZURE_CODESIGN_ENDPOINT
# AZURE_CODESIGN_PROFILE_NAME
Param
(
# Files folder
[Parameter(Mandatory=$true, Position=0)]
$FilesFolder
)
if (!$Env:AZURE_CODESIGN_ENDPOINT -or !$Env:AZURE_CODESIGN_ACCOUNT_NAME -or !$Env:AZURE_CODESIGN_PROFILE_NAME -or
!$Env:AZURE_TENANT_ID -or !$Env:AZURE_CLIENT_ID -or !$Env:AZURE_CLIENT_SECRET)
{
"Code signing variables not found; most likely running in a fork. Skipping signing."
exit
}
Install-Module -Name AzureCodeSigning -Scope CurrentUser -RequiredVersion 0.3.0 -Force -Repository PSGallery
$params = @{}
$params["Endpoint"] = $Env:AZURE_CODESIGN_ENDPOINT
$params["CodeSigningAccountName"] = $Env:AZURE_CODESIGN_ACCOUNT_NAME
$params["CertificateProfileName"] = $Env:AZURE_CODESIGN_PROFILE_NAME
$params["FilesFolder"] = $FilesFolder
$params["FilesFolderFilter"] = "exe"
$params["FileDigest"] = "SHA256"
$params["TimestampRfc3161"] = "http://timestamp.acs.microsoft.com"
$params["TimestampDigest"] = "SHA256"
Invoke-AzureCodeSigning @params

@ -59,8 +59,8 @@
static const size_t MD5_HASH_BYTES = 16;
/** Container for storing a MD5 hash/checksum/digest. */
struct MD5Hash : std::array<byte, MD5_HASH_BYTES> {
MD5Hash() : std::array<byte, MD5_HASH_BYTES>{} {}
struct MD5Hash : std::array<uint8_t, MD5_HASH_BYTES> {
MD5Hash() : std::array<uint8_t, MD5_HASH_BYTES>{} {}
/**
* Exclusively-or the given hash into this hash.

@ -147,6 +147,9 @@ add_files(
dock_gui.cpp
driver.cpp
driver.h
dropdown.cpp
dropdown_func.h
dropdown_type.h
economy.cpp
economy_base.h
economy_func.h
@ -420,6 +423,8 @@ add_files(
signs_func.h
signs_gui.cpp
signs_type.h
slider.cpp
slider_func.h
slope_func.h
slope_type.h
smallmap_colours.h

@ -67,22 +67,22 @@ int GetAircraftFlightLevel(T *v, bool takeoff = false);
struct AircraftCache {
uint32_t cached_max_range_sqr; ///< Cached squared maximum range.
uint16_t cached_max_range; ///< Cached maximum range.
byte image_movement_state; ///< Cached image aircraft movement state
uint8_t image_movement_state; ///< Cached image aircraft movement state
};
/**
* Aircraft, helicopters, rotors and their shadows belong to this class.
*/
struct Aircraft final : public SpecializedVehicle<Aircraft, VEH_AIRCRAFT> {
uint16_t crashed_counter; ///< Timer for handling crash animations.
byte pos; ///< Next desired position of the aircraft.
byte previous_pos; ///< Previous desired position of the aircraft.
StationID targetairport; ///< Airport to go to next.
byte state; ///< State of the airport. @see AirportMovementStates
uint16_t crashed_counter; ///< Timer for handling crash animations.
uint8_t pos; ///< Next desired position of the aircraft.
uint8_t previous_pos; ///< Previous desired position of the aircraft.
StationID targetairport; ///< Airport to go to next.
uint8_t state; ///< State of the airport. @see AirportMovementStates
Direction last_direction;
byte number_consecutive_turns; ///< Protection to prevent the aircraft of making a lot of turns in order to reach a specific point.
byte turn_counter; ///< Ticks between each turn to prevent > 45 degree turns.
byte flags; ///< Aircraft flags. @see AirVehicleFlags
uint8_t number_consecutive_turns; ///< Protection to prevent the aircraft of making a lot of turns in order to reach a specific point.
uint8_t turn_counter; ///< Ticks between each turn to prevent > 45 degree turns.
uint8_t flags; ///< Aircraft flags. @see AirVehicleFlags
AircraftCache acache;
@ -146,6 +146,6 @@ void GetRotorImage(const Aircraft *v, EngineImageType image_type, VehicleSpriteS
Station *GetTargetAirportIfValid(const Aircraft *v);
void HandleMissingAircraftOrders(Aircraft *v);
const char *AirportMovementStateToString(byte state);
const char *AirportMovementStateToString(uint8_t state);
#endif /* AIRCRAFT_H */

@ -692,7 +692,7 @@ static int UpdateAircraftSpeed(Aircraft *v, uint speed_limit = SPEED_LIMIT_NONE,
* ~ acceleration * 77 (km-ish/h / 256)
*/
uint spd = v->acceleration * 77;
byte t;
uint8_t t;
/* Adjust speed limits by plane speed factor to prevent taxiing
* and take-off speeds being too low. */
@ -710,7 +710,7 @@ static int UpdateAircraftSpeed(Aircraft *v, uint speed_limit = SPEED_LIMIT_NONE,
speed_limit = v->vcache.cached_max_speed;
}
v->subspeed = (t = v->subspeed) + (byte)spd;
v->subspeed = (t = v->subspeed) + (uint8_t)spd;
/* Aircraft's current speed is used twice so that very fast planes are
* forced to slow down rapidly in the short distance needed. The magic
@ -737,7 +737,7 @@ static int UpdateAircraftSpeed(Aircraft *v, uint speed_limit = SPEED_LIMIT_NONE,
spd = v->GetOldAdvanceSpeed(spd);
spd += v->progress;
v->progress = (byte)spd;
v->progress = (uint8_t)spd;
return spd >> 8;
}
@ -861,7 +861,7 @@ template int GetAircraftFlightLevel(Aircraft *v, bool takeoff);
* @param rotation The rotation of the airport.
* @return The index of the entry point
*/
static byte AircraftGetEntryPoint(const Aircraft *v, const AirportFTAClass *apc, Direction rotation)
static uint8_t AircraftGetEntryPoint(const Aircraft *v, const AirportFTAClass *apc, Direction rotation)
{
assert(v != nullptr);
assert(apc != nullptr);
@ -1775,7 +1775,7 @@ static void AircraftEventHandler_Flying(Aircraft *v, const AirportFTAClass *apc)
/* {32,FLYING,NOTHING_block,37}, {32,LANDING,N,33}, {32,HELILANDING,N,41},
* if it is an airplane, look for LANDING, for helicopter HELILANDING
* it is possible to choose from multiple landing runways, so loop until a free one is found */
byte landingtype = (v->subtype == AIR_HELICOPTER) ? HELILANDING : LANDING;
uint8_t landingtype = (v->subtype == AIR_HELICOPTER) ? HELILANDING : LANDING;
const AirportFTA *current = apc->layout[v->pos].next;
while (current != nullptr) {
if (current->heading == landingtype) {
@ -1922,8 +1922,8 @@ static bool AirportMove(Aircraft *v, const AirportFTAClass *apc)
const AirportFTA *current = &apc->layout[v->pos];
/* we have arrived in an important state (eg terminal, hangar, etc.) */
if (current->heading == v->state) {
byte prev_pos = v->pos; // location could be changed in state, so save it before-hand
byte prev_state = v->state;
uint8_t prev_pos = v->pos; // location could be changed in state, so save it before-hand
uint8_t prev_state = v->state;
_aircraft_state_handlers[v->state](v, apc);
if (v->state != FLYING) v->previous_pos = prev_pos;
if (v->state != prev_state || v->pos != prev_pos) UpdateAircraftCache(v);
@ -2059,7 +2059,7 @@ static const MovementTerminalMapping _airport_terminal_mapping[] = {
* @param last_terminal Terminal number to stop examining.
* @return A terminal or helipad has been found, and has been assigned to the aircraft.
*/
static bool FreeTerminal(Aircraft *v, byte i, byte last_terminal)
static bool FreeTerminal(Aircraft *v, uint8_t i, uint8_t last_terminal)
{
assert(last_terminal <= lengthof(_airport_terminal_mapping));
Station *st = Station::Get(v->targetairport);
@ -2259,8 +2259,8 @@ bool Aircraft::Tick()
}
if (HasBit(this->vcache.cached_veh_flags, VCF_REDRAW_ON_SPEED_CHANGE)) {
extern byte MapAircraftMovementState(const Aircraft *v);
byte state = MapAircraftMovementState(this);
extern uint8_t MapAircraftMovementState(const Aircraft *v);
uint8_t state = MapAircraftMovementState(this);
if (state != this->acache.image_movement_state) {
this->InvalidateImageCacheOfChain();
this->acache.image_movement_state = state;
@ -2317,7 +2317,7 @@ void UpdateAirplanesOnNewStation(const Station *st)
if (!st->airport.HasHangar()) RemoveOrderFromAllVehicles(OT_GOTO_DEPOT, st->index, true);
}
const char *AirportMovementStateToString(byte state)
const char *AirportMovementStateToString(uint8_t state)
{
#define AMS(s) case s: return #s;
switch (state) {

@ -110,12 +110,12 @@ AirportMovingData RotateAirportMovingData(const AirportMovingData *orig, Directi
AirportFTAClass::AirportFTAClass(
const AirportMovingData *moving_data_,
const byte *terminals_,
const byte num_helipads_,
const byte *entry_points_,
const uint8_t *terminals_,
const uint8_t num_helipads_,
const uint8_t *entry_points_,
Flags flags_,
const AirportFTAbuildup *apFA,
byte delta_z_
uint8_t delta_z_
) :
moving_data(moving_data_),
terminals(terminals_),
@ -204,7 +204,7 @@ static AirportFTA *AirportBuildAutomata(uint nofelements, const AirportFTAbuildu
* @param airport_type %Airport type to query FTA from. @see AirportTypes
* @return Finite state machine of the airport.
*/
const AirportFTAClass *GetAirport(const byte airport_type)
const AirportFTAClass *GetAirport(const uint8_t airport_type)
{
if (airport_type == AT_DUMMY) return &_airportfta_dummy;
return AirportSpec::Get(airport_type)->fsm;
@ -215,7 +215,7 @@ const AirportFTAClass *GetAirport(const byte airport_type)
* @param hangar_tile The tile on which the vehicle is build
* @return The position (index in airport node array) where the aircraft ends up
*/
byte GetVehiclePosOnBuild(TileIndex hangar_tile)
uint8_t GetVehiclePosOnBuild(TileIndex hangar_tile)
{
const Station *st = Station::GetByTile(hangar_tile);
const AirportFTAClass *apc = st->airport.GetFTA();

@ -152,12 +152,12 @@ public:
AirportFTAClass(
const AirportMovingData *moving_data,
const byte *terminals,
const byte num_helipads,
const byte *entry_points,
const uint8_t *terminals,
const uint8_t num_helipads,
const uint8_t *entry_points,
Flags flags,
const AirportFTAbuildup *apFA,
byte delta_z
uint8_t delta_z
);
~AirportFTAClass();
@ -167,7 +167,7 @@ public:
* @param position Element number to get movement data about.
* @return Pointer to the movement data.
*/
const AirportMovingData *MovingData(byte position) const
const AirportMovingData *MovingData(uint8_t position) const
{
assert(position < nofelements);
return &moving_data[position];
@ -175,12 +175,12 @@ public:
const AirportMovingData *moving_data; ///< Movement data.
struct AirportFTA *layout; ///< state machine for airport
const byte *terminals; ///< %Array with the number of terminal groups, followed by the number of terminals in each group.
const byte num_helipads; ///< Number of helipads on this airport. When 0 helicopters will go to normal terminals.
const uint8_t *terminals; ///< %Array with the number of terminal groups, followed by the number of terminals in each group.
const uint8_t num_helipads; ///< Number of helipads on this airport. When 0 helicopters will go to normal terminals.
Flags flags; ///< Flags for this airport type.
byte nofelements; ///< number of positions the airport consists of
const byte *entry_points; ///< when an airplane arrives at this airport, enter it at position entry_point, index depends on direction
byte delta_z; ///< Z adjustment for helicopter pads
uint8_t nofelements; ///< number of positions the airport consists of
const uint8_t *entry_points; ///< when an airplane arrives at this airport, enter it at position entry_point, index depends on direction
uint8_t delta_z; ///< Z adjustment for helicopter pads
};
DECLARE_ENUM_AS_BIT_SET(AirportFTAClass::Flags)
@ -190,12 +190,12 @@ DECLARE_ENUM_AS_BIT_SET(AirportFTAClass::Flags)
struct AirportFTA {
AirportFTA *next; ///< possible extra movement choices from this position
uint64_t block; ///< 64 bit blocks (st->airport.flags), should be enough for the most complex airports
byte position; ///< the position that an airplane is at
byte next_position; ///< next position from this position
byte heading; ///< heading (current orders), guiding an airplane to its target on an airport
uint8_t position; ///< the position that an airplane is at
uint8_t next_position; ///< next position from this position
uint8_t heading; ///< heading (current orders), guiding an airplane to its target on an airport
};
const AirportFTAClass *GetAirport(const byte airport_type);
byte GetVehiclePosOnBuild(TileIndex hangar_tile);
const AirportFTAClass *GetAirport(const uint8_t airport_type);
uint8_t GetVehiclePosOnBuild(TileIndex hangar_tile);
#endif /* AIRPORT_H */

@ -22,7 +22,7 @@
#include "station_type.h"
#include "newgrf_airport.h"
#include "newgrf_callbacks.h"
#include "widgets/dropdown_type.h"
#include "dropdown_type.h"
#include "core/geometry_func.hpp"
#include "hotkeys.h"
#include "vehicle_func.h"
@ -36,11 +36,11 @@
static AirportClassID _selected_airport_class; ///< the currently visible airport class
static int _selected_airport_index; ///< the index of the selected airport in the current class or -1
static byte _selected_airport_layout; ///< selected airport layout number.
static uint8_t _selected_airport_layout; ///< selected airport layout number.
static void ShowBuildAirportPicker(Window *parent);
SpriteID GetCustomAirportSprite(const AirportSpec *as, byte layout);
SpriteID GetCustomAirportSprite(const AirportSpec *as, uint8_t layout);
void CcBuildAirport(const CommandCost &result, TileIndex tile, uint32_t p1, uint32_t p2, uint64_t p3, uint32_t cmd)
{
@ -339,7 +339,7 @@ public:
for (int i = 0; i < NUM_AIRPORTS; i++) {
const AirportSpec *as = AirportSpec::Get(i);
if (!as->enabled) continue;
for (byte layout = 0; layout < as->num_table; layout++) {
for (uint8_t layout = 0; layout < as->num_table; layout++) {
SpriteID sprite = GetCustomAirportSprite(as, layout);
if (sprite != 0) {
Dimension d = GetSpriteSize(sprite);
@ -355,7 +355,7 @@ public:
for (int i = NEW_AIRPORT_OFFSET; i < NUM_AIRPORTS; i++) {
const AirportSpec *as = AirportSpec::Get(i);
if (!as->enabled) continue;
for (byte layout = 0; layout < as->num_table; layout++) {
for (uint8_t layout = 0; layout < as->num_table; layout++) {
StringID string = GetAirportTextCallback(as, layout, CBID_AIRPORT_ADDITIONAL_TEXT);
if (string == STR_UNDEFINED) continue;

@ -8,6 +8,7 @@
/** @file articulated_vehicles.cpp Implementation of articulated vehicles. */
#include "stdafx.h"
#include "articulated_vehicles.h"
#include "core/bitmath_func.hpp"
#include "core/random_func.hpp"
#include "train.h"
@ -141,15 +142,23 @@ void GetArticulatedPartsEngineIDs(EngineID engine_type, bool purchase_window, st
* Returns the default (non-refitted) capacity of a specific EngineID.
* @param engine the EngineID of interest
* @param cargo_type returns the default cargo type, if needed
* @param attempt_refit cargo ID to attempt to use
* @return capacity
*/
static inline uint16_t GetVehicleDefaultCapacity(EngineID engine, CargoID *cargo_type)
static inline uint16_t GetVehicleDefaultCapacity(EngineID engine, CargoID *cargo_type, CargoID attempt_refit = INVALID_CARGO)
{
const Engine *e = Engine::Get(engine);
CargoID cargo = (e->CanCarryCargo() ? e->GetDefaultCargoType() : INVALID_CARGO);
CargoID cargo = INVALID_CARGO;
if (e->CanCarryCargo()) {
if (attempt_refit != INVALID_CARGO && HasBit(e->info.refit_mask, attempt_refit)) {
cargo = attempt_refit;
} else {
cargo = e->GetDefaultCargoType();
}
}
if (cargo_type != nullptr) *cargo_type = cargo;
if (cargo == INVALID_CARGO) return 0;
return e->GetDisplayDefaultCapacity();
return e->GetDisplayDefaultCapacity(nullptr, cargo);
}
/**
@ -175,16 +184,20 @@ static inline CargoTypes GetAvailableVehicleCargoTypes(EngineID engine, bool inc
/**
* Get the capacity of the parts of a given engine.
* @param engine The engine to get the capacities from.
* @param attempt_refit Attempt to get capacity when refitting to this cargo.
* @return The cargo capacities.
*/
CargoArray GetCapacityOfArticulatedParts(EngineID engine)
CargoArray GetCapacityOfArticulatedParts(EngineID engine, CargoID attempt_refit)
{
CargoArray capacity{};
const Engine *e = Engine::Get(engine);
CargoID cargo_type;
uint16_t cargo_capacity = GetVehicleDefaultCapacity(engine, &cargo_type);
if (cargo_type < NUM_CARGO) capacity[cargo_type] = cargo_capacity;
auto get_engine_cargo = [&capacity, attempt_refit](EngineID eng) {
CargoID cargo_type;
uint16_t cargo_capacity = GetVehicleDefaultCapacity(eng, &cargo_type, attempt_refit);
if (cargo_type < NUM_CARGO) capacity[cargo_type] += cargo_capacity;
};
get_engine_cargo(engine);
if (!e->IsArticulatedCallbackVehicleType()) return capacity;
@ -194,8 +207,7 @@ CargoArray GetCapacityOfArticulatedParts(EngineID engine)
EngineID artic_engine = GetNextArticulatedPart(i, engine);
if (artic_engine == INVALID_ENGINE) break;
cargo_capacity = GetVehicleDefaultCapacity(artic_engine, &cargo_type);
if (cargo_type < NUM_CARGO) capacity[cargo_type] += cargo_capacity;
get_engine_cargo(artic_engine);
}
return capacity;

@ -16,7 +16,7 @@
uint CountArticulatedParts(EngineID engine_type, bool purchase_window);
void GetArticulatedPartsEngineIDs(EngineID engine_type, bool purchase_window, std::vector<EngineID> &ids);
CargoArray GetCapacityOfArticulatedParts(EngineID engine);
CargoArray GetCapacityOfArticulatedParts(EngineID engine, CargoID attempt_refit = INVALID_CARGO);
CargoTypes GetCargoTypesOfArticulatedParts(EngineID engine);
void AddArticulatedParts(Vehicle *first);
void GetArticulatedRefitMasks(EngineID engine, bool include_initial_cargo_type, CargoTypes *union_mask, CargoTypes *intersection_mask);

@ -343,7 +343,7 @@ static CommandCost BuildReplacementMultiPartShipSimple(EngineID e, const Vehicle
for (; v != nullptr && old != nullptr; v = v->Next(), old = old->Next()) {
if (old->cargo_type == INVALID_CARGO) continue;
byte subtype = GetBestFittingSubType(old, v, old->cargo_type);
uint8_t subtype = GetBestFittingSubType(old, v, old->cargo_type);
CommandCost refit_cost = DoCommand(0, v->index, old->cargo_type | (subtype << 8) | (1 << 16), DC_EXEC, GetCmdRefitVeh(v));
if (refit_cost.Succeeded()) cost.AddCost(refit_cost);
}
@ -396,7 +396,7 @@ static CommandCost BuildReplacementMultiPartShip(EngineID e, const Vehicle *old_
CargoID c = FindFirstBit(available);
assert(old_cargo_vehs[c] != nullptr);
byte subtype = GetBestFittingSubType(old_cargo_vehs[c], v, c);
uint8_t subtype = GetBestFittingSubType(old_cargo_vehs[c], v, c);
CommandCost refit_cost = DoCommand(0, v->index, c | (subtype << 8) | (1 << 16), DC_EXEC, GetCmdRefitVeh(v));
if (refit_cost.Succeeded()) cost.AddCost(refit_cost);
}
@ -453,7 +453,7 @@ static CommandCost BuildReplacementMultiPartShip(EngineID e, const Vehicle *old_
if (c == INVALID_CARGO) continue;
assert(old_cargo_vehs[c] != nullptr);
byte subtype = GetBestFittingSubType(old_cargo_vehs[c], v, c);
uint8_t subtype = GetBestFittingSubType(old_cargo_vehs[c], v, c);
CommandCost refit_cost = DoCommand(0, v->index, c | (subtype << 8) | (1 << 16), DC_EXEC, GetCmdRefitVeh(v));
if (refit_cost.Succeeded()) cost.AddCost(refit_cost);
}
@ -514,7 +514,7 @@ static CommandCost BuildReplacementVehicle(const Vehicle *old_veh, Vehicle **new
/* Refit the vehicle if needed */
if (refit_cargo != CARGO_NO_REFIT) {
byte subtype = GetBestFittingSubType(old_veh, new_veh, refit_cargo);
uint8_t subtype = GetBestFittingSubType(old_veh, new_veh, refit_cargo);
cost.AddCost(DoCommand(0, new_veh->index, refit_cargo | (subtype << 8), DC_EXEC, GetCmdRefitVeh(new_veh)));
assert(cost.Succeeded()); // This should be ensured by GetNewCargoTypeForReplace()
@ -778,7 +778,6 @@ static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon
/* Sell superfluous new vehicles that could not be inserted. */
if (cost.Succeeded() && wagon_removal) {
assert(Train::From(new_head)->gcache.cached_total_length <= _settings_game.vehicle.max_train_length * TILE_SIZE);
for (auto it = std::next(std::begin(replacements)); it != std::end(replacements); ++it) {
Vehicle *wagon = it->new_veh;
if (wagon == nullptr) continue;

@ -24,7 +24,7 @@
#include "core/geometry_func.hpp"
#include "rail_gui.h"
#include "road_gui.h"
#include "widgets/dropdown_func.h"
#include "dropdown_func.h"
#include "widgets/autoreplace_widget.h"
@ -32,7 +32,7 @@
void DrawEngineList(VehicleType type, const Rect &r, const GUIEngineList &eng_list, const Scrollbar &sb, EngineID selected_id, bool show_count, GroupID selected_group);
static bool EngineNumberSorter(const GUIEngineListItem &a, const GUIEngineListItem &b)
static bool EngineNumberSorter(const GUIEngineListItem &a, const GUIEngineListItem &b, const GUIEngineListSortCache &cache)
{
return Engine::Get(a.engine_id)->list_position < Engine::Get(b.engine_id)->list_position;
}
@ -83,7 +83,7 @@ class ReplaceVehicleWindow : public Window {
bool reset_sel_engine; ///< Also reset #sel_engine while updating left and/or right and no valid engine selected.
GroupID sel_group; ///< Group selected to replace.
int details_height; ///< Minimal needed height of the details panels, in text lines (found so far).
byte sort_criteria; ///< Criteria of sorting vehicles.
uint8_t sort_criteria; ///< Criteria of sorting vehicles.
bool descending_sort_order; ///< Order of sorting vehicles.
bool show_hidden_engines; ///< Whether to show the hidden engines.
RailType sel_railtype; ///< Type of rail tracks selected. #INVALID_RAILTYPE to show all.
@ -141,7 +141,7 @@ class ReplaceVehicleWindow : public Window {
std::vector<EngineID> variants;
EngineID selected_engine = INVALID_ENGINE;
VehicleType type = (VehicleType)this->window_number;
byte side = draw_left ? 0 : 1;
uint8_t side = draw_left ? 0 : 1;
GUIEngineList list;
@ -606,7 +606,7 @@ public:
case WID_RV_LEFT_MATRIX:
case WID_RV_RIGHT_MATRIX: {
byte click_side;
uint8_t click_side;
if (widget == WID_RV_LEFT_MATRIX) {
click_side = 0;
} else {

@ -314,7 +314,7 @@ static const uint NUM_SONGS_PLAYLIST = 32;
/* Functions to read DOS music CAT files, similar to but not quite the same as sound effect CAT files */
char *GetMusicCatEntryName(const std::string &filename, size_t entrynum);
byte *GetMusicCatEntryData(const std::string &filename, size_t entrynum, size_t &entrylen);
uint8_t *GetMusicCatEntryData(const std::string &filename, size_t entrynum, size_t &entrylen);
enum MusicTrackType {
MTT_STANDARDMIDI, ///< Standard MIDI file
@ -324,7 +324,7 @@ enum MusicTrackType {
/** Metadata about a music track. */
struct MusicSongInfo {
std::string songname; ///< name of song displayed in UI
byte tracknr; ///< track number of song displayed in UI
uint8_t tracknr; ///< track number of song displayed in UI
std::string filename; ///< file on disk containing song (when used in MusicSet class)
MusicTrackType filetype; ///< decoder required for song file
int cat_index; ///< entry index in CAT file, for filetype==MTT_MPSMIDI
@ -338,7 +338,7 @@ struct MusicSet : BaseSet<MusicSet, NUM_SONGS_AVAILABLE, false> {
/** Data about individual songs in set. */
MusicSongInfo songinfo[NUM_SONGS_AVAILABLE];
/** Number of valid songs in set. */
byte num_available;
uint8_t num_available;
bool FillSetDetails(const IniFile &ini, const std::string &path, const std::string &full_filename);
};

@ -80,8 +80,8 @@ struct BaseStation : StationPool::PoolItem<&_station_pool> {
std::vector<RoadStopSpecList> roadstop_speclist; ///< List of road stop specs of this station
uint16_t random_bits; ///< Random bits assigned to this station
byte waiting_triggers; ///< Waiting triggers (NewGRF) for this station
byte delete_ctr; ///< Delete counter. If greater than 0 then it is decremented until it reaches 0; the waypoint is then is deleted.
uint8_t waiting_triggers; ///< Waiting triggers (NewGRF) for this station
uint8_t delete_ctr; ///< Delete counter. If greater than 0 then it is decremented until it reaches 0; the waypoint is then is deleted.
uint8_t cached_anim_triggers; ///< NOSAVE: Combined animation trigger bitmask, used to determine if trigger processing should happen.
uint8_t cached_roadstop_anim_triggers; ///< NOSAVE: Combined animation trigger bitmask for road stops, used to determine if trigger processing should happen.
CargoTypes cached_cargo_triggers; ///< NOSAVE: Combined cargo trigger bitmask
@ -119,7 +119,7 @@ struct BaseStation : StationPool::PoolItem<&_station_pool> {
* @param available will return false if ever the variable asked for does not exist
* @return the value stored in the corresponding variable
*/
virtual uint32_t GetNewGRFVariable(const struct ResolverObject &object, uint16_t variable, byte parameter, bool *available) const = 0;
virtual uint32_t GetNewGRFVariable(const struct ResolverObject &object, uint16_t variable, uint8_t parameter, bool *available) const = 0;
/**
* Update the coordinated of the sign (as shown in the viewport).
@ -195,7 +195,7 @@ struct BaseStation : StationPool::PoolItem<&_station_pool> {
return (this->facilities & facilities) != 0;
}
inline byte GetRoadStopRandomBits(TileIndex tile) const
inline uint8_t GetRoadStopRandomBits(TileIndex tile) const
{
for (const RoadStopTileData &tile_data : this->custom_roadstop_tile_data) {
if (tile_data.tile == tile) return tile_data.random_bits;
@ -203,7 +203,7 @@ struct BaseStation : StationPool::PoolItem<&_station_pool> {
return 0;
}
inline byte GetRoadStopAnimationFrame(TileIndex tile) const
inline uint8_t GetRoadStopAnimationFrame(TileIndex tile) const
{
for (const RoadStopTileData &tile_data : this->custom_roadstop_tile_data) {
if (tile_data.tile == tile) return tile_data.animation_frame;
@ -212,11 +212,11 @@ struct BaseStation : StationPool::PoolItem<&_station_pool> {
}
private:
bool SetRoadStopTileData(TileIndex tile, byte data, bool animation);
bool SetRoadStopTileData(TileIndex tile, uint8_t data, bool animation);
public:
inline void SetRoadStopRandomBits(TileIndex tile, byte random_bits) { this->SetRoadStopTileData(tile, random_bits, false); }
inline bool SetRoadStopAnimationFrame(TileIndex tile, byte frame) { return this->SetRoadStopTileData(tile, frame, true); }
inline void SetRoadStopRandomBits(TileIndex tile, uint8_t random_bits) { this->SetRoadStopTileData(tile, random_bits, false); }
inline bool SetRoadStopAnimationFrame(TileIndex tile, uint8_t frame) { return this->SetRoadStopTileData(tile, frame, true); }
void RemoveRoadStopTileData(TileIndex tile);
static void PostDestructor(size_t index);

@ -36,14 +36,14 @@ inline void Blitter_32bppAnim::Draw(const Blitter::BlitterParams *bp, ZoomLevel
const uint16_t *src_n = (const uint16_t *)(src->data + src->offset[zoom][1]);
for (uint i = bp->skip_top; i != 0; i--) {
src_px = (const Colour *)((const byte *)src_px + *(const uint32_t *)src_px);
src_n = (const uint16_t *)((const byte *)src_n + *(const uint32_t *)src_n);
src_px = (const Colour *)((const uint8_t *)src_px + *(const uint32_t *)src_px);
src_n = (const uint16_t *)((const uint8_t *)src_n + *(const uint32_t *)src_n);
}
Colour *dst = (Colour *)bp->dst + bp->top * bp->pitch + bp->left;
uint16_t *anim = this->anim_buf + this->ScreenToAnimOffset((uint32_t *)bp->dst) + bp->top * this->anim_buf_pitch + bp->left;
const byte *remap = bp->remap; // store so we don't have to access it via bp every time
const uint8_t *remap = bp->remap; // store so we don't have to access it via bp every time
const int width = bp->width;
const int pitch = bp->pitch;
const int anim_pitch = this->anim_buf_pitch;
@ -54,10 +54,10 @@ inline void Blitter_32bppAnim::Draw(const Blitter::BlitterParams *bp, ZoomLevel
Colour *dst_ln = dst + pitch;
uint16_t *anim_ln = anim + anim_pitch;
const Colour *src_px_ln = (const Colour *)((const byte *)src_px + *(const uint32_t *)src_px);
const Colour *src_px_ln = (const Colour *)((const uint8_t *)src_px + *(const uint32_t *)src_px);
src_px++;
const uint16_t *src_n_ln = (const uint16_t *)((const byte *)src_n + *(const uint32_t *)src_n);
const uint16_t *src_n_ln = (const uint16_t *)((const uint8_t *)src_n + *(const uint32_t *)src_n);
src_n += 2;
Colour *dst_end = dst;

@ -33,7 +33,7 @@ template <BlitterMode mode, Blitter_32bppSSE2::ReadMode read_mode, Blitter_32bpp
GNU_TARGET("sse4.1")
inline void Blitter_32bppSSE4_Anim::Draw(const BlitterParams *bp, ZoomLevel zoom)
{
const byte * const remap = bp->remap;
const uint8_t * const remap = bp->remap;
Colour *dst_line = (Colour *) bp->dst + bp->top * bp->pitch + bp->left;
uint16_t *anim_line = this->anim_buf + this->ScreenToAnimOffset((uint32_t *)bp->dst) + bp->top * this->anim_buf_pitch + bp->left;
int effective_width = bp->width;
@ -42,7 +42,7 @@ inline void Blitter_32bppSSE4_Anim::Draw(const BlitterParams *bp, ZoomLevel zoom
const Blitter_32bppSSE_Base::SpriteData * const sd = (const Blitter_32bppSSE_Base::SpriteData *) bp->sprite;
const SpriteInfo * const si = &sd->infos[zoom];
const MapValue *src_mv_line = (const MapValue *) &sd->data[si->mv_offset] + bp->skip_top * si->sprite_width;
const Colour *src_rgba_line = (const Colour *) ((const byte *) &sd->data[si->sprite_offset] + bp->skip_top * si->sprite_line_size);
const Colour *src_rgba_line = (const Colour *) ((const uint8_t *) &sd->data[si->sprite_offset] + bp->skip_top * si->sprite_line_size);
if (read_mode != RM_WITH_MARGIN) {
src_rgba_line += bp->skip_left;
@ -104,20 +104,20 @@ inline void Blitter_32bppSSE4_Anim::Draw(const BlitterParams *bp, ZoomLevel zoom
if (animated) {
/* Remap colours. */
const byte m0 = mvX2;
const uint8_t m0 = mvX2;
if (m0 >= PALETTE_ANIM_START) {
const Colour c0 = (this->LookupColourInPalette(m0).data & 0x00FFFFFF) | (src[0].data & 0xFF000000);
InsertFirstUint32(AdjustBrightneSSE(c0, (byte) (mvX2 >> 8)).data, srcABCD);
InsertFirstUint32(AdjustBrightneSSE(c0, (uint8_t) (mvX2 >> 8)).data, srcABCD);
}
const byte m1 = mvX2 >> 16;
const uint8_t m1 = mvX2 >> 16;
if (m1 >= PALETTE_ANIM_START) {
const Colour c1 = (this->LookupColourInPalette(m1).data & 0x00FFFFFF) | (src[1].data & 0xFF000000);
InsertSecondUint32(AdjustBrightneSSE(c1, (byte) (mvX2 >> 24)).data, srcABCD);
InsertSecondUint32(AdjustBrightneSSE(c1, (uint8_t) (mvX2 >> 24)).data, srcABCD);
}
/* Update anim buffer. */
const byte a0 = src[0].a;
const byte a1 = src[1].a;
const uint8_t a0 = src[0].a;
const uint8_t a1 = src[1].a;
uint32_t anim01 = 0;
if (a0 == 255) {
if (a1 == 255) {
@ -185,9 +185,9 @@ bmno_full_transparency:
__m128i dstABCD = _mm_loadl_epi64((__m128i*) dst);
/* Remap colours. */
const uint m0 = (byte) mvX2;
const uint m0 = (uint8_t) mvX2;
const uint r0 = remap[m0];
const uint m1 = (byte) (mvX2 >> 16);
const uint m1 = (uint8_t) (mvX2 >> 16);
const uint r1 = remap[m1];
if (mvX2 & 0x00FF00FF) {
#define CMOV_REMAP(m_colour, m_colour_init, m_src, m_m) \
@ -195,7 +195,7 @@ bmno_full_transparency:
Colour m_colour = m_colour_init; \
{ \
const Colour srcm = (Colour) (m_src); \
const uint m = (byte) (m_m); \
const uint m = (uint8_t) (m_m); \
const uint r = remap[m]; \
const Colour cmap = (this->LookupColourInPalette(r).data & 0x00FFFFFF) | (srcm.data & 0xFF000000); \
m_colour = r == 0 ? m_colour : cmap; \
@ -225,8 +225,8 @@ bmno_full_transparency:
/* Update anim buffer. */
if (animated) {
const byte a0 = src[0].a;
const byte a1 = src[1].a;
const uint8_t a0 = src[0].a;
const uint8_t a1 = src[1].a;
uint32_t anim01 = mvX2 & 0xFF00FF00;
if (a0 == 255) {
anim01 |= r0;
@ -437,7 +437,7 @@ bmcr_alpha_blend_single_brightness:
next_line:
if (mode != BM_TRANSPARENT && mode != BM_TRANSPARENT_REMAP) src_mv_line += si->sprite_width;
src_rgba_line = (const Colour*) ((const byte*) src_rgba_line + si->sprite_line_size);
src_rgba_line = (const Colour*) ((const uint8_t*) src_rgba_line + si->sprite_line_size);
dst_line += bp->pitch;
anim_line += this->anim_buf_pitch;
}

@ -41,26 +41,26 @@ inline void Blitter_32bppOptimized::Draw(const Blitter::BlitterParams *bp, ZoomL
/* skip upper lines in src_px and src_n */
for (uint i = bp->skip_top; i != 0; i--) {
src_px = (const Colour *)((const byte *)src_px + *(const uint32_t *)src_px);
src_n = (const uint16_t *)((const byte *)src_n + *(const uint32_t *)src_n);
src_px = (const Colour *)((const uint8_t *)src_px + *(const uint32_t *)src_px);
src_n = (const uint16_t *)((const uint8_t *)src_n + *(const uint32_t *)src_n);
}
/* skip lines in dst */
Colour *dst = (Colour *)bp->dst + bp->top * bp->pitch + bp->left;
/* store so we don't have to access it via bp every time (compiler assumes pointer aliasing) */
const byte *remap = bp->remap;
const uint8_t *remap = bp->remap;
for (int y = 0; y < bp->height; y++) {
/* next dst line begins here */
Colour *dst_ln = dst + bp->pitch;
/* next src line begins here */
const Colour *src_px_ln = (const Colour *)((const byte *)src_px + *(const uint32_t *)src_px);
const Colour *src_px_ln = (const Colour *)((const uint8_t *)src_px + *(const uint32_t *)src_px);
src_px++;
/* next src_n line begins here */
const uint16_t *src_n_ln = (const uint16_t *)((const byte *)src_n + *(const uint32_t *)src_n);
const uint16_t *src_n_ln = (const uint16_t *)((const uint8_t *)src_n + *(const uint32_t *)src_n);
src_n += 2;
/* we will end this line when we reach this point */
@ -459,8 +459,8 @@ template <bool Tpal_to_rgb> Sprite *Blitter_32bppOptimized::EncodeInternal(const
dst_n_ln = (uint32_t *)dst_n;
}
lengths[z][0] = (byte *)dst_px_ln - (byte *)dst_px_orig[z]; // all are aligned to 4B boundary
lengths[z][1] = (byte *)dst_n_ln - (byte *)dst_n_orig[z];
lengths[z][0] = (uint8_t *)dst_px_ln - (uint8_t *)dst_px_orig[z]; // all are aligned to 4B boundary
lengths[z][1] = (uint8_t *)dst_n_ln - (uint8_t *)dst_n_orig[z];
px_buffer_next = (Colour *)dst_px_ln;
n_buffer_next = (uint16_t *)dst_n_ln;

@ -19,7 +19,7 @@ public:
struct SpriteData {
BlitterSpriteFlags flags;
uint32_t offset[ZOOM_LVL_SPR_COUNT][2]; ///< Offsets (from .data) to streams for different zoom levels, and the normal and remap image information.
byte data[]; ///< Data, all zoomlevels.
uint8_t data[]; ///< Data, all zoomlevels.
};
Blitter_32bppOptimized()

@ -142,7 +142,7 @@ Sprite *Blitter_32bppSSE_Base::Encode(const SpriteLoader::SpriteCollection &spri
(*dst_rgba_line).data = nb_pix_transp;
Colour *nb_right = dst_rgba_line + 1;
dst_rgba_line = (Colour*) ((byte*) dst_rgba_line + sd.infos[z].sprite_line_size);
dst_rgba_line = (Colour*) ((uint8_t*) dst_rgba_line + sd.infos[z].sprite_line_size);
/* Count the number of transparent pixels from the right. */
dst_rgba = dst_rgba_line - 1;

@ -61,7 +61,7 @@ public:
struct SpriteData {
BlitterSpriteFlags flags;
SpriteInfo infos[ZOOM_LVL_SPR_COUNT];
byte data[]; ///< Data, all zoomlevels.
uint8_t data[]; ///< Data, all zoomlevels.
};
Sprite *Encode(const SpriteLoader::SpriteCollection &sprite, AllocatorProc *allocator);

@ -10,10 +10,17 @@
#ifndef BLITTER_32BPP_SSE_FUNC_HPP
#define BLITTER_32BPP_SSE_FUNC_HPP
/* ATTENTION
* This file is compiled multiple times with different defines for SSE_VERSION and MARGIN_NORMAL_THRESHOLD.
* Be careful when declaring things with external linkage.
* Use internal linkage instead, i.e. "static".
*/
#define INTERNAL_LINKAGE static
#ifdef WITH_SSE
GNU_TARGET(SSE_TARGET)
inline void InsertFirstUint32(const uint32_t value, __m128i &into)
INTERNAL_LINKAGE inline void InsertFirstUint32(const uint32_t value, __m128i &into)
{
#if (SSE_VERSION >= 4)
into = _mm_insert_epi32(into, value, 0);
@ -24,7 +31,7 @@ inline void InsertFirstUint32(const uint32_t value, __m128i &into)
}
GNU_TARGET(SSE_TARGET)
inline void InsertSecondUint32(const uint32_t value, __m128i &into)
INTERNAL_LINKAGE inline void InsertSecondUint32(const uint32_t value, __m128i &into)
{
#if (SSE_VERSION >= 4)
into = _mm_insert_epi32(into, value, 1);
@ -35,7 +42,7 @@ inline void InsertSecondUint32(const uint32_t value, __m128i &into)
}
GNU_TARGET(SSE_TARGET)
inline void LoadUint64(const uint64_t value, __m128i &into)
INTERNAL_LINKAGE inline void LoadUint64(const uint64_t value, __m128i &into)
{
#ifdef POINTER_IS_64BIT
into = _mm_cvtsi64_si128(value);
@ -50,7 +57,7 @@ inline void LoadUint64(const uint64_t value, __m128i &into)
}
GNU_TARGET(SSE_TARGET)
inline __m128i PackUnsaturated(__m128i from, const __m128i &mask)
INTERNAL_LINKAGE inline __m128i PackUnsaturated(__m128i from, const __m128i &mask)
{
#if (SSE_VERSION == 2)
from = _mm_and_si128(from, mask); // PAND, wipe high bytes to keep low bytes when packing
@ -61,7 +68,7 @@ inline __m128i PackUnsaturated(__m128i from, const __m128i &mask)
}
GNU_TARGET(SSE_TARGET)
inline __m128i DistributeAlpha(const __m128i from, const __m128i &mask)
INTERNAL_LINKAGE inline __m128i DistributeAlpha(const __m128i from, const __m128i &mask)
{
#if (SSE_VERSION == 2)
__m128i alphaAB = _mm_shufflelo_epi16(from, 0x3F); // PSHUFLW, put alpha1 in front of each rgb1
@ -73,7 +80,7 @@ inline __m128i DistributeAlpha(const __m128i from, const __m128i &mask)
}
GNU_TARGET(SSE_TARGET)
inline __m128i AlphaBlendTwoPixels(__m128i src, __m128i dst, const __m128i &distribution_mask, const __m128i &pack_mask, const __m128i &alpha_mask)
INTERNAL_LINKAGE inline __m128i AlphaBlendTwoPixels(__m128i src, __m128i dst, const __m128i &distribution_mask, const __m128i &pack_mask, const __m128i &alpha_mask)
{
__m128i srcAB = _mm_unpacklo_epi8(src, _mm_setzero_si128()); // PUNPCKLBW, expand each uint8_t into uint16
__m128i dstAB = _mm_unpacklo_epi8(dst, _mm_setzero_si128());
@ -97,7 +104,7 @@ inline __m128i AlphaBlendTwoPixels(__m128i src, __m128i dst, const __m128i &dist
* rgb = rgb * ((256/4) * 4 - (alpha/4)) / ((256/4) * 4)
*/
GNU_TARGET(SSE_TARGET)
inline __m128i DarkenTwoPixels(__m128i src, __m128i dst, const __m128i &distribution_mask, const __m128i &tr_nom_base)
INTERNAL_LINKAGE inline __m128i DarkenTwoPixels(__m128i src, __m128i dst, const __m128i &distribution_mask, const __m128i &tr_nom_base)
{
__m128i srcAB = _mm_unpacklo_epi8(src, _mm_setzero_si128());
__m128i dstAB = _mm_unpacklo_epi8(dst, _mm_setzero_si128());
@ -111,7 +118,7 @@ inline __m128i DarkenTwoPixels(__m128i src, __m128i dst, const __m128i &distribu
IGNORE_UNINITIALIZED_WARNING_START
GNU_TARGET(SSE_TARGET)
static Colour ReallyAdjustBrightness(Colour colour, uint8_t brightness)
INTERNAL_LINKAGE Colour ReallyAdjustBrightness(Colour colour, uint8_t brightness)
{
uint64_t c16 = colour.b | (uint64_t) colour.g << 16 | (uint64_t) colour.r << 32;
c16 *= brightness;
@ -145,7 +152,7 @@ IGNORE_UNINITIALIZED_WARNING_STOP
/** ReallyAdjustBrightness() is not called that often.
* Inlining this function implies a far jump, which has a huge latency.
*/
inline Colour AdjustBrightneSSE(Colour colour, uint8_t brightness)
INTERNAL_LINKAGE inline Colour AdjustBrightneSSE(Colour colour, uint8_t brightness)
{
/* Shortcut for normal brightness. */
if (likely(brightness == Blitter_32bppBase::DEFAULT_BRIGHTNESS)) return colour;
@ -154,7 +161,7 @@ inline Colour AdjustBrightneSSE(Colour colour, uint8_t brightness)
}
GNU_TARGET(SSE_TARGET)
inline __m128i AdjustBrightnessOfTwoPixels([[maybe_unused]] __m128i from, [[maybe_unused]] uint32_t brightness)
INTERNAL_LINKAGE inline __m128i AdjustBrightnessOfTwoPixels([[maybe_unused]] __m128i from, [[maybe_unused]] uint32_t brightness)
{
#if (SSE_VERSION < 3)
NOT_REACHED();
@ -214,7 +221,7 @@ inline void Blitter_32bppSSSE3::Draw(const Blitter::BlitterParams *bp, ZoomLevel
inline void Blitter_32bppSSE4::Draw(const Blitter::BlitterParams *bp, ZoomLevel zoom)
#endif
{
const byte * const remap = bp->remap;
const uint8_t * const remap = bp->remap;
Colour *dst_line = (Colour *) bp->dst + bp->top * bp->pitch + bp->left;
int effective_width = bp->width;
@ -222,7 +229,7 @@ inline void Blitter_32bppSSE4::Draw(const Blitter::BlitterParams *bp, ZoomLevel
const SpriteData * const sd = (const SpriteData *) bp->sprite;
const SpriteInfo * const si = &sd->infos[zoom];
const MapValue *src_mv_line = (const MapValue *) &sd->data[si->mv_offset] + bp->skip_top * si->sprite_width;
const Colour *src_rgba_line = (const Colour *) ((const byte *) &sd->data[si->sprite_offset] + bp->skip_top * si->sprite_line_size);
const Colour *src_rgba_line = (const Colour *) ((const uint8_t *) &sd->data[si->sprite_offset] + bp->skip_top * si->sprite_line_size);
uint32_t bm_normal_brightness = 0;
if (mode == BM_NORMAL_WITH_BRIGHTNESS) {
@ -313,7 +320,7 @@ inline void Blitter_32bppSSE4::Draw(const Blitter::BlitterParams *bp, ZoomLevel
Colour m_colour = m_colour_init; \
{ \
const Colour srcm = (Colour) (m_src); \
const uint m = (byte) (m_m); \
const uint m = (uint8_t) (m_m); \
const uint r = remap[m]; \
const Colour cmap = (this->LookupColourInPalette(r).data & 0x00FFFFFF) | (srcm.data & 0xFF000000); \
m_colour = r == 0 ? m_colour : cmap; \
@ -496,7 +503,7 @@ bmcr_alpha_blend_single_brightness:
next_line:
if (mode == BM_COLOUR_REMAP || mode == BM_CRASH_REMAP || mode == BM_COLOUR_REMAP_WITH_BRIGHTNESS) src_mv_line += si->sprite_width;
src_rgba_line = (const Colour*) ((const byte*) src_rgba_line + si->sprite_line_size);
src_rgba_line = (const Colour*) ((const uint8_t*) src_rgba_line + si->sprite_line_size);
dst_line += bp->pitch;
}
}

@ -10,6 +10,12 @@
#ifndef BLITTER_32BPP_SSE_TYPE_H
#define BLITTER_32BPP_SSE_TYPE_H
/* ATTENTION
* This file is compiled multiple times with different defines for SSE_VERSION.
* Be careful when declaring things with external linkage.
* Use internal linkage instead, i.e. "static".
*/
#ifdef WITH_SSE
#include "32bpp_simple.hpp"

@ -167,8 +167,8 @@ inline void Blitter_40bppAnim::Draw(const Blitter::BlitterParams *bp, ZoomLevel
/* skip upper lines in src_px and src_n */
for (uint i = bp->skip_top; i != 0; i--) {
src_px = (const Colour *)((const byte *)src_px + *(const uint32_t *)src_px);
src_n = (const uint16_t *)((const byte *)src_n + *(const uint32_t *)src_n);
src_px = (const Colour *)((const uint8_t *)src_px + *(const uint32_t *)src_px);
src_n = (const uint16_t *)((const uint8_t *)src_n + *(const uint32_t *)src_n);
}
/* skip lines in dst */
@ -177,7 +177,7 @@ inline void Blitter_40bppAnim::Draw(const Blitter::BlitterParams *bp, ZoomLevel
uint8_t *anim = VideoDriver::GetInstance()->GetAnimBuffer() + ((uint32_t *)bp->dst - (uint32_t *)_screen.dst_ptr) + bp->top * bp->pitch + bp->left;
/* store so we don't have to access it via bp everytime (compiler assumes pointer aliasing) */
const byte *remap = bp->remap;
const uint8_t *remap = bp->remap;
for (int y = 0; y < bp->height; y++) {
/* next dst line begins here */
@ -185,11 +185,11 @@ inline void Blitter_40bppAnim::Draw(const Blitter::BlitterParams *bp, ZoomLevel
uint8_t *anim_ln = anim + bp->pitch;
/* next src line begins here */
const Colour *src_px_ln = (const Colour *)((const byte *)src_px + *(const uint32_t *)src_px);
const Colour *src_px_ln = (const Colour *)((const uint8_t *)src_px + *(const uint32_t *)src_px);
src_px++;
/* next src_n line begins here */
const uint16_t *src_n_ln = (const uint16_t *)((const byte *)src_n + *(const uint32_t *)src_n);
const uint16_t *src_n_ln = (const uint16_t *)((const uint8_t *)src_n + *(const uint32_t *)src_n);
src_n += 2;
/* we will end this line when we reach this point */

@ -148,10 +148,10 @@ Sprite *Blitter_8bppOptimized::Encode(const SpriteLoader::SpriteCollection &spri
/* Don't allocate memory each time, but just keep some
* memory around as this function is called quite often
* and the memory usage is quite low. */
static ReusableBuffer<byte> temp_buffer;
static ReusableBuffer<uint8_t> temp_buffer;
SpriteData *temp_dst = (SpriteData *)temp_buffer.Allocate(memory);
memset(temp_dst, 0, sizeof(*temp_dst));
byte *dst = temp_dst->data;
uint8_t *dst = temp_dst->data;
/* Make the sprites per zoom-level */
for (ZoomLevel i = zoom_min; i <= zoom_max; i++) {
@ -167,7 +167,7 @@ Sprite *Blitter_8bppOptimized::Encode(const SpriteLoader::SpriteCollection &spri
uint trans = 0;
uint pixels = 0;
uint last_colour = 0;
byte *count_dst = nullptr;
uint8_t *count_dst = nullptr;
/* Store the scaled image */
const SpriteLoader::CommonPixel *src = &sprite[i].data[y * sprite[i].width];
@ -214,7 +214,7 @@ Sprite *Blitter_8bppOptimized::Encode(const SpriteLoader::SpriteCollection &spri
}
}
uint size = dst - (byte *)temp_dst;
uint size = dst - (uint8_t *)temp_dst;
/* Safety check, to make sure we guessed the size correctly */
assert(size < memory);

@ -19,7 +19,7 @@ public:
/** Data stored about a (single) sprite. */
struct SpriteData {
uint32_t offset[ZOOM_LVL_SPR_COUNT]; ///< Offsets (from .data) to streams for different zoom levels.
byte data[]; ///< Data, all zoomlevels.
uint8_t data[]; ///< Data, all zoomlevels.
};
void Draw(Blitter::BlitterParams *bp, BlitterMode mode, ZoomLevel zoom) override;

@ -58,7 +58,7 @@ public:
/** Parameters related to blitting. */
struct BlitterParams {
const void *sprite; ///< Pointer to the sprite how ever the encoder stored it
const byte *remap; ///< XXX -- Temporary storage for remap array
const uint8_t *remap; ///< XXX -- Temporary storage for remap array
int brightness_adjust; ///< Brightness adjustment
int skip_left; ///< How much pixels of the source to skip on the left (based on zoom of dst)

@ -39,7 +39,7 @@ static inline bool EndOfBuffer(BmpBuffer *buffer)
return buffer->pos == buffer->read;
}
static inline byte ReadByte(BmpBuffer *buffer)
static inline uint8_t ReadByte(BmpBuffer *buffer)
{
if (buffer->read < 0) return 0;
@ -83,9 +83,9 @@ static inline void SetStreamOffset(BmpBuffer *buffer, int offset)
static inline bool BmpRead1(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
{
uint x, y, i;
byte pad = GB(4 - info->width / 8, 0, 2);
byte *pixel_row;
byte b;
uint8_t pad = GB(4 - info->width / 8, 0, 2);
uint8_t *pixel_row;
uint8_t b;
for (y = info->height; y > 0; y--) {
x = 0;
pixel_row = &data->bitmap[(y - 1) * info->width];
@ -110,9 +110,9 @@ static inline bool BmpRead1(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
static inline bool BmpRead4(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
{
uint x, y;
byte pad = GB(4 - info->width / 2, 0, 2);
byte *pixel_row;
byte b;
uint8_t pad = GB(4 - info->width / 2, 0, 2);
uint8_t *pixel_row;
uint8_t b;
for (y = info->height; y > 0; y--) {
x = 0;
pixel_row = &data->bitmap[(y - 1) * info->width];
@ -140,12 +140,12 @@ static inline bool BmpRead4Rle(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
{
uint x = 0;
uint y = info->height - 1;
byte *pixel = &data->bitmap[y * info->width];
uint8_t *pixel = &data->bitmap[y * info->width];
while (y != 0 || x < info->width) {
if (EndOfBuffer(buffer)) return false; // the file is shorter than expected
byte n = ReadByte(buffer);
byte c = ReadByte(buffer);
uint8_t n = ReadByte(buffer);
uint8_t c = ReadByte(buffer);
if (n == 0) {
switch (c) {
case 0: // end of line
@ -159,8 +159,8 @@ static inline bool BmpRead4Rle(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
case 2: { // delta
if (EndOfBuffer(buffer)) return false;
byte dx = ReadByte(buffer);
byte dy = ReadByte(buffer);
uint8_t dx = ReadByte(buffer);
uint8_t dy = ReadByte(buffer);
/* Check for over- and underflow. */
if (x + dx >= info->width || x + dx < x || dy > y) return false;
@ -175,7 +175,7 @@ static inline bool BmpRead4Rle(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
uint i = 0;
while (i++ < c) {
if (EndOfBuffer(buffer) || x >= info->width) return false;
byte b = ReadByte(buffer);
uint8_t b = ReadByte(buffer);
*pixel++ = GB(b, 4, 4);
x++;
if (i++ < c) {
@ -214,8 +214,8 @@ static inline bool BmpRead8(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
{
uint i;
uint y;
byte pad = GB(4 - info->width, 0, 2);
byte *pixel;
uint8_t pad = GB(4 - info->width, 0, 2);
uint8_t *pixel;
for (y = info->height; y > 0; y--) {
if (EndOfBuffer(buffer)) return false; // the file is shorter than expected
pixel = &data->bitmap[(y - 1) * info->width];
@ -233,12 +233,12 @@ static inline bool BmpRead8Rle(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
{
uint x = 0;
uint y = info->height - 1;
byte *pixel = &data->bitmap[y * info->width];
uint8_t *pixel = &data->bitmap[y * info->width];
while (y != 0 || x < info->width) {
if (EndOfBuffer(buffer)) return false; // the file is shorter than expected
byte n = ReadByte(buffer);
byte c = ReadByte(buffer);
uint8_t n = ReadByte(buffer);
uint8_t c = ReadByte(buffer);
if (n == 0) {
switch (c) {
case 0: // end of line
@ -252,8 +252,8 @@ static inline bool BmpRead8Rle(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
case 2: { // delta
if (EndOfBuffer(buffer)) return false;
byte dx = ReadByte(buffer);
byte dy = ReadByte(buffer);
uint8_t dx = ReadByte(buffer);
uint8_t dy = ReadByte(buffer);
/* Check for over- and underflow. */
if (x + dx >= info->width || x + dx < x || dy > y) return false;
@ -294,8 +294,8 @@ static inline bool BmpRead8Rle(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
static inline bool BmpRead24(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
{
uint x, y;
byte pad = GB(4 - info->width * 3, 0, 2);
byte *pixel_row;
uint8_t pad = GB(4 - info->width * 3, 0, 2);
uint8_t *pixel_row;
for (y = info->height; y > 0; y--) {
pixel_row = &data->bitmap[(y - 1) * info->width * 3];
for (x = 0; x < info->width; x++) {
@ -395,7 +395,7 @@ bool BmpReadBitmap(BmpBuffer *buffer, BmpInfo *info, BmpData *data)
{
assert(info != nullptr && data != nullptr);
data->bitmap = CallocT<byte>(static_cast<size_t>(info->width) * info->height * ((info->bpp == 24) ? 3 : 1));
data->bitmap = CallocT<uint8_t>(static_cast<size_t>(info->width) * info->height * ((info->bpp == 24) ? 3 : 1));
/* Load image */
SetStreamOffset(buffer, info->offset);

@ -24,13 +24,13 @@ struct BmpInfo {
struct BmpData {
Colour *palette;
byte *bitmap;
uint8_t *bitmap;
};
#define BMP_BUFFER_SIZE 1024
struct BmpBuffer {
byte data[BMP_BUFFER_SIZE];
uint8_t data[BMP_BUFFER_SIZE];
int pos;
int read;
FILE *file;

@ -63,7 +63,7 @@ enum BridgeSpecCtrlFlags {
*/
struct BridgeSpec {
CalTime::Year avail_year; ///< the year where it becomes available
byte min_length; ///< the minimum length (not counting start and end tile)
uint8_t min_length; ///< the minimum length (not counting start and end tile)
uint16_t max_length; ///< the maximum length (not counting start and end tile)
uint16_t price; ///< the price multiplier
uint16_t speed; ///< maximum travel speed (1 unit = 1/1.6 mph = 1 km-ish/h)
@ -72,9 +72,9 @@ struct BridgeSpec {
StringID material; ///< the string that contains the bridge description
StringID transport_name[2]; ///< description of the bridge, when built for road or rail
PalSpriteID **sprite_table; ///< table of sprites for drawing the bridge
byte flags; ///< bit 0 set: disable drawing of far pillars.
byte ctrl_flags; ///< control flags
byte pillar_flags[12]; ///< bridge pillar flags: 6 x pairs of x and y flags
uint8_t flags; ///< bit 0 set: disable drawing of far pillars.
uint8_t ctrl_flags; ///< control flags
uint8_t pillar_flags[12]; ///< bridge pillar flags: 6 x pairs of x and y flags
};
extern BridgeSpec _bridge[MAX_BRIDGES];

@ -18,7 +18,7 @@
#include "gfx_func.h"
#include "tunnelbridge.h"
#include "sortlist_type.h"
#include "widgets/dropdown_func.h"
#include "dropdown_func.h"
#include "core/geometry_func.hpp"
#include "cmd_helper.h"
#include "tunnelbridge_map.h"
@ -373,7 +373,7 @@ static WindowDesc _build_bridge_desc(__FILE__, __LINE__,
* @param transport_type The transport type
* @param road_rail_type The road/rail type
*/
void ShowBuildBridgeWindow(TileIndex start, TileIndex end, TransportType transport_type, byte road_rail_type)
void ShowBuildBridgeWindow(TileIndex start, TileIndex end, TransportType transport_type, uint8_t road_rail_type)
{
CloseWindowByClass(WC_BUILD_BRIDGE);

@ -360,7 +360,7 @@ inline bool IsCustomBridgeHeadTile(TileIndex t)
inline TrackBits GetBridgeReservationTrackBits(TileIndex t)
{
assert_tile(IsRailBridgeHeadTile(t), t);
byte track_b = GB(_m[t].m2, 0, 3);
uint8_t track_b = GB(_m[t].m2, 0, 3);
Track track = (Track)(track_b - 1); // map array saves Track+1
if (track_b == 0) return TRACK_BIT_NONE;
return (TrackBits)(TrackToTrackBits(track) | (HasBit(_m[t].m2, 3) ? TrackToTrackBits(TrackToOppositeTrack(track)) : 0));
@ -378,7 +378,7 @@ inline void SetBridgeReservationTrackBits(TileIndex t, TrackBits b)
assert(!TracksOverlap(b));
Track track = RemoveFirstTrack(&b);
SB(_m[t].m2, 0, 3, track == INVALID_TRACK ? 0 : track + 1);
SB(_m[t].m2, 3, 1, (byte)(b != TRACK_BIT_NONE));
SB(_m[t].m2, 3, 1, (uint8_t)(b != TRACK_BIT_NONE));
}

@ -25,7 +25,7 @@
#include "window_func.h"
#include "date_func.h"
#include "vehicle_func.h"
#include "widgets/dropdown_func.h"
#include "dropdown_func.h"
#include "engine_gui.h"
#include "cargotype.h"
#include "core/geometry_func.hpp"
@ -197,19 +197,19 @@ static constexpr NWidgetPart _nested_build_vehicle_widgets_train_advanced[] = {
EndContainer(),
};
bool _engine_sort_direction; ///< \c false = descending, \c true = ascending.
byte _engine_sort_last_criteria[] = {0, 0, 0, 0}; ///< Last set sort criteria, for each vehicle type.
bool _engine_sort_direction; ///< \c false = descending, \c true = ascending.
uint8_t _engine_sort_last_criteria[] = {0, 0, 0, 0}; ///< Last set sort criteria, for each vehicle type.
bool _engine_sort_last_order[] = {false, false, false, false}; ///< Last set direction of the sort order, for each vehicle type.
bool _engine_sort_show_hidden_engines[] = {false, false, false, false}; ///< Last set 'show hidden engines' setting for each vehicle type.
bool _engine_sort_show_hidden_locos = false; ///< Last set 'show hidden locos' setting.
bool _engine_sort_show_hidden_wagons = false; ///< Last set 'show hidden wagons' setting.
static CargoID _engine_sort_last_cargo_criteria[] = {CargoFilterCriteria::CF_ANY, CargoFilterCriteria::CF_ANY, CargoFilterCriteria::CF_ANY, CargoFilterCriteria::CF_ANY}; ///< Last set filter criteria, for each vehicle type.
static byte _last_sort_criteria_loco = 0;
static uint8_t _last_sort_criteria_loco = 0;
static bool _last_sort_order_loco = false;
static CargoID _last_filter_criteria_loco = CargoFilterCriteria::CF_ANY;
static byte _last_sort_criteria_wagon = 0;
static uint8_t _last_sort_criteria_wagon = 0;
static bool _last_sort_order_wagon = false;
static CargoID _last_filter_criteria_wagon = CargoFilterCriteria::CF_ANY;
@ -219,7 +219,7 @@ static CargoID _last_filter_criteria_wagon = CargoFilterCriteria::CF_ANY;
* @param b second engine to compare
* @return for descending order: returns true if a < b. Vice versa for ascending order
*/
static bool EngineNumberSorter(const GUIEngineListItem &a, const GUIEngineListItem &b)
static bool EngineNumberSorter(const GUIEngineListItem &a, const GUIEngineListItem &b, const GUIEngineListSortCache &cache)
{
int r = Engine::Get(a.engine_id)->list_position - Engine::Get(b.engine_id)->list_position;
@ -232,14 +232,14 @@ static bool EngineNumberSorter(const GUIEngineListItem &a, const GUIEngineListIt
* @param b second engine to compare
* @return for descending order: returns true if a < b. Vice versa for ascending order
*/
static bool EngineIntroDateSorter(const GUIEngineListItem &a, const GUIEngineListItem &b)
static bool EngineIntroDateSorter(const GUIEngineListItem &a, const GUIEngineListItem &b, const GUIEngineListSortCache &cache)
{
const auto va = Engine::Get(a.engine_id)->intro_date;
const auto vb = Engine::Get(b.engine_id)->intro_date;
const auto r = va - vb;
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
if (r == 0) return EngineNumberSorter(a, b, cache);
return _engine_sort_direction ? r > 0 : r < 0;
}
@ -249,13 +249,13 @@ static bool EngineIntroDateSorter(const GUIEngineListItem &a, const GUIEngineLis
* @param b second engine to compare
* @return for descending order: returns true if a < b. Vice versa for ascending order
*/
static bool EngineVehicleCountSorter(const GUIEngineListItem &a, const GUIEngineListItem &b)
static bool EngineVehicleCountSorter(const GUIEngineListItem &a, const GUIEngineListItem &b, const GUIEngineListSortCache &cache)
{
const GroupStatistics &stats = GroupStatistics::Get(_local_company, ALL_GROUP, Engine::Get(a.engine_id)->type);
const int r = ((int) stats.GetNumEngines(a.engine_id)) - ((int) stats.GetNumEngines(b.engine_id));
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
if (r == 0) return EngineNumberSorter(a, b, cache);
return _engine_sort_direction ? r > 0 : r < 0;
}
@ -268,7 +268,7 @@ static EngineID _last_engine[2] = { INVALID_ENGINE, INVALID_ENGINE };
* @param b second engine to compare
* @return for descending order: returns true if a < b. Vice versa for ascending order
*/
static bool EngineNameSorter(const GUIEngineListItem &a, const GUIEngineListItem &b)
static bool EngineNameSorter(const GUIEngineListItem &a, const GUIEngineListItem &b, const GUIEngineListSortCache &cache)
{
static std::string last_name[2] = { {}, {} };
@ -287,7 +287,7 @@ static bool EngineNameSorter(const GUIEngineListItem &a, const GUIEngineListItem
int r = StrNaturalCompare(last_name[0], last_name[1]); // Sort by name (natural sorting).
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
if (r == 0) return EngineNumberSorter(a, b, cache);
return _engine_sort_direction ? r > 0 : r < 0;
}
@ -297,14 +297,14 @@ static bool EngineNameSorter(const GUIEngineListItem &a, const GUIEngineListItem
* @param b second engine to compare
* @return for descending order: returns true if a < b. Vice versa for ascending order
*/
static bool EngineReliabilitySorter(const GUIEngineListItem &a, const GUIEngineListItem &b)
static bool EngineReliabilitySorter(const GUIEngineListItem &a, const GUIEngineListItem &b, const GUIEngineListSortCache &cache)
{
const int va = Engine::Get(a.engine_id)->reliability;
const int vb = Engine::Get(b.engine_id)->reliability;
const int r = va - vb;
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
if (r == 0) return EngineNumberSorter(a, b, cache);
return _engine_sort_direction ? r > 0 : r < 0;
}
@ -314,14 +314,14 @@ static bool EngineReliabilitySorter(const GUIEngineListItem &a, const GUIEngineL
* @param b second engine to compare
* @return for descending order: returns true if a < b. Vice versa for ascending order
*/
static bool EngineCostSorter(const GUIEngineListItem &a, const GUIEngineListItem &b)
static bool EngineCostSorter(const GUIEngineListItem &a, const GUIEngineListItem &b, const GUIEngineListSortCache &cache)
{
Money va = Engine::Get(a.engine_id)->GetCost();
Money vb = Engine::Get(b.engine_id)->GetCost();
int r = ClampTo<int32_t>(va - vb);
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
if (r == 0) return EngineNumberSorter(a, b, cache);
return _engine_sort_direction ? r > 0 : r < 0;
}
@ -331,14 +331,14 @@ static bool EngineCostSorter(const GUIEngineListItem &a, const GUIEngineListItem
* @param b second engine to compare
* @return for descending order: returns true if a < b. Vice versa for ascending order
*/
static bool EngineSpeedSorter(const GUIEngineListItem &a, const GUIEngineListItem &b)
static bool EngineSpeedSorter(const GUIEngineListItem &a, const GUIEngineListItem &b, const GUIEngineListSortCache &cache)
{
int va = Engine::Get(a.engine_id)->GetDisplayMaxSpeed();
int vb = Engine::Get(b.engine_id)->GetDisplayMaxSpeed();
int r = va - vb;
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
if (r == 0) return EngineNumberSorter(a, b, cache);
return _engine_sort_direction ? r > 0 : r < 0;
}
@ -348,14 +348,14 @@ static bool EngineSpeedSorter(const GUIEngineListItem &a, const GUIEngineListIte
* @param b second engine to compare
* @return for descending order: returns true if a < b. Vice versa for ascending order
*/
static bool EnginePowerSorter(const GUIEngineListItem &a, const GUIEngineListItem &b)
static bool EnginePowerSorter(const GUIEngineListItem &a, const GUIEngineListItem &b, const GUIEngineListSortCache &cache)
{
int va = Engine::Get(a.engine_id)->GetPower();
int vb = Engine::Get(b.engine_id)->GetPower();
int r = va - vb;
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
if (r == 0) return EngineNumberSorter(a, b, cache);
return _engine_sort_direction ? r > 0 : r < 0;
}
@ -365,14 +365,14 @@ static bool EnginePowerSorter(const GUIEngineListItem &a, const GUIEngineListIte
* @param b second engine to compare
* @return for descending order: returns true if a < b. Vice versa for ascending order
*/
static bool EngineTractiveEffortSorter(const GUIEngineListItem &a, const GUIEngineListItem &b)
static bool EngineTractiveEffortSorter(const GUIEngineListItem &a, const GUIEngineListItem &b, const GUIEngineListSortCache &cache)
{
int va = Engine::Get(a.engine_id)->GetDisplayMaxTractiveEffort();
int vb = Engine::Get(b.engine_id)->GetDisplayMaxTractiveEffort();
int r = va - vb;
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
if (r == 0) return EngineNumberSorter(a, b, cache);
return _engine_sort_direction ? r > 0 : r < 0;
}
@ -382,18 +382,18 @@ static bool EngineTractiveEffortSorter(const GUIEngineListItem &a, const GUIEngi
* @param b second engine to compare
* @return for descending order: returns true if a < b. Vice versa for ascending order
*/
static bool EngineRunningCostSorter(const GUIEngineListItem &a, const GUIEngineListItem &b)
static bool EngineRunningCostSorter(const GUIEngineListItem &a, const GUIEngineListItem &b, const GUIEngineListSortCache &cache)
{
Money va = Engine::Get(a.engine_id)->GetRunningCost();
Money vb = Engine::Get(b.engine_id)->GetRunningCost();
int r = ClampTo<int32_t>(va - vb);
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
if (r == 0) return EngineNumberSorter(a, b, cache);
return _engine_sort_direction ? r > 0 : r < 0;
}
static bool GenericEngineValueVsRunningCostSorter(const GUIEngineListItem &a, const uint value_a, const GUIEngineListItem &b, const uint value_b)
static bool GenericEngineValueVsRunningCostSorter(const GUIEngineListItem &a, const uint value_a, const GUIEngineListItem &b, const uint value_b, const GUIEngineListSortCache &cache)
{
const Engine *e_a = Engine::Get(a.engine_id);
const Engine *e_b = Engine::Get(b.engine_id);
@ -405,7 +405,7 @@ static bool GenericEngineValueVsRunningCostSorter(const GUIEngineListItem &a, co
if (r_a == 0) {
if (r_b == 0) {
/* If it is ambiguous which to return go with their ID */
if (value_a == value_b) return EngineNumberSorter(a, b);
if (value_a == value_b) return EngineNumberSorter(a, b, cache);
return _engine_sort_direction != (value_a < value_b);
}
return !_engine_sort_direction;
@ -420,8 +420,8 @@ static bool GenericEngineValueVsRunningCostSorter(const GUIEngineListItem &a, co
* since we want consistent sorting.
* Also if both have no power then sort with reverse of running cost to simulate
* previous sorting behaviour for wagons. */
if (v_a == 0 && v_b == 0) return EngineRunningCostSorter(b, a);
if (v_a == v_b) return EngineNumberSorter(a, b);
if (v_a == 0 && v_b == 0) return EngineRunningCostSorter(b, a, cache);
if (v_a == v_b) return EngineNumberSorter(a, b, cache);
return _engine_sort_direction != (v_a < v_b);
}
@ -431,9 +431,9 @@ static bool GenericEngineValueVsRunningCostSorter(const GUIEngineListItem &a, co
* @param b second engine to compare
* @return for descending order: returns true if a < b. Vice versa for ascending order
*/
static bool EnginePowerVsRunningCostSorter(const GUIEngineListItem &a, const GUIEngineListItem &b)
static bool EnginePowerVsRunningCostSorter(const GUIEngineListItem &a, const GUIEngineListItem &b, const GUIEngineListSortCache &cache)
{
return GenericEngineValueVsRunningCostSorter(a, Engine::Get(a.engine_id)->GetPower(), b, Engine::Get(b.engine_id)->GetPower());
return GenericEngineValueVsRunningCostSorter(a, Engine::Get(a.engine_id)->GetPower(), b, Engine::Get(b.engine_id)->GetPower(), cache);
}
/* Train sorting functions */
@ -444,17 +444,17 @@ static bool EnginePowerVsRunningCostSorter(const GUIEngineListItem &a, const GUI
* @param b second engine to compare
* @return for descending order: returns true if a < b. Vice versa for ascending order
*/
static bool TrainEngineCapacitySorter(const GUIEngineListItem &a, const GUIEngineListItem &b)
static bool TrainEngineCapacitySorter(const GUIEngineListItem &a, const GUIEngineListItem &b, const GUIEngineListSortCache &cache)
{
const RailVehicleInfo *rvi_a = RailVehInfo(a.engine_id);
const RailVehicleInfo *rvi_b = RailVehInfo(b.engine_id);
int va = GetTotalCapacityOfArticulatedParts(a.engine_id) * (rvi_a->railveh_type == RAILVEH_MULTIHEAD ? 2 : 1);
int vb = GetTotalCapacityOfArticulatedParts(b.engine_id) * (rvi_b->railveh_type == RAILVEH_MULTIHEAD ? 2 : 1);
int va = cache.GetArticulatedCapacity(a.engine_id, rvi_a->railveh_type == RAILVEH_MULTIHEAD);
int vb = cache.GetArticulatedCapacity(b.engine_id, rvi_b->railveh_type == RAILVEH_MULTIHEAD);
int r = va - vb;
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
if (r == 0) return EngineNumberSorter(a, b, cache);
return _engine_sort_direction ? r > 0 : r < 0;
}
@ -464,15 +464,15 @@ static bool TrainEngineCapacitySorter(const GUIEngineListItem &a, const GUIEngin
* @param b second engine to compare
* @return for descending order: returns true if a < b. Vice versa for ascending order
*/
static bool TrainEngineCapacityVsRunningCostSorter(const GUIEngineListItem &a, const GUIEngineListItem &b)
static bool TrainEngineCapacityVsRunningCostSorter(const GUIEngineListItem &a, const GUIEngineListItem &b, const GUIEngineListSortCache &cache)
{
const RailVehicleInfo *rvi_a = RailVehInfo(a.engine_id);
const RailVehicleInfo *rvi_b = RailVehInfo(b.engine_id);
uint va = GetTotalCapacityOfArticulatedParts(a.engine_id) * (rvi_a->railveh_type == RAILVEH_MULTIHEAD ? 2 : 1);
uint vb = GetTotalCapacityOfArticulatedParts(b.engine_id) * (rvi_b->railveh_type == RAILVEH_MULTIHEAD ? 2 : 1);
uint va = cache.GetArticulatedCapacity(a.engine_id, rvi_a->railveh_type == RAILVEH_MULTIHEAD);
uint vb = cache.GetArticulatedCapacity(b.engine_id, rvi_b->railveh_type == RAILVEH_MULTIHEAD);
return GenericEngineValueVsRunningCostSorter(a, va, b, vb);
return GenericEngineValueVsRunningCostSorter(a, va, b, vb, cache);
}
/**
@ -481,14 +481,14 @@ static bool TrainEngineCapacityVsRunningCostSorter(const GUIEngineListItem &a, c
* @param b second engine to compare
* @return for descending order: returns true if a < b. Vice versa for ascending order
*/
static bool TrainEnginesThenWagonsSorter(const GUIEngineListItem &a, const GUIEngineListItem &b)
static bool TrainEnginesThenWagonsSorter(const GUIEngineListItem &a, const GUIEngineListItem &b, const GUIEngineListSortCache &cache)
{
int val_a = (RailVehInfo(a.engine_id)->railveh_type == RAILVEH_WAGON ? 1 : 0);
int val_b = (RailVehInfo(b.engine_id)->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);
if (r == 0) return EngineNumberSorter(a, b, cache);
return _engine_sort_direction ? r > 0 : r < 0;
}
@ -500,14 +500,14 @@ static bool TrainEnginesThenWagonsSorter(const GUIEngineListItem &a, const GUIEn
* @param b second engine to compare
* @return for descending order: returns true if a < b. Vice versa for ascending order
*/
static bool RoadVehEngineCapacitySorter(const GUIEngineListItem &a, const GUIEngineListItem &b)
static bool RoadVehEngineCapacitySorter(const GUIEngineListItem &a, const GUIEngineListItem &b, const GUIEngineListSortCache &cache)
{
int va = GetTotalCapacityOfArticulatedParts(a.engine_id);
int vb = GetTotalCapacityOfArticulatedParts(b.engine_id);
int va = cache.GetArticulatedCapacity(a.engine_id);
int vb = cache.GetArticulatedCapacity(b.engine_id);
int r = va - vb;
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
if (r == 0) return EngineNumberSorter(a, b, cache);
return _engine_sort_direction ? r > 0 : r < 0;
}
@ -517,9 +517,11 @@ static bool RoadVehEngineCapacitySorter(const GUIEngineListItem &a, const GUIEng
* @param b second engine to compare
* @return for descending order: returns true if a < b. Vice versa for ascending order
*/
static bool RoadVehEngineCapacityVsRunningCostSorter(const GUIEngineListItem &a, const GUIEngineListItem &b)
static bool RoadVehEngineCapacityVsRunningCostSorter(const GUIEngineListItem &a, const GUIEngineListItem &b, const GUIEngineListSortCache &cache)
{
return GenericEngineValueVsRunningCostSorter(a, GetTotalCapacityOfArticulatedParts(a.engine_id), b, GetTotalCapacityOfArticulatedParts(b.engine_id));
int capacity_a = cache.GetArticulatedCapacity(a.engine_id);
int capacity_b = cache.GetArticulatedCapacity(b.engine_id);
return GenericEngineValueVsRunningCostSorter(a, capacity_a, b, capacity_b, cache);
}
/* Ship vehicle sorting functions */
@ -530,14 +532,14 @@ static bool RoadVehEngineCapacityVsRunningCostSorter(const GUIEngineListItem &a,
* @param b second engine to compare
* @return for descending order: returns true if a < b. Vice versa for ascending order
*/
static bool ShipEngineCapacitySorter(const GUIEngineListItem &a, const GUIEngineListItem &b)
static bool ShipEngineCapacitySorter(const GUIEngineListItem &a, const GUIEngineListItem &b, const GUIEngineListSortCache &cache)
{
int va = GetTotalCapacityOfArticulatedParts(a.engine_id);
int vb = GetTotalCapacityOfArticulatedParts(b.engine_id);
int va = cache.GetArticulatedCapacity(a.engine_id);
int vb = cache.GetArticulatedCapacity(b.engine_id);
int r = va - vb;
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
if (r == 0) return EngineNumberSorter(a, b, cache);
return _engine_sort_direction ? r > 0 : r < 0;
}
@ -547,9 +549,11 @@ static bool ShipEngineCapacitySorter(const GUIEngineListItem &a, const GUIEngine
* @param b second engine to compare
* @return for descending order: returns true if a < b. Vice versa for ascending order
*/
static bool ShipEngineCapacityVsRunningCostSorter(const GUIEngineListItem &a, const GUIEngineListItem &b)
static bool ShipEngineCapacityVsRunningCostSorter(const GUIEngineListItem &a, const GUIEngineListItem &b, const GUIEngineListSortCache &cache)
{
return GenericEngineValueVsRunningCostSorter(a, GetTotalCapacityOfArticulatedParts(a.engine_id), b, GetTotalCapacityOfArticulatedParts(b.engine_id));
int capacity_a = cache.GetArticulatedCapacity(a.engine_id);
int capacity_b = cache.GetArticulatedCapacity(b.engine_id);
return GenericEngineValueVsRunningCostSorter(a, capacity_a, b, capacity_b, cache);
}
/* Aircraft sorting functions */
@ -560,7 +564,7 @@ static bool ShipEngineCapacityVsRunningCostSorter(const GUIEngineListItem &a, co
* @param b second engine to compare
* @return for descending order: returns true if a < b. Vice versa for ascending order
*/
static bool AircraftEngineCargoSorter(const GUIEngineListItem &a, const GUIEngineListItem &b)
static bool AircraftEngineCargoSorter(const GUIEngineListItem &a, const GUIEngineListItem &b, const GUIEngineListSortCache &cache)
{
const Engine *e_a = Engine::Get(a.engine_id);
const Engine *e_b = Engine::Get(b.engine_id);
@ -576,7 +580,7 @@ static bool AircraftEngineCargoSorter(const GUIEngineListItem &a, const GUIEngin
if (r == 0) {
/* Use EngineID to sort instead since we want consistent sorting */
return EngineNumberSorter(a, b);
return EngineNumberSorter(a, b, cache);
}
}
return _engine_sort_direction ? r > 0 : r < 0;
@ -588,7 +592,7 @@ static bool AircraftEngineCargoSorter(const GUIEngineListItem &a, const GUIEngin
* @param b second engine to compare
* @return for descending order: returns true if a < b. Vice versa for ascending order
*/
static bool AircraftEngineCapacityVsRunningCostSorter(const GUIEngineListItem &a, const GUIEngineListItem &b)
static bool AircraftEngineCapacityVsRunningCostSorter(const GUIEngineListItem &a, const GUIEngineListItem &b, const GUIEngineListSortCache &cache)
{
const Engine *e_a = Engine::Get(a.engine_id);
const Engine *e_b = Engine::Get(b.engine_id);
@ -597,7 +601,7 @@ static bool AircraftEngineCapacityVsRunningCostSorter(const GUIEngineListItem &a
int va = e_a->GetDisplayDefaultCapacity(&mail_a);
int vb = e_b->GetDisplayDefaultCapacity(&mail_b);
return GenericEngineValueVsRunningCostSorter(a, va + mail_a, b, vb + mail_b);
return GenericEngineValueVsRunningCostSorter(a, va + mail_a, b, vb + mail_b, cache);
}
/**
@ -606,7 +610,7 @@ static bool AircraftEngineCapacityVsRunningCostSorter(const GUIEngineListItem &a
* @param b second engine to compare
* @return for descending order: returns true if a < b. Vice versa for ascending order
*/
static bool AircraftRangeSorter(const GUIEngineListItem &a, const GUIEngineListItem &b)
static bool AircraftRangeSorter(const GUIEngineListItem &a, const GUIEngineListItem &b, const GUIEngineListSortCache &cache)
{
uint16_t r_a = Engine::Get(a.engine_id)->GetRange();
uint16_t r_b = Engine::Get(b.engine_id)->GetRange();
@ -614,7 +618,7 @@ static bool AircraftRangeSorter(const GUIEngineListItem &a, const GUIEngineListI
int r = r_a - r_b;
/* Use EngineID to sort instead since we want consistent sorting */
if (r == 0) return EngineNumberSorter(a, b);
if (r == 0) return EngineNumberSorter(a, b, cache);
return _engine_sort_direction ? r > 0 : r < 0;
}
@ -788,10 +792,10 @@ static int DrawCargoCapacityInfo(int left, int right, int y, TestedEngineDetails
static StringID GetRunningCostString()
{
if (EconTime::UsingWallclockUnits()) {
return STR_PURCHASE_INFO_RUNNINGCOST_PERIOD;
} else if (DayLengthFactor() > 1 && !_settings_client.gui.show_running_costs_calendar_year) {
if (DayLengthFactor() > 1 && !_settings_client.gui.show_running_costs_calendar_year) {
return STR_PURCHASE_INFO_RUNNINGCOST_ORIG_YEAR;
} else if (EconTime::UsingWallclockUnits()) {
return STR_PURCHASE_INFO_RUNNINGCOST_PERIOD;
} else {
return STR_PURCHASE_INFO_RUNNINGCOST_YEAR;
}
@ -1425,8 +1429,91 @@ struct BuildVehicleWindowBase : Window {
return list;
}
void FillTestedEngineCapacity(EngineID engine, CargoID cargo, TestedEngineDetails &te) const
{
const Engine *e = Engine::Get(engine);
if (!e->CanPossiblyCarryCargo()) {
te.cost = 0;
te.cargo = INVALID_CARGO;
te.all_capacities.Clear();
return;
}
if (this->virtual_train_mode) {
if (cargo != INVALID_CARGO && cargo != e->GetDefaultCargoType()) {
SavedRandomSeeds saved_seeds;
SaveRandomSeeds(&saved_seeds);
StringID err;
Train *t = BuildVirtualRailVehicle(engine, err, 0, false);
if (t != nullptr) {
const CommandCost ret = CmdRefitVehicle(0, DC_QUERY_COST, t->index, cargo | (1 << 16), nullptr);
te.cost = ret.GetCost();
te.capacity = _returned_refit_capacity;
te.mail_capacity = _returned_mail_refit_capacity;
te.cargo = (cargo == INVALID_CARGO) ? e->GetDefaultCargoType() : cargo;
te.all_capacities = _returned_vehicle_capacities;
delete t;
RestoreRandomSeeds(saved_seeds);
return;
} else {
RestoreRandomSeeds(saved_seeds);
}
}
} else if (!this->listview_mode) {
/* Query for cost and refitted capacity */
CommandCost ret = DoCommand(this->window_number, engine | (cargo << 24), 0, DC_QUERY_COST, GetCmdBuildVeh(this->vehicle_type), nullptr);
if (ret.Succeeded()) {
te.cost = ret.GetCost() - e->GetCost();
te.capacity = _returned_refit_capacity;
te.mail_capacity = _returned_mail_refit_capacity;
te.cargo = (cargo == INVALID_CARGO) ? e->GetDefaultCargoType() : cargo;
te.all_capacities = _returned_vehicle_capacities;
return;
}
}
/* Purchase test was not possible or failed, fill in the defaults instead. */
te = {};
te.FillDefaultCapacities(e);
}
};
/**
* Update cargo filter
* @param parent parent window, may be nullptr
* @param cargo_filter_criteria cargo filter criteria
*/
void GUIEngineListSortCache::UpdateCargoFilter(const BuildVehicleWindowBase *parent, CargoID cargo_filter_criteria)
{
this->parent = parent;
if (cargo_filter_criteria >= NUM_CARGO) cargo_filter_criteria = INVALID_CARGO;
if (cargo_filter_criteria != this->current_cargo) {
this->current_cargo = cargo_filter_criteria;
this->capacities.clear();
}
}
uint GUIEngineListSortCache::GetArticulatedCapacity(EngineID eng, bool dual_headed) const
{
auto iter = this->capacities.insert({ eng, 0 });
if (iter.second) {
/* New cache entry */
const Engine *e = Engine::Get(eng);
if (this->current_cargo != INVALID_CARGO && this->current_cargo != e->GetDefaultCargoType() && HasBit(e->info.callback_mask, CBM_VEHICLE_REFIT_CAPACITY) && e->refit_capacity_values == nullptr && this->parent != nullptr) {
/* Expensive path simulating vehicle construction is required to determine capacity */
TestedEngineDetails te{};
this->parent->FillTestedEngineCapacity(eng, this->current_cargo, te);
iter.first->second = te.all_capacities.GetSum<uint>();
} else {
iter.first->second = GetTotalCapacityOfArticulatedParts(eng, this->current_cargo) * (dual_headed ? 2 : 1);
}
}
return iter.first->second;
}
/** GUI for building vehicles. */
struct BuildVehicleWindow : BuildVehicleWindowBase {
union {
@ -1434,7 +1521,7 @@ struct BuildVehicleWindow : BuildVehicleWindowBase {
RoadType roadtype; ///< Road type to show, or #INVALID_ROADTYPE.
} filter; ///< Filter to apply.
bool descending_sort_order; ///< Sort direction, @see _engine_sort_direction
byte sort_criteria; ///< Current sort criterium.
uint8_t sort_criteria; ///< Current sort criterium.
bool show_hidden_engines; ///< State of the 'show hidden engines' button.
EngineID sel_engine; ///< Currently selected engine, or #INVALID_ENGINE
EngineID rename_engine; ///< Engine being renamed.
@ -1579,50 +1666,7 @@ struct BuildVehicleWindow : BuildVehicleWindowBase {
if (this->sel_engine == INVALID_ENGINE) return;
const Engine *e = Engine::Get(this->sel_engine);
if (!e->CanPossiblyCarryCargo()) {
this->te.cost = 0;
this->te.cargo = INVALID_CARGO;
this->te.all_capacities.Clear();
return;
}
if (this->virtual_train_mode) {
if (cargo != INVALID_CARGO && cargo != e->GetDefaultCargoType()) {
SavedRandomSeeds saved_seeds;
SaveRandomSeeds(&saved_seeds);
StringID err;
Train *t = BuildVirtualRailVehicle(this->sel_engine, err, 0, false);
if (t != nullptr) {
const CommandCost ret = CmdRefitVehicle(0, DC_QUERY_COST, t->index, cargo | (1 << 16), nullptr);
this->te.cost = ret.GetCost();
this->te.capacity = _returned_refit_capacity;
this->te.mail_capacity = _returned_mail_refit_capacity;
this->te.cargo = (cargo == INVALID_CARGO) ? e->GetDefaultCargoType() : cargo;
this->te.all_capacities = _returned_vehicle_capacities;
delete t;
RestoreRandomSeeds(saved_seeds);
return;
} else {
RestoreRandomSeeds(saved_seeds);
}
}
} else if (!this->listview_mode) {
/* Query for cost and refitted capacity */
CommandCost ret = DoCommand(this->window_number, this->sel_engine | (cargo << 24), 0, DC_QUERY_COST, GetCmdBuildVeh(this->vehicle_type), nullptr);
if (ret.Succeeded()) {
this->te.cost = ret.GetCost() - e->GetCost();
this->te.capacity = _returned_refit_capacity;
this->te.mail_capacity = _returned_mail_refit_capacity;
this->te.cargo = (cargo == INVALID_CARGO) ? e->GetDefaultCargoType() : cargo;
this->te.all_capacities = _returned_vehicle_capacities;
return;
}
}
/* Purchase test was not possible or failed, fill in the defaults instead. */
this->te = {};
this->te.FillDefaultCapacities(e);
this->FillTestedEngineCapacity(this->sel_engine, cargo, this->te);
}
void OnInit() override
@ -1722,6 +1766,9 @@ struct BuildVehicleWindow : BuildVehicleWindowBase {
/* invalidate cached values for name sorter - engine names could change */
_last_engine[0] = _last_engine[1] = INVALID_ENGINE;
/* setup engine capacity cache */
list.SortParameterData().UpdateCargoFilter(this, this->cargo_filter_criteria);
/* make engines first, and then wagons, sorted by selected sort_criteria */
_engine_sort_direction = false;
EngList_Sort(list, TrainEnginesThenWagonsSorter);
@ -1859,6 +1906,9 @@ struct BuildVehicleWindow : BuildVehicleWindowBase {
}
}
/* setup engine capacity cache */
this->eng_list.SortParameterData().UpdateCargoFilter(this, this->cargo_filter_criteria);
_engine_sort_direction = this->descending_sort_order;
EngList_Sort(this->eng_list, _engine_sort_functions[this->vehicle_type][this->sort_criteria]);
@ -2192,7 +2242,7 @@ static Hotkey buildvehicle_hotkeys[] = {
};
HotkeyList BuildVehicleWindow::hotkeys("buildvehicle", buildvehicle_hotkeys);
static EngList_SortTypeFunction * const _sorter_loco[11] = {
static EngList_SortTypeFunction * const _sorter_loco[12] = {
/* Locomotives */
&EngineNumberSorter,
&EngineCostSorter,
@ -2204,10 +2254,11 @@ static EngList_SortTypeFunction * const _sorter_loco[11] = {
&EngineRunningCostSorter,
&EnginePowerVsRunningCostSorter,
&EngineReliabilitySorter,
&TrainEngineCapacitySorter
&TrainEngineCapacitySorter,
&TrainEngineCapacityVsRunningCostSorter
};
static EngList_SortTypeFunction * const _sorter_wagon[7] = {
static EngList_SortTypeFunction * const _sorter_wagon[8] = {
/* Wagons */
&EngineNumberSorter,
&EngineCostSorter,
@ -2215,10 +2266,11 @@ static EngList_SortTypeFunction * const _sorter_wagon[7] = {
&EngineIntroDateSorter,
&EngineNameSorter,
&EngineRunningCostSorter,
&TrainEngineCapacitySorter
&TrainEngineCapacitySorter,
&TrainEngineCapacityVsRunningCostSorter
};
static const StringID _sort_listing_loco[12] = {
static const StringID _sort_listing_loco[13] = {
/* Locomotives */
STR_SORT_BY_ENGINE_ID,
STR_SORT_BY_COST,
@ -2231,10 +2283,11 @@ static const StringID _sort_listing_loco[12] = {
STR_SORT_BY_POWER_VS_RUNNING_COST,
STR_SORT_BY_RELIABILITY,
STR_SORT_BY_CARGO_CAPACITY,
STR_SORT_BY_CARGO_CAPACITY_VS_RUNNING_COST,
INVALID_STRING_ID
};
static const StringID _sort_listing_wagon[8] = {
static const StringID _sort_listing_wagon[9] = {
/* Wagons */
STR_SORT_BY_ENGINE_ID,
STR_SORT_BY_COST,
@ -2243,6 +2296,7 @@ static const StringID _sort_listing_wagon[8] = {
STR_SORT_BY_NAME,
STR_SORT_BY_RUNNING_COST,
STR_SORT_BY_CARGO_CAPACITY,
STR_SORT_BY_CARGO_CAPACITY_VS_RUNNING_COST,
INVALID_STRING_ID
};
@ -2285,7 +2339,7 @@ struct BuildVehicleWindowTrainAdvanced final : BuildVehicleWindowBase {
struct PanelState {
bool descending_sort_order; ///< Sort direction, @see _engine_sort_direction
byte sort_criteria; ///< Current sort criterium.
uint8_t sort_criteria; ///< Current sort criterium.
EngineID sel_engine; ///< Currently selected engine, or #INVALID_ENGINE
EngineID rename_engine {}; ///< Engine being renamed.
GUIEngineList eng_list;
@ -2482,50 +2536,7 @@ struct BuildVehicleWindowTrainAdvanced final : BuildVehicleWindowBase {
if (state.sel_engine == INVALID_ENGINE) return;
const Engine *e = Engine::Get(state.sel_engine);
if (!e->CanPossiblyCarryCargo()) {
state.te.cost = 0;
state.te.cargo = INVALID_CARGO;
state.te.all_capacities.Clear();
return;
}
if (this->virtual_train_mode) {
if (cargo != INVALID_CARGO && cargo != e->GetDefaultCargoType()) {
SavedRandomSeeds saved_seeds;
SaveRandomSeeds(&saved_seeds);
StringID err;
Train *t = BuildVirtualRailVehicle(state.sel_engine, err, 0, false);
if (t != nullptr) {
const CommandCost ret = CmdRefitVehicle(0, DC_QUERY_COST, t->index, cargo | (1 << 16), nullptr);
state.te.cost = ret.GetCost();
state.te.capacity = _returned_refit_capacity;
state.te.mail_capacity = _returned_mail_refit_capacity;
state.te.cargo = (cargo == INVALID_CARGO) ? e->GetDefaultCargoType() : cargo;
state.te.all_capacities = _returned_vehicle_capacities;
delete t;
RestoreRandomSeeds(saved_seeds);
return;
} else {
RestoreRandomSeeds(saved_seeds);
}
}
} else if (!this->listview_mode) {
/* Query for cost and refitted capacity */
const CommandCost ret = DoCommand(this->window_number, state.sel_engine | (cargo << 24), 0, DC_QUERY_COST, GetCmdBuildVeh(this->vehicle_type), nullptr);
if (ret.Succeeded()) {
state.te.cost = ret.GetCost() - e->GetCost();
state.te.capacity = _returned_refit_capacity;
state.te.mail_capacity = _returned_mail_refit_capacity;
state.te.cargo = (cargo == INVALID_CARGO) ? e->GetDefaultCargoType() : cargo;
state.te.all_capacities = _returned_vehicle_capacities;
return;
}
}
/* Purchase test was not possible or failed, fill in the defaults instead. */
state.te = {};
state.te.FillDefaultCapacities(e);
this->FillTestedEngineCapacity(state.sel_engine, cargo, state.te);
}
void SelectColumn(bool wagon)
@ -2574,7 +2585,8 @@ struct BuildVehicleWindowTrainAdvanced final : BuildVehicleWindowBase {
/* Filter engine name */
state.string_filter.ResetState();
state.string_filter.AddLine(GetString(e->info.string_id));
SetDParam(0, PackEngineNameDParam(e->index, EngineNameContext::PurchaseList));
state.string_filter.AddLine(GetString(STR_ENGINE_NAME));
/* Filter NewGRF extra text */
auto text = GetNewGRFAdditionalText(e->index);
@ -2640,6 +2652,9 @@ struct BuildVehicleWindowTrainAdvanced final : BuildVehicleWindowBase {
/* invalidate cached values for name sorter - engine names could change */
_last_engine[0] = _last_engine[1] = INVALID_ENGINE;
/* setup engine capacity cache */
list.SortParameterData().UpdateCargoFilter(this, state.cargo_filter_criteria);
/* Sort */
_engine_sort_direction = state.descending_sort_order;
EngList_Sort(list, sorters[state.sort_criteria]);
@ -3124,7 +3139,7 @@ struct BuildVehicleWindowTrainAdvanced final : BuildVehicleWindowBase {
switch (widget) {
case WID_BV_SORT_DROPDOWN_LOCO: {
if (this->loco.sort_criteria != index) {
this->loco.sort_criteria = static_cast<byte>(index);
this->loco.sort_criteria = static_cast<uint8_t>(index);
_last_sort_criteria_loco = this->loco.sort_criteria;
this->loco.eng_list.ForceRebuild();
}
@ -3133,7 +3148,7 @@ struct BuildVehicleWindowTrainAdvanced final : BuildVehicleWindowBase {
case WID_BV_CARGO_FILTER_DROPDOWN_LOCO: { // Select a cargo filter criteria
if (this->loco.cargo_filter_criteria != index) {
this->loco.cargo_filter_criteria = static_cast<byte>(index);
this->loco.cargo_filter_criteria = static_cast<uint8_t>(index);
_last_filter_criteria_loco = this->loco.cargo_filter_criteria;
/* deactivate filter if criteria is 'Show All', activate it otherwise */
this->loco.eng_list.SetFilterState(this->loco.cargo_filter_criteria != CargoFilterCriteria::CF_ANY);
@ -3144,7 +3159,7 @@ struct BuildVehicleWindowTrainAdvanced final : BuildVehicleWindowBase {
case WID_BV_SORT_DROPDOWN_WAGON: {
if (this->wagon.sort_criteria != index) {
this->wagon.sort_criteria = static_cast<byte>(index);
this->wagon.sort_criteria = static_cast<uint8_t>(index);
_last_sort_criteria_wagon = this->wagon.sort_criteria;
this->wagon.eng_list.ForceRebuild();
}
@ -3153,7 +3168,7 @@ struct BuildVehicleWindowTrainAdvanced final : BuildVehicleWindowBase {
case WID_BV_CARGO_FILTER_DROPDOWN_WAGON: { // Select a cargo filter criteria
if (this->wagon.cargo_filter_criteria != index) {
this->wagon.cargo_filter_criteria = static_cast<byte>(index);
this->wagon.cargo_filter_criteria = static_cast<uint8_t>(index);
_last_filter_criteria_wagon = this->wagon.cargo_filter_criteria;
/* deactivate filter if criteria is 'Show All', activate it otherwise */
this->wagon.eng_list.SetFilterState(this->wagon.cargo_filter_criteria != CargoFilterCriteria::CF_ANY);

@ -22,7 +22,7 @@ using CargoLabel = StrongType::Typedef<uint32_t, struct CargoLabelTag, StrongTyp
/**
* Cargo slots to indicate a cargo type within a game.
*/
using CargoID = byte;
using CargoID = uint8_t;
/**
* Available types of cargo
@ -149,7 +149,7 @@ struct CargoArray : std::array<uint, NUM_CARGO> {
/** Types of cargo source and destination */
enum class SourceType : byte {
enum class SourceType : uint8_t {
Industry, ///< Source/destination is an industry
Town, ///< Source/destination is a town
Headquarters, ///< Source/destination are company headquarters

@ -19,7 +19,7 @@
#include <vector>
/** Town growth effect when delivering cargo. */
enum TownAcceptanceEffect : byte {
enum TownAcceptanceEffect : uint8_t {
TAE_BEGIN = 0,
TAE_NONE = TAE_BEGIN, ///< Cargo has no effect.
TAE_PASSENGERS, ///< Cargo behaves passenger-like.
@ -32,7 +32,7 @@ enum TownAcceptanceEffect : byte {
};
/** Town effect when producing cargo. */
enum TownProductionEffect : byte {
enum TownProductionEffect : uint8_t {
TPE_NONE, ///< Town will not produce this cargo type.
TPE_PASSENGERS, ///< Cargo behaves passenger-like for production.
TPE_MAIL, ///< Cargo behaves mail-like for production.
@ -61,7 +61,7 @@ enum CargoClass {
CC_SPECIAL = 1 << 15, ///< Special bit used for livery refit tricks instead of normal cargoes.
};
static const byte INVALID_CARGO_BITNUM = 0xFF; ///< Constant representing invalid cargo
static const uint8_t INVALID_CARGO_BITNUM = 0xFF; ///< Constant representing invalid cargo
static const uint TOWN_PRODUCTION_DIVISOR = 256;

@ -507,7 +507,7 @@ struct CheatWindow : Window {
}
if (ce->mode == CNM_MONEY) {
if (!_networking) *ce->been_used = true;
DoCommandPEx(0, 0, 0, (std::strtoll(str, nullptr, 10) / _currency->rate), IsNetworkSettingsAdmin() ? CMD_MONEY_CHEAT_ADMIN : CMD_MONEY_CHEAT);
DoCommandPEx(0, 0, 0, (std::strtoll(str, nullptr, 10) / GetCurrency().rate), IsNetworkSettingsAdmin() ? CMD_MONEY_CHEAT_ADMIN : CMD_MONEY_CHEAT);
return;
}

@ -46,12 +46,12 @@ static CommandCost ClearTile_Clear(TileIndex tile, DoCommandFlag flags)
return price;
}
SpriteID GetSpriteIDForClearLand(const Slope slope, byte set)
SpriteID GetSpriteIDForClearLand(const Slope slope, uint8_t set)
{
return SPR_FLAT_BARE_LAND + SlopeToSpriteOffset(slope) + set * 19;
}
void DrawClearLandTile(const TileInfo *ti, byte set)
void DrawClearLandTile(const TileInfo *ti, uint8_t set)
{
DrawGroundSprite(GetSpriteIDForClearLand(ti->tileh, set), PAL_NONE);
}

@ -13,9 +13,9 @@
#include "tile_cmd.h"
void DrawHillyLandTile(const TileInfo *ti);
void DrawClearLandTile(const TileInfo *ti, byte set);
void DrawClearLandTile(const TileInfo *ti, uint8_t set);
SpriteID GetSpriteIDForClearLand(const Slope slope, byte set);
SpriteID GetSpriteIDForClearLand(const Slope slope, uint8_t set);
SpriteID GetSpriteIDForHillyLand(const Slope slope, const uint rough_index);
SpriteID GetSpriteIDForRocks(const Slope slope, const uint tile_hash);
SpriteID GetSpriteIDForFields(const Slope slope, const uint field_type);

@ -1119,7 +1119,7 @@ CommandCost DoCommandPInternal(TileIndex tile, uint32_t p1, uint32_t p2, uint64_
_additional_cash_required = 0;
/* Get pointer to command handler */
byte cmd_id = cmd & CMD_ID_MASK;
uint cmd_id = cmd & CMD_ID_MASK;
assert(cmd_id < lengthof(_command_proc_table));
const Command &command = _command_proc_table[cmd_id];
@ -1177,10 +1177,10 @@ CommandCost DoCommandPInternal(TileIndex tile, uint32_t p1, uint32_t p2, uint64_
if (_debug_desync_level >= 1) {
std::string aux_str;
if (aux_data != nullptr) {
std::vector<byte> buffer;
std::vector<uint8_t> buffer;
CommandSerialisationBuffer serialiser(buffer, SHRT_MAX);
aux_data->Serialise(serialiser);
aux_str = FormatArrayAsHex(buffer);
aux_str = FormatArrayAsHex(buffer, false);
}
std::string text_buf;
if (text != nullptr) {

@ -25,7 +25,7 @@ struct CommandDeserialisationBuffer : public BufferDeserialisationHelper<Command
CommandDeserialisationBuffer(const uint8_t *buffer, size_t size) : buffer(buffer), size(size) {}
const byte *GetDeserialisationBuffer() const { return this->buffer; }
const uint8_t *GetDeserialisationBuffer() const { return this->buffer; }
size_t GetDeserialisationBufferSize() const { return this->size; }
size_t &GetDeserialisationPosition() { return this->pos; }
@ -44,17 +44,17 @@ struct CommandDeserialisationBuffer : public BufferDeserialisationHelper<Command
};
struct CommandSerialisationBuffer : public BufferSerialisationHelper<CommandSerialisationBuffer> {
std::vector<byte> &buffer;
std::vector<uint8_t> &buffer;
size_t limit;
CommandSerialisationBuffer(std::vector<byte> &buffer, size_t limit) : buffer(buffer), limit(limit) {}
CommandSerialisationBuffer(std::vector<uint8_t> &buffer, size_t limit) : buffer(buffer), limit(limit) {}
std::vector<byte> &GetSerialisationBuffer() { return this->buffer; }
std::vector<uint8_t> &GetSerialisationBuffer() { return this->buffer; }
size_t GetSerialisationLimit() const { return this->limit; }
};
struct CommandAuxiliarySerialised : public CommandAuxiliaryBase {
std::vector<byte> serialised_data;
std::vector<uint8_t> serialised_data;
CommandAuxiliaryBase *Clone() const override
{

@ -65,7 +65,7 @@ private:
std::vector<BitmapStorage> used_bitmap;
};
enum CompanyBankruptcyFlags : byte {
enum CompanyBankruptcyFlags : uint8_t {
CBRF_NONE = 0x0,
CBRF_SALE = 0x1, ///< the company has been marked for sale
CBRF_SALE_ONLY = 0x2, ///< the company has been marked for sale without being in a bankruptcy state first
@ -88,13 +88,13 @@ struct CompanyProperties {
CompanyManagerFace face; ///< Face description of the president.
Money money; ///< Money owned by the company.
byte money_fraction; ///< Fraction of money of the company, too small to represent in #money.
uint8_t money_fraction; ///< Fraction of money of the company, too small to represent in #money.
Money current_loan; ///< Amount of money borrowed from the bank.
Money max_loan; ///< Max allowed amount of the loan or COMPANY_MAX_LOAN_DEFAULT.
Colours colour; ///< Company colour.
byte block_preview; ///< Number of quarters that the company is not allowed to get new exclusive engine previews (see CompaniesGenStatistics).
uint8_t block_preview; ///< Number of quarters that the company is not allowed to get new exclusive engine previews (see CompaniesGenStatistics).
TileIndex location_of_HQ; ///< Northern tile of HQ; #INVALID_TILE when there is none.
TileIndex last_build_coordinate; ///< Coordinate of the last build thing by this company.
@ -105,7 +105,8 @@ struct CompanyProperties {
int32_t display_inaugurated_period;///< Wallclock display period of starting the company.
YearDelta age_years; ///< Number of economy years that the company has been operational.
byte months_of_bankruptcy; ///< Number of months that the company is unable to pay its debts
uint8_t months_empty = 0; ///< NOSAVE: Number of months this company has not had a client in multiplayer.
uint8_t months_of_bankruptcy; ///< Number of months that the company is unable to pay its debts
CompanyID bankrupt_last_asked; ///< Which company was most recently asked about buying it?
CompanyBankruptcyFlags bankrupt_flags; ///< bankruptcy flags
CompanyMask bankrupt_asked; ///< which companies were asked about buying it?
@ -127,7 +128,7 @@ struct CompanyProperties {
std::array<Expenses, 3> yearly_expenses{}; ///< Expenses of the company for the last three years.
CompanyEconomyEntry cur_economy; ///< Economic data of the company of this quarter.
CompanyEconomyEntry old_economy[MAX_HISTORY_QUARTERS]; ///< Economic data of the company of the last #MAX_HISTORY_QUARTERS quarters.
byte num_valid_stat_ent; ///< Number of valid statistical entries in #old_economy.
uint8_t num_valid_stat_ent; ///< Number of valid statistical entries in #old_economy.
Livery livery[LS_END];

@ -37,7 +37,6 @@
#include "story_base.h"
#include "zoning.h"
#include "tbtr_template_vehicle_func.h"
#include "widgets/statusbar_widget.h"
#include "core/backup_type.hpp"
#include "debug_desync.h"
#include "timer/timer.h"
@ -45,6 +44,8 @@
#include "tilehighlight_func.h"
#include "plans_func.h"
#include "widgets/statusbar_widget.h"
#include "table/strings.h"
#include <vector>
@ -323,10 +324,10 @@ void SubtractMoneyFromCompany(const CommandCost &cost)
void SubtractMoneyFromCompanyFract(CompanyID company, const CommandCost &cst)
{
Company *c = Company::Get(company);
byte m = c->money_fraction;
uint8_t m = c->money_fraction;
Money cost = cst.GetCost();
c->money_fraction = m - (byte)cost;
c->money_fraction = m - (uint8_t)cost;
cost >>= 8;
if (c->money_fraction > m) cost++;
if (cost != 0) SubtractMoneyFromAnyCompany(c, CommandCost(cst.GetExpensesType(), cost));
@ -473,7 +474,7 @@ bad_town_name:;
}
/** Sorting weights for the company colours. */
static const byte _colour_sort[COLOUR_END] = {2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 3, 1, 1, 1};
static const uint8_t _colour_sort[COLOUR_END] = {2, 2, 3, 2, 3, 2, 3, 2, 3, 2, 2, 2, 3, 1, 1, 1};
/** Similar colours, so we can try to prevent same coloured companies. */
static const Colours _similar_colour[COLOUR_END][2] = {
{ COLOUR_BLUE, COLOUR_LIGHT_BLUE }, // COLOUR_DARK_BLUE
@ -668,7 +669,7 @@ Company *DoStartupNewCompany(DoStartupNewCompanyFlag flags, CompanyID company)
}
/** Start a new competitor company if possible. */
TimeoutTimer<TimerGameTick> _new_competitor_timeout(0, []() {
TimeoutTimer<TimerGameTick> _new_competitor_timeout({ TimerGameTick::Priority::COMPETITOR_TIMEOUT, 0 }, []() {
if (_game_mode == GM_MENU || !AI::CanStartNew()) return;
if (_networking && Company::GetNumItems() >= _settings_client.network.max_companies) return;
@ -850,7 +851,7 @@ void OnTick_Companies(bool main_tick)
/* Randomize a bit when the AI is actually going to start; ranges from 87.5% .. 112.5% of indicated value. */
timeout += ScriptObject::GetRandomizer(OWNER_NONE).Next(timeout / 4) - timeout / 8;
_new_competitor_timeout.Reset(std::max(1, timeout));
_new_competitor_timeout.Reset({ TimerGameTick::Priority::COMPETITOR_TIMEOUT, static_cast<uint>(std::max(1, timeout)) });
}
}
@ -931,6 +932,7 @@ void CompanyAdminRemove(CompanyID company_id, CompanyRemoveReason reason)
* - bits 0..15: CompanyCtrlAction
* - bits 16..23: CompanyID
* - bits 24..31: CompanyRemoveReason (with CCA_DELETE)
* - bits 24..31: CompanyID to merge (with CCA_MERGE)
* @param p2 ClientID
* @param text unused
* @return the cost of this operation or an error
@ -1071,6 +1073,38 @@ CommandCost CmdCompanyCtrl(TileIndex tile, DoCommandFlag flags, uint32_t p1, uin
break;
}
case CCA_MERGE: {
Company *c = Company::GetIfValid(company_id);
if (c == nullptr) return CMD_ERROR;
CompanyID to_merge_id = (CompanyID)GB(p1, 24, 8);
if (to_merge_id == company_id) return CMD_ERROR;
Company *to_merge = Company::GetIfValid(to_merge_id);
if (to_merge == nullptr) return CMD_ERROR;
if (!(flags & DC_EXEC)) return CommandCost();
SubtractMoneyFromAnyCompany(c, CommandCost(EXPENSES_OTHER, to_merge->current_loan - to_merge->money));
DEBUG(desync, 1, "merge_companies: %s, company_id: %u, merged_company_id: %u", debug_date_dumper().HexDate(), company_id, to_merge_id);
CompanyNewsInformation *cni = new CompanyNewsInformation(to_merge, c);
SetDParam(0, STR_NEWS_COMPANY_MERGER_TITLE);
SetDParam(1, STR_NEWS_MERGER_TAKEOVER_TITLE);
SetDParamStr(2, cni->company_name);
SetDParamStr(3, cni->other_company_name);
AddCompanyNewsItem(STR_MESSAGE_NEWS_FORMAT, cni);
AI::BroadcastNewEvent(new ScriptEventCompanyMerger(to_merge_id, company_id));
Game::NewEvent(new ScriptEventCompanyMerger(to_merge_id, company_id));
ChangeOwnershipOfCompanyItems(to_merge_id, company_id);
PostAcquireCompany(to_merge);
break;
}
default: return CMD_ERROR;
}

@ -23,7 +23,7 @@
#include "company_manager_face.h"
#include "strings_func.h"
#include "date_func.h"
#include "widgets/dropdown_type.h"
#include "dropdown_type.h"
#include "tilehighlight_func.h"
#include "company_base.h"
#include "core/geometry_func.hpp"
@ -37,7 +37,7 @@
#include "station_func.h"
#include "zoom_func.h"
#include "sortlist_type.h"
#include "group_gui_list.h"
#include "group_gui.h"
#include "core/backup_type.hpp"
#include "widgets/company_widget.h"
@ -530,12 +530,12 @@ struct CompanyFinancesWindow : Window {
if (this->query_widget == WID_CF_INCREASE_LOAN) {
const Company *c = Company::Get((CompanyID)this->window_number);
Money amount = std::min<Money>(std::strtoull(str, nullptr, 10) / _currency->rate, _economy.max_loan - c->current_loan);
Money amount = std::min<Money>(std::strtoull(str, nullptr, 10) / GetCurrency().rate, _economy.max_loan - c->current_loan);
amount = LOAN_INTERVAL * CeilDivT<Money>(amount, LOAN_INTERVAL);
DoCommandP(0, amount >> 32, (amount & 0xFFFFFFFC) | 2, CMD_INCREASE_LOAN | CMD_MSG(STR_ERROR_CAN_T_BORROW_ANY_MORE_MONEY));
} else if (this->query_widget == WID_CF_REPAY_LOAN) {
const Company *c = Company::Get((CompanyID)this->window_number);
Money amount = std::min<Money>(std::strtoull(str, nullptr, 10) / _currency->rate, c->current_loan);
Money amount = std::min<Money>(std::strtoull(str, nullptr, 10) / GetCurrency().rate, c->current_loan);
amount = LOAN_INTERVAL * CeilDivT<Money>(amount, LOAN_INTERVAL);
DoCommandP(0, amount >> 32, (amount & 0xFFFFFFFC) | 2, CMD_DECREASE_LOAN | CMD_MSG(STR_ERROR_CAN_T_REPAY_LOAN));
}
@ -643,7 +643,6 @@ private:
uint rows;
uint line_height;
GUIGroupList groups;
std::vector<int> indents;
Scrollbar *vscroll;
void ShowColourDropDownMenu(uint32_t widget)
@ -651,7 +650,7 @@ private:
uint32_t used_colours = 0;
const Livery *livery, *default_livery = nullptr;
bool primary = widget == WID_SCL_PRI_COL_DROPDOWN;
byte default_col = 0;
uint8_t default_col = 0;
/* Disallow other company colours for the primary colour */
if (this->livery_class < LC_GROUP_RAIL && HasBit(this->sel, LS_DEFAULT) && primary) {
@ -692,7 +691,7 @@ private:
list.push_back(std::make_unique<DropDownListColourItem<>>(i, HasBit(used_colours, i)));
}
byte sel;
uint8_t sel;
if (default_livery == nullptr || HasBit(livery->in_use, primary ? 0 : 1)) {
sel = primary ? livery->colour1 : livery->colour2;
} else {
@ -701,37 +700,16 @@ private:
ShowDropDownList(this, std::move(list), sel, widget);
}
void AddChildren(GUIGroupList &source, GroupID parent, int indent)
{
for (const Group *g : source) {
if (g->parent != parent) continue;
this->groups.push_back(g);
this->indents.push_back(indent);
AddChildren(source, g->index, indent + 1);
}
}
void BuildGroupList(CompanyID owner)
{
if (!this->groups.NeedRebuild()) return;
this->groups.clear();
this->indents.clear();
if (this->livery_class >= LC_GROUP_RAIL) {
GUIGroupList list;
VehicleType vtype = (VehicleType)(this->livery_class - LC_GROUP_RAIL);
for (const Group *g : Group::Iterate()) {
if (g->owner == owner && g->vehicle_type == vtype) {
list.push_back(g);
}
}
list.ForceResort();
SortGUIGroupList(list);
AddChildren(list, INVALID_GROUP, 0);
BuildGuiGroupList(this->groups, false, owner, vtype);
}
this->groups.shrink_to_fit();
@ -795,7 +773,7 @@ public:
/* Position scrollbar to selected group */
for (uint i = 0; i < this->rows; i++) {
if (this->groups[i]->index == sel) {
if (this->groups[i].group->index == sel) {
this->vscroll->SetPosition(i - this->vscroll->GetCapacity() / 2);
break;
}
@ -965,11 +943,11 @@ public:
}
}
} else {
uint max = static_cast<uint>(std::min<size_t>(this->vscroll->GetPosition() + this->vscroll->GetCapacity(), this->groups.size()));
for (uint i = this->vscroll->GetPosition(); i < max; ++i) {
const Group *g = this->groups[i];
auto [first, last] = this->vscroll->GetVisibleRangeIterators(this->groups);
for (auto it = first; it != last; ++it) {
const Group *g = it->group;
SetDParam(0, g->index);
draw_livery(STR_GROUP_NAME, g->livery, this->sel == g->index, false, this->indents[i] * WidgetDimensions::scaled.hsep_indent);
draw_livery(STR_GROUP_NAME, g->livery, this->sel == g->index, false, it->indent * WidgetDimensions::scaled.hsep_indent);
}
if (this->vscroll->GetCount() == 0) {
@ -1012,7 +990,7 @@ public:
this->BuildGroupList((CompanyID)this->window_number);
if (!this->groups.empty()) {
this->sel = this->groups[0]->index;
this->sel = this->groups[0].group->index;
}
}
@ -1029,10 +1007,10 @@ public:
break;
case WID_SCL_MATRIX: {
uint row = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_SCL_MATRIX);
if (row >= this->rows) return;
if (this->livery_class < LC_GROUP_RAIL) {
uint row = this->vscroll->GetScrolledRowFromWidget(pt.y, this, widget);
if (row >= this->rows) return;
LiveryScheme j = (LiveryScheme)row;
for (LiveryScheme scheme = LS_BEGIN; scheme <= j && scheme < LS_END; scheme++) {
@ -1046,7 +1024,10 @@ public:
this->sel = 1 << j;
}
} else {
this->sel = this->groups[row]->index;
auto it = this->vscroll->GetScrolledItemFromWidget(this->groups, pt.y, this, widget);
if (it == std::end(this->groups)) return;
this->sel = it->group->index;
}
this->SetDirty();
break;
@ -1099,7 +1080,7 @@ public:
if (!Group::IsValidID(this->sel)) {
this->sel = INVALID_GROUP;
if (!this->groups.empty()) this->sel = this->groups[0]->index;
if (!this->groups.empty()) this->sel = this->groups[0].group->index;
}
this->SetDirty();
@ -2636,7 +2617,7 @@ struct CompanyWindow : Window
}
case WID_C_BUILD_HQ:
if ((byte)this->window_number != _local_company) return;
if ((uint8_t)this->window_number != _local_company) return;
if (this->IsWidgetLowered(WID_C_BUILD_HQ)) {
ResetObjectToPlace();
this->RaiseButtons();
@ -2730,7 +2711,7 @@ struct CompanyWindow : Window
default: NOT_REACHED();
case WID_C_GIVE_MONEY:
DoCommandPEx(0, this->window_number, 0, (std::strtoull(str, nullptr, 10) / _currency->rate), CMD_GIVE_MONEY | CMD_MSG(STR_ERROR_CAN_T_GIVE_MONEY), CcGiveMoney);
DoCommandPEx(0, this->window_number, 0, (std::strtoull(str, nullptr, 10) / GetCurrency().rate), CMD_GIVE_MONEY | CMD_MSG(STR_ERROR_CAN_T_GIVE_MONEY), CcGiveMoney);
break;
case WID_C_PRESIDENT_NAME:

@ -54,9 +54,9 @@ DECLARE_POSTFIX_INCREMENT(CompanyManagerFaceVariable)
/** Information about the valid values of CompanyManagerFace bitgroups as well as the sprites to draw */
struct CompanyManagerFaceBitsInfo {
byte offset; ///< Offset in bits into the CompanyManagerFace
byte length; ///< Number of bits used in the CompanyManagerFace
byte valid_values[GE_END]; ///< The number of valid values per gender/ethnicity
uint8_t offset; ///< Offset in bits into the CompanyManagerFace
uint8_t length; ///< Number of bits used in the CompanyManagerFace
uint8_t valid_values[GE_END]; ///< The number of valid values per gender/ethnicity
SpriteID first_sprite[GE_END]; ///< The first sprite per gender/ethnicity
};

@ -15,7 +15,7 @@
/**
* Enum for all companies/owners.
*/
enum Owner : byte {
enum Owner : uint8_t {
/* All companies below MAX_COMPANIES are playable
* companies, above, they are special, computer controlled 'companies' */
OWNER_BEGIN = 0x00, ///< First owner
@ -47,7 +47,7 @@ static const uint MIN_COMPETITORS_INTERVAL = 0; ///< The minimum interval (in
static const uint MAX_COMPETITORS_INTERVAL = 500; ///< The maximum interval (in minutes) between competitors.
/** Define basic enum properties */
template <> struct EnumPropsT<Owner> : MakeEnumPropsT<Owner, byte, OWNER_BEGIN, OWNER_END, INVALID_OWNER> {};
template <> struct EnumPropsT<Owner> : MakeEnumPropsT<Owner, uint8_t, OWNER_BEGIN, OWNER_END, INVALID_OWNER> {};
typedef Owner CompanyID;
@ -71,6 +71,7 @@ enum CompanyCtrlAction {
CCA_NEW_AI, ///< Create a new AI company.
CCA_DELETE, ///< Delete a company.
CCA_SALE, ///< Offer a company for sale.
CCA_MERGE, ///< Merge companies.
CCA_END, ///< Sentinel for end.
};

@ -13,6 +13,7 @@
#include "network/network_func.h"
#include "network/network_admin.h"
#include "debug.h"
#include "debug_fmt.h"
#include "console_func.h"
#include "settings_type.h"
@ -49,18 +50,16 @@ void IConsoleInit()
IConsoleStdLibRegister();
}
static void IConsoleWriteToLogFile(const char *string)
static void IConsoleWriteToLogFile(const std::string &string)
{
if (_iconsole_output_file != nullptr) {
/* if there is an console output file ... also print it there */
log_prefix prefix_writer;
const char *header = prefix_writer.GetLogPrefix();
if ((strlen(header) != 0 && fwrite(header, strlen(header), 1, _iconsole_output_file) != 1) ||
fwrite(string, strlen(string), 1, _iconsole_output_file) != 1 ||
fwrite("\n", 1, 1, _iconsole_output_file) != 1) {
try {
fmt::print(_iconsole_output_file, "{}{}\n", log_prefix().GetLogPrefix(), string);
} catch (const std::system_error &) {
fclose(_iconsole_output_file);
_iconsole_output_file = nullptr;
IConsolePrintF(CC_DEFAULT, "cannot write to log file");
IConsolePrint(CC_ERROR, "Cannot write to console log file; closing the log file.");
}
}
}
@ -68,7 +67,7 @@ static void IConsoleWriteToLogFile(const char *string)
bool CloseConsoleLogIfActive()
{
if (_iconsole_output_file != nullptr) {
IConsolePrintF(CC_DEFAULT, "file output complete");
IConsolePrint(CC_INFO, "Console log file closed.");
fclose(_iconsole_output_file);
_iconsole_output_file = nullptr;
return true;
@ -89,10 +88,10 @@ void IConsoleFree()
* as well as to a logfile. If the network server is a dedicated server, all activities
* are also logged. All lines to print are added to a temporary buffer which can be
* used as a history to print them onscreen
* @param colour_code the colour of the command. Red in case of errors, etc.
* @param string the message entered or output on the console (notice, error, etc.)
* @param colour_code The colour of the command.
* @param string The message to output on the console (notice, error, etc.)
*/
void IConsolePrint(TextColour colour_code, const char *string)
void IConsolePrint(TextColour colour_code, const std::string &string)
{
assert(IsValidConsoleColour(colour_code));
@ -113,13 +112,13 @@ void IConsolePrint(TextColour colour_code, const char *string)
if (_network_dedicated) {
NetworkAdminConsole("console", str);
fprintf(stdout, "%s%s\n", log_prefix().GetLogPrefix(), str.c_str());
fmt::print("{}{}\n", log_prefix().GetLogPrefix(), str);
fflush(stdout);
IConsoleWriteToLogFile(str.c_str());
IConsoleWriteToLogFile(str);
return;
}
IConsoleWriteToLogFile(str.c_str());
IConsoleWriteToLogFile(str);
IConsoleGUIPrint(colour_code, std::move(str));
}
@ -133,35 +132,14 @@ void CDECL IConsolePrintF(TextColour colour_code, const char *format, ...)
assert(IsValidConsoleColour(colour_code));
va_list va;
char buf[ICON_MAX_STREAMSIZE];
va_start(va, format);
vseprintf(buf, lastof(buf), format, va);
std::string buf = stdstr_vfmt(format, va);
va_end(va);
IConsolePrint(colour_code, buf);
}
/**
* It is possible to print warnings to the console. These are mostly
* errors or mishaps, but non-fatal. You need at least a level 1 (developer) for
* debugging messages to show up
*/
void IConsoleWarning(const char *string)
{
if (_settings_client.gui.developer == 0) return;
IConsolePrintF(CC_WARNING, "WARNING: %s", string);
}
/**
* It is possible to print error information to the console. This can include
* game errors, or errors in general you would want the user to notice
*/
void IConsoleError(const char *string)
{
IConsolePrintF(CC_ERROR, "ERROR: %s", string);
}
/**
* Change a string into its number representation. Supports
* decimal and hexadecimal numbers as well as 'on'/'off' 'true'/'false'
@ -227,7 +205,7 @@ std::string RemoveUnderscores(std::string name)
/* static */ void IConsole::AliasRegister(const std::string &name, const std::string &cmd)
{
auto result = IConsole::Aliases().try_emplace(RemoveUnderscores(name), name, cmd);
if (!result.second) IConsoleError("an alias with this name already exists; insertion aborted");
if (!result.second) IConsolePrint(CC_ERROR, "An alias with the name '{}' already exists.", name);
}
/**
@ -249,14 +227,14 @@ std::string RemoveUnderscores(std::string name)
* @param tokencount the number of parameters passed
* @param *tokens are the parameters given to the original command (0 is the first param)
*/
static void IConsoleAliasExec(const IConsoleAlias *alias, byte tokencount, char *tokens[ICON_TOKEN_COUNT], const uint recurse_count)
static void IConsoleAliasExec(const IConsoleAlias *alias, uint8_t tokencount, char *tokens[ICON_TOKEN_COUNT], const uint recurse_count)
{
std::string alias_buffer;
DEBUG(console, 6, "Requested command is an alias; parsing...");
Debug(console, 6, "Requested command is an alias; parsing...");
if (recurse_count > ICON_MAX_RECURSE) {
IConsoleError("Too many alias expansions, recursion limit reached. Aborting");
IConsolePrint(CC_ERROR, "Too many alias expansions, recursion limit reached.");
return;
}
@ -301,8 +279,8 @@ static void IConsoleAliasExec(const IConsoleAlias *alias, byte tokencount, char
int param = *cmdptr - 'A';
if (param < 0 || param >= tokencount) {
IConsoleError("too many or wrong amount of parameters passed to alias, aborting");
IConsolePrintF(CC_WARNING, "Usage of alias '%s': %s", alias->name.c_str(), alias->cmdline.c_str());
IConsolePrint(CC_ERROR, "Too many or wrong amount of parameters passed to alias.");
IConsolePrint(CC_HELP, "Usage of alias '{}': '{}'.", alias->name, alias->cmdline);
return;
}
@ -320,7 +298,7 @@ static void IConsoleAliasExec(const IConsoleAlias *alias, byte tokencount, char
}
if (alias_buffer.size() >= ICON_MAX_STREAMSIZE - 1) {
IConsoleError("Requested alias execution would overflow execution buffer");
IConsolePrint(CC_ERROR, "Requested alias execution would overflow execution buffer.");
return;
}
}
@ -346,12 +324,12 @@ void IConsoleCmdExec(const std::string &command_string, const uint recurse_count
for (cmdptr = command_string.c_str(); *cmdptr != '\0'; cmdptr++) {
if (!IsValidChar(*cmdptr, CS_ALPHANUMERAL)) {
IConsolePrintF(CC_ERROR, "Command '%s' contains malformed characters.", command_string.c_str());
IConsolePrint(CC_ERROR, "Command '{}' contains malformed characters.", command_string);
return;
}
}
DEBUG(console, 4, "Executing cmdline: '%s'", command_string.c_str());
Debug(console, 4, "Executing cmdline: '{}'", command_string);
memset(&tokens, 0, sizeof(tokens));
memset(&tokenstream, 0, sizeof(tokenstream));
@ -361,7 +339,7 @@ void IConsoleCmdExec(const std::string &command_string, const uint recurse_count
* of characters in our stream or the max amount of tokens we can handle */
for (cmdptr = command_string.c_str(), t_index = 0, tstream_i = 0; *cmdptr != '\0'; cmdptr++) {
if (tstream_i >= lengthof(tokenstream)) {
IConsoleError("command line too long");
IConsolePrint(CC_ERROR, "Command line too long.");
return;
}
@ -382,7 +360,7 @@ void IConsoleCmdExec(const std::string &command_string, const uint recurse_count
longtoken = !longtoken;
if (!foundtoken) {
if (t_index >= lengthof(tokens)) {
IConsoleError("command line too long");
IConsolePrint(CC_ERROR, "Command line too long.");
return;
}
tokens[t_index++] = &tokenstream[tstream_i];
@ -400,7 +378,7 @@ void IConsoleCmdExec(const std::string &command_string, const uint recurse_count
if (!foundtoken) {
if (t_index >= lengthof(tokens)) {
IConsoleError("command line too long");
IConsolePrint(CC_ERROR, "Command line too long.");
return;
}
tokens[t_index++] = &tokenstream[tstream_i - 1];
@ -411,7 +389,7 @@ void IConsoleCmdExec(const std::string &command_string, const uint recurse_count
}
for (uint i = 0; i < lengthof(tokens) && tokens[i] != nullptr; i++) {
DEBUG(console, 8, "Token %d is: '%s'", i, tokens[i]);
Debug(console, 8, "Token {} is: '{}'", i, tokens[i]);
}
IConsoleCmdExecTokens(t_index, tokens, recurse_count);
@ -450,5 +428,5 @@ void IConsoleCmdExecTokens(uint token_count, char *tokens[], const uint recurse_
return;
}
IConsoleError("command not found");
IConsolePrint(CC_ERROR, "Command '{}' not found.", tokens[0]);
}

File diff suppressed because it is too large Load Diff

@ -11,6 +11,7 @@
#define CONSOLE_FUNC_H
#include "console_type.h"
#include "core/format.hpp"
/* console modes */
extern IConsoleModes _iconsole_mode;
@ -21,10 +22,30 @@ void IConsoleFree();
void IConsoleClose();
/* console output */
void IConsolePrint(TextColour colour_code, const char *string);
void IConsolePrint(TextColour colour_code, const std::string &string);
/**
* Handle the printing of text entered into the console or redirected there
* by any other means. Text can be redirected to other clients in a network game
* as well as to a logfile. If the network server is a dedicated server, all activities
* are also logged. All lines to print are added to a temporary buffer which can be
* used as a history to print them onscreen
* @param colour_code The colour of the command.
* @param format_string The formatting string to tell what to do with the remaining arguments.
* @param first_arg The first argument to the format.
* @param other_args The other arguments to the format.
* @tparam A The type of the first argument.
* @tparam Args The types of the other arguments.
*/
template <typename A, typename ... Args>
inline void IConsolePrint(TextColour colour_code, fmt::format_string<A, Args...> format, A first_arg, Args&&... other_args)
{
/* The separate first_arg argument is added to aid overloading.
* Otherwise the calls that do no need formatting will still use this function. */
IConsolePrint(colour_code, fmt::format(format, std::forward<A>(first_arg), std::forward<Args>(other_args)...));
}
void CDECL IConsolePrintF(TextColour colour_code, const char *format, ...) WARN_FORMAT(2, 3);
void IConsoleWarning(const char *string);
void IConsoleError(const char *string);
/* Parser */
void IConsoleCmdExec(const std::string &command_string, const uint recurse_count = 0);

@ -31,7 +31,7 @@ enum ConsoleHookResult {
* If you want to handle multiple words as one, enclose them in double-quotes
* eg. 'say "hello everybody"'
*/
typedef bool IConsoleCmdProc(byte argc, char *argv[]);
typedef bool IConsoleCmdProc(uint8_t argc, char *argv[]);
typedef ConsoleHookResult IConsoleHook(bool echo);
struct IConsoleCmd {
IConsoleCmd(const std::string &name, IConsoleCmdProc *proc, IConsoleHook *hook, bool unlisted) : name(name), proc(proc), hook(hook), unlisted(unlisted) {}

@ -23,6 +23,7 @@ enum IConsoleModes {
static const TextColour CC_DEFAULT = TC_SILVER; ///< Default colour of the console.
static const TextColour CC_ERROR = TC_RED; ///< Colour for error lines.
static const TextColour CC_WARNING = TC_LIGHT_BLUE; ///< Colour for warning lines.
static const TextColour CC_HELP = TC_LIGHT_BLUE; ///< Colour for help lines.
static const TextColour CC_INFO = TC_YELLOW; ///< Colour for information lines.
static const TextColour CC_DEBUG = TC_LIGHT_BROWN; ///< Colour for debug output.
static const TextColour CC_COMMAND = TC_GOLD; ///< Colour for the console's commands.

@ -94,14 +94,14 @@ public:
* @param size the amount of bytes to allocate.
* @return the given amounts of bytes zeroed.
*/
inline void *operator new(size_t size) { return CallocT<byte>(size); }
inline void *operator new(size_t size) { return CallocT<uint8_t>(size); }
/**
* Memory allocator for an array of class instances.
* @param size the amount of bytes to allocate.
* @return the given amounts of bytes zeroed.
*/
inline void *operator new[](size_t size) { return CallocT<byte>(size); }
inline void *operator new[](size_t size) { return CallocT<uint8_t>(size); }
/**
* Memory release for a single class instance.

@ -49,7 +49,7 @@ inline bool ShouldLogUpdateStateChecksum()
return _networking && (!_network_server || (NetworkClientSocket::IsValidID(0) && NetworkClientSocket::Get(0)->status != NetworkClientSocket::STATUS_INACTIVE));
}
# define DEBUG_UPDATESTATECHECKSUM(str, ...) if (ShouldLogUpdateStateChecksum()) DEBUG(statecsum, 0, "%s; %04x; %02x; " OTTD_PRINTFHEX64PAD "; %s:%d " str, \
debug_date_dumper().HexDate(), _frame_counter, (byte)_current_company, _state_checksum.state, __FILE__, __LINE__, __VA_ARGS__);
debug_date_dumper().HexDate(), _frame_counter, (uint8_t)_current_company, _state_checksum.state, __FILE__, __LINE__, __VA_ARGS__);
#else
# define DEBUG_UPDATESTATECHECKSUM(str, ...)
#endif /* RANDOM_DEBUG */

@ -49,7 +49,7 @@
* other templates below. Here we have only forward declaration. For each enum type
* we will create specialization derived from MakeEnumPropsT<>.
* i.e.:
* template <> struct EnumPropsT<Track> : MakeEnumPropsT<Track, byte, TRACK_BEGIN, TRACK_END, INVALID_TRACK> {};
* template <> struct EnumPropsT<Track> : MakeEnumPropsT<Track, uint8_t, TRACK_BEGIN, TRACK_END, INVALID_TRACK> {};
*/
template <typename Tenum_t> struct EnumPropsT;
@ -58,7 +58,7 @@ template <typename Tenum_t> struct EnumPropsT;
* from outsize. It is used as base class of several EnumPropsT specializations each
* dedicated to one of commonly used enumeration types.
* @param Tenum_t enumeration type that you want to describe
* @param Tstorage_t what storage type would be sufficient (i.e. byte)
* @param Tstorage_t what storage type would be sufficient (i.e. uint8_t)
* @param Tbegin first valid value from the contiguous range (i.e. TRACK_BEGIN)
* @param Tend one past the last valid value from the contiguous range (i.e. TRACK_END)
* @param Tinvalid value used as invalid value marker (i.e. INVALID_TRACK)
@ -67,7 +67,7 @@ template <typename Tenum_t> struct EnumPropsT;
template <typename Tenum_t, typename Tstorage_t, Tenum_t Tbegin, Tenum_t Tend, Tenum_t Tinvalid, uint Tnum_bits = 8 * sizeof(Tstorage_t)>
struct MakeEnumPropsT {
typedef Tenum_t type; ///< enum type (i.e. Trackdir)
typedef Tstorage_t storage; ///< storage type (i.e. byte)
typedef Tstorage_t storage; ///< storage type (i.e. uint8_t)
static const Tenum_t begin = Tbegin; ///< lowest valid value (i.e. TRACKDIR_BEGIN)
static const Tenum_t end = Tend; ///< one after the last valid value (i.e. TRACKDIR_END)
static const Tenum_t invalid = Tinvalid; ///< what value is used as invalid value (i.e. INVALID_TRACKDIR)

@ -46,7 +46,7 @@ inline void MemMoveT(T *destination, const T *source, size_t num = 1)
* @param num number of items to be set (!not number of bytes!)
*/
template <typename T>
inline void MemSetT(T *ptr, byte value, size_t num = 1)
inline void MemSetT(T *ptr, uint8_t value, size_t num = 1)
{
memset(ptr, value, num * sizeof(T));
}

@ -138,7 +138,7 @@ public:
inline constexpr OverflowSafeInt operator * (const int factor) const { OverflowSafeInt result = *this; result *= (int64_t)factor; return result; }
inline constexpr OverflowSafeInt operator * (const uint factor) const { OverflowSafeInt result = *this; result *= (int64_t)factor; return result; }
inline constexpr OverflowSafeInt operator * (const uint16_t factor) const { OverflowSafeInt result = *this; result *= (int64_t)factor; return result; }
inline constexpr OverflowSafeInt operator * (const byte factor) const { OverflowSafeInt result = *this; result *= (int64_t)factor; return result; }
inline constexpr OverflowSafeInt operator * (const uint8_t factor) const { OverflowSafeInt result = *this; result *= (int64_t)factor; return result; }
/* Operators for division. */
inline constexpr OverflowSafeInt& operator /= (const int64_t divisor) { this->m_value /= divisor; return *this; }
@ -197,11 +197,11 @@ template <class T> inline constexpr OverflowSafeInt<T> operator - (const uint a
template <class T> inline constexpr OverflowSafeInt<T> operator * (const uint a, const OverflowSafeInt<T> b) { return b * a; }
template <class T> inline constexpr OverflowSafeInt<T> operator / (const uint a, const OverflowSafeInt<T> b) { return (OverflowSafeInt<T>)a / (int)b; }
/* Sometimes we got byte operator OverflowSafeInt instead of vice versa. Handle that properly. */
template <class T> inline constexpr OverflowSafeInt<T> operator + (const byte a, const OverflowSafeInt<T> b) { return b + (uint)a; }
template <class T> inline constexpr OverflowSafeInt<T> operator - (const byte a, const OverflowSafeInt<T> b) { return -b + (uint)a; }
template <class T> inline constexpr OverflowSafeInt<T> operator * (const byte a, const OverflowSafeInt<T> b) { return b * (uint)a; }
template <class T> inline constexpr OverflowSafeInt<T> operator / (const byte a, const OverflowSafeInt<T> b) { return (OverflowSafeInt<T>)a / (int)b; }
/* Sometimes we got uint8_t operator OverflowSafeInt instead of vice versa. Handle that properly. */
template <class T> inline constexpr OverflowSafeInt<T> operator + (const uint8_t a, const OverflowSafeInt<T> b) { return b + (uint)a; }
template <class T> inline constexpr OverflowSafeInt<T> operator - (const uint8_t a, const OverflowSafeInt<T> b) { return -b + (uint)a; }
template <class T> inline constexpr OverflowSafeInt<T> operator * (const uint8_t a, const OverflowSafeInt<T> b) { return b * (uint)a; }
template <class T> inline constexpr OverflowSafeInt<T> operator / (const uint8_t a, const OverflowSafeInt<T> b) { return (OverflowSafeInt<T>)a / (int)b; }
typedef OverflowSafeInt<int64_t> OverflowSafeInt64;
typedef OverflowSafeInt<int32_t> OverflowSafeInt32;

@ -125,9 +125,9 @@ DEFINE_POOL_METHOD(inline void *)::AllocateItem(size_t size, size_t index, Pool:
memset((void *)item, 0, sizeof(Titem));
}
} else if (Tzero) {
item = (Titem *)CallocT<byte>(size);
item = (Titem *)CallocT<uint8_t>(size);
} else {
item = (Titem *)MallocT<byte>(size);
item = (Titem *)MallocT<uint8_t>(size);
}
this->data[index] = Tops::PutPtr(item, param);
SetBit(this->free_bitmap[index / 64], index % 64);

@ -87,7 +87,7 @@ void SetRandomSeed(uint32_t seed)
uint32_t DoRandom(int line, const char *file)
{
if (_networking && (!_network_server || (NetworkClientSocket::IsValidID(0) && NetworkClientSocket::Get(0)->status != NetworkClientSocket::STATUS_INACTIVE))) {
DEBUG(random, 0, "%s; %04x; %02x; %s:%d", debug_date_dumper().HexDate(), _frame_counter, (byte)_current_company, file, line);
DEBUG(random, 0, "%s; %04x; %02x; %s:%d", debug_date_dumper().HexDate(), _frame_counter, (uint8_t)_current_company, file, line);
}
return _random.Next();

@ -25,7 +25,7 @@
template <class T>
class ring_buffer
{
std::unique_ptr<byte, FreeDeleter> data;
std::unique_ptr<uint8_t, FreeDeleter> data;
uint32_t head = 0;
uint32_t count = 0;
uint32_t mask = (uint32_t)-1;
@ -219,11 +219,11 @@ public:
void construct_from(const U &other)
{
uint32_t cap = round_up_size((uint32_t)other.size());
this->data.reset(MallocT<byte>(cap * sizeof(T)));
this->data.reset(MallocT<uint8_t>(cap * sizeof(T)));
this->mask = cap - 1;
this->head = 0;
this->count = (uint32_t)other.size();
byte *ptr = this->data.get();
uint8_t *ptr = this->data.get();
for (const T &item : other) {
new (ptr) T(item);
ptr += sizeof(T);
@ -259,12 +259,12 @@ public:
if (!other.empty()) {
if (other.size() > this->capacity()) {
uint32_t cap = round_up_size(other.count);
this->data.reset(MallocT<byte>(cap * sizeof(T)));
this->data.reset(MallocT<uint8_t>(cap * sizeof(T)));
this->mask = cap - 1;
}
this->head = 0;
this->count = other.count;
byte *ptr = this->data.get();
uint8_t *ptr = this->data.get();
for (const T &item : other) {
new (ptr) T(item);
ptr += sizeof(T);
@ -341,8 +341,8 @@ private:
void reallocate(uint32_t new_cap)
{
const uint32_t cap = round_up_size(new_cap);
byte *new_buf = MallocT<byte>(cap * sizeof(T));
byte *pos = new_buf;
uint8_t *new_buf = MallocT<uint8_t>(cap * sizeof(T));
uint8_t *pos = new_buf;
for (T &item : *this) {
new (pos) T(std::move(item));
item.~T();
@ -522,8 +522,8 @@ private:
if (this->count + num > (uint32_t)this->capacity()) {
/* grow container */
const uint32_t cap = round_up_size(this->count + num);
byte *new_buf = MallocT<byte>(cap * sizeof(T));
byte *write_to = new_buf;
uint8_t *new_buf = MallocT<uint8_t>(cap * sizeof(T));
uint8_t *write_to = new_buf;
const uint32_t end = this->head + this->count;
for (uint32_t idx = this->head; idx != end; idx++) {
if (idx == pos) {

@ -16,7 +16,7 @@
* @param bytes_to_write The amount of bytes we want to try to write.
* @return True iff the given amount of bytes can be written to the packet.
*/
[[maybe_unused]] static bool BufferCanWriteToPacket(const std::vector<byte> &buffer, size_t limit, size_t bytes_to_write)
[[maybe_unused]] static bool BufferCanWriteToPacket(const std::vector<uint8_t> &buffer, size_t limit, size_t bytes_to_write)
{
return buffer.size() + bytes_to_write <= limit;
}
@ -37,7 +37,7 @@
* Package a boolean in the packet.
* @param data The data to send.
*/
void BufferSend_bool(std::vector<byte> &buffer, size_t limit, bool data)
void BufferSend_bool(std::vector<uint8_t> &buffer, size_t limit, bool data)
{
BufferSend_uint8(buffer, limit, data ? 1 : 0);
}
@ -46,7 +46,7 @@ void BufferSend_bool(std::vector<byte> &buffer, size_t limit, bool data)
* Package a 8 bits integer in the packet.
* @param data The data to send.
*/
void BufferSend_uint8(std::vector<byte> &buffer, size_t limit, uint8_t data)
void BufferSend_uint8(std::vector<uint8_t> &buffer, size_t limit, uint8_t data)
{
assert(BufferCanWriteToPacket(buffer, limit, sizeof(data)));
buffer.emplace_back(data);
@ -56,7 +56,7 @@ void BufferSend_uint8(std::vector<byte> &buffer, size_t limit, uint8_t data)
* Package a 16 bits integer in the packet.
* @param data The data to send.
*/
void BufferSend_uint16(std::vector<byte> &buffer, size_t limit, uint16_t data)
void BufferSend_uint16(std::vector<uint8_t> &buffer, size_t limit, uint16_t data)
{
assert(BufferCanWriteToPacket(buffer, limit, sizeof(data)));
buffer.insert(buffer.end(), {
@ -69,7 +69,7 @@ void BufferSend_uint16(std::vector<byte> &buffer, size_t limit, uint16_t data)
* Package a 32 bits integer in the packet.
* @param data The data to send.
*/
void BufferSend_uint32(std::vector<byte> &buffer, size_t limit, uint32_t data)
void BufferSend_uint32(std::vector<uint8_t> &buffer, size_t limit, uint32_t data)
{
assert(BufferCanWriteToPacket(buffer, limit, sizeof(data)));
buffer.insert(buffer.end(), {
@ -84,7 +84,7 @@ void BufferSend_uint32(std::vector<byte> &buffer, size_t limit, uint32_t data)
* Package a 64 bits integer in the packet.
* @param data The data to send.
*/
void BufferSend_uint64(std::vector<byte> &buffer, size_t limit, uint64_t data)
void BufferSend_uint64(std::vector<uint8_t> &buffer, size_t limit, uint64_t data)
{
assert(BufferCanWriteToPacket(buffer, limit, sizeof(data)));
buffer.insert(buffer.end(), {
@ -104,7 +104,7 @@ void BufferSend_uint64(std::vector<byte> &buffer, size_t limit, uint64_t data)
* the string + '\0'. No size-byte or something.
* @param data The string to send
*/
void BufferSend_string(std::vector<byte> &buffer, size_t limit, const std::string_view data)
void BufferSend_string(std::vector<uint8_t> &buffer, size_t limit, const std::string_view data)
{
assert(BufferCanWriteToPacket(buffer, limit, data.size() + 1));
buffer.insert(buffer.end(), data.begin(), data.end());
@ -119,7 +119,7 @@ void BufferSend_string(std::vector<byte> &buffer, size_t limit, const std::strin
* @param end The end of the buffer to send.
* @return The number of bytes that were added to this packet.
*/
size_t BufferSend_binary_until_full(std::vector<byte> &buffer, size_t limit, const byte *begin, const byte *end)
size_t BufferSend_binary_until_full(std::vector<uint8_t> &buffer, size_t limit, const uint8_t *begin, const uint8_t *end)
{
size_t amount = std::min<size_t>(end - begin, limit - buffer.size());
buffer.insert(buffer.end(), begin, begin + amount);
@ -130,7 +130,7 @@ size_t BufferSend_binary_until_full(std::vector<byte> &buffer, size_t limit, con
* Sends a binary data over the network.
* @param data The data to send
*/
void BufferSend_binary(std::vector<byte> &buffer, size_t limit, const byte *data, const size_t size)
void BufferSend_binary(std::vector<uint8_t> &buffer, size_t limit, const uint8_t *data, const size_t size)
{
assert(data != nullptr);
assert(BufferCanWriteToPacket(buffer, limit, size));
@ -142,7 +142,7 @@ void BufferSend_binary(std::vector<byte> &buffer, size_t limit, const byte *data
* The data is length prefixed with a uint16.
* @param data The string to send
*/
void BufferSend_buffer(std::vector<byte> &buffer, size_t limit, const byte *data, const size_t size)
void BufferSend_buffer(std::vector<uint8_t> &buffer, size_t limit, const uint8_t *data, const size_t size)
{
assert(size <= UINT16_MAX);
assert(BufferCanWriteToPacket(buffer, limit, size + 2));

@ -18,15 +18,15 @@
#include <string>
#include <limits>
void BufferSend_bool (std::vector<byte> &buffer, size_t limit, bool data);
void BufferSend_uint8 (std::vector<byte> &buffer, size_t limit, uint8_t data);
void BufferSend_uint16(std::vector<byte> &buffer, size_t limit, uint16_t data);
void BufferSend_uint32(std::vector<byte> &buffer, size_t limit, uint32_t data);
void BufferSend_uint64(std::vector<byte> &buffer, size_t limit, uint64_t data);
void BufferSend_string(std::vector<byte> &buffer, size_t limit, const std::string_view data);
size_t BufferSend_binary_until_full(std::vector<byte> &buffer, size_t limit, const byte *begin, const byte *end);
void BufferSend_binary(std::vector<byte> &buffer, size_t limit, const byte *data, const size_t size);
void BufferSend_buffer(std::vector<byte> &buffer, size_t limit, const byte *data, const size_t size);
void BufferSend_bool (std::vector<uint8_t> &buffer, size_t limit, bool data);
void BufferSend_uint8 (std::vector<uint8_t> &buffer, size_t limit, uint8_t data);
void BufferSend_uint16(std::vector<uint8_t> &buffer, size_t limit, uint16_t data);
void BufferSend_uint32(std::vector<uint8_t> &buffer, size_t limit, uint32_t data);
void BufferSend_uint64(std::vector<uint8_t> &buffer, size_t limit, uint64_t data);
void BufferSend_string(std::vector<uint8_t> &buffer, size_t limit, const std::string_view data);
size_t BufferSend_binary_until_full(std::vector<uint8_t> &buffer, size_t limit, const uint8_t *begin, const uint8_t *end);
void BufferSend_binary(std::vector<uint8_t> &buffer, size_t limit, const uint8_t *data, const size_t size);
void BufferSend_buffer(std::vector<uint8_t> &buffer, size_t limit, const uint8_t *data, const size_t size);
template <typename T>
struct BufferSerialisationHelper {
@ -66,30 +66,30 @@ struct BufferSerialisationHelper {
BufferSend_string(self->GetSerialisationBuffer(), self->GetSerialisationLimit(), data);
}
size_t Send_binary_until_full(const byte *begin, const byte *end)
size_t Send_binary_until_full(const uint8_t *begin, const uint8_t *end)
{
T *self = static_cast<T *>(this);
return BufferSend_binary_until_full(self->GetSerialisationBuffer(), self->GetSerialisationLimit(), begin, end);
}
void Send_binary(const byte *data, const size_t size)
void Send_binary(const uint8_t *data, const size_t size)
{
T *self = static_cast<T *>(this);
BufferSend_binary(self->GetSerialisationBuffer(), self->GetSerialisationLimit(), data, size);
}
void Send_binary(std::span<const byte> data)
void Send_binary(std::span<const uint8_t> data)
{
this->Send_binary(data.data(), data.size());
}
void Send_buffer(const byte *data, const size_t size)
void Send_buffer(const uint8_t *data, const size_t size)
{
T *self = static_cast<T *>(this);
BufferSend_buffer(self->GetSerialisationBuffer(), self->GetSerialisationLimit(), data, size);
}
void Send_buffer(const std::vector<byte> &data)
void Send_buffer(const std::vector<uint8_t> &data)
{
this->Send_buffer(data.data(), data.size());
}
@ -100,7 +100,7 @@ void BufferRecvStringValidate(std::string &buffer, StringValidationSettings sett
template <typename T>
struct BufferDeserialisationHelper {
private:
const byte *GetBuffer()
const uint8_t *GetBuffer()
{
return static_cast<T *>(this)->GetDeserialisationBuffer();
}
@ -253,7 +253,7 @@ public:
* @param buffer The buffer to put the data into.
* @param size The size of the data.
*/
void Recv_binary(byte *buffer, size_t size)
void Recv_binary(uint8_t *buffer, size_t size)
{
if (!this->CanRecvBytes(size, true)) return;
@ -267,7 +267,7 @@ public:
* Reads binary data.
* @param buffer The buffer to put the data into.
*/
void Recv_binary(std::span<byte> buffer)
void Recv_binary(std::span<uint8_t> buffer)
{
this->Recv_binary(buffer.data(), buffer.size());
}
@ -331,11 +331,11 @@ public:
};
struct BufferSerialiser : public BufferSerialisationHelper<BufferSerialiser> {
std::vector<byte> &buffer;
std::vector<uint8_t> &buffer;
BufferSerialiser(std::vector<byte> &buffer) : buffer(buffer) {}
BufferSerialiser(std::vector<uint8_t> &buffer) : buffer(buffer) {}
std::vector<byte> &GetSerialisationBuffer() { return this->buffer; }
std::vector<uint8_t> &GetSerialisationBuffer() { return this->buffer; }
size_t GetSerialisationLimit() const { return std::numeric_limits<size_t>::max(); }
};

@ -25,7 +25,7 @@
* | | Euro year | | | | name
* | | | | | | | | */
/** The original currency specifications. */
static const CurrencySpec origin_currency_specs[CURRENCY_END] = {
static const std::array<CurrencySpec, CURRENCY_END> origin_currency_specs = {{
{ 1, "", CF_NOEURO, "\u00a3", "", "GBP", 0, STR_GAME_OPTIONS_CURRENCY_GBP }, ///< british pound
{ 2, "", CF_NOEURO, "$", "", "USD", 0, STR_GAME_OPTIONS_CURRENCY_USD }, ///< american dollar
{ 2, "", CF_ISEURO, "\u20ac", "", "EUR", 0, STR_GAME_OPTIONS_CURRENCY_EUR }, ///< euro
@ -70,10 +70,10 @@ static const CurrencySpec origin_currency_specs[CURRENCY_END] = {
{ 5, "", CF_NOEURO, "RM", "", "MYR", 0, STR_GAME_OPTIONS_CURRENCY_MYR }, ///< Malaysian Ringgit
{ 1, "", 2014, "", NBSP "Ls", "LVL", 1, STR_GAME_OPTIONS_CURRENCY_LVL }, ///< latvian lats
{ 400, "", 2002, "", "$00", "PTE", 1, STR_GAME_OPTIONS_CURRENCY_PTE }, ///< portuguese escudo
};
}};
/** Array of currencies used by the system */
CurrencySpec _currency_specs[CURRENCY_END];
std::array<CurrencySpec, CURRENCY_END> _currency_specs;
/**
* This array represent the position of OpenTTD's currencies,
@ -81,7 +81,7 @@ CurrencySpec _currency_specs[CURRENCY_END];
* When a grf sends currencies, they are based on the order defined by TTDPatch.
* So, we must reindex them to our own order.
*/
const byte TTDPatch_To_OTTDIndex[] =
const uint8_t TTDPatch_To_OTTDIndex[] =
{
CURRENCY_GBP,
CURRENCY_USD,
@ -112,7 +112,7 @@ const byte TTDPatch_To_OTTDIndex[] =
* @param grfcurr_id currency id coming from newgrf
* @return the corrected index
*/
byte GetNewgrfCurrencyIdConverted(byte grfcurr_id)
uint8_t GetNewgrfCurrencyIdConverted(uint8_t grfcurr_id)
{
return (grfcurr_id >= lengthof(TTDPatch_To_OTTDIndex)) ? grfcurr_id : TTDPatch_To_OTTDIndex[grfcurr_id];
}

@ -11,7 +11,7 @@
#define CURRENCY_H
#include "date_type.h"
#include "string_func.h"
#include "settings_type.h"
#include "strings_type.h"
static const int CF_NOEURO = 0; ///< Currency never switches to the Euro (as far as known).
@ -87,26 +87,40 @@ struct CurrencySpec {
* It is not a spec from Newgrf,
* rather a way to let users do what they want with custom currency
*/
byte symbol_pos;
uint8_t symbol_pos;
StringID name;
CurrencySpec() = default;
CurrencySpec(uint16_t rate, const char *separator, CalTime::Year to_euro, const char *prefix, const char *suffix, const char *code, byte symbol_pos, StringID name) :
CurrencySpec(uint16_t rate, const char *separator, CalTime::Year to_euro, const char *prefix, const char *suffix, const char *code, uint8_t symbol_pos, StringID name) :
rate(rate), separator(separator), to_euro(to_euro), prefix(prefix), suffix(suffix), code(code), symbol_pos(symbol_pos), name(name)
{
}
};
extern CurrencySpec _currency_specs[CURRENCY_END];
extern std::array<CurrencySpec, CURRENCY_END> _currency_specs;
/* XXX small hack, but makes the rest of the code a bit nicer to read */
#define _custom_currency (_currency_specs[CURRENCY_CUSTOM])
#define _currency ((const CurrencySpec*)&_currency_specs[GetGameSettings().locale.currency])
/**
* Get the custom currency.
* @return Reference to custom currency.
*/
inline CurrencySpec &GetCustomCurrency()
{
return _currency_specs[CURRENCY_CUSTOM];
}
/**
* Get the currently selected currency.
* @return Read-only reference to the current currency.
*/
inline const CurrencySpec &GetCurrency()
{
return _currency_specs[GetGameSettings().locale.currency];
}
uint64_t GetMaskOfAllowedCurrencies();
void CheckSwitchToEuro();
void ResetCurrencies(bool preserve_custom = true);
byte GetNewgrfCurrencyIdConverted(byte grfcurr_id);
uint8_t GetNewgrfCurrencyIdConverted(uint8_t grfcurr_id);
#endif /* CURRENCY_H */

@ -436,6 +436,8 @@ static void OnNewEconomyMonth()
*/
static void OnNewCalendarDay()
{
EnginesDailyLoop();
if (!_settings_time.time_in_minutes || _settings_client.gui.date_with_time > 0) {
SetWindowWidgetDirty(WC_STATUS_BAR, 0, WID_S_LEFT);
}
@ -455,7 +457,6 @@ static void OnNewEconomyDay()
IndustryDailyLoop();
StationDailyLoop();
EnginesDailyLoop();
ClearOutOfDateSignalSpeedRestrictions();
if (_quit_after_days > 0) {
@ -466,7 +467,7 @@ static void OnNewEconomyDay()
}
}
static void IncreaseCalendarDate()
void IncreaseCalendarDate()
{
/* If calendar day progress is frozen, don't try to advance time. */
if (CalTime::IsCalendarFrozen()) return;

@ -15,8 +15,8 @@
#include "date_gui.h"
#include "core/geometry_func.hpp"
#include "settings_type.h"
#include "dropdown_type.h"
#include "widgets/dropdown_type.h"
#include "widgets/date_widget.h"
#include "safeguards.h"

@ -123,8 +123,6 @@ private:
char buffer[24];
};
const char *GetLogPrefix();
void ClearDesyncMsgLog();
void LogDesyncMsg(std::string msg);
char *DumpDesyncMsgLog(char *buffer, const char *last);

@ -1146,7 +1146,7 @@ static void DepotSellAllConfirmationCallback(Window *win, bool confirmed)
if (confirmed) {
DepotWindow *w = (DepotWindow*)win;
TileIndex tile = w->window_number;
byte vehtype = w->type;
uint8_t vehtype = w->type;
DoCommandP(tile, vehtype, 0, CMD_DEPOT_SELL_ALL_VEHICLES);
}
}

@ -21,7 +21,7 @@
* your viewport and not rotated by 45 degrees left or right to get
* a "north" used in you games.
*/
enum Direction : byte {
enum Direction : uint8_t {
DIR_BEGIN = 0, ///< Used to iterate
DIR_N = 0, ///< North
DIR_NE = 1, ///< Northeast
@ -39,7 +39,7 @@ enum Direction : byte {
DECLARE_POSTFIX_INCREMENT(Direction)
/** Define basic enum properties */
template <> struct EnumPropsT<Direction> : MakeEnumPropsT<Direction, byte, DIR_BEGIN, DIR_END, INVALID_DIR, 3> {};
template <> struct EnumPropsT<Direction> : MakeEnumPropsT<Direction, uint8_t, DIR_BEGIN, DIR_END, INVALID_DIR, 3> {};
/**
@ -59,7 +59,7 @@ template <> struct EnumPropsT<Direction> : MakeEnumPropsT<Direction, byte, DIR_B
* modulo DIR_END or use the #ChangeDirDiff(DirDiff, DirDiff) function.
* @see ChangeDirDiff(DirDiff, DirDiff)
*/
enum DirDiff : byte {
enum DirDiff : uint8_t {
DIRDIFF_SAME = 0, ///< Both directions faces to the same direction
DIRDIFF_45RIGHT = 1, ///< Angle of 45 degrees right
DIRDIFF_90RIGHT = 2, ///< Angle of 90 degrees right
@ -74,7 +74,7 @@ enum DirDiff : byte {
*
* This enumeration is used for the 4 direction of the tile-edges.
*/
enum DiagDirection : byte {
enum DiagDirection : uint8_t {
DIAGDIR_BEGIN = 0, ///< Used for iterations
DIAGDIR_NE = 0, ///< Northeast, upper right on your monitor
DIAGDIR_SE = 1, ///< Southeast
@ -87,7 +87,7 @@ DECLARE_POSTFIX_INCREMENT(DiagDirection)
DECLARE_ENUM_AS_ADDABLE(DiagDirection)
/** Define basic enum properties */
template <> struct EnumPropsT<DiagDirection> : MakeEnumPropsT<DiagDirection, byte, DIAGDIR_BEGIN, DIAGDIR_END, INVALID_DIAGDIR, 2> {};
template <> struct EnumPropsT<DiagDirection> : MakeEnumPropsT<DiagDirection, uint8_t, DIAGDIR_BEGIN, DIAGDIR_END, INVALID_DIAGDIR, 2> {};
/**
@ -119,14 +119,14 @@ DECLARE_POSTFIX_INCREMENT(DiagDirDiff)
* (and south-east edge). The Y axis must be so the one which goes
* align the north-east edge (and south-west) edge.
*/
enum Axis : byte {
enum Axis : uint8_t {
AXIS_X = 0, ///< The X axis
AXIS_Y = 1, ///< The y axis
AXIS_END, ///< Used for iterations
INVALID_AXIS = 0xFF, ///< Flag for an invalid Axis
};
/** Helper information for extract tool. */
template <> struct EnumPropsT<Axis> : MakeEnumPropsT<Axis, byte, AXIS_X, AXIS_END, INVALID_AXIS, 1> {};
template <> struct EnumPropsT<Axis> : MakeEnumPropsT<Axis, uint8_t, AXIS_X, AXIS_END, INVALID_AXIS, 1> {};
DECLARE_ENUM_AS_ADDABLE(Axis)
#endif /* DIRECTION_TYPE_H */

@ -963,11 +963,11 @@ static const Disaster _disasters[] = {
void DoDisaster()
{
byte buf[lengthof(_disasters)];
uint8_t buf[lengthof(_disasters)];
byte j = 0;
uint8_t j = 0;
for (size_t i = 0; i != lengthof(_disasters); i++) {
if (CalTime::CurYear() >= _disasters[i].min_year && CalTime::CurYear() < _disasters[i].max_year) buf[j++] = (byte)i;
if (CalTime::CurYear() >= _disasters[i].min_year && CalTime::CurYear() < _disasters[i].max_year) buf[j++] = (uint8_t)i;
}
if (j == 0) return;

@ -37,7 +37,7 @@ enum DisasterSubType {
struct DisasterVehicle final : public SpecializedVehicle<DisasterVehicle, VEH_DISASTER> {
SpriteID image_override; ///< Override for the default disaster vehicle sprite.
VehicleID big_ufo_destroyer_target; ///< The big UFO that this destroyer is supposed to bomb.
byte flags; ///< Flags about the state of the vehicle, @see AirVehicleFlags
uint8_t flags; ///< Flags about the state of the vehicle, @see AirVehicleFlags
uint16_t state; ///< Action stage of the disaster vehicle.
/** For use by saveload. */

@ -7,18 +7,18 @@
/** @file dropdown.cpp Implementation of the dropdown widget. */
#include "../stdafx.h"
#include "../window_gui.h"
#include "../string_func.h"
#include "../strings_func.h"
#include "../window_func.h"
#include "../guitimer_func.h"
#include "../zoom_func.h"
#include "stdafx.h"
#include "window_gui.h"
#include "string_func.h"
#include "strings_func.h"
#include "window_func.h"
#include "guitimer_func.h"
#include "zoom_func.h"
#include "dropdown_type.h"
#include "dropdown_widget.h"
#include "widgets/dropdown_widget.h"
#include "../safeguards.h"
#include "safeguards.h"
static constexpr NWidgetPart _nested_dropdown_menu_widgets[] = {
@ -44,7 +44,7 @@ struct DropdownWindow : Window {
Rect wi_rect; ///< Rect of the button that opened the dropdown.
DropDownList list; ///< List with dropdown menu items.
int selected_result; ///< Result value of the selected item in the list.
byte click_delay = 0; ///< Timer to delay selection.
uint8_t click_delay = 0; ///< Timer to delay selection.
bool drag_mode = true;
DropDownModeFlags mode_flags; ///< Mode flags.
int scrolling = 0; ///< If non-zero, auto-scroll the item list (one time).
@ -154,7 +154,12 @@ struct DropdownWindow : Window {
this->position.y = button_rect.bottom + 1;
}
this->position.x = (_current_text_dir == TD_RTL) ? button_rect.right + 1 - (int)widget_dim.width : button_rect.left;
if (_current_text_dir == TD_RTL) {
/* In case the list is wider than the parent button, the list should be right aligned to the button and overflow to the left. */
this->position.x = button_rect.right + 1 - (int)(widget_dim.width + (list_dim.height > widget_dim.height ? NWidgetScrollbar::GetVerticalDimension().width : 0));
} else {
this->position.x = button_rect.left;
}
this->items_dim = widget_dim;
this->GetWidget<NWidgetStacked>(WID_DM_SHOW_SCROLL)->SetDisplayedPlane(list_dim.height > widget_dim.height ? 0 : SZSP_NONE);

@ -7,10 +7,10 @@
/** @file dropdown_func.h Functions related to the drop down widget. */
#ifndef WIDGETS_DROPDOWN_FUNC_H
#define WIDGETS_DROPDOWN_FUNC_H
#ifndef DROPDOWN_FUNC_H
#define DROPDOWN_FUNC_H
#include "../window_gui.h"
#include "window_gui.h"
#include "dropdown_type.h"
/* Show drop down menu containing a fixed list of strings */
@ -21,4 +21,4 @@ int HideDropDownMenu(Window *pw);
void GetParentWindowInfo(Window *w, WindowClass &parent_wc, WindowNumber &parent_wn);
#endif /* WIDGETS_DROPDOWN_FUNC_H */
#endif /* DROPDOWN_FUNC_H */

@ -7,16 +7,16 @@
/** @file dropdown_type.h Types related to the drop down widget. */
#ifndef WIDGETS_DROPDOWN_TYPE_H
#define WIDGETS_DROPDOWN_TYPE_H
#include "../window_type.h"
#include "../gfx_func.h"
#include "../gfx_type.h"
#include "../string_func.h"
#include "../strings_func.h"
#include "../table/strings.h"
#include "../window_gui.h"
#ifndef DROPDOWN_TYPE_H
#define DROPDOWN_TYPE_H
#include "window_type.h"
#include "gfx_func.h"
#include "gfx_type.h"
#include "string_func.h"
#include "strings_func.h"
#include "table/strings.h"
#include "window_gui.h"
#include <vector>
enum DropDownSyncFocus {
@ -250,4 +250,4 @@ Dimension GetDropDownListDimension(const DropDownList &list);
void ReplaceDropDownList(Window *parent, DropDownList &&list);
#endif /* WIDGETS_DROPDOWN_TYPE_H */
#endif /* DROPDOWN_TYPE_H */

@ -142,7 +142,7 @@ Money CalculateCompanyValueExcludingShares(const Company *c, bool including_loan
uint num = 0;
for (const Station *st : Station::Iterate()) {
if (st->owner == owner) num += CountBits((byte)st->facilities);
if (st->owner == owner) num += CountBits((uint8_t)st->facilities);
}
Money value = num * _price[PR_STATION_VALUE] * 25;
@ -264,7 +264,7 @@ int UpdateCompanyRatingAndValue(Company *c, bool update)
uint num = 0;
for (const Station *st : Station::Iterate()) {
/* Only count stations that are actually serviced */
if (st->owner == owner && (st->time_since_load <= 20 || st->time_since_unload <= 20)) num += CountBits((byte)st->facilities);
if (st->owner == owner && (st->time_since_load <= 20 || st->time_since_unload <= 20)) num += CountBits((uint8_t)st->facilities);
}
_score_part[owner][SCORE_STATIONS] = num;
}
@ -2490,11 +2490,16 @@ static void DoAcquireCompany(Company *c, bool hostile_takeover)
ChangeOwnershipOfCompanyItems(ci, _current_company);
PostAcquireCompany(c);
}
void PostAcquireCompany(Company *c)
{
if (c->is_ai) AI::Stop(c->index);
c->bankrupt_asked = 0;
DeleteCompanyWindows(ci);
DeleteCompanyWindows(c->index);
InvalidateWindowClassesData(WC_TRAINS_LIST, 0);
InvalidateWindowClassesData(WC_TRACE_RESTRICT_SLOTS, 0);
InvalidateWindowClassesData(WC_SHIPS_LIST, 0);

@ -60,4 +60,6 @@ int PercentageToScaleQuantityFactor(uint percentage);
void UpdateCargoScalers();
void PostAcquireCompany(Company *c);
#endif /* ECONOMY_FUNC_H */

@ -28,9 +28,9 @@ enum EconomyType : uint8_t {
struct Economy {
Money max_loan; ///< NOSAVE: Maximum possible loan
int16_t fluct; ///< Economy fluctuation status
byte interest_rate; ///< Interest
byte infl_amount; ///< inflation amount
byte infl_amount_pr; ///< inflation rate for payment rates
uint8_t interest_rate; ///< Interest
uint8_t infl_amount; ///< inflation amount
uint8_t infl_amount_pr; ///< inflation rate for payment rates
uint32_t industry_daily_change_counter; ///< Bits 31-16 are number of industry to be performed, 15-0 are fractional collected daily
uint32_t industry_daily_increment; ///< The value which will increment industry_daily_change_counter. Computed value. NOSAVE
uint64_t inflation_prices; ///< Cumulated inflation of prices since game start; 16 bit fractional part
@ -154,7 +154,7 @@ typedef Money Prices[PR_END]; ///< Prices of everything. @see Price
typedef int8_t PriceMultipliers[PR_END];
/** Types of expenses. */
enum ExpensesType : byte {
enum ExpensesType : uint8_t {
EXPENSES_CONSTRUCTION = 0, ///< Construction costs.
EXPENSES_NEW_VEHICLES, ///< New vehicles.
EXPENSES_TRAIN_RUN, ///< Running costs trains.
@ -175,7 +175,7 @@ enum ExpensesType : byte {
};
/** Define basic enum properties for ExpensesType */
template <> struct EnumPropsT<ExpensesType> : MakeEnumPropsT<ExpensesType, byte, EXPENSES_CONSTRUCTION, EXPENSES_END, INVALID_EXPENSES, 8> {};
template <> struct EnumPropsT<ExpensesType> : MakeEnumPropsT<ExpensesType, uint8_t, EXPENSES_CONSTRUCTION, EXPENSES_END, INVALID_EXPENSES, 8> {};
/**
* Data type for storage of Money for each #ExpensesType category.
@ -241,21 +241,21 @@ static const uint LOCK_DEPOT_TILE_FACTOR = 2;
struct CargoPayment;
typedef uint32_t CargoPaymentID;
enum CargoPaymentAlgorithm : byte {
enum CargoPaymentAlgorithm : uint8_t {
CPA_BEGIN = 0, ///< Used for iterations and limit testing
CPA_TRADITIONAL = 0, ///< Traditional algorithm
CPA_MODERN, ///< Modern algorithm
CPA_END, ///< Used for iterations and limit testing
};
enum TickRateMode : byte {
enum TickRateMode : uint8_t {
TRM_BEGIN = 0, ///< Used for iterations and limit testing
TRM_TRADITIONAL = 0, ///< Traditional value (30ms)
TRM_MODERN, ///< Modern value (27ms)
TRM_END, ///< Used for iterations and limit testing
};
enum CargoScalingMode : byte {
enum CargoScalingMode : uint8_t {
CSM_BEGIN = 0, ///< Used for iterations and limit testing
CSM_MONTHLY = 0, ///< Traditional cargo scaling
CSM_DAYLENGTH, ///< Also scale by day length

@ -267,9 +267,9 @@ static void BulldozerInit(EffectVehicle *v)
}
struct BulldozerMovement {
byte direction:2;
byte image:2;
byte duration:3;
uint8_t direction:2;
uint8_t image:2;
uint8_t duration:3;
};
static const BulldozerMovement _bulldozer_movement[] = {
@ -344,7 +344,7 @@ struct BubbleMovement {
int8_t x:4;
int8_t y:4;
int8_t z:4;
byte image:4;
uint8_t image:4;
};
#define MK(x, y, z, i) { x, y, z, i }

@ -22,8 +22,8 @@
* - bubbles (industry)
*/
struct EffectVehicle final : public SpecializedVehicle<EffectVehicle, VEH_EFFECT> {
uint16_t animation_state; ///< State primarily used to change the graphics/behaviour.
byte animation_substate; ///< Sub state to time the change of the graphics/behaviour.
uint16_t animation_state; ///< State primarily used to change the graphics/behaviour.
uint8_t animation_substate; ///< Sub state to time the change of the graphics/behaviour.
/** We don't want GCC to zero our struct! It already is zeroed and has an index! */
EffectVehicle() : SpecializedVehicleBase() {}

@ -88,7 +88,7 @@ struct DualTrackBits {
* @param override pointer to PCP override, can be nullptr
* @return trackbits of tile if it is electrified
*/
static DualTrackBits GetRailTrackBitsUniversal(TileIndex t, byte *override)
static DualTrackBits GetRailTrackBitsUniversal(TileIndex t, uint8_t *override)
{
DualTrackBits out;
out.primary = TRACK_BIT_NONE;
@ -326,10 +326,10 @@ static void DrawRailCatenaryRailway(const TileInfo *ti)
}
TLG tlg = GetTLG(ti->tile);
byte PCPstatus = 0;
byte OverridePCP = 0;
byte PPPpreferred[DIAGDIR_END];
byte PPPallowed[DIAGDIR_END];
uint8_t PCPstatus = 0;
uint8_t OverridePCP = 0;
uint8_t PPPpreferred[DIAGDIR_END];
uint8_t PPPallowed[DIAGDIR_END];
/* Find which rail bits are present, and select the override points.
* We don't draw a pylon:
@ -499,7 +499,7 @@ static void DrawRailCatenaryRailway(const TileInfo *ti)
if (PPPallowed[i] != 0 && HasBit(PCPstatus, i) && !HasBit(OverridePCP, i) &&
(!IsRailStationTile(ti->tile) || CanStationTileHavePylons(ti->tile))) {
for (Direction k = DIR_BEGIN; k < DIR_END; k++) {
byte temp = PPPorder[i][GetTLG(ti->tile)][k];
uint8_t temp = PPPorder[i][GetTLG(ti->tile)][k];
if (HasBit(PPPallowed[i], temp)) {
uint x = ti->x + x_pcp_offsets[i] + x_ppp_offsets[temp];
@ -579,7 +579,7 @@ static void DrawRailCatenaryRailway(const TileInfo *ti)
/* Drawing of pylons is finished, now draw the wires */
for (Track t : SetTrackBitIterator(wireconfig[TS_HOME])) {
SpriteID wire_base = get_wire_sprite(t, (t == halftile_track));
byte PCPconfig = HasBit(PCPstatus, PCPpositions[t][0]) +
uint8_t PCPconfig = HasBit(PCPstatus, PCPpositions[t][0]) +
(HasBit(PCPstatus, PCPpositions[t][1]) << 1);
const SortableSpriteStruct *sss;

@ -223,9 +223,10 @@ bool Engine::CanPossiblyCarryCargo() const
* For aircraft the main capacity is determined. Mail might be present as well.
* @param v Vehicle of interest; nullptr in purchase list
* @param mail_capacity returns secondary cargo (mail) capacity of aircraft
* @param attempt_refit cargo ID to attempt to use, when v is nullptr
* @return Capacity
*/
uint Engine::DetermineCapacity(const Vehicle *v, uint16_t *mail_capacity) const
uint Engine::DetermineCapacity(const Vehicle *v, uint16_t *mail_capacity, CargoID attempt_refit) const
{
assert(v == nullptr || this->index == v->engine_type);
if (mail_capacity != nullptr) *mail_capacity = 0;
@ -234,7 +235,16 @@ uint Engine::DetermineCapacity(const Vehicle *v, uint16_t *mail_capacity) const
bool new_multipliers = HasBit(this->info.misc_flags, EF_NO_DEFAULT_CARGO_MULTIPLIER);
CargoID default_cargo = this->GetDefaultCargoType();
CargoID cargo_type = (v != nullptr) ? v->cargo_type : default_cargo;
CargoID cargo_type;
if (v != nullptr) {
cargo_type = v->cargo_type;
} else {
if (attempt_refit != INVALID_CARGO && HasBit(this->info.refit_mask, attempt_refit)) {
cargo_type = attempt_refit;
} else {
cargo_type = default_cargo;
}
}
if (mail_capacity != nullptr && this->type == VEH_AIRCRAFT && IsCargoInClass(cargo_type, CC_PASSENGERS)) {
*mail_capacity = GetEngineProperty(this->index, PROP_AIRCRAFT_MAIL_CAPACITY, this->u.air.mail_capacity, v);

@ -26,7 +26,7 @@ struct WagonOverride {
};
/** Flags used client-side in the purchase/autorenew engine list. */
enum class EngineDisplayFlags : byte {
enum class EngineDisplayFlags : uint8_t {
None = 0, ///< No flag set.
HasVariants = (1U << 0), ///< Set if engine has variants.
IsFolded = (1U << 1), ///< Set if display of variants should be folded (hidden).
@ -54,10 +54,10 @@ struct Engine : EnginePool::PoolItem<&_engine_pool> {
uint16_t duration_phase_1; ///< First reliability phase in months, increasing reliability from #reliability_start to #reliability_max.
uint16_t duration_phase_2; ///< Second reliability phase in months, keeping #reliability_max.
uint16_t duration_phase_3; ///< Third reliability phase in months, decaying to #reliability_final.
byte flags; ///< Flags of the engine. @see EngineFlags
uint8_t flags; ///< Flags of the engine. @see EngineFlags
CompanyMask preview_asked; ///< Bit for each company which has already been offered a preview.
CompanyID preview_company; ///< Company which is currently being offered a preview \c INVALID_COMPANY means no company.
byte preview_wait; ///< Daily countdown timer for timeout of offering the engine to the #preview_company company.
uint8_t preview_wait; ///< Daily countdown timer for timeout of offering the engine to the #preview_company company.
CompanyMask company_avail; ///< Bit for each company whether the engine is available for that company.
CompanyMask company_hidden; ///< Bit for each company whether the engine is normally hidden in the build gui for that company.
uint8_t original_image_index; ///< Original vehicle image index, thus the image index of the overridden vehicle
@ -112,7 +112,7 @@ struct Engine : EnginePool::PoolItem<&_engine_pool> {
return this->info.cargo_type;
}
uint DetermineCapacity(const Vehicle *v, uint16_t *mail_capacity = nullptr) const;
uint DetermineCapacity(const Vehicle *v, uint16_t *mail_capacity = nullptr, CargoID attempt_refit = INVALID_CARGO) const;
bool CanCarryCargo() const;
bool CanPossiblyCarryCargo() const;
@ -125,12 +125,13 @@ struct Engine : EnginePool::PoolItem<&_engine_pool> {
* For articulated engines use GetCapacityOfArticulatedParts
*
* @param mail_capacity returns secondary cargo (mail) capacity of aircraft
* @param attempt_refit cargo ID to attempt to use
* @return The default capacity
* @see GetDefaultCargoType
*/
uint GetDisplayDefaultCapacity(uint16_t *mail_capacity = nullptr) const
uint GetDisplayDefaultCapacity(uint16_t *mail_capacity = nullptr, CargoID attempt_refit = INVALID_CARGO) const
{
return this->DetermineCapacity(nullptr, mail_capacity);
return this->DetermineCapacity(nullptr, mail_capacity, attempt_refit);
}
Money GetRunningCost() const;

@ -29,6 +29,6 @@ void SetYearEngineAgingStops();
void CalcEngineReliability(Engine *e, bool new_month);
void StartupOneEngine(Engine *e, const CalTime::YearMonthDay &aging_ymd, const CalTime::YearMonthDay &expire_stop_ymd, uint32_t seed, CalTime::Date no_introduce_after_date);
uint GetTotalCapacityOfArticulatedParts(EngineID engine);
uint GetTotalCapacityOfArticulatedParts(EngineID engine, CargoID attempt_refit = INVALID_CARGO);
#endif /* ENGINE_FUNC_H */

@ -159,11 +159,12 @@ void ShowEnginePreviewWindow(EngineID engine)
/**
* Get the capacity of an engine with articulated parts.
* @param engine The engine to get the capacity of.
* @param attempt_refit Attempt to get capacity when refitting to this cargo.
* @return The capacity.
*/
uint GetTotalCapacityOfArticulatedParts(EngineID engine)
uint GetTotalCapacityOfArticulatedParts(EngineID engine, CargoID attempt_refit)
{
CargoArray cap = GetCapacityOfArticulatedParts(engine);
CargoArray cap = GetCapacityOfArticulatedParts(engine, attempt_refit);
return cap.GetSum<uint>();
}
@ -204,10 +205,10 @@ static StringID ProcessEngineCapacityString(StringID str)
static StringID GetRunningCostString()
{
if (EconTime::UsingWallclockUnits()) {
return STR_ENGINE_PREVIEW_RUNCOST_PERIOD;
} else if (DayLengthFactor() > 1 && !_settings_client.gui.show_running_costs_calendar_year) {
if (DayLengthFactor() > 1 && !_settings_client.gui.show_running_costs_calendar_year) {
return STR_ENGINE_PREVIEW_RUNCOST_ORIG_YEAR;
} else if (EconTime::UsingWallclockUnits()) {
return STR_ENGINE_PREVIEW_RUNCOST_PERIOD;
} else {
return STR_ENGINE_PREVIEW_RUNCOST_YEAR;
}
@ -373,7 +374,9 @@ void DrawVehicleEngine(int left, int right, int preferred_x, int y, EngineID eng
void EngList_Sort(GUIEngineList &el, EngList_SortTypeFunction compare)
{
if (el.size() < 2) return;
std::sort(el.begin(), el.end(), compare);
std::sort(el.begin(), el.end(), [&](const GUIEngineListItem &a, const GUIEngineListItem &b) {
return compare(a, b, el.SortParameterData());
});
}
/**
@ -388,6 +391,8 @@ void EngList_SortPartial(GUIEngineList &el, EngList_SortTypeFunction compare, si
if (num_items < 2) return;
assert(begin < el.size());
assert(begin + num_items <= el.size());
std::sort(el.begin() + begin, el.begin() + begin + num_items, compare);
std::sort(el.begin() + begin, el.begin() + begin + num_items, [&](const GUIEngineListItem &a, const GUIEngineListItem &b) {
return compare(a, b, el.SortParameterData());
});
}

@ -16,6 +16,25 @@
#include "vehicle_type.h"
#include "engine_base.h"
#include "window_type.h"
#include "3rdparty/cpp-btree/btree_map.h"
struct BuildVehicleWindowBase;
struct GUIEngineListSortCache {
const BuildVehicleWindowBase *parent = nullptr;
CargoID current_cargo = INVALID_CARGO;
mutable btree::btree_map<EngineID, uint> capacities;
void UpdateCargoFilter(const BuildVehicleWindowBase *parent, CargoID cargo_filter_criteria);
uint GetArticulatedCapacity(EngineID eng, bool dual_headed = false) const;
};
template <>
struct GUIListParamConfig<GUIEngineListSortCache>
{
using SortParameterReference = GUIEngineListSortCache;
static const bool constructor_init = false;
};
struct GUIEngineListItem {
EngineID engine_id; ///< Engine to display in build purchase list
@ -29,9 +48,9 @@ struct GUIEngineListItem {
bool operator == (const EngineID &other) const { return this->engine_id == other; }
};
typedef GUIList<GUIEngineListItem, std::nullptr_t, CargoID> GUIEngineList;
typedef GUIList<GUIEngineListItem, GUIEngineListSortCache, CargoID> GUIEngineList;
typedef bool EngList_SortTypeFunction(const GUIEngineListItem&, const GUIEngineListItem&); ///< argument type for #EngList_Sort.
typedef bool EngList_SortTypeFunction(const GUIEngineListItem&, const GUIEngineListItem&, const GUIEngineListSortCache &); ///< argument type for #EngList_Sort.
void EngList_Sort(GUIEngineList &el, EngList_SortTypeFunction compare);
void EngList_SortPartial(GUIEngineList &el, EngList_SortTypeFunction compare, size_t begin, size_t num_items);
@ -45,7 +64,7 @@ void DrawShipEngine(int left, int right, int preferred_x, int y, EngineID engine
void DrawAircraftEngine(int left, int right, int preferred_x, int y, EngineID engine, PaletteID pal, EngineImageType image_type);
extern bool _engine_sort_direction;
extern byte _engine_sort_last_criteria[];
extern uint8_t _engine_sort_last_criteria[];
extern bool _engine_sort_last_order[];
extern bool _engine_sort_show_hidden_engines[];
extern const StringID _engine_sort_listing[][14];

@ -41,42 +41,42 @@ enum EngineClass {
/** Information about a rail vehicle. */
struct RailVehicleInfo {
byte image_index;
uint8_t image_index;
RailVehicleTypes railveh_type;
byte cost_factor; ///< Purchase cost factor; For multiheaded engines the sum of both engine prices.
uint8_t cost_factor; ///< Purchase cost factor; For multiheaded engines the sum of both engine prices.
RailType railtype; ///< Railtype, mangled if elrail is disabled.
RailType intended_railtype; ///< Intended railtype, regardless of elrail being enabled or disabled.
uint16_t max_speed; ///< Maximum speed (1 unit = 1/1.6 mph = 1 km-ish/h)
uint16_t power; ///< Power of engine (hp); For multiheaded engines the sum of both engine powers.
uint16_t weight; ///< Weight of vehicle (tons); For multiheaded engines the weight of each single engine.
byte running_cost; ///< Running cost of engine; For multiheaded engines the sum of both running costs.
uint8_t running_cost; ///< Running cost of engine; For multiheaded engines the sum of both running costs.
Price running_cost_class;
EngineClass engclass; ///< Class of engine for this vehicle
byte capacity; ///< Cargo capacity of vehicle; For multiheaded engines the capacity of each single engine.
byte ai_passenger_only; ///< Bit value to tell AI that this engine is for passenger use only
uint8_t capacity; ///< Cargo capacity of vehicle; For multiheaded engines the capacity of each single engine.
uint8_t ai_passenger_only; ///< Bit value to tell AI that this engine is for passenger use only
uint16_t pow_wag_power; ///< Extra power applied to consist if wagon should be powered
byte pow_wag_weight; ///< Extra weight applied to consist if wagon should be powered
byte visual_effect; ///< Bitstuffed NewGRF visual effect data
byte shorten_factor; ///< length on main map for this type is 8 - shorten_factor
byte tractive_effort; ///< Tractive effort coefficient
byte air_drag; ///< Coefficient of air drag
byte user_def_data; ///< Property 0x25: "User-defined bit mask" Used only for (very few) NewGRF vehicles
uint8_t pow_wag_weight; ///< Extra weight applied to consist if wagon should be powered
uint8_t visual_effect; ///< Bitstuffed NewGRF visual effect data
uint8_t shorten_factor; ///< length on main map for this type is 8 - shorten_factor
uint8_t tractive_effort; ///< Tractive effort coefficient
uint8_t air_drag; ///< Coefficient of air drag
uint8_t user_def_data; ///< Property 0x25: "User-defined bit mask" Used only for (very few) NewGRF vehicles
int16_t curve_speed_mod; ///< Modifier to maximum speed in curves (fixed-point binary with 8 fractional bits)
};
/** Information about a ship vehicle. */
struct ShipVehicleInfo {
byte image_index;
byte cost_factor;
uint8_t acceleration; ///< Acceleration (1 unit = 1/3.2 mph per tick = 0.5 km-ish/h per tick)
uint16_t max_speed; ///< Maximum speed (1 unit = 1/3.2 mph = 0.5 km-ish/h)
uint8_t image_index;
uint8_t cost_factor;
uint8_t acceleration; ///< Acceleration (1 unit = 1/3.2 mph per tick = 0.5 km-ish/h per tick)
uint16_t max_speed; ///< Maximum speed (1 unit = 1/3.2 mph = 0.5 km-ish/h)
uint16_t capacity;
byte running_cost;
uint8_t running_cost;
SoundID sfx;
bool old_refittable; ///< Is ship refittable; only used during initialisation. Later use EngineInfo::refit_mask.
byte visual_effect; ///< Bitstuffed NewGRF visual effect data
byte ocean_speed_frac; ///< Fraction of maximum speed for ocean tiles.
byte canal_speed_frac; ///< Fraction of maximum speed for canal/river tiles.
bool old_refittable; ///< Is ship refittable; only used during initialisation. Later use EngineInfo::refit_mask.
uint8_t visual_effect; ///< Bitstuffed NewGRF visual effect data
uint8_t ocean_speed_frac; ///< Fraction of maximum speed for ocean tiles.
uint8_t canal_speed_frac; ///< Fraction of maximum speed for canal/river tiles.
/** Apply ocean/canal speed fraction to a velocity */
uint ApplyWaterClassSpeedFrac(uint raw_speed, bool is_ocean) const
@ -99,33 +99,33 @@ enum AircraftSubTypeBits {
/** Information about a aircraft vehicle. */
struct AircraftVehicleInfo {
byte image_index;
byte cost_factor;
byte running_cost;
byte subtype; ///< Type of aircraft. @see AircraftSubTypeBits
uint8_t image_index;
uint8_t cost_factor;
uint8_t running_cost;
uint8_t subtype; ///< Type of aircraft. @see AircraftSubTypeBits
SoundID sfx;
byte acceleration;
uint8_t acceleration;
uint16_t max_speed; ///< Maximum speed (1 unit = 8 mph = 12.8 km-ish/h)
byte mail_capacity; ///< Mail capacity (bags).
uint8_t mail_capacity; ///< Mail capacity (bags).
uint16_t passenger_capacity; ///< Passenger capacity (persons).
uint16_t max_range; ///< Maximum range of this aircraft.
};
/** Information about a road vehicle. */
struct RoadVehicleInfo {
byte image_index;
byte cost_factor;
byte running_cost;
uint8_t image_index;
uint8_t cost_factor;
uint8_t running_cost;
Price running_cost_class;
SoundID sfx;
uint16_t max_speed; ///< Maximum speed (1 unit = 1/3.2 mph = 0.5 km-ish/h)
byte capacity;
uint8_t capacity;
uint8_t weight; ///< Weight in 1/4t units
uint8_t power; ///< Power in 10hp units
uint8_t tractive_effort; ///< Coefficient of tractive effort
uint8_t air_drag; ///< Coefficient of air drag
byte visual_effect; ///< Bitstuffed NewGRF visual effect data
byte shorten_factor; ///< length on main map for this type is 8 - shorten_factor
uint8_t visual_effect; ///< Bitstuffed NewGRF visual effect data
uint8_t shorten_factor; ///< length on main map for this type is 8 - shorten_factor
RoadType roadtype; ///< Road type
};
@ -143,17 +143,17 @@ DECLARE_ENUM_AS_BIT_SET(ExtraEngineFlags);
* @see table/engines.h
*/
struct EngineInfo {
CalTime::Date base_intro; ///< Basic date of engine introduction (without random parts).
YearDelta lifelength; ///< Lifetime of a single vehicle
YearDelta base_life; ///< Basic duration of engine availability (without random parts). \c 0xFF means infinite life.
byte decay_speed;
byte load_amount;
byte climates; ///< Climates supported by the engine.
CalTime::Date base_intro; ///< Basic date of engine introduction (without random parts).
YearDelta lifelength; ///< Lifetime of a single vehicle
YearDelta base_life; ///< Basic duration of engine availability (without random parts). \c 0xFF means infinite life.
uint8_t decay_speed;
uint8_t load_amount;
uint8_t climates; ///< Climates supported by the engine.
CargoID cargo_type;
std::variant<CargoLabel, MixedCargoType> cargo_label;
CargoTypes refit_mask;
byte refit_cost;
byte misc_flags; ///< Miscellaneous flags. @see EngineMiscFlags
uint8_t refit_cost;
uint8_t misc_flags; ///< Miscellaneous flags. @see EngineMiscFlags
uint16_t callback_mask; ///< Bitmask of vehicle callbacks that have to be called
int8_t retire_early; ///< Number of years early to retire vehicle
StringID string_id; ///< Default name of engine

@ -386,8 +386,8 @@ void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel
if (textref_stack_size > 0) StopTextRefStackUsage();
switch (wl) {
case WL_WARNING: IConsolePrint(CC_WARNING, message.c_str()); break;
default: IConsoleError(message.c_str()); break;
case WL_WARNING: IConsolePrint(CC_WARNING, message); break;
default: IConsolePrint(CC_ERROR, message); break;
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save