openMSX
Display.cc
Go to the documentation of this file.
1#include "Display.hh"
2
3#include "RendererFactory.hh"
4#include "ImGuiManager.hh"
5#include "Layer.hh"
6#include "OutputSurface.hh"
7#include "VideoLayer.hh"
8#include "VideoSystem.hh"
10
11#include "BooleanSetting.hh"
12#include "CommandException.hh"
13#include "EventDistributor.hh"
14#include "Event.hh"
15#include "FileOperations.hh"
16#include "FileContext.hh"
17#include "CliComm.hh"
18#include "Timer.hh"
19#include "IntegerSetting.hh"
20#include "EnumSetting.hh"
21#include "Reactor.hh"
22#include "MSXMotherBoard.hh"
23#include "HardwareConfig.hh"
24#include "TclArgParser.hh"
25#include "XMLElement.hh"
26#include "Version.hh"
27
28#include "narrow.hh"
29#include "outer.hh"
30#include "ranges.hh"
31#include "stl.hh"
32#include "unreachable.hh"
33#include "xrange.hh"
34
35#include <array>
36#include <cassert>
37
38using std::string;
39
40namespace openmsx {
41
43 : RTSchedulable(reactor_.getRTScheduler())
44 , screenShotCmd(reactor_.getCommandController())
45 , fpsInfo(reactor_.getOpenMSXInfoCommand())
46 , osdGui(reactor_.getCommandController(), *this)
47 , reactor(reactor_)
48 , renderSettings(reactor.getCommandController())
49{
50 frameDurationSum = 0;
51 repeat(NUM_FRAME_DURATIONS, [&] {
52 frameDurations.addFront(20);
53 frameDurationSum += 20;
54 });
55 prevTimeStamp = Timer::getTime();
56
57 EventDistributor& eventDistributor = reactor.getEventDistributor();
59 *this);
61 *this);
63 *this);
65 *this);
66 renderSettings.getRendererSetting().attach(*this);
67}
68
70{
71 renderSettings.getRendererSetting().detach(*this);
72
73 EventDistributor& eventDistributor = reactor.getEventDistributor();
75 *this);
77 *this);
79 *this);
81 *this);
82
83 resetVideoSystem();
84
85 assert(listeners.empty());
86}
87
89{
90 assert(!videoSystem);
91 assert(currentRenderer == RenderSettings::UNINITIALIZED);
92 assert(!switchInProgress);
93 currentRenderer = renderSettings.getRenderer();
94 switchInProgress = true;
95 doRendererSwitch();
96}
97
99{
100 assert(videoSystem);
101 return *videoSystem;
102}
103
105{
106 return videoSystem ? videoSystem->getOutputSurface() : nullptr;
107}
108
109void Display::resetVideoSystem()
110{
111 videoSystem.reset();
112 // At this point all layers except for the Video9000 layer
113 // should be gone.
114 //assert(layers.empty());
115}
116
118{
119 return reactor.getCliComm();
120}
121
123{
124 assert(!contains(listeners, &listener));
125 listeners.push_back(&listener);
126}
127
129{
130 move_pop_back(listeners, rfind_unguarded(listeners, &listener));
131}
132
134{
135 auto it = ranges::find_if(layers, &Layer::isActive);
136 return (it != layers.end()) ? *it : nullptr;
137}
138
139Display::Layers::iterator Display::baseLayer()
140{
141 // Note: It is possible to cache this, but since the number of layers is
142 // low at the moment, it's not really worth it.
143 auto it = end(layers);
144 while (true) {
145 if (it == begin(layers)) {
146 // There should always be at least one opaque layer.
147 // TODO: This is not true for DummyVideoSystem.
148 // Anyway, a missing layer will probably stand out visually,
149 // so do we really have to assert on it?
150 //UNREACHABLE;
151 return it;
152 }
153 --it;
154 if ((*it)->getCoverage() == Layer::COVER_FULL) return it;
155 }
156}
157
158void Display::executeRT()
159{
160 repaint();
161}
162
163int Display::signalEvent(const Event& event)
164{
165 std::visit(overloaded{
166 [&](const FinishFrameEvent& e) {
167 if (e.needRender()) {
168 repaint();
169 reactor.getEventDistributor().distributeEvent(FrameDrawnEvent());
170 }
171 },
172 [&](const SwitchRendererEvent& /*e*/) {
173 doRendererSwitch(); // might throw
174 },
175 [&](const MachineLoadedEvent& /*e*/) {
176 videoSystem->updateWindowTitle();
177 },
178 [&](const WindowEvent& e) {
179 const auto& evt = e.getSdlWindowEvent();
180 if (evt.event == SDL_WINDOWEVENT_EXPOSED) {
181 // Don't render too often, and certainly not when the screen
182 // will anyway soon be rendered.
183 repaintDelayed(100 * 1000); // 10fps
184 }
185 if (PLATFORM_ANDROID && e.isMainWindow() &&
186 evt.event == one_of(SDL_WINDOWEVENT_FOCUS_GAINED, SDL_WINDOWEVENT_FOCUS_LOST)) {
187 // On Android, the rendering must be frozen when the app is sent to
188 // the background, because Android takes away all graphics resources
189 // from the app. It simply destroys the entire graphics context.
190 // Though, a repaint() must happen within the focus-lost event
191 // so that the SDL Android port realizes that the graphics context
192 // is gone and will re-build it again on the first flush to the
193 // surface after the focus has been regained.
194
195 // Perform a repaint before updating the renderFrozen flag:
196 // -When loosing the focus, this repaint will flush a last
197 // time the SDL surface, making sure that the Android SDL
198 // port discovers that the graphics context is gone.
199 // -When gaining the focus, this repaint does nothing as
200 // the renderFrozen flag is still false
201 repaint();
202 bool lost = evt.event == SDL_WINDOWEVENT_FOCUS_LOST;
203 ad_printf("Setting renderFrozen to %d", lost);
204 renderFrozen = lost;
205 }
206 },
207 [](const EventBase&) { /*ignore*/ }
208 }, event);
209 return 0;
210}
211
213{
214 string title = Version::full();
215 if (!Version::RELEASE) {
216 strAppend(title, " [", BUILD_FLAVOUR, ']');
217 }
218 if (MSXMotherBoard* motherboard = reactor.getMotherBoard()) {
219 if (const HardwareConfig* machine = motherboard->getMachineConfig()) {
220 const auto& config = machine->getConfig();
221 strAppend(title, " - ",
222 config.getChild("info").getChildData("manufacturer"), ' ',
223 config.getChild("info").getChildData("code"));
224 }
225 }
226 return title;
227}
228
230{
231 if (auto pos = videoSystem->getWindowPosition()) {
233 }
234 return retrieveWindowPosition();
235}
236
238{
240 videoSystem->setWindowPosition(pos);
241}
242
247
252
253void Display::update(const Setting& setting) noexcept
254{
255 if (&setting == &renderSettings.getRendererSetting()) {
256 checkRendererSwitch();
257 } else {
259 }
260}
261
262void Display::checkRendererSwitch()
263{
264 if (switchInProgress) {
265 // This method only queues a request to switch renderer (see
266 // comments below why). If there already is such a request
267 // queued we don't need to do it again.
268 return;
269 }
270 auto newRenderer = renderSettings.getRenderer();
271 if (newRenderer != currentRenderer) {
272 currentRenderer = newRenderer;
273 // don't do the actual switching in the Tcl callback
274 // it seems creating and destroying Settings (= Tcl vars)
275 // causes problems???
276 switchInProgress = true;
277 reactor.getEventDistributor().distributeEvent(SwitchRendererEvent());
278 }
279}
280
281void Display::doRendererSwitch()
282{
283 assert(switchInProgress);
284
285 bool success = false;
286 while (!success) {
287 try {
288 doRendererSwitch2();
289 success = true;
290 } catch (MSXException& e) {
291 auto& rendererSetting = renderSettings.getRendererSetting();
292 string errorMsg = strCat(
293 "Couldn't activate renderer ",
294 rendererSetting.getString(),
295 ": ", e.getMessage());
296 // now try some things that might work against this:
297 auto& scaleFactorSetting = renderSettings.getScaleFactorSetting();
298 auto curVal = scaleFactorSetting.getInt();
299 if (curVal == MIN_SCALE_FACTOR) {
300 throw FatalError(
301 e.getMessage(),
302 " (and I have no other ideas to try...)"); // give up and die... :(
303 }
304 strAppend(errorMsg, "\nTrying to decrease scale_factor setting from ",
305 curVal, " to ", curVal - 1, "...");
306 scaleFactorSetting.setInt(curVal - 1);
307 getCliComm().printWarning(errorMsg);
308 }
309 }
310
311 switchInProgress = false;
312}
313
314void Display::doRendererSwitch2()
315{
316 for (auto& l : listeners) {
317 l->preVideoSystemChange();
318 }
319
320 resetVideoSystem();
321 videoSystem = RendererFactory::createVideoSystem(reactor);
322
323 for (auto& l : listeners) {
324 l->postVideoSystemChange();
325 }
326}
327
329{
330 if (switchInProgress) {
331 // The checkRendererSwitch() method will queue a
332 // SWITCH_RENDERER_EVENT, but before that event is handled
333 // we shouldn't do any repaints (with inconsistent setting
334 // values and render objects). This can happen when this
335 // method gets called because of a DELAYED_REPAINT_EVENT
336 // (DELAYED_REPAINT_EVENT was already queued before
337 // SWITCH_RENDERER_EVENT is queued).
338 return;
339 }
340
341 cancelRT(); // cancel delayed repaint
342
343 if (!renderFrozen) {
344 assert(videoSystem);
345 if (OutputSurface* surface = videoSystem->getOutputSurface()) {
346 repaintImpl(*surface);
347 videoSystem->flush();
348 }
349 }
350
351 // update fps statistics
352 auto now = Timer::getTime();
353 auto duration = now - prevTimeStamp;
354 prevTimeStamp = now;
355 frameDurationSum += duration - frameDurations.removeBack();
356 frameDurations.addFront(duration);
357
358 // TODO maybe revisit this later (and/or simplify other calls to repaintDelayed())
359 // This ensures a minimum framerate for ImGui
360 repaintDelayed(40 * 1000); // 25fps
361}
362
364{
365 for (auto it = baseLayer(); it != end(layers); ++it) {
366 if ((*it)->getCoverage() != Layer::COVER_NONE) {
367 (*it)->paint(surface);
368 }
369 }
370}
371
373{
374 // Request a repaint from the VideoSystem. This may call repaintImpl()
375 // directly or for example defer to a signal callback on VisibleSurface.
376 videoSystem->repaint();
377}
378
379void Display::repaintDelayed(uint64_t delta)
380{
381 if (isPendingRT()) {
382 // already a pending repaint
383 return;
384 }
385 scheduleRT(unsigned(delta));
386}
387
389{
390 int z = layer.getZ();
391 auto it = ranges::find_if(layers, [&](Layer* l) { return l->getZ() > z; });
392 layers.insert(it, &layer);
393 layer.setDisplay(*this);
394}
395
397{
398 layers.erase(rfind_unguarded(layers, &layer));
399}
400
401void Display::updateZ(Layer& layer) noexcept
402{
403 // Remove at old Z-index...
404 removeLayer(layer);
405 // ...and re-insert at new Z-index.
406 addLayer(layer);
407}
408
409
410// ScreenShotCmd
411
412Display::ScreenShotCmd::ScreenShotCmd(CommandController& commandController_)
413 : Command(commandController_, "screenshot")
414{
415}
416
417void Display::ScreenShotCmd::execute(std::span<const TclObject> tokens, TclObject& result)
418{
419 std::string_view prefix = "openmsx";
420 bool rawShot = false;
421 bool msxOnly = false;
422 bool doubleSize = false;
423 bool withOsd = false;
424 std::array info = {
425 valueArg("-prefix", prefix),
426 flagArg("-raw", rawShot),
427 flagArg("-msxonly", msxOnly),
428 flagArg("-doublesize", doubleSize),
429 flagArg("-with-osd", withOsd)
430 };
431 auto arguments = parseTclArgs(getInterpreter(), tokens.subspan(1), info);
432
433 auto& display = OUTER(Display, screenShotCmd);
434 if (msxOnly) {
435 display.getCliComm().printWarning(
436 "The -msxonly option has been deprecated and will "
437 "be removed in a future release. Instead, use the "
438 "-raw option for the same effect.");
439 rawShot = true;
440 }
441 if (doubleSize && !rawShot) {
442 throw CommandException("-doublesize option can only be used in "
443 "combination with -raw");
444 }
445 if (rawShot && withOsd) {
446 throw CommandException("-with-osd cannot be used in "
447 "combination with -raw");
448 }
449
450 std::string_view fname;
451 switch (arguments.size()) {
452 case 0:
453 // nothing
454 break;
455 case 1:
456 fname = arguments[0].getString();
457 break;
458 default:
459 throw SyntaxError();
460 }
462 fname, "screenshots", prefix, ".png");
463
464 if (!rawShot) {
465 // include all layers (OSD stuff, console)
466 try {
467 display.getVideoSystem().takeScreenShot(filename, withOsd);
468 } catch (MSXException& e) {
469 throw CommandException(
470 "Failed to take screenshot: ", e.getMessage());
471 }
472 } else {
473 auto* videoLayer = dynamic_cast<VideoLayer*>(
474 display.findActiveLayer());
475 if (!videoLayer) {
476 throw CommandException(
477 "Current renderer doesn't support taking screenshots.");
478 }
479 unsigned height = doubleSize ? 480 : 240;
480 try {
481 videoLayer->takeRawScreenShot(height, filename);
482 } catch (MSXException& e) {
483 throw CommandException(
484 "Failed to take screenshot: ", e.getMessage());
485 }
486 }
487
488 display.getCliComm().printInfo("Screen saved to ", filename);
489 result = filename;
490}
491
492string Display::ScreenShotCmd::help(std::span<const TclObject> /*tokens*/) const
493{
494 // Note: -no-sprites and -guess-name options are implemented in Tcl.
495 // TODO: find a way to extend the help and completion for a command
496 // when extending it in Tcl
497 return "screenshot Write screenshot to file \"openmsxNNNN.png\"\n"
498 "screenshot <filename> Write screenshot to indicated file\n"
499 "screenshot -prefix foo Write screenshot to file \"fooNNNN.png\"\n"
500 "screenshot -raw 320x240 raw screenshot (of MSX screen only)\n"
501 "screenshot -raw -doublesize 640x480 raw screenshot (of MSX screen only)\n"
502 "screenshot -with-osd Include OSD elements in the screenshot\n"
503 "screenshot -no-sprites Don't include sprites in the screenshot\n"
504 "screenshot -guess-name Guess the name of the running software and use it as prefix\n";
505}
506
507void Display::ScreenShotCmd::tabCompletion(std::vector<string>& tokens) const
508{
509 using namespace std::literals;
510 static constexpr std::array extra = {
511 "-prefix"sv, "-raw"sv, "-doublesize"sv, "-with-osd"sv, "-no-sprites"sv, "-guess-name"sv,
512 };
513 completeFileName(tokens, userFileContext(), extra);
514}
515
516
517// FpsInfoTopic
518
519Display::FpsInfoTopic::FpsInfoTopic(InfoCommand& openMSXInfoCommand)
520 : InfoTopic(openMSXInfoCommand, "fps")
521{
522}
523
524void Display::FpsInfoTopic::execute(std::span<const TclObject> /*tokens*/,
525 TclObject& result) const
526{
527 auto& display = OUTER(Display, fpsInfo);
528 result = 1000000.0f * Display::NUM_FRAME_DURATIONS / narrow_cast<float>(display.frameDurationSum);
529}
530
531string Display::FpsInfoTopic::help(std::span<const TclObject> /*tokens*/) const
532{
533 return "Returns the current rendering speed in frames per second.";
534}
535
536} // namespace openmsx
BaseSetting * setting
#define MIN_SCALE_FACTOR
Definition build-info.hh:18
#define PLATFORM_ANDROID
Definition build-info.hh:17
constexpr T & removeBack()
constexpr void addFront(const T &element)
void printWarning(std::string_view message)
Definition CliComm.cc:10
std::string getWindowTitle()
Definition Display.cc:212
void repaint()
Redraw the display.
Definition Display.cc:372
void repaintImpl()
Definition Display.cc:328
gl::ivec2 retrieveWindowPosition()
Definition Display.cc:248
void detach(VideoSystemChangeListener &listener)
Definition Display.cc:128
CliComm & getCliComm() const
Definition Display.cc:117
void storeWindowPosition(gl::ivec2 pos)
Definition Display.cc:243
void removeLayer(Layer &layer)
Definition Display.cc:396
VideoSystem & getVideoSystem()
Definition Display.cc:98
Display(Reactor &reactor)
Definition Display.cc:42
void attach(VideoSystemChangeListener &listener)
Definition Display.cc:122
void createVideoSystem()
Definition Display.cc:88
void repaintDelayed(uint64_t delta)
Definition Display.cc:379
void setWindowPosition(gl::ivec2 pos)
Definition Display.cc:237
Layer * findActiveLayer() const
Definition Display.cc:133
OutputSurface * getOutputSurface()
Definition Display.cc:104
gl::ivec2 getWindowPosition()
Get/set x,y coordinates of top-left window corner.
Definition Display.cc:229
void addLayer(Layer &layer)
Definition Display.cc:388
void unregisterEventListener(EventType type, EventListener &listener)
Unregisters a previously registered event listener.
void distributeEvent(Event &&event)
Schedule the given event for delivery.
void registerEventListener(EventType type, EventListener &listener, Priority priority=OTHER)
Registers a given object to receive certain events.
void storeWindowPosition(gl::ivec2 pos)
gl::ivec2 retrieveWindowPosition() const
int getInt() const noexcept
Interface for display layers.
Definition Layer.hh:12
@ COVER_FULL
Layer fully covers the screen: any underlying layers are invisible.
Definition Layer.hh:32
@ COVER_NONE
Layer is not visible, that is completely transparent.
Definition Layer.hh:39
void setDisplay(LayerListener &display_)
Store pointer to Display.
Definition Layer.hh:60
ZIndex getZ() const
Query the Z-index of this layer.
Definition Layer.hh:50
bool isActive() const
Definition Layer.hh:51
A frame buffer where pixels can be written to.
void scheduleRT(uint64_t delta)
Contains the main loop of openMSX.
Definition Reactor.hh:72
ImGuiManager & getImGuiManager()
Definition Reactor.hh:96
MSXMotherBoard * getMotherBoard() const
Definition Reactor.cc:409
CliComm & getCliComm()
Definition Reactor.cc:324
EventDistributor & getEventDistributor()
Definition Reactor.hh:86
RendererSetting & getRendererSetting()
The current renderer.
IntegerSetting & getScaleFactorSetting()
The current scaling factor.
RendererID getRenderer() const
void detach(Observer< T > &observer)
Definition Subject.hh:56
void attach(Observer< T > &observer)
Definition Subject.hh:50
static std::string full()
Definition Version.cc:8
static const bool RELEASE
Definition Version.hh:12
Video back-end system.
constexpr double e
Definition Math.hh:21
string parseCommandFileArgument(string_view argument, string_view directory, string_view prefix, string_view extension)
Helper function for parsing filename arguments in Tcl commands.
std::unique_ptr< VideoSystem > createVideoSystem(Reactor &reactor)
Create the video system required by the current renderer setting.
uint64_t getTime()
Get current (real) time in us.
Definition Timer.cc:7
This file implemented 3 utility functions:
Definition Autofire.cc:9
std::variant< KeyUpEvent, KeyDownEvent, MouseMotionEvent, MouseButtonUpEvent, MouseButtonDownEvent, MouseWheelEvent, JoystickAxisMotionEvent, JoystickHatEvent, JoystickButtonUpEvent, JoystickButtonDownEvent, OsdControlReleaseEvent, OsdControlPressEvent, WindowEvent, TextEvent, FileDropEvent, QuitEvent, FinishFrameEvent, CliCommandEvent, GroupEvent, BootEvent, FrameDrawnEvent, BreakEvent, SwitchRendererEvent, TakeReverseSnapshotEvent, AfterTimedEvent, MachineLoadedEvent, MachineActivatedEvent, MachineDeactivatedEvent, MidiInReaderEvent, MidiInWindowsEvent, MidiInCoreMidiEvent, MidiInCoreMidiVirtualEvent, MidiInALSAEvent, Rs232TesterEvent, ImGuiDelayedActionEvent, ImGuiActiveEvent > Event
Definition Event.hh:452
ArgsInfo valueArg(std::string_view name, T &value)
std::vector< TclObject > parseTclArgs(Interpreter &interp, std::span< const TclObject > inArgs, std::span< const ArgsInfo > table)
const FileContext & userFileContext()
ArgsInfo flagArg(std::string_view name, bool &flag)
auto find_if(InputRange &&range, UnaryPredicate pred)
Definition ranges.hh:173
#define ad_printf(...)
Definition openmsx.hh:11
#define OUTER(type, member)
Definition outer.hh:41
void move_pop_back(VECTOR &v, typename VECTOR::iterator it)
Erase the pointed to element from the given vector.
Definition stl.hh:134
auto rfind_unguarded(RANGE &range, const VAL &val, Proj proj={})
Similar to the find(_if)_unguarded functions above, but searches from the back to front.
Definition stl.hh:109
constexpr bool contains(ITER first, ITER last, const VAL &val)
Check if a range contains a given value, using linear search.
Definition stl.hh:32
std::string strCat()
Definition strCat.hh:703
void strAppend(std::string &result, Ts &&...ts)
Definition strCat.hh:752
#define UNREACHABLE
constexpr void repeat(T n, Op op)
Repeat the given operation 'op' 'n' times.
Definition xrange.hh:147
constexpr auto begin(const zstring_view &x)
constexpr auto end(const zstring_view &x)