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 <http://www.gnu.org/licenses/>.
8 /** @file framerate_gui.cpp GUI for displaying framerate/game speed information. */
10 #include "framerate_type.h"
13 #include "window_gui.h"
14 #include "window_func.h"
15 #include "table/sprites.h"
16 #include "string_func.h"
17 #include "strings_func.h"
18 #include "console_func.h"
19 #include "console_type.h"
20 #include "guitimer_func.h"
21 #include "company_base.h"
22 #include "ai/ai_info.hpp"
23 #include "ai/ai_instance.hpp"
24 #include "game/game.hpp"
25 #include "game/game_instance.hpp"
27 #include "widgets/framerate_widget.h"
28 #include "safeguards.h"
32 * Private declarations for performance measurement implementation
36 /** Number of data points to keep in buffer for each performance measurement */
37 const int NUM_FRAMERATE_POINTS
= 512;
38 /** %Units a second is divided into in performance measurements */
39 const TimingMeasurement TIMESTAMP_PRECISION
= 1000000;
41 struct PerformanceData
{
42 /** Duration value indicating the value is not valid should be considered a gap in measurements */
43 static const TimingMeasurement INVALID_DURATION
= UINT64_MAX
;
45 /** Time spent processing each cycle of the performance element, circular buffer */
46 TimingMeasurement durations
[NUM_FRAMERATE_POINTS
];
47 /** Start time of each cycle of the performance element, circular buffer */
48 TimingMeasurement timestamps
[NUM_FRAMERATE_POINTS
];
49 /** Expected number of cycles per second when the system is running without slowdowns */
51 /** Next index to write to in \c durations and \c timestamps */
53 /** Last index written to in \c durations and \c timestamps */
55 /** Number of data points recorded, clamped to \c NUM_FRAMERATE_POINTS */
58 /** Current accumulated duration */
59 TimingMeasurement acc_duration
;
60 /** Start time for current accumulation cycle */
61 TimingMeasurement acc_timestamp
;
64 * Initialize a data element with an expected collection rate
65 * @param expected_rate
66 * Expected number of cycles per second of the performance element. Use 1 if unknown or not relevant.
67 * The rate is used for highlighting slow-running elements in the GUI.
69 explicit PerformanceData(double expected_rate
) : expected_rate(expected_rate
), next_index(0), prev_index(0), num_valid(0) { }
71 /** Collect a complete measurement, given start and ending times for a processing block */
72 void Add(TimingMeasurement start_time
, TimingMeasurement end_time
)
74 this->durations
[this->next_index
] = end_time
- start_time
;
75 this->timestamps
[this->next_index
] = start_time
;
76 this->prev_index
= this->next_index
;
77 this->next_index
+= 1;
78 if (this->next_index
>= NUM_FRAMERATE_POINTS
) this->next_index
= 0;
79 this->num_valid
= min(NUM_FRAMERATE_POINTS
, this->num_valid
+ 1);
82 /** Begin an accumulation of multiple measurements into a single value, from a given start time */
83 void BeginAccumulate(TimingMeasurement start_time
)
85 this->timestamps
[this->next_index
] = this->acc_timestamp
;
86 this->durations
[this->next_index
] = this->acc_duration
;
87 this->prev_index
= this->next_index
;
88 this->next_index
+= 1;
89 if (this->next_index
>= NUM_FRAMERATE_POINTS
) this->next_index
= 0;
90 this->num_valid
= min(NUM_FRAMERATE_POINTS
, this->num_valid
+ 1);
92 this->acc_duration
= 0;
93 this->acc_timestamp
= start_time
;
96 /** Accumulate a period onto the current measurement */
97 void AddAccumulate(TimingMeasurement duration
)
99 this->acc_duration
+= duration
;
102 /** Indicate a pause/expected discontinuity in processing the element */
103 void AddPause(TimingMeasurement start_time
)
105 if (this->durations
[this->prev_index
] != INVALID_DURATION
) {
106 this->timestamps
[this->next_index
] = start_time
;
107 this->durations
[this->next_index
] = INVALID_DURATION
;
108 this->prev_index
= this->next_index
;
109 this->next_index
+= 1;
110 if (this->next_index
>= NUM_FRAMERATE_POINTS
) this->next_index
= 0;
111 this->num_valid
+= 1;
115 /** Get average cycle processing time over a number of data points */
116 double GetAverageDurationMilliseconds(int count
)
118 count
= min(count
, this->num_valid
);
120 int first_point
= this->prev_index
- count
;
121 if (first_point
< 0) first_point
+= NUM_FRAMERATE_POINTS
;
123 /* Sum durations, skipping invalid points */
125 for (int i
= first_point
; i
< first_point
+ count
; i
++) {
126 auto d
= this->durations
[i
% NUM_FRAMERATE_POINTS
];
127 if (d
!= INVALID_DURATION
) {
130 /* Don't count the invalid durations */
135 if (count
== 0) return 0; // avoid div by zero
136 return sumtime
* 1000 / count
/ TIMESTAMP_PRECISION
;
139 /** Get current rate of a performance element, based on approximately the past one second of data */
142 /* Start at last recorded point, end at latest when reaching the earliest recorded point */
143 int point
= this->prev_index
;
144 int last_point
= this->next_index
- this->num_valid
;
145 if (last_point
< 0) last_point
+= NUM_FRAMERATE_POINTS
;
147 /* Number of data points collected */
149 /* Time of previous data point */
150 TimingMeasurement last
= this->timestamps
[point
];
151 /* Total duration covered by collected points */
152 TimingMeasurement total
= 0;
154 while (point
!= last_point
) {
155 /* Only record valid data points, but pretend the gaps in measurements aren't there */
156 if (this->durations
[point
] != INVALID_DURATION
) {
157 total
+= last
- this->timestamps
[point
];
160 last
= this->timestamps
[point
];
161 if (total
>= TIMESTAMP_PRECISION
) break; // end after 1 second has been collected
163 if (point
< 0) point
= NUM_FRAMERATE_POINTS
- 1;
166 if (total
== 0 || count
== 0) return 0;
167 return (double)count
* TIMESTAMP_PRECISION
/ total
;
171 /** %Game loop rate, cycles per second */
172 static const double GL_RATE
= 1000.0 / MILLISECONDS_PER_TICK
;
175 * Storage for all performance element measurements.
176 * Elements are initialized with the expected rate in recorded values per second.
179 PerformanceData _pf_data
[PFE_MAX
] = {
180 PerformanceData(GL_RATE
), // PFE_GAMELOOP
181 PerformanceData(1), // PFE_ACC_GL_ECONOMY
182 PerformanceData(1), // PFE_ACC_GL_TRAINS
183 PerformanceData(1), // PFE_ACC_GL_ROADVEHS
184 PerformanceData(1), // PFE_ACC_GL_SHIPS
185 PerformanceData(1), // PFE_ACC_GL_AIRCRAFT
186 PerformanceData(1), // PFE_GL_LANDSCAPE
187 PerformanceData(1), // PFE_GL_LINKGRAPH
188 PerformanceData(GL_RATE
), // PFE_DRAWING
189 PerformanceData(1), // PFE_ACC_DRAWWORLD
190 PerformanceData(60.0), // PFE_VIDEO
191 PerformanceData(1000.0 * 8192 / 44100), // PFE_SOUND
192 PerformanceData(1), // PFE_ALLSCRIPTS
193 PerformanceData(1), // PFE_GAMESCRIPT
194 PerformanceData(1), // PFE_AI0 ...
208 PerformanceData(1), // PFE_AI14
215 * Return a timestamp with \c TIMESTAMP_PRECISION ticks per second precision.
216 * The basis of the timestamp is implementation defined, but the value should be steady,
217 * so differences can be taken to reliably measure intervals.
219 static TimingMeasurement
GetPerformanceTimer()
221 using namespace std::chrono
;
222 return (TimingMeasurement
)time_point_cast
<microseconds
>(high_resolution_clock::now()).time_since_epoch().count();
227 * Begin a cycle of a measured element.
228 * @param elem The element to be measured
230 PerformanceMeasurer::PerformanceMeasurer(PerformanceElement elem
)
232 assert(elem
< PFE_MAX
);
235 this->start_time
= GetPerformanceTimer();
238 /** Finish a cycle of a measured element and store the measurement taken. */
239 PerformanceMeasurer::~PerformanceMeasurer()
241 if (this->elem
== PFE_ALLSCRIPTS
) {
242 /* Hack to not record scripts total when no scripts are active */
243 bool any_active
= _pf_data
[PFE_GAMESCRIPT
].num_valid
> 0;
244 for (uint e
= PFE_AI0
; e
< PFE_MAX
; e
++) any_active
|= _pf_data
[e
].num_valid
> 0;
246 PerformanceMeasurer::SetInactive(PFE_ALLSCRIPTS
);
250 _pf_data
[this->elem
].Add(this->start_time
, GetPerformanceTimer());
253 /** Set the rate of expected cycles per second of a performance element. */
254 void PerformanceMeasurer::SetExpectedRate(double rate
)
256 _pf_data
[this->elem
].expected_rate
= rate
;
259 /** Mark a performance element as not currently in use. */
260 /* static */ void PerformanceMeasurer::SetInactive(PerformanceElement elem
)
262 _pf_data
[elem
].num_valid
= 0;
263 _pf_data
[elem
].next_index
= 0;
264 _pf_data
[elem
].prev_index
= 0;
268 * Indicate that a cycle of "pause" where no processing occurs.
269 * @param elem The element not currently being processed
271 /* static */ void PerformanceMeasurer::Paused(PerformanceElement elem
)
273 _pf_data
[elem
].AddPause(GetPerformanceTimer());
278 * Begin measuring one block of the accumulating value.
279 * @param elem The element to be measured
281 PerformanceAccumulator::PerformanceAccumulator(PerformanceElement elem
)
283 assert(elem
< PFE_MAX
);
286 this->start_time
= GetPerformanceTimer();
289 /** Finish and add one block of the accumulating value. */
290 PerformanceAccumulator::~PerformanceAccumulator()
292 _pf_data
[this->elem
].AddAccumulate(GetPerformanceTimer() - this->start_time
);
296 * Store the previous accumulator value and reset for a new cycle of accumulating measurements.
297 * @note This function must be called once per frame, otherwise measurements are not collected.
298 * @param elem The element to begin a new measurement cycle of
300 void PerformanceAccumulator::Reset(PerformanceElement elem
)
302 _pf_data
[elem
].BeginAccumulate(GetPerformanceTimer());
306 void ShowFrametimeGraphWindow(PerformanceElement elem
);
309 static const PerformanceElement DISPLAY_ORDER_PFE
[PFE_MAX
] = {
341 static const char * GetAIName(int ai_index
)
343 if (!Company::IsValidAiID(ai_index
)) return "";
344 return Company::Get(ai_index
)->ai_info
->GetName();
347 /** @hideinitializer */
348 static const NWidgetPart _framerate_window_widgets
[] = {
349 NWidget(NWID_HORIZONTAL
),
350 NWidget(WWT_CLOSEBOX
, COLOUR_GREY
),
351 NWidget(WWT_CAPTION
, COLOUR_GREY
, WID_FRW_CAPTION
), SetDataTip(STR_FRAMERATE_CAPTION
, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS
),
352 NWidget(WWT_SHADEBOX
, COLOUR_GREY
),
353 NWidget(WWT_STICKYBOX
, COLOUR_GREY
),
355 NWidget(WWT_PANEL
, COLOUR_GREY
),
356 NWidget(NWID_VERTICAL
), SetPadding(6), SetPIP(0, 3, 0),
357 NWidget(WWT_TEXT
, COLOUR_GREY
, WID_FRW_RATE_GAMELOOP
), SetDataTip(STR_FRAMERATE_RATE_GAMELOOP
, STR_FRAMERATE_RATE_GAMELOOP_TOOLTIP
),
358 NWidget(WWT_TEXT
, COLOUR_GREY
, WID_FRW_RATE_DRAWING
), SetDataTip(STR_FRAMERATE_RATE_BLITTER
, STR_FRAMERATE_RATE_BLITTER_TOOLTIP
),
359 NWidget(WWT_TEXT
, COLOUR_GREY
, WID_FRW_RATE_FACTOR
), SetDataTip(STR_FRAMERATE_SPEED_FACTOR
, STR_FRAMERATE_SPEED_FACTOR_TOOLTIP
),
362 NWidget(NWID_HORIZONTAL
),
363 NWidget(WWT_PANEL
, COLOUR_GREY
),
364 NWidget(NWID_VERTICAL
), SetPadding(6), SetPIP(0, 3, 0),
365 NWidget(NWID_HORIZONTAL
), SetPIP(0, 6, 0),
366 NWidget(WWT_EMPTY
, COLOUR_GREY
, WID_FRW_TIMES_NAMES
), SetScrollbar(WID_FRW_SCROLLBAR
),
367 NWidget(WWT_EMPTY
, COLOUR_GREY
, WID_FRW_TIMES_CURRENT
), SetScrollbar(WID_FRW_SCROLLBAR
),
368 NWidget(WWT_EMPTY
, COLOUR_GREY
, WID_FRW_TIMES_AVERAGE
), SetScrollbar(WID_FRW_SCROLLBAR
),
369 NWidget(NWID_SELECTION
, INVALID_COLOUR
, WID_FRW_SEL_MEMORY
),
370 NWidget(WWT_EMPTY
, COLOUR_GREY
, WID_FRW_ALLOCSIZE
), SetScrollbar(WID_FRW_SCROLLBAR
),
373 NWidget(WWT_TEXT
, COLOUR_GREY
, WID_FRW_INFO_DATA_POINTS
), SetDataTip(STR_FRAMERATE_DATA_POINTS
, 0x0),
376 NWidget(NWID_VERTICAL
),
377 NWidget(NWID_VSCROLLBAR
, COLOUR_GREY
, WID_FRW_SCROLLBAR
),
378 NWidget(WWT_RESIZEBOX
, COLOUR_GREY
),
383 struct FramerateWindow
: Window
{
386 GUITimer next_update
;
390 struct CachedDecimal
{
394 inline void SetRate(double value
, double target
)
396 const double threshold_good
= target
* 0.95;
397 const double threshold_bad
= target
* 2 / 3;
398 value
= min(9999.99, value
);
399 this->value
= (uint32
)(value
* 100);
400 this->strid
= (value
> threshold_good
) ? STR_FRAMERATE_FPS_GOOD
: (value
< threshold_bad
) ? STR_FRAMERATE_FPS_BAD
: STR_FRAMERATE_FPS_WARN
;
403 inline void SetTime(double value
, double target
)
405 const double threshold_good
= target
/ 3;
406 const double threshold_bad
= target
;
407 value
= min(9999.99, value
);
408 this->value
= (uint32
)(value
* 100);
409 this->strid
= (value
< threshold_good
) ? STR_FRAMERATE_MS_GOOD
: (value
> threshold_bad
) ? STR_FRAMERATE_MS_BAD
: STR_FRAMERATE_MS_WARN
;
412 inline void InsertDParams(uint n
) const
414 SetDParam(n
, this->value
);
419 CachedDecimal rate_gameloop
; ///< cached game loop tick rate
420 CachedDecimal rate_drawing
; ///< cached drawing frame rate
421 CachedDecimal speed_gameloop
; ///< cached game loop speed factor
422 CachedDecimal times_shortterm
[PFE_MAX
]; ///< cached short term average times
423 CachedDecimal times_longterm
[PFE_MAX
]; ///< cached long term average times
425 static const int VSPACING
= 3; ///< space between column heading and values
426 static const int MIN_ELEMENTS
= 5; ///< smallest number of elements to display
428 FramerateWindow(WindowDesc
*desc
, WindowNumber number
) : Window(desc
)
430 this->InitNested(number
);
431 this->small
= this->IsShaded();
432 this->showing_memory
= true;
434 this->num_displayed
= this->num_active
;
435 this->next_update
.SetInterval(100);
437 /* Window is always initialised to MIN_ELEMENTS height, resize to contain num_displayed */
438 ResizeWindow(this, 0, (max(MIN_ELEMENTS
, this->num_displayed
) - MIN_ELEMENTS
) * FONT_HEIGHT_NORMAL
);
441 void OnRealtimeTick(uint delta_ms
) override
443 bool elapsed
= this->next_update
.Elapsed(delta_ms
);
445 /* Check if the shaded state has changed, switch caption text if it has */
446 if (this->small
!= this->IsShaded()) {
447 this->small
= this->IsShaded();
448 this->GetWidget
<NWidgetLeaf
>(WID_FRW_CAPTION
)->SetDataTip(this->small
? STR_FRAMERATE_CAPTION_SMALL
: STR_FRAMERATE_CAPTION
, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS
);
455 this->next_update
.SetInterval(100);
461 double gl_rate
= _pf_data
[PFE_GAMELOOP
].GetRate();
462 bool have_script
= false;
463 this->rate_gameloop
.SetRate(gl_rate
, _pf_data
[PFE_GAMELOOP
].expected_rate
);
464 this->speed_gameloop
.SetRate(gl_rate
/ _pf_data
[PFE_GAMELOOP
].expected_rate
, 1.0);
465 if (this->small
) return; // in small mode, this is everything needed
467 this->rate_drawing
.SetRate(_pf_data
[PFE_DRAWING
].GetRate(), _pf_data
[PFE_DRAWING
].expected_rate
);
470 for (PerformanceElement e
= PFE_FIRST
; e
< PFE_MAX
; e
++) {
471 this->times_shortterm
[e
].SetTime(_pf_data
[e
].GetAverageDurationMilliseconds(8), MILLISECONDS_PER_TICK
);
472 this->times_longterm
[e
].SetTime(_pf_data
[e
].GetAverageDurationMilliseconds(NUM_FRAMERATE_POINTS
), MILLISECONDS_PER_TICK
);
473 if (_pf_data
[e
].num_valid
> 0) {
475 if (e
== PFE_GAMESCRIPT
|| e
>= PFE_AI0
) have_script
= true;
479 if (this->showing_memory
!= have_script
) {
480 NWidgetStacked
*plane
= this->GetWidget
<NWidgetStacked
>(WID_FRW_SEL_MEMORY
);
481 plane
->SetDisplayedPlane(have_script
? 0 : SZSP_VERTICAL
);
482 this->showing_memory
= have_script
;
485 if (new_active
!= this->num_active
) {
486 this->num_active
= new_active
;
487 Scrollbar
*sb
= this->GetScrollbar(WID_FRW_SCROLLBAR
);
488 sb
->SetCount(this->num_active
);
489 sb
->SetCapacity(min(this->num_displayed
, this->num_active
));
494 void SetStringParameters(int widget
) const override
497 case WID_FRW_CAPTION
:
498 /* When the window is shaded, the caption shows game loop rate and speed factor */
499 if (!this->small
) break;
500 SetDParam(0, this->rate_gameloop
.strid
);
501 this->rate_gameloop
.InsertDParams(1);
502 this->speed_gameloop
.InsertDParams(3);
505 case WID_FRW_RATE_GAMELOOP
:
506 SetDParam(0, this->rate_gameloop
.strid
);
507 this->rate_gameloop
.InsertDParams(1);
509 case WID_FRW_RATE_DRAWING
:
510 SetDParam(0, this->rate_drawing
.strid
);
511 this->rate_drawing
.InsertDParams(1);
513 case WID_FRW_RATE_FACTOR
:
514 this->speed_gameloop
.InsertDParams(0);
516 case WID_FRW_INFO_DATA_POINTS
:
517 SetDParam(0, NUM_FRAMERATE_POINTS
);
522 void UpdateWidgetSize(int widget
, Dimension
*size
, const Dimension
&padding
, Dimension
*fill
, Dimension
*resize
) override
525 case WID_FRW_RATE_GAMELOOP
:
526 SetDParam(0, STR_FRAMERATE_FPS_GOOD
);
527 SetDParam(1, 999999);
529 *size
= GetStringBoundingBox(STR_FRAMERATE_RATE_GAMELOOP
);
531 case WID_FRW_RATE_DRAWING
:
532 SetDParam(0, STR_FRAMERATE_FPS_GOOD
);
533 SetDParam(1, 999999);
535 *size
= GetStringBoundingBox(STR_FRAMERATE_RATE_BLITTER
);
537 case WID_FRW_RATE_FACTOR
:
538 SetDParam(0, 999999);
540 *size
= GetStringBoundingBox(STR_FRAMERATE_SPEED_FACTOR
);
543 case WID_FRW_TIMES_NAMES
: {
545 size
->height
= FONT_HEIGHT_NORMAL
+ VSPACING
+ MIN_ELEMENTS
* FONT_HEIGHT_NORMAL
;
547 resize
->height
= FONT_HEIGHT_NORMAL
;
548 for (PerformanceElement e
: DISPLAY_ORDER_PFE
) {
549 if (_pf_data
[e
].num_valid
== 0) continue;
552 line_size
= GetStringBoundingBox(STR_FRAMERATE_GAMELOOP
+ e
);
554 SetDParam(0, e
- PFE_AI0
+ 1);
555 SetDParamStr(1, GetAIName(e
- PFE_AI0
));
556 line_size
= GetStringBoundingBox(STR_FRAMERATE_AI
);
558 size
->width
= max(size
->width
, line_size
.width
);
563 case WID_FRW_TIMES_CURRENT
:
564 case WID_FRW_TIMES_AVERAGE
:
565 case WID_FRW_ALLOCSIZE
: {
566 *size
= GetStringBoundingBox(STR_FRAMERATE_CURRENT
+ (widget
- WID_FRW_TIMES_CURRENT
));
567 SetDParam(0, 999999);
569 Dimension item_size
= GetStringBoundingBox(STR_FRAMERATE_MS_GOOD
);
570 size
->width
= max(size
->width
, item_size
.width
);
571 size
->height
+= FONT_HEIGHT_NORMAL
* MIN_ELEMENTS
+ VSPACING
;
573 resize
->height
= FONT_HEIGHT_NORMAL
;
579 /** Render a column of formatted average durations */
580 void DrawElementTimesColumn(const Rect
&r
, StringID heading_str
, const CachedDecimal
*values
) const
582 const Scrollbar
*sb
= this->GetScrollbar(WID_FRW_SCROLLBAR
);
583 uint16 skip
= sb
->GetPosition();
584 int drawable
= this->num_displayed
;
586 DrawString(r
.left
, r
.right
, y
, heading_str
, TC_FROMSTRING
, SA_CENTER
, true);
587 y
+= FONT_HEIGHT_NORMAL
+ VSPACING
;
588 for (PerformanceElement e
: DISPLAY_ORDER_PFE
) {
589 if (_pf_data
[e
].num_valid
== 0) continue;
593 values
[e
].InsertDParams(0);
594 DrawString(r
.left
, r
.right
, y
, values
[e
].strid
, TC_FROMSTRING
, SA_RIGHT
);
595 y
+= FONT_HEIGHT_NORMAL
;
597 if (drawable
== 0) break;
602 void DrawElementAllocationsColumn(const Rect
&r
) const
604 const Scrollbar
*sb
= this->GetScrollbar(WID_FRW_SCROLLBAR
);
605 uint16 skip
= sb
->GetPosition();
606 int drawable
= this->num_displayed
;
608 DrawString(r
.left
, r
.right
, y
, STR_FRAMERATE_MEMORYUSE
, TC_FROMSTRING
, SA_CENTER
, true);
609 y
+= FONT_HEIGHT_NORMAL
+ VSPACING
;
610 for (PerformanceElement e
: DISPLAY_ORDER_PFE
) {
611 if (_pf_data
[e
].num_valid
== 0) continue;
614 } else if (e
== PFE_GAMESCRIPT
|| e
>= PFE_AI0
) {
615 if (e
== PFE_GAMESCRIPT
) {
616 SetDParam(0, Game::GetInstance()->GetAllocatedMemory());
618 SetDParam(0, Company::Get(e
- PFE_AI0
)->ai_instance
->GetAllocatedMemory());
620 DrawString(r
.left
, r
.right
, y
, STR_FRAMERATE_BYTES_GOOD
, TC_FROMSTRING
, SA_RIGHT
);
621 y
+= FONT_HEIGHT_NORMAL
;
623 if (drawable
== 0) break;
625 /* skip non-script */
626 y
+= FONT_HEIGHT_NORMAL
;
628 if (drawable
== 0) break;
633 void DrawWidget(const Rect
&r
, int widget
) const override
636 case WID_FRW_TIMES_NAMES
: {
637 /* Render a column of titles for performance element names */
638 const Scrollbar
*sb
= this->GetScrollbar(WID_FRW_SCROLLBAR
);
639 uint16 skip
= sb
->GetPosition();
640 int drawable
= this->num_displayed
;
641 int y
= r
.top
+ FONT_HEIGHT_NORMAL
+ VSPACING
; // first line contains headings in the value columns
642 for (PerformanceElement e
: DISPLAY_ORDER_PFE
) {
643 if (_pf_data
[e
].num_valid
== 0) continue;
648 DrawString(r
.left
, r
.right
, y
, STR_FRAMERATE_GAMELOOP
+ e
, TC_FROMSTRING
, SA_LEFT
);
650 SetDParam(0, e
- PFE_AI0
+ 1);
651 SetDParamStr(1, GetAIName(e
- PFE_AI0
));
652 DrawString(r
.left
, r
.right
, y
, STR_FRAMERATE_AI
, TC_FROMSTRING
, SA_LEFT
);
654 y
+= FONT_HEIGHT_NORMAL
;
656 if (drawable
== 0) break;
661 case WID_FRW_TIMES_CURRENT
:
662 /* Render short-term average values */
663 DrawElementTimesColumn(r
, STR_FRAMERATE_CURRENT
, this->times_shortterm
);
665 case WID_FRW_TIMES_AVERAGE
:
666 /* Render averages of all recorded values */
667 DrawElementTimesColumn(r
, STR_FRAMERATE_AVERAGE
, this->times_longterm
);
669 case WID_FRW_ALLOCSIZE
:
670 DrawElementAllocationsColumn(r
);
675 void OnClick(Point pt
, int widget
, int click_count
) override
678 case WID_FRW_TIMES_NAMES
:
679 case WID_FRW_TIMES_CURRENT
:
680 case WID_FRW_TIMES_AVERAGE
: {
681 /* Open time graph windows when clicking detail measurement lines */
682 const Scrollbar
*sb
= this->GetScrollbar(WID_FRW_SCROLLBAR
);
683 int line
= sb
->GetScrolledRowFromWidget(pt
.y
- FONT_HEIGHT_NORMAL
- VSPACING
, this, widget
, VSPACING
, FONT_HEIGHT_NORMAL
);
684 if (line
!= INT_MAX
) {
686 /* Find the visible line that was clicked */
687 for (PerformanceElement e
: DISPLAY_ORDER_PFE
) {
688 if (_pf_data
[e
].num_valid
> 0) line
--;
690 ShowFrametimeGraphWindow(e
);
700 void OnResize() override
702 auto *wid
= this->GetWidget
<NWidgetResizeBase
>(WID_FRW_TIMES_NAMES
);
703 this->num_displayed
= (wid
->current_y
- wid
->min_y
- VSPACING
) / FONT_HEIGHT_NORMAL
- 1; // subtract 1 for headings
704 this->GetScrollbar(WID_FRW_SCROLLBAR
)->SetCapacity(this->num_displayed
);
708 static WindowDesc
_framerate_display_desc(
709 WDP_AUTO
, "framerate_display", 0, 0,
710 WC_FRAMERATE_DISPLAY
, WC_NONE
,
712 _framerate_window_widgets
, lengthof(_framerate_window_widgets
)
716 /** @hideinitializer */
717 static const NWidgetPart _frametime_graph_window_widgets
[] = {
718 NWidget(NWID_HORIZONTAL
),
719 NWidget(WWT_CLOSEBOX
, COLOUR_GREY
),
720 NWidget(WWT_CAPTION
, COLOUR_GREY
, WID_FGW_CAPTION
), SetDataTip(STR_WHITE_STRING
, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS
),
721 NWidget(WWT_STICKYBOX
, COLOUR_GREY
),
723 NWidget(WWT_PANEL
, COLOUR_GREY
),
724 NWidget(NWID_VERTICAL
), SetPadding(6),
725 NWidget(WWT_EMPTY
, COLOUR_GREY
, WID_FGW_GRAPH
),
730 struct FrametimeGraphWindow
: Window
{
731 int vertical_scale
; ///< number of TIMESTAMP_PRECISION units vertically
732 int horizontal_scale
; ///< number of half-second units horizontally
733 GUITimer next_scale_update
; ///< interval for next scale update
735 PerformanceElement element
; ///< what element this window renders graph for
736 Dimension graph_size
; ///< size of the main graph area (excluding axis labels)
738 FrametimeGraphWindow(WindowDesc
*desc
, WindowNumber number
) : Window(desc
)
740 this->element
= (PerformanceElement
)number
;
741 this->horizontal_scale
= 4;
742 this->vertical_scale
= TIMESTAMP_PRECISION
/ 10;
743 this->next_scale_update
.SetInterval(1);
745 this->InitNested(number
);
748 void SetStringParameters(int widget
) const override
751 case WID_FGW_CAPTION
:
752 if (this->element
< PFE_AI0
) {
753 SetDParam(0, STR_FRAMETIME_CAPTION_GAMELOOP
+ this->element
);
755 SetDParam(0, STR_FRAMETIME_CAPTION_AI
);
756 SetDParam(1, this->element
- PFE_AI0
+ 1);
757 SetDParamStr(2, GetAIName(this->element
- PFE_AI0
));
763 void UpdateWidgetSize(int widget
, Dimension
*size
, const Dimension
&padding
, Dimension
*fill
, Dimension
*resize
) override
765 if (widget
== WID_FGW_GRAPH
) {
767 Dimension size_ms_label
= GetStringBoundingBox(STR_FRAMERATE_GRAPH_MILLISECONDS
);
769 Dimension size_s_label
= GetStringBoundingBox(STR_FRAMERATE_GRAPH_SECONDS
);
771 /* Size graph in height to fit at least 10 vertical labels with space between, or at least 100 pixels */
772 graph_size
.height
= max
<uint
>(100, 10 * (size_ms_label
.height
+ 1));
773 /* Always 2:1 graph area */
774 graph_size
.width
= 2 * graph_size
.height
;
777 size
->width
+= size_ms_label
.width
+ 2;
778 size
->height
+= size_s_label
.height
+ 2;
782 void SelectHorizontalScale(TimingMeasurement range
)
784 /* Determine horizontal scale based on period covered by 60 points
785 * (slightly less than 2 seconds at full game speed) */
786 struct ScaleDef
{ TimingMeasurement range
; int scale
; };
787 static const ScaleDef hscales
[] = {
794 for (const ScaleDef
*sc
= hscales
; sc
< hscales
+ lengthof(hscales
); sc
++) {
795 if (range
< sc
->range
) this->horizontal_scale
= sc
->scale
;
799 void SelectVerticalScale(TimingMeasurement range
)
801 /* Determine vertical scale based on peak value (within the horizontal scale + a bit) */
802 static const TimingMeasurement vscales
[] = {
803 TIMESTAMP_PRECISION
* 100,
804 TIMESTAMP_PRECISION
* 10,
805 TIMESTAMP_PRECISION
* 5,
807 TIMESTAMP_PRECISION
/ 2,
808 TIMESTAMP_PRECISION
/ 5,
809 TIMESTAMP_PRECISION
/ 10,
810 TIMESTAMP_PRECISION
/ 50,
811 TIMESTAMP_PRECISION
/ 200,
813 for (const TimingMeasurement
*sc
= vscales
; sc
< vscales
+ lengthof(vscales
); sc
++) {
814 if (range
< *sc
) this->vertical_scale
= (int)*sc
;
818 /** Recalculate the graph scaling factors based on current recorded data */
821 const TimingMeasurement
*durations
= _pf_data
[this->element
].durations
;
822 const TimingMeasurement
*timestamps
= _pf_data
[this->element
].timestamps
;
823 int num_valid
= _pf_data
[this->element
].num_valid
;
824 int point
= _pf_data
[this->element
].prev_index
;
826 TimingMeasurement lastts
= timestamps
[point
];
827 TimingMeasurement time_sum
= 0;
828 TimingMeasurement peak_value
= 0;
831 /* Sensible default for when too few measurements are available */
832 this->horizontal_scale
= 4;
834 for (int i
= 1; i
< num_valid
; i
++) {
836 if (point
< 0) point
= NUM_FRAMERATE_POINTS
- 1;
838 TimingMeasurement value
= durations
[point
];
839 if (value
== PerformanceData::INVALID_DURATION
) {
840 /* Skip gaps in data by pretending time is continuous across them */
841 lastts
= timestamps
[point
];
844 if (value
> peak_value
) peak_value
= value
;
847 /* Accumulate period of time covered by data */
848 time_sum
+= lastts
- timestamps
[point
];
849 lastts
= timestamps
[point
];
851 /* Enough data to select a range and get decent data density */
852 if (count
== 60) this->SelectHorizontalScale(time_sum
/ TIMESTAMP_PRECISION
);
854 /* End when enough points have been collected and the horizontal scale has been exceeded */
855 if (count
>= 60 && time_sum
>= (this->horizontal_scale
+ 2) * TIMESTAMP_PRECISION
/ 2) break;
858 this->SelectVerticalScale(peak_value
);
861 void OnRealtimeTick(uint delta_ms
) override
865 if (this->next_scale_update
.Elapsed(delta_ms
)) {
866 this->next_scale_update
.SetInterval(500);
871 /** Scale and interpolate a value from a source range into a destination range */
873 static inline T
Scinterlate(T dst_min
, T dst_max
, T src_min
, T src_max
, T value
)
875 T dst_diff
= dst_max
- dst_min
;
876 T src_diff
= src_max
- src_min
;
877 return (value
- src_min
) * dst_diff
/ src_diff
+ dst_min
;
880 void DrawWidget(const Rect
&r
, int widget
) const override
882 if (widget
== WID_FGW_GRAPH
) {
883 const TimingMeasurement
*durations
= _pf_data
[this->element
].durations
;
884 const TimingMeasurement
*timestamps
= _pf_data
[this->element
].timestamps
;
885 int point
= _pf_data
[this->element
].prev_index
;
887 const int x_zero
= r
.right
- (int)this->graph_size
.width
;
888 const int x_max
= r
.right
;
889 const int y_zero
= r
.top
+ (int)this->graph_size
.height
;
890 const int y_max
= r
.top
;
891 const int c_grid
= PC_DARK_GREY
;
892 const int c_lines
= PC_BLACK
;
893 const int c_peak
= PC_DARK_RED
;
895 const TimingMeasurement draw_horz_scale
= (TimingMeasurement
)this->horizontal_scale
* TIMESTAMP_PRECISION
/ 2;
896 const TimingMeasurement draw_vert_scale
= (TimingMeasurement
)this->vertical_scale
;
898 /* Number of \c horizontal_scale units in each horizontal division */
899 const uint horz_div_scl
= (this->horizontal_scale
<= 20) ? 1 : 10;
900 /* Number of divisions of the horizontal axis */
901 const uint horz_divisions
= this->horizontal_scale
/ horz_div_scl
;
902 /* Number of divisions of the vertical axis */
903 const uint vert_divisions
= 10;
905 /* Draw division lines and labels for the vertical axis */
906 for (uint division
= 0; division
< vert_divisions
; division
++) {
907 int y
= Scinterlate(y_zero
, y_max
, 0, (int)vert_divisions
, (int)division
);
908 GfxDrawLine(x_zero
, y
, x_max
, y
, c_grid
);
909 if (division
% 2 == 0) {
910 if ((TimingMeasurement
)this->vertical_scale
> TIMESTAMP_PRECISION
) {
911 SetDParam(0, this->vertical_scale
* division
/ 10 / TIMESTAMP_PRECISION
);
912 DrawString(r
.left
, x_zero
- 2, y
- FONT_HEIGHT_SMALL
, STR_FRAMERATE_GRAPH_SECONDS
, TC_GREY
, SA_RIGHT
| SA_FORCE
, false, FS_SMALL
);
914 SetDParam(0, this->vertical_scale
* division
/ 10 * 1000 / TIMESTAMP_PRECISION
);
915 DrawString(r
.left
, x_zero
- 2, y
- FONT_HEIGHT_SMALL
, STR_FRAMERATE_GRAPH_MILLISECONDS
, TC_GREY
, SA_RIGHT
| SA_FORCE
, false, FS_SMALL
);
919 /* Draw division lines and labels for the horizontal axis */
920 for (uint division
= horz_divisions
; division
> 0; division
--) {
921 int x
= Scinterlate(x_zero
, x_max
, 0, (int)horz_divisions
, (int)horz_divisions
- (int)division
);
922 GfxDrawLine(x
, y_max
, x
, y_zero
, c_grid
);
923 if (division
% 2 == 0) {
924 SetDParam(0, division
* horz_div_scl
/ 2);
925 DrawString(x
, x_max
, y_zero
+ 2, STR_FRAMERATE_GRAPH_SECONDS
, TC_GREY
, SA_LEFT
| SA_FORCE
, false, FS_SMALL
);
929 /* Position of last rendered data point */
932 (int)Scinterlate
<int64
>(y_zero
, y_max
, 0, this->vertical_scale
, durations
[point
])
934 /* Timestamp of last rendered data point */
935 TimingMeasurement lastts
= timestamps
[point
];
937 TimingMeasurement peak_value
= 0;
938 Point peak_point
= { 0, 0 };
939 TimingMeasurement value_sum
= 0;
940 TimingMeasurement time_sum
= 0;
941 int points_drawn
= 0;
943 for (int i
= 1; i
< NUM_FRAMERATE_POINTS
; i
++) {
945 if (point
< 0) point
= NUM_FRAMERATE_POINTS
- 1;
947 TimingMeasurement value
= durations
[point
];
948 if (value
== PerformanceData::INVALID_DURATION
) {
949 /* Skip gaps in measurements, pretend the data points on each side are continuous */
950 lastts
= timestamps
[point
];
954 /* Use total time period covered for value along horizontal axis */
955 time_sum
+= lastts
- timestamps
[point
];
956 lastts
= timestamps
[point
];
957 /* Stop if past the width of the graph */
958 if (time_sum
> draw_horz_scale
) break;
960 /* Draw line from previous point to new point */
962 (int)Scinterlate
<int64
>(x_zero
, x_max
, 0, (int64
)draw_horz_scale
, (int64
)draw_horz_scale
- (int64
)time_sum
),
963 (int)Scinterlate
<int64
>(y_zero
, y_max
, 0, (int64
)draw_vert_scale
, (int64
)value
)
965 assert(newpoint
.x
<= lastpoint
.x
);
966 GfxDrawLine(lastpoint
.x
, lastpoint
.y
, newpoint
.x
, newpoint
.y
, c_lines
);
967 lastpoint
= newpoint
;
969 /* Record peak and average value across graphed data */
972 if (value
> peak_value
) {
974 peak_point
= newpoint
;
978 /* If the peak value is significantly larger than the average, mark and label it */
979 if (points_drawn
> 0 && peak_value
> TIMESTAMP_PRECISION
/ 100 && 2 * peak_value
> 3 * value_sum
/ points_drawn
) {
980 TextColour tc_peak
= (TextColour
)(TC_IS_PALETTE_COLOUR
| c_peak
);
981 GfxFillRect(peak_point
.x
- 1, peak_point
.y
- 1, peak_point
.x
+ 1, peak_point
.y
+ 1, c_peak
);
982 SetDParam(0, peak_value
* 1000 / TIMESTAMP_PRECISION
);
983 int label_y
= max(y_max
, peak_point
.y
- FONT_HEIGHT_SMALL
);
984 if (peak_point
.x
- x_zero
> (int)this->graph_size
.width
/ 2) {
985 DrawString(x_zero
, peak_point
.x
- 2, label_y
, STR_FRAMERATE_GRAPH_MILLISECONDS
, tc_peak
, SA_RIGHT
| SA_FORCE
, false, FS_SMALL
);
987 DrawString(peak_point
.x
+ 2, x_max
, label_y
, STR_FRAMERATE_GRAPH_MILLISECONDS
, tc_peak
, SA_LEFT
| SA_FORCE
, false, FS_SMALL
);
994 static WindowDesc
_frametime_graph_window_desc(
995 WDP_AUTO
, "frametime_graph", 140, 90,
996 WC_FRAMETIME_GRAPH
, WC_NONE
,
998 _frametime_graph_window_widgets
, lengthof(_frametime_graph_window_widgets
)
1003 /** Open the general framerate window */
1004 void ShowFramerateWindow()
1006 AllocateWindowDescFront
<FramerateWindow
>(&_framerate_display_desc
, 0);
1009 /** Open a graph window for a performance element */
1010 void ShowFrametimeGraphWindow(PerformanceElement elem
)
1012 if (elem
< PFE_FIRST
|| elem
>= PFE_MAX
) return; // maybe warn?
1013 AllocateWindowDescFront
<FrametimeGraphWindow
>(&_frametime_graph_window_desc
, elem
, true);
1016 /** Print performance statistics to game console */
1017 void ConPrintFramerate()
1019 const int count1
= NUM_FRAMERATE_POINTS
/ 8;
1020 const int count2
= NUM_FRAMERATE_POINTS
/ 4;
1021 const int count3
= NUM_FRAMERATE_POINTS
/ 1;
1023 IConsolePrintF(TC_SILVER
, "Based on num. data points: %d %d %d", count1
, count2
, count3
);
1025 static const char *MEASUREMENT_NAMES
[PFE_MAX
] = {
1027 " GL station ticks",
1029 " GL road vehicle ticks",
1031 " GL aircraft ticks",
1032 " GL landscape ticks",
1033 " GL link graph delays",
1035 " Viewport drawing",
1038 "AI/GS scripts total",
1041 char ai_name_buf
[128];
1043 static const PerformanceElement rate_elements
[] = { PFE_GAMELOOP
, PFE_DRAWING
, PFE_VIDEO
};
1045 bool printed_anything
= false;
1047 for (const PerformanceElement
*e
= rate_elements
; e
< rate_elements
+ lengthof(rate_elements
); e
++) {
1048 auto &pf
= _pf_data
[*e
];
1049 if (pf
.num_valid
== 0) continue;
1050 IConsolePrintF(TC_GREEN
, "%s rate: %.2ffps (expected: %.2ffps)",
1051 MEASUREMENT_NAMES
[*e
],
1054 printed_anything
= true;
1057 for (PerformanceElement e
= PFE_FIRST
; e
< PFE_MAX
; e
++) {
1058 auto &pf
= _pf_data
[e
];
1059 if (pf
.num_valid
== 0) continue;
1062 name
= MEASUREMENT_NAMES
[e
];
1064 seprintf(ai_name_buf
, lastof(ai_name_buf
), "AI %d %s", e
- PFE_AI0
+ 1, GetAIName(e
- PFE_AI0
)),
1067 IConsolePrintF(TC_LIGHT_BLUE
, "%s times: %.2fms %.2fms %.2fms",
1069 pf
.GetAverageDurationMilliseconds(count1
),
1070 pf
.GetAverageDurationMilliseconds(count2
),
1071 pf
.GetAverageDurationMilliseconds(count3
));
1072 printed_anything
= true;
1075 if (!printed_anything
) {
1076 IConsoleWarning("No performance measurements have been taken yet");