openMSX
Display.cc
Go to the documentation of this file.
1 #include "Display.hh"
2 #include "RendererFactory.hh"
3 #include "Layer.hh"
4 #include "VideoSystem.hh"
5 #include "VideoLayer.hh"
6 #include "EventDistributor.hh"
7 #include "FinishFrameEvent.hh"
8 #include "FileOperations.hh"
9 #include "FileContext.hh"
10 #include "InputEvents.hh"
11 #include "CliComm.hh"
12 #include "Timer.hh"
13 #include "BooleanSetting.hh"
14 #include "IntegerSetting.hh"
15 #include "EnumSetting.hh"
16 #include "Reactor.hh"
17 #include "MSXMotherBoard.hh"
18 #include "HardwareConfig.hh"
19 #include "XMLElement.hh"
21 #include "CommandException.hh"
22 #include "StringOp.hh"
23 #include "Version.hh"
24 #include "build-info.hh"
25 #include "checked_cast.hh"
26 #include "outer.hh"
27 #include "stl.hh"
28 #include "unreachable.hh"
29 #include <algorithm>
30 #include <cassert>
31 
32 using std::string;
33 using std::vector;
34 
35 namespace openmsx {
36 
38  : RTSchedulable(reactor_.getRTScheduler())
39  , screenShotCmd(reactor_.getCommandController())
40  , fpsInfo(reactor_.getOpenMSXInfoCommand())
41  , osdGui(reactor_.getCommandController(), *this)
42  , reactor(reactor_)
43  , renderSettings(reactor.getCommandController())
44  , commandConsole(reactor.getGlobalCommandController(),
45  reactor.getEventDistributor(), *this)
46  , currentRenderer(RenderSettings::UNINITIALIZED)
47  , resolution(-1, -1)
48  , switchInProgress(false)
49 {
50  frameDurationSum = 0;
51  for (unsigned i = 0; i < NUM_FRAME_DURATIONS; ++i) {
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 #if PLATFORM_ANDROID
68  *this);
69 #endif
70  renderSettings.getRendererSetting().attach(*this);
71  renderSettings.getFullScreenSetting().attach(*this);
72  renderSettings.getScaleFactorSetting().attach(*this);
73  renderFrozen = false;
74 }
75 
77 {
78  renderSettings.getRendererSetting().detach(*this);
79  renderSettings.getFullScreenSetting().detach(*this);
80  renderSettings.getScaleFactorSetting().detach(*this);
81 
82  EventDistributor& eventDistributor = reactor.getEventDistributor();
83 #if PLATFORM_ANDROID
85  *this);
86 #endif
88  *this);
90  *this);
92  *this);
94  *this);
95 
96  resetVideoSystem();
97 
98  assert(listeners.empty());
99 }
100 
102 {
103  assert(!videoSystem);
104  assert(currentRenderer == RenderSettings::UNINITIALIZED);
105  assert(!switchInProgress);
106  currentRenderer = renderSettings.getRenderer();
107  switchInProgress = true;
108  doRendererSwitch();
109 }
110 
112 {
113  assert(videoSystem);
114  return *videoSystem;
115 }
116 
117 void Display::resetVideoSystem()
118 {
119  videoSystem.reset();
120  // At this point all layers expect for the Video9000 layer
121  // should be gone.
122  //assert(layers.empty());
123 }
124 
126 {
127  return reactor.getCliComm();
128 }
129 
131 {
132  assert(!contains(listeners, &listener));
133  listeners.push_back(&listener);
134 }
135 
137 {
138  move_pop_back(listeners, rfind_unguarded(listeners, &listener));
139 }
140 
142 {
143  for (auto& l : layers) {
144  if (l->getZ() == Layer::Z_MSX_ACTIVE) {
145  return l;
146  }
147  }
148  return nullptr;
149 }
150 
151 Display::Layers::iterator Display::baseLayer()
152 {
153  // Note: It is possible to cache this, but since the number of layers is
154  // low at the moment, it's not really worth it.
155  auto it = end(layers);
156  while (true) {
157  if (it == begin(layers)) {
158  // There should always be at least one opaque layer.
159  // TODO: This is not true for DummyVideoSystem.
160  // Anyway, a missing layer will probably stand out visually,
161  // so do we really have to assert on it?
162  //UNREACHABLE;
163  return it;
164  }
165  --it;
166  if ((*it)->getCoverage() == Layer::COVER_FULL) return it;
167  }
168 }
169 
170 void Display::executeRT()
171 {
172  repaint();
173 }
174 
175 int Display::signalEvent(const std::shared_ptr<const Event>& event)
176 {
177  if (event->getType() == OPENMSX_FINISH_FRAME_EVENT) {
178  auto& ffe = checked_cast<const FinishFrameEvent&>(*event);
179  if (ffe.needRender()) {
180  repaint();
182  std::make_shared<SimpleEvent>(
184  }
185  } else if (event->getType() == OPENMSX_SWITCH_RENDERER_EVENT) {
186  doRendererSwitch();
187  } else if (event->getType() == OPENMSX_MACHINE_LOADED_EVENT) {
188  videoSystem->updateWindowTitle();
189  } else if (event->getType() == OPENMSX_EXPOSE_EVENT) {
190  // Don't render too often, and certainly not when the screen
191  // will anyway soon be rendered.
192  repaintDelayed(100 * 1000); // 10fps
193  } else if (PLATFORM_ANDROID && event->getType() == OPENMSX_FOCUS_EVENT) {
194  // On Android, the rendering must be frozen when the app is sent to
195  // the background, because Android takes away all graphics resources
196  // from the app. It simply destroys the entire graphics context.
197  // Though, a repaint() must happen within the focus-lost event
198  // so that the SDL Android port realises that the graphix context
199  // is gone and will re-build it again on the first flush to the
200  // surface after the focus has been regained.
201 
202  // Perform a repaint before updating the renderFrozen flag:
203  // -When loosing the focus, this repaint will flush a last
204  // time the SDL surface, making sure that the Android SDL
205  // port discovers that the graphics context is gone.
206  // -When gaining the focus, this repaint does nothing as
207  // the renderFrozen flag is still false
208  repaint();
209  auto& focusEvent = checked_cast<const FocusEvent&>(*event);
210  ad_printf("Setting renderFrozen to %d", !focusEvent.getGain());
211  renderFrozen = !focusEvent.getGain();
212  }
213  return 0;
214 }
215 
217 {
218  string title = Version::full();
219  if (!Version::RELEASE) {
220  strAppend(title, " [", BUILD_FLAVOUR, ']');
221  }
222  if (MSXMotherBoard* motherboard = reactor.getMotherBoard()) {
223  if (const HardwareConfig* machine = motherboard->getMachineConfig()) {
224  const XMLElement& config = machine->getConfig();
225  strAppend(title, " - ",
226  config.getChild("info").getChildData("manufacturer"), ' ',
227  config.getChild("info").getChildData("code"));
228  }
229  }
230  return title;
231 }
232 
233 void Display::update(const Setting& setting)
234 {
235  if (&setting == &renderSettings.getRendererSetting()) {
236  checkRendererSwitch();
237  } else if (&setting == &renderSettings.getFullScreenSetting()) {
238  checkRendererSwitch();
239  } else if (&setting == &renderSettings.getScaleFactorSetting()) {
240  checkRendererSwitch();
241  } else {
242  UNREACHABLE;
243  }
244 }
245 
246 void Display::checkRendererSwitch()
247 {
248  if (switchInProgress) {
249  // This method only queues a request to switch renderer (see
250  // comments below why). If there already is such a request
251  // queued we don't need to do it again.
252  return;
253  }
254  auto newRenderer = renderSettings.getRenderer();
255  if ((newRenderer != currentRenderer) ||
256  !getVideoSystem().checkSettings()) {
257  currentRenderer = newRenderer;
258  // don't do the actualing swithing in the Tcl callback
259  // it seems creating and destroying Settings (= Tcl vars)
260  // causes problems???
261  switchInProgress = true;
263  std::make_shared<SimpleEvent>(
265  }
266 }
267 
268 void Display::doRendererSwitch()
269 {
270  assert(switchInProgress);
271 
272  bool success = false;
273  while (!success) {
274  try {
275  doRendererSwitch2();
276  success = true;
277  } catch (MSXException& e) {
278  auto& rendererSetting = renderSettings.getRendererSetting();
279  string errorMsg = strCat(
280  "Couldn't activate renderer ",
281  rendererSetting.getString(),
282  ": ", e.getMessage());
283  // now try some things that might work against this:
284  if (rendererSetting.getEnum() != RenderSettings::SDL) {
285  errorMsg += "\nTrying to switch to SDL renderer instead...";
286  rendererSetting.setEnum(RenderSettings::SDL);
287  currentRenderer = RenderSettings::SDL;
288  } else {
289  auto& scaleFactorSetting = renderSettings.getScaleFactorSetting();
290  unsigned curval = scaleFactorSetting.getInt();
291  if (curval == 1) {
292  throw MSXException(
293  e.getMessage(),
294  " (and I have no other ideas to try...)"); // give up and die... :(
295  }
296  strAppend(errorMsg, "\nTrying to decrease scale_factor setting from ",
297  curval, " to ", curval - 1, "...");
298  scaleFactorSetting.setInt(curval - 1);
299  }
300  getCliComm().printWarning(errorMsg);
301  }
302  }
303 
304  switchInProgress = false;
305 }
306 
307 void 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  repaint(*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 
353 {
354  for (auto it = baseLayer(); it != end(layers); ++it) {
355  if ((*it)->getCoverage() != Layer::COVER_NONE) {
356  (*it)->paint(surface);
357  }
358  }
359 }
360 
361 void Display::repaintDelayed(uint64_t delta)
362 {
363  if (isPendingRT()) {
364  // already a pending repaint
365  return;
366  }
367  scheduleRT(unsigned(delta));
368 }
369 
371 {
372  int z = layer.getZ();
373  auto it = find_if(begin(layers), end(layers),
374  [&](Layer* l) { return l->getZ() > z; });
375  layers.insert(it, &layer);
376  layer.setDisplay(*this);
377 }
378 
380 {
381  layers.erase(rfind_unguarded(layers, &layer));
382 }
383 
384 void Display::updateZ(Layer& layer)
385 {
386  // Remove at old Z-index...
387  removeLayer(layer);
388  // ...and re-insert at new Z-index.
389  addLayer(layer);
390 }
391 
392 
393 // ScreenShotCmd
394 
395 Display::ScreenShotCmd::ScreenShotCmd(CommandController& commandController_)
396  : Command(commandController_, "screenshot")
397 {
398 }
399 
400 void Display::ScreenShotCmd::execute(array_ref<TclObject> tokens, TclObject& result)
401 {
402  auto& display = OUTER(Display, screenShotCmd);
403  bool rawShot = false;
404  bool withOsd = false;
405  bool doubleSize = false;
406  string_view prefix = "openmsx";
407  vector<TclObject> arguments;
408  for (unsigned i = 1; i < tokens.size(); ++i) {
409  string_view tok = tokens[i].getString();
410  if (StringOp::startsWith(tok, '-')) {
411  if (tok == "--") {
412  arguments.insert(end(arguments),
413  std::begin(tokens) + i + 1, std::end(tokens));
414  break;
415  }
416  if (tok == "-prefix") {
417  if (++i == tokens.size()) {
418  throw CommandException("Missing argument");
419  }
420  prefix = tokens[i].getString();
421  } else if (tok == "-raw") {
422  rawShot = true;
423  } else if (tok == "-msxonly") {
424  display.getCliComm().printWarning(
425  "The -msxonly option has been deprecated and will "
426  "be removed in a future release. Instead, use the "
427  "-raw option for the same effect.");
428  rawShot = true;
429  } else if (tok == "-doublesize") {
430  doubleSize = true;
431  } else if (tok == "-with-osd") {
432  withOsd = true;
433  } else {
434  throw CommandException("Invalid option: ", tok);
435  }
436  } else {
437  arguments.push_back(tokens[i]);
438  }
439  }
440  if (doubleSize && !rawShot) {
441  throw CommandException("-doublesize option can only be used in "
442  "combination with -raw");
443  }
444  if (rawShot && withOsd) {
445  throw CommandException("-with-osd cannot be used in "
446  "combination with -raw");
447  }
448 
449  string_view fname;
450  switch (arguments.size()) {
451  case 0:
452  // nothing
453  break;
454  case 1:
455  fname = arguments[0].getString();
456  break;
457  default:
458  throw SyntaxError();
459  }
461  fname, "screenshots", prefix, ".png");
462 
463  if (!rawShot) {
464  // include all layers (OSD stuff, console)
465  try {
466  display.getVideoSystem().takeScreenShot(filename, withOsd);
467  } catch (MSXException& e) {
468  throw CommandException(
469  "Failed to take screenshot: ", e.getMessage());
470  }
471  } else {
472  auto videoLayer = dynamic_cast<VideoLayer*>(
473  display.findActiveLayer());
474  if (!videoLayer) {
475  throw CommandException(
476  "Current renderer doesn't support taking screenshots.");
477  }
478  unsigned height = doubleSize ? 480 : 240;
479  try {
480  videoLayer->takeRawScreenShot(height, filename);
481  } catch (MSXException& e) {
482  throw CommandException(
483  "Failed to take screenshot: ", e.getMessage());
484  }
485  }
486 
487  display.getCliComm().printInfo("Screen saved to ", filename);
488  result.setString(filename);
489 }
490 
491 string Display::ScreenShotCmd::help(const vector<string>& /*tokens*/) const
492 {
493  // Note: -no-sprites option is implemented in Tcl
494  return "screenshot Write screenshot to file \"openmsxNNNN.png\"\n"
495  "screenshot <filename> Write screenshot to indicated file\n"
496  "screenshot -prefix foo Write screenshot to file \"fooNNNN.png\"\n"
497  "screenshot -raw 320x240 raw screenshot (of MSX screen only)\n"
498  "screenshot -raw -doublesize 640x480 raw screenshot (of MSX screen only)\n"
499  "screenshot -with-osd Include OSD elements in the screenshot\n"
500  "screenshot -no-sprites Don't include sprites in the screenshot\n";
501 }
502 
503 void Display::ScreenShotCmd::tabCompletion(vector<string>& tokens) const
504 {
505  static const char* const extra[] = {
506  "-prefix", "-raw", "-doublesize", "-with-osd", "-no-sprites",
507  };
508  completeFileName(tokens, userFileContext(), extra);
509 }
510 
511 
512 // FpsInfoTopic
513 
514 Display::FpsInfoTopic::FpsInfoTopic(InfoCommand& openMSXInfoCommand)
515  : InfoTopic(openMSXInfoCommand, "fps")
516 {
517 }
518 
519 void Display::FpsInfoTopic::execute(array_ref<TclObject> /*tokens*/,
520  TclObject& result) const
521 {
522  auto& display = OUTER(Display, fpsInfo);
523  float fps = 1000000.0f * Display::NUM_FRAME_DURATIONS / display.frameDurationSum;
524  result.setDouble(fps);
525 }
526 
527 string Display::FpsInfoTopic::help(const vector<string>& /*tokens*/) const
528 {
529  return "Returns the current rendering speed in frames per second.";
530 }
531 
532 } // namespace openmsx
void setDouble(double value)
Definition: TclObject.cc:47
void setDisplay(LayerListener &display_)
Store pointer to Display.
Definition: Layer.hh:59
Contains the main loop of openMSX.
Definition: Reactor.hh:63
Sent when a OPENMSX_FINISH_FRAME_EVENT caused a redraw of the screen.
Definition: Event.hh:36
void createVideoSystem()
Definition: Display.cc:101
string_view::const_iterator begin(const string_view &x)
Definition: string_view.hh:152
Layer is not visible, that is completely transparent.
Definition: Layer.hh:39
Represents the output window/screen of openMSX.
Definition: Display.hh:32
std::string getWindowTitle()
Definition: Display.cc:216
Send when a (new) machine configuration is loaded.
Definition: Event.hh:51
string parseCommandFileArgument(string_view argument, string_view directory, string_view prefix, string_view extension)
Helper function for parsing filename arguments in Tcl commands.
void registerEventListener(EventType type, EventListener &listener, Priority priority=OTHER)
Registers a given object to receive certain events.
void addLayer(Layer &layer)
Definition: Display.cc:370
void unregisterEventListener(EventType type, EventListener &listener)
Unregisters a previously registered event listener.
Interface for display layers.
Definition: Layer.hh:11
Display(Reactor &reactor)
Definition: Display.cc:37
Layer fully covers the screen: any underlying layers are invisible.
Definition: Layer.hh:32
bool contains(ITER first, ITER last, const VAL &val)
Check if a range contains a given value, using linear search.
Definition: stl.hh:102
bool startsWith(string_view total, string_view part)
Definition: StringOp.cc:71
void distributeEvent(const EventPtr &event)
Schedule the given event for delivery.
A frame buffer where pixels can be written to.
unique_ptr< VideoSystem > createVideoSystem(Reactor &reactor)
Create the video system required by the current renderer setting.
void move_pop_back(VECTOR &v, typename VECTOR::iterator it)
Erase the pointed to element from the given vector.
Definition: stl.hh:192
CliComm & getCliComm() const
Definition: Display.cc:125
#define PLATFORM_ANDROID
Definition: build-info.hh:18
static const bool RELEASE
Definition: Version.hh:12
EventDistributor & getEventDistributor()
Definition: Reactor.hh:78
MSXMotherBoard * getMotherBoard() const
Definition: Reactor.cc:335
VideoSystem & getVideoSystem()
Definition: Display.cc:111
void strAppend(std::string &result, Ts &&...ts)
Definition: strCat.hh:648
const std::string & getMessage() const
Definition: MSXException.hh:23
void attach(Observer< T > &observer)
Definition: Subject.hh:52
void repaint()
Redraw the display.
Definition: Display.cc:321
bool isPendingRT() const
FileContext userFileContext(string_view savePath)
Definition: FileContext.cc:161
Sent when VDP (V99x8 or V9990) reaches the end of a frame.
Definition: Event.hh:30
void removeLayer(Layer &layer)
Definition: Display.cc:379
auto rfind_unguarded(RANGE &range, const VAL &val) -> decltype(std::begin(range))
Similar to the find(_if)_unguarded functions above, but searches from the back to front...
Definition: stl.hh:164
This class implements a subset of the proposal for std::array_ref (proposed for the next c++ standard...
Definition: array_ref.hh:19
void detach(VideoSystemChangeListener &listener)
Definition: Display.cc:136
RendererSetting & getRendererSetting()
The current renderer.
string_view::const_iterator end(const string_view &x)
Definition: string_view.hh:153
Layer * findActiveLayer() const
Definition: Display.cc:141
Video back-end system.
Definition: VideoSystem.hh:20
void repaintDelayed(uint64_t delta)
Definition: Display.cc:361
Thanks to enen for testing this on a real cartridge:
Definition: Autofire.cc:5
const std::string & getChildData(string_view name) const
Definition: XMLElement.cc:192
Send when (part of) the openMSX window gets exposed, and thus should be repainted.
Definition: Event.hh:60
void setString(string_view value)
Definition: TclObject.cc:14
ZIndex getZ() const
Query the Z-index of this layer.
Definition: Layer.hh:50
void scheduleRT(uint64_t delta)
size_type size() const
Definition: array_ref.hh:61
This class implements a (close approximation) of the std::string_view class.
Definition: string_view.hh:15
void attach(VideoSystemChangeListener &listener)
Definition: Display.cc:130
RendererID getRenderer() const
Class containing all settings for renderers.
void detach(Observer< T > &observer)
Definition: Subject.hh:58
static std::string full()
Definition: Version.cc:8
CliComm & getCliComm()
Definition: Reactor.cc:272
BooleanSetting & getFullScreenSetting()
Full screen [on, off].
std::string strCat(Ts &&...ts)
Definition: strCat.hh:577
uint64_t getTime()
Get current (real) time in us.
Definition: Timer.cc:8
#define OUTER(type, member)
Definition: outer.hh:38
void addFront(const T &element)
const XMLElement & getChild(string_view name) const
Definition: XMLElement.cc:166
void printWarning(string_view message)
Definition: CliComm.cc:20
#define ad_printf(...)
Definition: openmsx.hh:11
IntegerSetting & getScaleFactorSetting()
The current scaling factor.
This event is send when a device (v99x8, v9990, video9000, laserdisc) reaches the end of a frame...
#define UNREACHABLE
Definition: unreachable.hh:35