OpenTTD Source 20261123-master-g1c55c72fd0
screensaver.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
11
12#include "core/math_func.hpp"
13#include "core/random_func.hpp"
14#include "company_base.h"
15#include "screensaver.h"
16#include "timer/timer.h"
18#include "vehicle_base.h"
19#include "vehicle_type.h"
20#include "window_func.h"
21#include "window_gui.h"
22
23#include "safeguards.h"
24
33{
34 /* First pass, add up vehicles of all buildable types for all companies, keeping the types apart. */
36 for (const Company *c : Company::Iterate()) {
38 counts[type] += c->group_all[type].num_vehicle;
39 }
40 }
41
42 /* Weight each type by the square root of its number of vehicles, to stop the most common type dominating. */
44 uint total_weight = 0;
46 weights[type] = IntSqrt(counts[type]);
47 total_weight += weights[type];
48 }
49
50 /* If no type has any vehicles, we can't pick a vehicle so exit. */
51 if (total_weight == 0) return nullptr;
52
53 /* Pick the type to follow, using the weight as a probability. */
54 uint r = InteractiveRandomRange(total_weight);
56 while (r >= weights[type]) {
57 r -= weights[type];
58 ++type;
59 assert(type < VehicleType::CompanyEnd);
60 }
61 assert(weights[type] > 0);
62
63 /* Then pick a random vehicle index between 0 and the number of vehicles of that type. */
64 uint n = InteractiveRandomRange(counts[type]);
65
66 /* Loop over all the vehicles until we get to that vehicle. */
67 for (const Vehicle *v : Vehicle::Iterate()) {
68 /* Skip anything that isn't the type we picked; as we only ever pick a company-buildable type,
69 * this also skips everything companies can't build. */
70 if (v->type != type) continue;
71
72 /* Skip vehicles if they're not "front vehicles" so we don't count train cars (or similar) as targets to follow. */
73 if (!v->IsPrimaryVehicle()) continue;
74
75 /* Otherwise, it is a vehicle we should count, so count down until zero. */
76 if (n-- == 0) return v;
77 }
78
79 /* In case we go over all the vehicles, return \c nullptr in that case. */
80 return nullptr;
81}
82
94static void SwitchVehicle(bool exit_on_invalid = true)
95{
96 /* Do not do anything in the main menu. */
97 if (_game_mode == GameMode::Menu) return;
98
99 const Window *main_win = GetMainWindow();
100
101 /* We start with a high chance of keeping with a moving vehicle. */
102 static int movement_bias = 48;
103
104 /* If we are targeting an invalid vehicle, stop running */
105 if (exit_on_invalid && main_win->viewport->follow_vehicle == VehicleID::Invalid()) {
107 return;
108 }
109
110 /* If we're targeting a vehicle, we have a chance to return early and not pick a new one. */
111 auto v = Vehicle::GetIfValid(main_win->viewport->follow_vehicle);
112 if (v != nullptr) {
113
114 /* Every time we stick on a moving vehicle, we make it less likely that
115 * we stick around next cycle to prevent staying on one vehicle for forever. */
116 if (v->cur_speed > 0 && !Chance16I(1, movement_bias, InteractiveRandom())) {
117 movement_bias -= 1;
118 return;
119 }
120
121 /* If we're not moving, we have a flat 25% chance to stay until the call
122 * to encourage switching to a moving vehicle. */
123 if (v->cur_speed == 0 && Chance16I(3, 4, InteractiveRandom())) {
124 return;
125 }
126 }
127
128 /* Reset our bias so that the next vehicle gets its full time. */
129 movement_bias = 48;
130
131 /* Try to get a vehicle (this fails if the vehicle picked isn't valid to follow). */
132 const Vehicle *new_vehicle = PickRandomVehicle();
133 /* If we didn't find vehicle to follow, try again next cycle. */
134 if (new_vehicle == nullptr) return;
135
136 /* Swap the main window over to following the new vehicle. */
137 main_win->viewport->CancelFollow(*main_win);
138 main_win->viewport->follow_vehicle = new_vehicle->index;
139}
140
141
142/* The screensaver is based off a timer on a fixed interval which rotates between vehicles. */
143
150
157static std::unique_ptr<IntervalTimer<TimerGameTick>> _switch_timer;
158
169{
170 const Window *main_win = GetMainWindow();
171
172 _switch_timer.reset();
173 main_win->viewport->CancelFollow(*main_win);
174}
175
191{
192 /* If we are in screensaver mode, exit it. */
193 if (_switch_timer != nullptr) {
195 return;
196 }
197
198 /* If we aren't, start it with a new timer. */
199 _switch_timer = std::make_unique<IntervalTimer<TimerGameTick>>(
201 [](uint) { SwitchVehicle(); }
202 );
203
204 /* Fire our callback once to start us following a first vehicle; otherwise we'd have to wait for the first time the timer fired.
205 * We pass false here to ignore if there is no followed vehicle */
206 SwitchVehicle(false);
207}
Iterate a range of enum values.
@ None
These timers can be executed in any order; the order is not relevant.
Definition of stuff that is very close to a company, like the company struct itself.
uint32_t IntSqrt(uint32_t num)
Compute the integer square root.
Definition math_func.cpp:42
Integer math functions.
@ Menu
In the main menu.
Definition openttd.h:19
Pseudo random number generator.
bool Chance16I(const uint32_t a, const uint32_t b, const uint32_t r)
Checks if a given randomize-number is below a given probability.
A number of safeguards to prevent using unsafe methods.
static const auto _screensaver_check_interval
We use a fixed period for updating the screensaver's followed vehicle, stored in this variable.
static const Vehicle * PickRandomVehicle()
Selects a random vehicle, picking the type by the square root of its number of vehicles,...
static void SwitchVehicle(bool exit_on_invalid=true)
Switches the current followed vehicle to a new random one.
void ToggleScreensaverMode()
Enters or exits "Screensaver Mode".
void ExitScreensaverMode()
Exits "Screensaver Mode".
static std::unique_ptr< IntervalTimer< TimerGameTick > > _switch_timer
The screensaver runs on an interval timer, stored in this pointer when it is running and freed when i...
Exports a function to turn on and off a screensaver mode.
Definition of base types and functions in a cross-platform compatible way.
static Pool::IterateWrapper< Company > Iterate(size_t from=0)
static Vehicle * GetIfValid(auto index)
Vehicle data structure.
Data structure for an opened window.
Definition window_gui.h:272
std::unique_ptr< ViewportData > viewport
Pointer to viewport data, if present.
Definition window_gui.h:317
Definition of Interval and OneShot timers.
Definition of the tick-based game-timer.
Base class for all vehicles.
Types related to vehicles.
VehicleType
Available vehicle types.
@ Begin
Begin marker.
@ CompanyEnd
Last company-ownable type.
EnumIndexArray< T, VehicleType, Tend > VehicleTypeIndexArray
Array with VehicleType as index.
Window * GetMainWindow()
Get the main window, i.e.
Definition window.cpp:1228
Window functions not directly related to making/drawing windows.
Functions, definitions and such used only by the GUI.