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