# GT Mode (milestone M4) — implementation notes The career mode: credits, garage, dealers, tune shop, wheels, car wash and oil, licenses, races and championships, prize money and prize cars, car settings, records, saves; plus the arcade-mode progression that the original keeps in the same game state. The rules and save data are described in [docs/behaviour/gt_mode.md](../behaviour/gt_mode.md) ("gt_mode §n" below names its sections); this page describes the code. ## Layout | File | Role | |---|---| | `src/game/gcf.*` | `gameconf/product.gcf` reader (constants such as the 18,000 Cr start, race-code list, prize sets) | | `src/game/gt_catalog.*` | what GT mode offers, read from `menu/gt_mode.mbl`: dealer cars, race series (single / championship), license tests, tune-shop page → item | | `src/game/gt_parts.*` | tune-shop goods ids (0..86 → table, stage), the shop menu items, part lookup and prices | | `src/game/gt_state.h` | `GameState` / `GarageCar` / `CarCondition` / `ArcadeProgress`: plain data | | `src/game/gt_setting.*` | car settings menu rules: slider ranges / values / texts, locks, setting files | | `src/game/gt_mode.*` | `GtData` (disc data, loaded once) and `GtMode` (all rules; deterministic) incl. the bridge to `sim::CarSpec` | | `src/game/language_rules.*` | what the game's language decides: prize-car labels, Opel / Vauxhall dealer buttons, the licence car and S-1's `_uk` demonstration, which paint name shows (car names: `data::car_name_fields`) | | `src/game/gt_save.*` | native save (text, versioned) and import/export of the original PS2 GAMEDATA file | | `src/game/save_library.*` | the save library: any number of native saves in `/saves/`, the current one, migration of older saves | | `src/game/save_folder.*` | the save folder (saves and replays): the user data folder or the player's choice, and the copy when it changes | | `src/menu/flow/save_page.*` | the save page (title Load / Save / File Operation, home Save, Trade, Load Garage, Load / Save Settings) on the original's file list art | | `src/game/gt_mode_menu.h`, `src/game/gt_mode_menu/` | binds GT mode to the interactive menus through `menu::flow::GtModeHooks` (files: "Menu integration" below) | | `src/menu/flow/gt_mode_hooks.*` | the hook interface (menu side; no dependency on `src/game`) | | `src/app/screen_gtmode.cpp` | installs the hooks; menu 3D renders of cars and wheels (`MenuModelRenderer`); `gt3r --screen gtmode` = save overview | | `src/app/screen_gtmode_setting.cpp` | the car settings menu and records screens (`make_gt_setting_screen`, `make_records_screen`) | | `tests/test_gtmode*.cpp` | logic tests and the menus on a small invented world (`test_gtmode_menu_synth.cpp`, data in `tests/gtmode_synth.h`), both without the disc; disc tests | ## Rules (`GtMode`) - **New game**: credits = gcf `initial` (18,000 on this disc), day 1, empty garage, no ride car. - **Money**: every sum read from the disc (car and part prices, prizes and bonuses, the gcf tag-10 sums) goes through `GtData::money` (×100 in Japanese, `money_scale`); there are no built-in amounts, and `GtData::load` refuses a game config that lacks one of the tag-10 values. The prize pages' texts are `credits_text` / `prize_remain_text`, the latter with `GtData::prize_prefix` (`text/realtime.dat` in the game's language, else the game's built-in word). Mod car prices are stored like disc prices (docs/MODDING.md). - **Cars**: `buy_car` (checks not-for-sale flag, money, 200-car garage; newest first; the first car becomes the ride car), `sell_car` (price / 4, refused for flag bit 1), `ride`, `add_prize_car`. A new car gets the stock parts, stock settings (`sim::stock_settings`), the stock goods owned (front tires also own the rear set; rally cars own dirt tires) and the break-in condition (97 % power). - **Tune shop** (ride car): `part_offer`, `can_buy_part` (owned → already, no record → not exist, money), `buy_part`, `fit_part` (owned goods only; stage 0 = stock; turbo ↔ NA tune exclusive; front tires fit the rear set; the part's settings group is re-initialised), `buy_all_tires`, `power_with` (before/after PS). - **Wheels / wash / oil**: inventory of bought wheels (500 Cr each, never used up), `fit_wheel` (the garage's change: inventory wheels or stock), `fit_shop_wheel` (the shop's "fit it?": the focused wheel, held or not), `wash` (50), `change_oil` (250). `engine_factor()` is the condition's power multiplier (physics §10.3) the menus' power figures use. - **Engine condition through a run** (gt_mode §13): GT races and championships, machine tests, free runs and arcade races carry the car's condition (`carries_engine_condition`); the request gets `run_condition()` (odometer in 2 m units, E, O; an arcade car: zeros), the race car advances the words tick by tick with the factor applied live, and `end_run()` puts the result's words back into the garage car and adds the odometer units to the total distance (`gt_menu::fill_condition` / `apply_condition`; arcade results count their distance too, finished or not). Licence tests, time trials and 2 Player Battle run with a fresh engine and hand nothing back, also with a garage car. `driven()` advances the words in one piece (tests, `GT3R_GTMODE_FAKE_RACE`). - **Licenses**: `judge` (time vs. the event's gold/silver/bronze), `record_license` (best medal kept; license held when 8 medals; all gold → the license prize car once), `can_open_license_page` (B → A → IB → IA → S; B and rally always open), `can_take_test` (8th test needs 1–7). - **Races**: `rules(code)` decodes the event record fields GT mode needs; `check_entry` reproduces RegurationResult (dirt tires, license, drivetrain, regulation list, NA/turbo, car class/tuned); `can_enter` maps it to the license / regulation popups. `record_race` pays the place prize (every time), keeps the best place, counts races/wins and awards prize cars. `start_championship` + `record_round` run a championship: field drawn once, its paints kept from round 1 (`Championship::paints`, from the round's `GameResult::opponent_paints`, handed to later rounds as `GameRequest::opponent_paints`), points 10-6-4-3-2-1, champion only with strictly more points, bonus and prize car on every championship win. `enter()` = one day. - **Prize cars**: `award_prizes(code)` scans the gcf prize sets (series all won, championship, endurance, license all gold, league complete, completion %); single-car sets once, multi-car sets on every win, picked by weight with the state's generator. The whole game's set (`gtmode_complete`, gt_mode §23) is eligible when the checked code is a GT-mode one (`gt_mode_code`: series, championship, endurance, rally, licence, machine test; not arcade) and every gcf section-4 result is won (`all_races_won`: 364 on this disc); it is not the 100 % completion rule (`achieve_complete`). Prize sets are checked after a race win, a championship title and a licence turning all gold, as in the game. - **Language**: `GtData::prize_candidate` puts each candidate's label through `prize_car_label` before the paints and the pick (a swapped one gets a random paint), also for the car_get candidate list; the cd/ region pages leave out the `opel` / `vauxhall` button (`gt_menu::listed` → `MenuController::listed`); licence tests drive `license_car` (race launch, the quick race, the GT-mode request, the theater) and load `demo_replay_path`'s run. `Car::name` / `name_alt` and `GtData::color_name` are in the language (game text: kana in Japanese, drawn by the game fonts). `Car::latin_name` / `color_name_latin` are game text too: the race screens draw them with the game fonts (`race::result_car_name`), the app's own screens convert them to UTF-8 or cut them to ASCII, and online descriptors cut them to ASCII. A mod's texts go in as game text (`data::add_mod_car`). - **Bridge**: `car_spec(GarageCar)` = `sim::build_car_spec(db, car, parts, settings)`; the engine condition is not in the spec (the race car carries it, above). `power_peak()` / `power_ps()` are the original's computed menu figure (gt_mode §5 "Power figures": `game::spec_power_peak(spec, engine_factor)`, the 100-rpm sweep of the built curve, each looked-up torque × the condition factor); `power_text()` prints it the menus' way (`display_power`: truncated, HP = PS × 0.98619 on NTSC-U data). `completion_text()` / `completion_percent()` / `completion_file_text()` are the status page's and the file lists' truncated texts. Settings screens that move the gear slider must call `sim::apply_gear_slider` (computed gearboxes); the drivetrain-split word is stored but ignored, as in the original. Randomness follows the original (gt_mode §20; `base/game_random.h`): one generator (x = 17x + 17, output x ^ rotl16(x)) on several states. The trophy pick, prize-car pick and the paint of prize cars without a fixed colour use the GT-mode state `GameState::rng` (saved, kept by a new game; `pick_trophy_index`, `pick_weighted`, `prize_paint_index`); `record_round` picks the trophy before the prize cars (`Award::trophy`), as trophy_get comes before car_get. Each presentation opens with the original's "stir" (1..12 steps from a hardware random value + the shared state, gt_mode §20.2; ours takes that value from the clock, `hardware_random()`), and `on_frame` steps the state once per menu frame like the original's menu loops, so the rolls are unpredictable the same way. Opponents are drawn by `race::draw_opponents` on the race module's state (`race_info_random()`), shared with the paint colours of the race; arcade Single Race draws its field the same way (`screen_race_launch.cpp`). Given the same states, every draw equals the original's (verified against the original's behaviour, 0 mismatches). ## Menu integration (`src/game/gt_mode_menu/`) The bindings are the adapter between the generic menu runtime (`menu/flow/`, which does not depend on `src/game`) and the rules (`GtMode`). They stay on the game side: the public header `game/gt_mode_menu.h` is also the session's API (`GtModeSession`, the save library, the race screens' saves), used by `app/` and `game/` itself, and `game/` already builds on `menu/flow/`. One file per concern, sharing the private `internal.h`: | File | What lives there | |---|---| | `internal.h` | Private: `MenuState` (everything the module keeps between hook calls: disc data, session, queued presentations, sounds / popup / movie for the flow, map pointer, wheel-shop pin, save library, snapshot, attract cycle; `menu_state()`), `Show`, the presentation timeline constants, the list geometry; declarations grouped by file | | `install.cpp` | `install_gt_mode_menu()`: wires each hook to its file; `attach` | | `common.cpp` | `menu_state()`, `reset_gt_mode_menu_for_tests()` (a fresh `MenuState`), shared helpers (names, prices, settings working copy, autosave, layout lookups) | | `session.cpp` | `GtModeSession`, `start_session` (the one place a session is created: `attach`, `ensure_gt_mode_session`), save library, snapshot, the race screens' direct saves, `begin_setting` / `begin_records` | | `actions.cpp` | `on_event`: the GT-mode control's actions | | `prechecks.cpp` | `intercept` (pre-check popups), `enabled` | | `races.cpp` | `prepare_request`, `on_result`, `next_request`, `resume_request`, attract demos | | `presentations.cpp` | prize pages, license card, trophy, prize car, name entry: queueing, timelines, the prize counter's page state (its step: `game/prize_count_up.h`), `presentation_model` | | `widget_text.cpp` | `widget_text` | | `widget_art.cpp` | image widgets from hidden art (`widget_draws`), `hide_art`, `car_for_widget`, the oil change's and the car wash's timelines (`oil_cylinder_at`, `wash_spin_at`, `car_wash_spin`) | | `lists.cpp` | `on_tick` (every frame, busy or not: the car wash and the oil change), `on_frame` (per-frame input and timelines; a queued effect plays on a frame the page plays none and never holds the page's code), map pointer, garage / permitted-car / wheel-shop lists, tap and hover, `permitted_car_names` | | `extra_draws.cpp` | `extra_draws`, one helper per page element it adds | | `arcade.cpp` | the arcade hooks (pickers, refusals, entry art, garage-class races, arcade results) | | `save_backend.cpp` | the save page's files and operations (`save_list` / `save_run`) | `install_gt_mode_menu()` registers `GtModeHooks`; `GameFlow` calls them for the `gt_mode`, `setting` and `records` controls and the presentations (prize car, license, name entry); the arcade control uses only the arcade hooks, `intercept` / `enabled`, and the widget hooks on `ar/goodies` (Phase 7). The options flow is untouched. - `attach`: loads `GtData` from the disc and the current save of the save library (new game if none) when the title menu opens — the original's boot-time memory-card load. - `on_event`: the GT-mode control's action table — `set_car_code`, `buy_car`, `ride_car`, `sell_car`, `set_garage_car`, `set_focus_parts`, `buy_parts`, `fit_parts`, `buy_fit_parts`, `buy_all_tires`, `set_focus_wheel_code`, `buy_wheel`, `fit_wheel`, `change_wheel`, `wash_car`, `oil_change`, `set_race_code*`; Finish actions `go_race`, `go_license`, `go_machine_test`, `go_free_run` cost a day (`go_race` on a championship item starts the championship); `go_save_in_home` / `go_save_game_menu`, `go_load_game_menu`, `go_file_operation`, `go_trade` and the arcade `load_guest_garage` open the save page ("Saves" below). - `intercept`: the pre-check popups (`00cmn/no_money`, `not_for_buy`, `max_car`, `not_for_sell`, `ride_car`, `not_for_change_wheel`, `ts/already_you_have`, `ts/not_exist`, `already_you_have_all_tires`, `hm/need_dirt_tire`, `license_violation`, `regulation_violation`, `lc/no_license_*`, `lc/no_last_exam`, `cd_ride_sure`). This needed a small `MenuController::intercept` hook. - `enabled`: the F1 series needs the S license. - `widget_text`: code-filled text widgets by class — status bar (`user_money`, `user_day`, `user_day_unit`, `user_carname`), dealer (`goods_car_price`, `car_buy_price`, `focused_carname`), garage (`car_sell_price`, `car_max_power`, `car_kilometrage`, `car_drive_type`), tune shop (`price_`; `disp_ps_befor/after`, "%d %s", AFTER "----" for a part the car cannot take; the `ts/` pages' texts get `font_inset`, menus §5.7; on the engine parts' "Installed successfully" pages `car_previous_torque` / `car_current_torque`, which despite their names show the power before the part, kept by `fit_parts` / `buy_fit_parts`, and now, "%d %s"), wheel shop / wash / oil prices, licenses (`disp_time_gold/silver/bronze`, `license_car_name`, `license_launch_speed`), race info (`race_prize_1..6`, `regulation_*`), status page (`status_*`), spec pages (`spec_*`). This needed a text override in `menu::ElementDraw` (renderer). - `extra_draws` / `on_frame`: the code-drawn garage list (`hm/hm_gr`, Up/Down), the race information's Cars Permitted list (popup `00cmn/car_reguration`: `permitted_car_names`, each car of the event's regulation as name + second name, a string once at its last place, rows of the `link_menu` template in `menu_regulated_car`, Up/Down; "No Limitations" without a list), the records page's places (`records_free_tt`, Up/Down); these three are GT3's vertical ButtonList (`ListRows`, `menu::flow::column_layout`: rows 4 apart, the cursor row centred, the offset eased in `MenuState::list_off`, the scroll bar by `list_scroll_bar`), the status bar day number (hidden-layer widget), and the wheel inventory cursor. Dealer pages (maker and car lists) are tile strips in the controller's scrolling window (`menu_car_goods`, and `menu_dealer` on the England and Germany pages, are among its window widgets; items parked off the screen vertically, as on the Toyota list, count as parked). - **Car wash / oil change progress popups** (gt_mode §13): the shop buttons open "Washing . . ." / "Changing oil . . ." popups whose `ignore_control` widget takes the controls away when the page is built (`MenuController::ignoring_control`: no key or tap does anything and the popup's "Complete" button is not drawn) until game code gives them back (`give_control`). `GtModeHooks::on_tick` runs every frame, also during the confirm feedback, and steps both: the oil gauge's drain and refill (~325 frames) and the car wash (`wash_spin_at`: its effect after 31 frames, then 181 frames in which the car's turntable gets an extra `kWashSpinPush` of yaw acceleration a frame, about 15 fast turns; the car keeps its old dirt until the last push). The app's showroom applies each push once (`car_wash_spin`: a serial per wash and the pushes so far), as its real-time steps allow. Before this the "Complete" button could be chosen at once, and leaving the page ended the oil change before its refill. - Popups: one level. A popup item confirmed inside a popup replaces it (`MenuController::build`), so the tune shop's Purchase? → Install parts now? → Installed (and the trade's Buy? → Bought) close back to the page they were opened from. A part is bought once per car (`can_buy_part`: `ts/already_you_have`); owned parts are swapped in the settings' Change Parts pages. - Focus (menus §4.2): the GT-mode control keeps the stored race code, so a race series or licence page opens on the race entered or just driven (`race_page_focus`); other pages open on the item leading back to where you came from, else the first (nothing remembers the item confirmed last). - `prepare_request` → `GameRequest`: `event`, `race_code`, the garage car as `car_spec` (+ `car`, `car_model`, `car_color`) and `opponents` (championship field or a fresh draw). License tests drive the event's entry-0 car; free run sets `course`. - `on_result` ← `GameResult`: the engine condition back into the garage car, prize money / championship round / license medal, prize cars, then an autosave. `next_request` chains the next championship round without reopening the menu. Phase 2 additions: - **Status bar**: the day counter is drawn as one string ("12 days") in the import page's hidden `user_day` widget, widened to end before the Cr icon; the layout's `user_day_unit` widget is left empty. - **Paint picker**: on a dealer car page Up/Down choose the paint (the page's buttons move with Left/Right); swatches are drawn in the `car_color_box` row from `race::CarColors` (carcolor.db), the name in `color_name_box` from carcolor.sdb (definition word +4 = name index, M). The index is reset when the focus car changes and used by `buy_car`. - **Garage sorting**: START on `hm/hm_gr` opens `hm/hm_gr_panel` (`MenuController::popup`); `sort_*` picks the key; `GtMode::garage_order` sorts (date newest first, name, maker, colour, price, distance, power, drive, aspiration), the header shows the key's hidden label and each row its value in the hidden `info` column. - **Image widgets** (no parts of their own; drawn from the page's hidden layer into the widget's box): license cups `disp_license_cup_` → `cup_gold/silver/bronze`; league pages `event_status` → the result row of the item behind focus layer `s_` (`frame` / `frame_arrow` slots with their `mark_`, a championship's own slot first), `need_license` → `lc_mark_`; series pages `event_status_buttonNN` → button NN's `mark_` and course logo at their layout places from the button's corner (gt_mode §22.1); `car_logo` → the hidden element named after the car. - **3D cars**: `car_render_*` widgets (dealer, garage, shops) and the prize presentation's `render_model` are drawn by the app (`screen_gtmode.cpp`) through `GtModeWidgetDrawer`, called by the menu renderer's new overlay hook after the widget's own art. The car turns on a turntable; because the model shader's alpha is not coverage, it is rendered once as a transmission picture (`DrawOptions::transmission`): the colour over black (B), and an alpha that each GS blend multiplies by its own destination factor (opaque 0, alpha 1 − As, additive 1, the floor shadow's multiply As), so it holds what the pixel lets through (T). It is composited exactly as page × T + B (a premultiplied blend), as the older pair of renders over black and over white did. The views, prizes and targets a page stops drawing are freed 30 frames later (`set_gt_mode_widget_trim`, after each menu frame), not at the next race. - **Presentations**: a result that obtains a license or awards prize cars queues `lc_get/license_get` (layers `_mess0/1`) and `car_get/car_get` (reason line = the page's hidden text element for the prize set: "Event Winner", "Championship winner", "B License all gold", ...). `GameFlow` shows them (`GtModeHooks::presentation`) before the next championship round or the menu. - **Prize car page** (gt_mode §10.1): the roll stays at the result (`award_prizes`; its rolls, `GtMode::last_prize_rolls`, carry each candidate's paint and the pick into the `Show`); the page's `CarGetRoulette` (`src/game/car_get_roulette.*`, the program's state machine in EE singles: hold, spin, slowdown onto the pick, the camera's fly-in, the others' drop) is started by `next_presentation` and stepped by `presentation_frame`. The page takes the controls when built (`GtModeHooks::Presentation::take_controls` → `MenuController::take_control`; `on_frame`'s automatic give-back skips it, `car_get_holding`) and gets them back on the release, with the `after` band and the `car_get_message` ticker (its marquee restarted from then, `menu::flow::text_effects`; the band's 24-frame fade from then). The app draws the others' floor lights and cars at `CarGetRoulette::others_opacity` (the original puts the page's background back over them), then the lit car's light and the lit car, every car with the colour scale `shade` (black silhouettes, then the car won lighting up: `DrawItem::tint` and `reflection_scale`), through the page's camera over the full frame (`screen_gtmode.cpp` `draw_car_get`; the floor lights are the widget's hit-mark image as projected quads). - **Championship resume**: a championship saved between rounds resumes with the next round when GT mode is entered (`resume_request`). GameRequests of rounds carry `champ_round`, `champ_rounds`, `champ_last`; `GameResult::abandoned` ends the championship, an unfinished round counts as a retirement. - Dev aid: `GT3R_GTMODE_FAKE_RACE=1` wins every race at once (screenshots of the result path without driving; machine tests and time trials get a 60 s time). Phase 4: **car settings menu** (`src/game/gt_setting.*`, `src/app/screen_gtmode_setting.cpp`, gt_mode §14). GameFlow runs the original `setting.mbl` pages as control "setting" (`GameFlow::start("setting", "root")`, `exited()`); the screen `gtsetting` hosts it (`make_gt_setting_screen(event)` in `app/screen_gtmode.h`, for the race's pre-race quick menu; `gt3r --screen gtsetting` with `GT3R_GTSETTING_EVENT`). `begin_setting(event)` makes the working copy of the ride car; sliders (`slider_range` / `slider_set`) edit it, OK commits it to the garage car (saved), Back discards it; the values feed `sim::CarSettings`, the race's parameter block (the ride car's parts and settings) and the menus' `build_car_spec` through `GtMode::car_spec`. `GarageCar::ref_final` holds the gear reference final (garage car settings word +0x1AC, gt_mode §3.1; saved). Value texts, locks (`disable_*` overlays, status boxes), fitted-part marks (`attach_*`), slider markers and the part-change pages (`set_*`, with the `not_to_change` / `dirt_tire_only` guards) are bound in `src/game/gt_mode_menu/`. (Setting files and the gear chart followed in Phase 5.) Also: garage rows react to taps (`GtModeHooks::tap`); race pages show the course logo and result mark inside each race button and the course name in the text bar; `GameRequest::racing_gearbox`; `GameResult::license_medal` / `failure` (race-judged license tests, cross-checked by `GtMode::judge`). Phase 5: - **Setting files**: "Save Settings" stores the car's committed settings as a setting file (`GameState::setting_files`, at most 10 per car, in the native save); "Load Settings" applies the newest file of that car with the original's rule (a group is copied only if its part is still fitted; otherwise `load_warning`). The original's memory-card 'S' file (one car's saved settings, gt_mode §19) is read / written by `import_ps2_setting` / `export_ps2_setting`. The files are picked on the save page (Load / Save Settings: the current game's files, no card slots). - **Gear chart** (`gear_chart`): GT3's GearChart (gt_mode §14): a line per forward gear from `sim::exact::gear_chart` (the program's chart data from the working copy's spec, engine and driveline blocks) on a fixed 350 km/h speed scale, drawn as `menu::ElementDraw::Kind::Quad` strips. - **Widgets**: status-page license marks, the license-violation popup's license letter, the tune shop's maker logo, the oil gauge (a full cylinder in the page's hidden `clean` colouring blended into its `dirty` one by `GtMode::oil_age`; an oil change drains and refills it, also under its progress popup, with its two `oil` effects), torque before/after, spec treads and torque/weight ratio. - **Machine test records** (`GameState::machine`: best 0-400 m, 0-1000 m, top speed, saved) with the rankings, run by run (`GtMode::record_machine_test`). - **Endings**: after a win that completes the Beginner league the short ending plays once, Amateur or Professional the long one (`GameRequest::Kind::PlayMovie`, played by the menu screen). Phase 6: - **Wheel shop**: the brand pages' wheels as turning 3D models (wheel/