openMSX
PostProcessor.cc
Go to the documentation of this file.
1#include "PostProcessor.hh"
2
3#include "AviRecorder.hh"
4#include "CliComm.hh"
5#include "CommandException.hh"
6#include "Deflicker.hh"
8#include "Display.hh"
9#include "DoubledFrame.hh"
10#include "Event.hh"
11#include "EventDistributor.hh"
12#include "FloatSetting.hh"
13#include "GLContext.hh"
14#include "GLScaler.hh"
15#include "GLScalerFactory.hh"
16#include "MSXMotherBoard.hh"
17#include "OutputSurface.hh"
18#include "PNG.hh"
19#include "RawFrame.hh"
20#include "Reactor.hh"
21#include "RenderSettings.hh"
22#include "SuperImposedFrame.hh"
23#include "gl_transform.hh"
24
25#include "MemBuffer.hh"
26#include "aligned.hh"
27#include "narrow.hh"
28#include "random.hh"
29#include "ranges.hh"
30#include "stl.hh"
31#include "vla.hh"
32#include "xrange.hh"
33
34#include <algorithm>
35#include <cassert>
36#include <cstdint>
37#include <memory>
38#include <numeric>
39
40using namespace gl;
41
42namespace openmsx {
43
45 MSXMotherBoard& motherBoard_, Display& display_,
46 OutputSurface& screen_, const std::string& videoSource,
47 unsigned maxWidth_, unsigned height_, bool canDoInterlace_)
48 : VideoLayer(motherBoard_, videoSource)
49 , Schedulable(motherBoard_.getScheduler())
50 , display(display_)
51 , renderSettings(display_.getRenderSettings())
52 , eventDistributor(motherBoard_.getReactor().getEventDistributor())
53 , screen(screen_)
54 , maxWidth(maxWidth_)
55 , height(height_)
56 , canDoInterlace(canDoInterlace_)
57 , lastRotate(motherBoard_.getCurrentTime())
58{
59 if (canDoInterlace) {
60 deinterlacedFrame = std::make_unique<DeinterlacedFrame>();
61 interlacedFrame = std::make_unique<DoubledFrame>();
62 deflicker = std::make_unique<Deflicker>(lastFrames);
63 superImposedFrame = std::make_unique<SuperImposedFrame>();
64 } else {
65 // Laserdisc always produces non-interlaced frames, so we don't
66 // need lastFrames[1..3], deinterlacedFrame and
67 // interlacedFrame. Also it produces a complete frame at a
68 // time, so we don't need lastFrames[0] (and have a separate
69 // work buffer, for partially rendered frames).
70 }
71
72 preCalcNoise(renderSettings.getNoise());
73 initBuffers();
74
75 VertexShader vertexShader ("monitor3D.vert");
76 FragmentShader fragmentShader("monitor3D.frag");
77 monitor3DProg.attach(vertexShader);
78 monitor3DProg.attach(fragmentShader);
79 monitor3DProg.bindAttribLocation(0, "a_position");
80 monitor3DProg.bindAttribLocation(1, "a_normal");
81 monitor3DProg.bindAttribLocation(2, "a_texCoord");
82 monitor3DProg.link();
83 preCalcMonitor3D(renderSettings.getHorizontalStretch());
84
85 renderSettings.getNoiseSetting().attach(*this);
86 renderSettings.getHorizontalStretchSetting().attach(*this);
87}
88
90{
91 renderSettings.getHorizontalStretchSetting().detach(*this);
92 renderSettings.getNoiseSetting().detach(*this);
93
94 if (recorder) {
96 "Video recording stopped, because you "
97 "changed machine or changed a video setting "
98 "during recording.");
99 recorder->stop();
100 }
101}
102
103void PostProcessor::initBuffers()
104{
105 // combined positions and texture coordinates
106 static constexpr std::array pos_tex = {
107 vec2(-1, 1), vec2(-1,-1), vec2( 1,-1), vec2( 1, 1), // pos
108 vec2( 0, 1), vec2( 0, 0), vec2( 1, 0), vec2( 1, 1), // tex
109 };
110 glBindBuffer(GL_ARRAY_BUFFER, vbo.get());
111 glBufferData(GL_ARRAY_BUFFER, sizeof(pos_tex), pos_tex.data(), GL_STATIC_DRAW);
112 glBindBuffer(GL_ARRAY_BUFFER, 0);
113}
114
116{
117 return display.getCliComm();
118}
119
120unsigned PostProcessor::getLineWidth(
121 FrameSource* frame, unsigned y, unsigned step)
122{
123 return max_value(xrange(step), [&](auto i) { return frame->getLineWidth(y + i); });
124}
125
126void PostProcessor::executeUntil(EmuTime::param /*time*/)
127{
128 // insert fake end of frame event
129 eventDistributor.distributeEvent(FinishFrameEvent(
131}
132
133using WorkBuffer = std::vector<MemBuffer<FrameSource::Pixel, SSE_ALIGNMENT>>;
134static void getScaledFrame(const FrameSource& paintFrame,
135 std::span<const FrameSource::Pixel*> lines,
136 WorkBuffer& workBuffer)
137{
138 auto height = narrow<unsigned>(lines.size());
139 unsigned width = (height == 240) ? 320 : 640;
140 const FrameSource::Pixel* linePtr = nullptr;
141 FrameSource::Pixel* work = nullptr;
142 for (auto i : xrange(height)) {
143 if (linePtr == work) {
144 // If work buffer was used in previous iteration,
145 // then allocate a new one.
146 work = workBuffer.emplace_back(width).data();
147 }
148 if (height == 240) {
149 auto line = paintFrame.getLinePtr320_240(i, std::span<uint32_t, 320>{work, 320});
150 linePtr = line.data();
151 } else {
152 assert (height == 480);
153 auto line = paintFrame.getLinePtr640_480(i, std::span<uint32_t, 640>{work, 640});
154 linePtr = line.data();
155 }
156 lines[i] = linePtr;
157 }
158}
159
160void PostProcessor::takeRawScreenShot(unsigned height2, const std::string& filename)
161{
162 if (!paintFrame) {
163 throw CommandException("TODO");
164 }
165
166 VLA(const FrameSource::Pixel*, lines, height2);
167 WorkBuffer workBuffer;
168 getScaledFrame(*paintFrame, lines, workBuffer);
169 unsigned width = (height2 == 240) ? 320 : 640;
170 PNG::saveRGBA(width, lines, filename);
171}
172
173void PostProcessor::createRegions()
174{
175 regions.clear();
176
177 const unsigned srcHeight = paintFrame->getHeight();
178 const unsigned dstHeight = screen.getLogicalHeight();
179
180 unsigned g = std::gcd(srcHeight, dstHeight);
181 unsigned srcStep = srcHeight / g;
182 unsigned dstStep = dstHeight / g;
183
184 // TODO: Store all MSX lines in RawFrame and only scale the ones that fit
185 // on the PC screen, as a preparation for resizable output window.
186 unsigned srcStartY = 0;
187 unsigned dstStartY = 0;
188 while (dstStartY < dstHeight) {
189 // Currently this is true because the source frame height
190 // is always >= dstHeight/(dstStep/srcStep).
191 assert(srcStartY < srcHeight);
192
193 // get region with equal lineWidth
194 unsigned lineWidth = getLineWidth(paintFrame, srcStartY, srcStep);
195 unsigned srcEndY = srcStartY + srcStep;
196 unsigned dstEndY = dstStartY + dstStep;
197 while ((srcEndY < srcHeight) && (dstEndY < dstHeight) &&
198 (getLineWidth(paintFrame, srcEndY, srcStep) == lineWidth)) {
199 srcEndY += srcStep;
200 dstEndY += dstStep;
201 }
202
203 regions.emplace_back(srcStartY, srcEndY,
204 dstStartY, dstEndY,
205 lineWidth);
206
207 // next region
208 srcStartY = srcEndY;
209 dstStartY = dstEndY;
210 }
211}
212
214{
215 if (renderSettings.getInterleaveBlackFrame()) {
216 interleaveCount ^= 1;
217 if (interleaveCount) {
218 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
219 glClear(GL_COLOR_BUFFER_BIT);
220 return;
221 }
222 }
223
224 auto deform = renderSettings.getDisplayDeform();
225 float horStretch = renderSettings.getHorizontalStretch();
226 int glow = renderSettings.getGlow();
227
228 if ((screen.getViewOffset() != ivec2()) || // any part of the screen not covered by the viewport?
229 (deform == RenderSettings::DisplayDeform::_3D) || !paintFrame) {
230 glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
231 glClear(GL_COLOR_BUFFER_BIT);
232 if (!paintFrame) {
233 return;
234 }
235 }
236
237 // New scaler algorithm selected?
238 if (auto algo = renderSettings.getScaleAlgorithm();
239 scaleAlgorithm != algo) {
240 scaleAlgorithm = algo;
241 currScaler = GLScalerFactory::createScaler(renderSettings);
242
243 // Re-upload frame data, this is both
244 // - Chunks of RawFrame with a specific line width, possibly
245 // with some extra lines above and below each chunk that are
246 // also converted to this line width.
247 // - Extra data that is specific for the scaler (ATM only the
248 // hq and hqlite scalers require this).
249 // Re-uploading the first is not strictly needed. But switching
250 // scalers doesn't happen that often, so it also doesn't hurt
251 // and it keeps the code simpler.
252 uploadFrame();
253 }
254
255 auto size = screen.getLogicalSize();
256 glViewport(0, 0, size.x, size.y);
257 glBindTexture(GL_TEXTURE_2D, 0);
258 auto& renderedFrame = renderedFrames[frameCounter & 1];
259 if (renderedFrame.size != size) {
260 renderedFrame.tex.bind();
261 renderedFrame.tex.setInterpolation(true);
262 glTexImage2D(GL_TEXTURE_2D, // target
263 0, // level
264 GL_RGB, // internal format
265 size.x, // width
266 size.y, // height
267 0, // border
268 GL_RGB, // format
269 GL_UNSIGNED_BYTE, // type
270 nullptr); // data
271 renderedFrame.fbo = FrameBufferObject(renderedFrame.tex);
272 }
273 renderedFrame.fbo.push();
274
275 for (const auto& r : regions) {
276 auto it = find_unguarded(textures, r.lineWidth, &TextureData::width);
277 auto* superImpose = superImposeVideoFrame
278 ? &superImposeTex : nullptr;
279 currScaler->scaleImage(
280 it->tex, superImpose,
281 r.srcStartY, r.srcEndY, r.lineWidth, // src
282 r.dstStartY, r.dstEndY, size.x, // dst
283 paintFrame->getHeight()); // dst
284 }
285
286 drawNoise();
287 drawGlow(glow);
288
289 renderedFrame.fbo.pop();
290 renderedFrame.tex.bind();
291 auto [x, y] = screen.getViewOffset();
292 auto [w, h] = screen.getViewSize();
293 glViewport(x, y, w, h);
294
296 drawMonitor3D();
297 } else {
298 float x1 = (320.0f - float(horStretch)) * (1.0f / (2.0f * 320.0f));
299 float x2 = 1.0f - x1;
300 std::array tex = {
301 vec2(x1, 1), vec2(x1, 0), vec2(x2, 0), vec2(x2, 1)
302 };
303
304 const auto& glContext = *gl::context;
305 glContext.progTex.activate();
306 glUniform4f(glContext.unifTexColor,
307 1.0f, 1.0f, 1.0f, 1.0f);
308 mat4 I;
309 glUniformMatrix4fv(glContext.unifTexMvp, 1, GL_FALSE, I.data());
310
311 glBindBuffer(GL_ARRAY_BUFFER, vbo.get());
312 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
313 glEnableVertexAttribArray(0);
314
315 glBindBuffer(GL_ARRAY_BUFFER, stretchVBO.get());
316 glBufferData(GL_ARRAY_BUFFER, sizeof(tex), tex.data(), GL_STREAM_DRAW);
317 glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, nullptr);
318 glEnableVertexAttribArray(1);
319
320 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
321
322 glDisableVertexAttribArray(1);
323 glDisableVertexAttribArray(0);
324 glBindBuffer(GL_ARRAY_BUFFER, 0);
325 }
326 storedFrame = true;
327 //gl::checkGLError("PostProcessor::paint");
328}
329
330std::unique_ptr<RawFrame> PostProcessor::rotateFrames(
331 std::unique_ptr<RawFrame> finishedFrame, EmuTime::param time)
332{
333 if (renderSettings.getInterleaveBlackFrame()) {
334 auto delta = time - lastRotate; // time between last two calls
335 auto middle = time + delta / 2; // estimate for middle between now
336 // and next call
337 setSyncPoint(middle);
338 }
339 lastRotate = time;
340
341 // Figure out how many past frames we want to use.
342 int numRequired = 1;
343 bool doDeinterlace = false;
344 bool doInterlace = false;
345 bool doDeflicker = false;
346 auto currType = finishedFrame->getField();
347 if (canDoInterlace) {
349 if (renderSettings.getDeinterlace()) {
350 doDeinterlace = true;
351 numRequired = 2;
352 } else {
353 doInterlace = true;
354 }
355 } else if (renderSettings.getDeflicker()) {
356 doDeflicker = true;
357 numRequired = 4;
358 }
359 }
360
361 // Which frame can be returned (recycled) to caller. Prefer to return
362 // the youngest frame to improve cache locality.
363 int recycleIdx = (lastFramesCount < numRequired)
364 ? lastFramesCount++ // store one more
365 : (numRequired - 1); // youngest that's no longer needed
366 assert(recycleIdx < 4);
367 auto recycleFrame = std::move(lastFrames[recycleIdx]); // might be nullptr
368
369 // Insert new frame in front of lastFrames[], shift older frames
370 std::move_backward(&lastFrames[0], &lastFrames[recycleIdx],
371 &lastFrames[recycleIdx + 1]);
372 lastFrames[0] = std::move(finishedFrame);
373
374 // Are enough frames available?
375 if (lastFramesCount >= numRequired) {
376 // Only the last 'numRequired' are kept up to date.
377 lastFramesCount = numRequired;
378 } else {
379 // Not enough past frames, fall back to 'regular' rendering.
380 // This situation can only occur when:
381 // - The very first frame we render needs to be deinterlaced.
382 // In other case we have at least one valid frame from the
383 // past plus one new frame passed via the 'finishedFrame'
384 // parameter.
385 // - Or when (re)enabling the deflicker setting. Typically only
386 // 1 frame in lastFrames[] is kept up-to-date (and we're
387 // given 1 new frame), so it can take up-to 2 frame after
388 // enabling deflicker before it actually takes effect.
389 doDeinterlace = false;
390 doInterlace = false;
391 doDeflicker = false;
392 }
393
394 // Setup the to-be-painted frame
395 if (doDeinterlace) {
396 if (currType == FrameSource::FieldType::ODD) {
397 deinterlacedFrame->init(lastFrames[1].get(), lastFrames[0].get());
398 } else {
399 deinterlacedFrame->init(lastFrames[0].get(), lastFrames[1].get());
400 }
401 paintFrame = deinterlacedFrame.get();
402 } else if (doInterlace) {
403 interlacedFrame->init(
404 lastFrames[0].get(),
405 (currType == FrameSource::FieldType::ODD) ? 1 : 0);
406 paintFrame = interlacedFrame.get();
407 } else if (doDeflicker) {
408 deflicker->init();
409 paintFrame = deflicker.get();
410 } else {
411 paintFrame = lastFrames[0].get();
412 }
413 if (superImposeVdpFrame) {
414 superImposedFrame->init(paintFrame, superImposeVdpFrame);
415 paintFrame = superImposedFrame.get();
416 }
417
418 // Possibly record this frame
419 if (recorder && needRecord()) {
420 try {
421 recorder->addImage(paintFrame, time);
422 } catch (MSXException& e) {
424 "Recording stopped with error: ",
425 e.getMessage());
426 recorder->stop();
427 assert(!recorder);
428 }
429 }
430
431 // Return recycled frame to the caller
432 std::unique_ptr<RawFrame> reuseFrame = [&] {
433 if (canDoInterlace) {
434 if (!recycleFrame) [[unlikely]] {
435 recycleFrame = std::make_unique<RawFrame>(maxWidth, height);
436 }
437 return std::move(recycleFrame);
438 } else {
439 return std::move(lastFrames[0]);
440 }
441 }();
442
443 uploadFrame();
444 ++frameCounter;
445 noiseX = random_float(0.0f, 1.0f);
446 noiseY = random_float(0.0f, 1.0f);
447 return reuseFrame;
448}
449
450void PostProcessor::update(const Setting& setting) noexcept
451{
453 const auto& noiseSetting = renderSettings.getNoiseSetting();
454 const auto& horizontalStretch = renderSettings.getHorizontalStretchSetting();
455 if (&setting == &noiseSetting) {
456 preCalcNoise(noiseSetting.getFloat());
457 } else if (&setting == &horizontalStretch) {
458 preCalcMonitor3D(horizontalStretch.getFloat());
459 }
460}
461
462void PostProcessor::uploadFrame()
463{
464 createRegions();
465
466 const unsigned srcHeight = paintFrame->getHeight();
467 for (const auto& r : regions) {
468 // upload data
469 // TODO get before/after data from scaler
470 int before = 1;
471 unsigned after = 1;
472 uploadBlock(narrow<unsigned>(std::max(0, narrow<int>(r.srcStartY) - before)),
473 std::min(srcHeight, r.srcEndY + after),
474 r.lineWidth);
475 }
476
477 if (superImposeVideoFrame) {
478 int w = narrow<GLsizei>(superImposeVideoFrame->getWidth());
479 int h = narrow<GLsizei>(superImposeVideoFrame->getHeight());
480 if (superImposeTex.getWidth() != w ||
481 superImposeTex.getHeight() != h) {
482 superImposeTex.resize(w, h);
483 superImposeTex.setInterpolation(true);
484 }
485 superImposeTex.bind();
486 glTexSubImage2D(
487 GL_TEXTURE_2D, // target
488 0, // level
489 0, // offset x
490 0, // offset y
491 w, // width
492 h, // height
493 GL_RGBA, // format
494 GL_UNSIGNED_BYTE, // type
495 const_cast<RawFrame*>(superImposeVideoFrame)->getLineDirect(0).data()); // data
496 }
497}
498
499void PostProcessor::uploadBlock(
500 unsigned srcStartY, unsigned srcEndY, unsigned lineWidth)
501{
502 // create texture/pbo if needed
503 auto it = ranges::find(textures, lineWidth, &TextureData::width);
504 if (it == end(textures)) {
505 TextureData textureData;
506
507 textureData.tex.resize(narrow<GLsizei>(lineWidth),
508 narrow<GLsizei>(height * 2)); // *2 for interlace
509 textureData.pbo.setImage(lineWidth, height * 2);
510 textures.push_back(std::move(textureData));
511 it = end(textures) - 1;
512 }
513 auto& tex = it->tex;
514 auto& pbo = it->pbo;
515
516 // bind texture
517 tex.bind();
518
519 // upload data
520 pbo.bind();
521 uint32_t* mapped = pbo.mapWrite();
522 for (auto y : xrange(srcStartY, srcEndY)) {
523 auto* dest = mapped + y * size_t(lineWidth);
524 auto line = paintFrame->getLine(narrow<int>(y), std::span{dest, lineWidth});
525 if (line.data() != dest) {
526 ranges::copy(line, dest);
527 }
528 }
529 pbo.unmap();
530#if defined(__APPLE__)
531 // The nVidia GL driver for the GeForce 8000/9000 series seems to hang
532 // on texture data replacements that are 1 pixel wide and start on a
533 // line number that is a non-zero multiple of 16.
534 if (lineWidth == 1 && srcStartY != 0 && srcStartY % 16 == 0) {
535 srcStartY--;
536 }
537#endif
538 glTexSubImage2D(
539 GL_TEXTURE_2D, // target
540 0, // level
541 0, // offset x
542 narrow<GLint>(srcStartY), // offset y
543 narrow<GLint>(lineWidth), // width
544 narrow<GLint>(srcEndY - srcStartY), // height
545 GL_RGBA, // format
546 GL_UNSIGNED_BYTE, // type
547 pbo.getOffset(0, srcStartY)); // data
548 pbo.unbind();
549
550 // possibly upload scaler specific data
551 if (currScaler) {
552 currScaler->uploadBlock(srcStartY, srcEndY, lineWidth, *paintFrame);
553 }
554}
555
556void PostProcessor::drawGlow(int glow)
557{
558 if ((glow == 0) || !storedFrame) return;
559
560 const auto& glContext = *gl::context;
561 glContext.progTex.activate();
562 glEnable(GL_BLEND);
563 glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
564 renderedFrames[(frameCounter & 1) ^ 1].tex.bind();
565 glUniform4f(glContext.unifTexColor,
566 1.0f, 1.0f, 1.0f, narrow<float>(glow) * (31.0f / 3200.0f));
567 mat4 I;
568 glUniformMatrix4fv(glContext.unifTexMvp, 1, GL_FALSE, I.data());
569
570 glBindBuffer(GL_ARRAY_BUFFER, vbo.get());
571
572 const vec2* offset = nullptr;
573 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, offset); // pos
574 offset += 4; // see initBuffers()
575 glEnableVertexAttribArray(0);
576
577 glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, offset); // tex
578 glEnableVertexAttribArray(1);
579
580 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
581
582 glDisableVertexAttribArray(1);
583 glDisableVertexAttribArray(0);
584 glBindBuffer(GL_ARRAY_BUFFER, 0);
585 glDisable(GL_BLEND);
586}
587
588void PostProcessor::preCalcNoise(float factor)
589{
590 std::array<uint8_t, 256 * 256> buf1;
591 std::array<uint8_t, 256 * 256> buf2;
592 auto& generator = global_urng(); // fast (non-cryptographic) random numbers
593 std::normal_distribution<float> distribution(0.0f, 1.0f);
594 for (auto i : xrange(256 * 256)) {
595 float r = distribution(generator);
596 int s = std::clamp(int(roundf(r * factor)), -255, 255);
597 buf1[i] = narrow<uint8_t>((s > 0) ? s : 0);
598 buf2[i] = narrow<uint8_t>((s < 0) ? -s : 0);
599 }
600
601 // GL_LUMINANCE is no longer supported in newer openGL versions
602 auto format = (OPENGL_VERSION >= OPENGL_3_3) ? GL_RED : GL_LUMINANCE;
603 noiseTextureA.bind();
604 glTexImage2D(
605 GL_TEXTURE_2D, // target
606 0, // level
607 format, // internal format
608 256, // width
609 256, // height
610 0, // border
611 format, // format
612 GL_UNSIGNED_BYTE, // type
613 buf1.data()); // data
614#if OPENGL_VERSION >= OPENGL_3_3
615 GLint swizzleMask1[] = {GL_RED, GL_RED, GL_RED, GL_ONE};
616 glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask1);
617#endif
618
619 noiseTextureB.bind();
620 glTexImage2D(
621 GL_TEXTURE_2D, // target
622 0, // level
623 format, // internal format
624 256, // width
625 256, // height
626 0, // border
627 format, // format
628 GL_UNSIGNED_BYTE, // type
629 buf2.data()); // data
630#if OPENGL_VERSION >= OPENGL_3_3
631 GLint swizzleMask2[] = {GL_RED, GL_RED, GL_RED, GL_ONE};
632 glTexParameteriv(GL_TEXTURE_2D, GL_TEXTURE_SWIZZLE_RGBA, swizzleMask2);
633#endif
634}
635
636void PostProcessor::drawNoise() const
637{
638 if (renderSettings.getNoise() == 0.0f) return;
639
640 // Rotate and mirror noise texture in consecutive frames to avoid
641 // seeing 'patterns' in the noise.
642 static constexpr std::array pos = {
643 std::array{vec2{-1, -1}, vec2{ 1, -1}, vec2{ 1, 1}, vec2{-1, 1}},
644 std::array{vec2{-1, 1}, vec2{ 1, 1}, vec2{ 1, -1}, vec2{-1, -1}},
645 std::array{vec2{-1, 1}, vec2{-1, -1}, vec2{ 1, -1}, vec2{ 1, 1}},
646 std::array{vec2{ 1, 1}, vec2{ 1, -1}, vec2{-1, -1}, vec2{-1, 1}},
647 std::array{vec2{ 1, 1}, vec2{-1, 1}, vec2{-1, -1}, vec2{ 1, -1}},
648 std::array{vec2{ 1, -1}, vec2{-1, -1}, vec2{-1, 1}, vec2{ 1, 1}},
649 std::array{vec2{ 1, -1}, vec2{ 1, 1}, vec2{-1, 1}, vec2{-1, -1}},
650 std::array{vec2{-1, -1}, vec2{-1, 1}, vec2{ 1, 1}, vec2{ 1, -1}},
651 };
652 vec2 noise(noiseX, noiseY);
653 const std::array tex = {
654 noise + vec2(0.0f, 1.875f),
655 noise + vec2(2.0f, 1.875f),
656 noise + vec2(2.0f, 0.0f ),
657 noise + vec2(0.0f, 0.0f ),
658 };
659
660 const auto& glContext = *gl::context;
661 glContext.progTex.activate();
662
663 glEnable(GL_BLEND);
664 glBlendFunc(GL_ONE, GL_ONE);
665 glUniform4f(glContext.unifTexColor, 1.0f, 1.0f, 1.0f, 1.0f);
666 mat4 I;
667 glUniformMatrix4fv(glContext.unifTexMvp, 1, GL_FALSE, I.data());
668
669 unsigned seq = frameCounter & 7;
670 glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, pos[seq].data());
671 glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, tex.data());
672 glEnableVertexAttribArray(0);
673 glEnableVertexAttribArray(1);
674
675 noiseTextureA.bind();
676 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
677 glBlendEquation(GL_FUNC_REVERSE_SUBTRACT);
678 noiseTextureB.bind();
679 glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
680
681 glDisableVertexAttribArray(1);
682 glDisableVertexAttribArray(0);
683 glBlendEquation(GL_FUNC_ADD); // restore default
684 glDisable(GL_BLEND);
685}
686
687static constexpr int GRID_SIZE = 16;
688static constexpr int GRID_SIZE1 = GRID_SIZE + 1;
689static constexpr int NUM_INDICES = (GRID_SIZE1 * 2 + 2) * GRID_SIZE - 2;
695
696void PostProcessor::preCalcMonitor3D(float width)
697{
698 // precalculate vertex-positions, -normals and -texture-coordinates
699 std::array<std::array<Vertex, GRID_SIZE1>, GRID_SIZE1> vertices;
700
701 constexpr float GRID_SIZE2 = float(GRID_SIZE) * 0.5f;
702 float s = width * (1.0f / 320.0f);
703 float b = (320.0f - width) * (1.0f / (2.0f * 320.0f));
704
705 for (auto sx : xrange(GRID_SIZE1)) {
706 for (auto sy : xrange(GRID_SIZE1)) {
707 Vertex& v = vertices[sx][sy];
708 float x = (narrow<float>(sx) - GRID_SIZE2) / GRID_SIZE2;
709 float y = (narrow<float>(sy) - GRID_SIZE2) / GRID_SIZE2;
710
711 v.position = vec3(x, y, (x * x + y * y) * (1.0f / -12.0f));
712 v.normal = normalize(vec3(x * (1.0f / 6.0f), y * (1.0f / 6.0f), 1.0f)) * 1.2f;
713 v.tex = vec2((float(sx) / GRID_SIZE) * s + b,
714 float(sy) / GRID_SIZE);
715 }
716 }
717
718 // calculate indices
719 std::array<uint16_t, NUM_INDICES> indices;
720
721 uint16_t* ind = indices.data();
722 for (auto y : xrange(GRID_SIZE)) {
723 for (auto x : xrange(GRID_SIZE1)) {
724 *ind++ = narrow<uint16_t>((y + 0) * GRID_SIZE1 + x);
725 *ind++ = narrow<uint16_t>((y + 1) * GRID_SIZE1 + x);
726 }
727 // skip 2, filled in later
728 ind += 2;
729 }
730 assert((ind - indices.data()) == NUM_INDICES + 2);
731 ind = indices.data();
732 repeat(GRID_SIZE - 1, [&] {
733 ind += 2 * GRID_SIZE1;
734 // repeat prev and next index to restart strip
735 ind[0] = ind[-1];
736 ind[1] = ind[ 2];
737 ind += 2;
738 });
739
740 // upload calculated values to buffers
741 glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer.get());
742 glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices.data(),
743 GL_STATIC_DRAW);
744 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementBuffer.get());
745 glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(indices), indices.data(),
746 GL_STATIC_DRAW);
747 glBindBuffer(GL_ARRAY_BUFFER, 0);
748 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
749
750 // calculate transformation matrices
751 mat4 proj = frustum(-1, 1, -1, 1, 1, 10);
752 mat4 tran = translate(vec3(0.0f, 0.4f, -2.0f));
753 mat4 rotX = rotateX(radians(-10.0f));
754 mat4 scal = scale(vec3(2.2f, 2.2f, 2.2f));
755
756 mat3 normal(rotX);
757 mat4 mvp = proj * tran * rotX * scal;
758
759 // set uniforms
760 monitor3DProg.activate();
761 glUniform1i(monitor3DProg.getUniformLocation("u_tex"), 0);
762 glUniformMatrix4fv(monitor3DProg.getUniformLocation("u_mvpMatrix"),
763 1, GL_FALSE, mvp.data());
764 glUniformMatrix3fv(monitor3DProg.getUniformLocation("u_normalMatrix"),
765 1, GL_FALSE, normal.data());
766}
767
768void PostProcessor::drawMonitor3D() const
769{
770 monitor3DProg.activate();
771
772 char* base = nullptr;
773 glBindBuffer(GL_ARRAY_BUFFER, arrayBuffer.get());
774 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, elementBuffer.get());
775 glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex),
776 base);
777 glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex),
778 base + sizeof(vec3));
779 glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex),
780 base + sizeof(vec3) + sizeof(vec3));
781 glEnableVertexAttribArray(0);
782 glEnableVertexAttribArray(1);
783 glEnableVertexAttribArray(2);
784
785 glDrawElements(GL_TRIANGLE_STRIP, NUM_INDICES, GL_UNSIGNED_SHORT, nullptr);
786 glDisableVertexAttribArray(2);
787 glDisableVertexAttribArray(1);
788 glDisableVertexAttribArray(0);
789
790 glBindBuffer(GL_ARRAY_BUFFER, 0);
791 glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
792}
793
794} // namespace openmsx
#define OPENGL_3_3
Definition GLUtil.hh:23
#define OPENGL_VERSION
Definition GLUtil.hh:24
BaseSetting * setting
int g
GLuint get() const
Definition GLUtil.hh:477
GLsizei getHeight() const
Definition GLUtil.hh:114
GLsizei getWidth() const
Definition GLUtil.hh:113
void resize(GLsizei width, GLsizei height)
Definition GLUtil.cc:86
Wrapper around an OpenGL fragment shader: a program executed on the GPU that computes the colors of p...
Definition GLUtil.hh:381
void activate() const
Makes this program the active shader program.
Definition GLUtil.cc:283
void attach(const Shader &shader)
Adds a given shader to this program.
Definition GLUtil.cc:238
void link()
Links all attached shaders together into one program.
Definition GLUtil.cc:250
void bindAttribLocation(unsigned index, const char *name)
Bind the given name for a vertex shader attribute to the given location.
Definition GLUtil.cc:270
GLint getUniformLocation(const char *name) const
Gets a reference to a uniform variable declared in the shader source.
Definition GLUtil.cc:275
void bind() const
Makes this texture the active GL texture.
Definition GLUtil.hh:84
void setInterpolation(bool interpolation)
Enable/disable bilinear interpolation for this texture.
Definition GLUtil.cc:62
Wrapper around an OpenGL vertex shader: a program executed on the GPU that computes per-vertex stuff.
Definition GLUtil.hh:366
constexpr const T * data() const
Definition gl_mat.hh:100
void addImage(const FrameSource *frame, EmuTime::param time)
void printWarning(std::string_view message)
Definition CliComm.cc:12
Represents the output window/screen of openMSX.
Definition Display.hh:32
CliComm & getCliComm() const
Definition Display.cc:110
void distributeEvent(Event &&event)
Schedule the given event for delivery.
Interface for getting lines from a video frame.
std::span< const Pixel > getLine(int line, std::span< Pixel > buf) const
Gets a pointer to the pixels of the given line number.
virtual unsigned getLineWidth(unsigned line) const =0
Gets the number of display pixels on the given line.
std::span< const Pixel, 320 > getLinePtr320_240(unsigned line, std::span< Pixel, 320 > buf) const
Get a pointer to a given line in this frame, the frame is scaled to 320x240 pixels.
unsigned getWidth() const
Get the width of (all) lines in this frame.
std::span< const Pixel, 640 > getLinePtr640_480(unsigned line, std::span< Pixel, 640 > buf) const
Get a pointer to a given line in this frame, the frame is scaled to 640x480 pixels.
unsigned getHeight() const
Gets the number of lines in this frame.
@ ODD
Interlacing is on and this is an odd frame.
@ NONINTERLACED
Interlacing is off for this frame.
A frame buffer where pixels can be written to.
gl::ivec2 getLogicalSize() const
gl::ivec2 getViewOffset() const
gl::ivec2 getViewSize() const
std::unique_ptr< RawFrame > rotateFrames(std::unique_ptr< RawFrame > finishedFrame, EmuTime::param time)
Sets up the "abcdFrame" variables for a new frame.
PostProcessor(MSXMotherBoard &motherBoard, Display &display, OutputSurface &screen, const std::string &videoSource, unsigned maxWidth, unsigned height, bool canDoInterlace)
void takeRawScreenShot(unsigned height, const std::string &filename) override
Create a raw (=non-post-processed) screenshot.
void paint(OutputSurface &output) override
Paint this layer.
bool getInterleaveBlackFrame() const
Is black frame interleaving enabled?
FloatSetting & getNoiseSetting()
The amount of noise to add to the frame.
float getHorizontalStretch() const
DisplayDeform getDisplayDeform() const
FloatSetting & getHorizontalStretchSetting()
Amount of horizontal stretch.
ScaleAlgorithm getScaleAlgorithm() const
Every class that wants to get scheduled at some point must inherit from this class.
void setSyncPoint(EmuTime::param timestamp)
void detach(Observer< T > &observer)
Definition Subject.hh:60
void attach(Observer< T > &observer)
Definition Subject.hh:54
int getVideoSource() const
Returns the ID for this VideoLayer.
Definition VideoLayer.cc:40
bool needRecord() const
Definition VideoLayer.cc:92
int getVideoSourceSetting() const
Definition VideoLayer.cc:44
void update(const Setting &setting) noexcept override
Definition VideoLayer.cc:49
Definition gl_mat.hh:23
vecN< 3, float > vec3
Definition gl_vec.hh:179
mat4 rotateX(float angle)
vecN< 2, float > vec2
Definition gl_vec.hh:178
std::optional< Context > context
Definition GLContext.cc:10
constexpr T radians(T d)
Definition gl_vec.hh:206
constexpr mat4 frustum(float left, float right, float bottom, float top, float nearVal, float farVal)
vecN< N, T > normalize(const vecN< N, T > &x)
Definition gl_vec.hh:383
constexpr mat4 translate(const vec3 &xyz)
constexpr mat4 scale(const vec3 &xyz)
void format(SectorAccessibleDisk &disk, MSXBootSectorType bootType)
Format the given disk (= a single partition).
std::unique_ptr< GLScaler > createScaler(RenderSettings &renderSettings)
Instantiates a Scaler.
void saveRGBA(size_t width, std::span< const uint32_t * > rowPointers, const std::string &filename)
Definition PNG.cc:327
This file implemented 3 utility functions:
Definition Autofire.cc:11
std::vector< MemBuffer< FrameSource::Pixel, SSE_ALIGNMENT > > WorkBuffer
auto find(InputRange &&range, const T &value)
Definition ranges.hh:162
constexpr auto copy(InputRange &&range, OutputIter out)
Definition ranges.hh:252
auto & global_urng()
Return reference to a (shared) global random number generator.
Definition random.hh:8
float random_float(float from, float upto)
Return a random float in the range [from, upto) (note: half-open interval).
Definition random.hh:50
ITER find_unguarded(ITER first, ITER last, const VAL &val, Proj proj={})
Faster alternative to 'find' when it's guaranteed that the value will be found (if not the behavior i...
Definition stl.hh:72
auto max_value(InputIterator first, InputIterator last, Proj proj={})
Definition stl.hh:224
#define VLA(TYPE, NAME, LENGTH)
Definition vla.hh:12
constexpr void repeat(T n, Op op)
Repeat the given operation 'op' 'n' times.
Definition xrange.hh:147
constexpr auto xrange(T e)
Definition xrange.hh:132
constexpr auto end(const zstring_view &x)