#include #include #include #include #include "ImageDecoder.h" #include "CWallpaper.h" #include "FrameMaterial.h" #include "WallpaperEngine/Data/Parsers/TextureParser.h" #include "WallpaperEngine/Data/Utils/BinaryReader.h" #include "WallpaperEngine/Logging/Log.h" #include "WallpaperEngine/Render/Wallpapers/CScene.h" #include "WallpaperEngine/Render/Wallpapers/CSplat.h" #include "WallpaperEngine/Render/Wallpapers/CVideo.h" #include "WallpaperEngine/Render/Wallpapers/CWeb.h" #include "WallpaperEngine/Data/Model/Project.h" #include "WallpaperEngine/Data/Model/Wallpaper.h" #include "WallpaperEngine/Data/Utils/FloatCompare.h" using namespace WallpaperEngine::Render; using WallpaperEngine::Data::Utils::BinaryReader; CWallpaper::CWallpaper ( const Wallpaper& wallpaperData, RenderContext& context, AudioContext& audioContext, const WallpaperState::TextureUVsScaling& scalingMode, const uint32_t& clampMode ) : ContextAware (context), FBOProvider (nullptr), m_wallpaperData (wallpaperData), m_audioContext (audioContext), m_state (scalingMode, clampMode) { glGenVertexArrays (1, &this->m_vaoBuffer); glBindVertexArray (this->m_vaoBuffer); this->setupShaders (); constexpr GLfloat texCoords[] = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f }; constexpr GLfloat position[] = { -1.0f, 1.0f, 0.0f, 1.0, 1.0f, 0.0f, -1.0f, -1.0f, 0.0f, -1.0f, -1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, -1.0f, 0.0f }; glGenBuffers (1, &this->m_texCoordBuffer); glBindBuffer (GL_ARRAY_BUFFER, this->m_texCoordBuffer); glBufferData (GL_ARRAY_BUFFER, sizeof (texCoords), texCoords, GL_DYNAMIC_DRAW); glEnableVertexAttribArray (this->a_TexCoord); glVertexAttribPointer (this->a_TexCoord, 2, GL_FLOAT, GL_FALSE, 0, nullptr); glGenBuffers (1, &this->m_positionBuffer); glBindBuffer (GL_ARRAY_BUFFER, this->m_positionBuffer); glBufferData (GL_ARRAY_BUFFER, sizeof (position), position, GL_STATIC_DRAW); glEnableVertexAttribArray (this->a_Position); glVertexAttribPointer (this->a_Position, 3, GL_FLOAT, GL_FALSE, 0, nullptr); } CWallpaper::~CWallpaper () { if (this->m_backBuffer.texture != GL_NONE) { glDeleteFramebuffers (1, &this->m_backBuffer.framebuffer); glDeleteTextures (1, &this->m_backBuffer.texture); } GLuint attachedShaders[2]; GLsizei attachedCount = 0; glGetAttachedShaders (this->m_shader, 2, &attachedCount, attachedShaders); for (auto i = 0; i < attachedCount; i++) { glDeleteShader (attachedShaders[i]); } glDeleteProgram (this->m_shader); if (this->m_lutTexture != GL_NONE) { glDeleteTextures (1, &this->m_lutTexture); } if (this->m_outputSampler != GL_NONE) { glDeleteSamplers (1, &this->m_outputSampler); } glDeleteBuffers (1, &this->m_texCoordBuffer); glDeleteBuffers (1, &this->m_positionBuffer); glDeleteVertexArrays (1, &this->m_vaoBuffer); } const AssetLocator& CWallpaper::getAssetLocator () const { return *this->m_wallpaperData.project.assetLocator; } const Wallpaper& CWallpaper::getWallpaperData () const { return this->m_wallpaperData; } GLuint CWallpaper::getWallpaperFramebuffer () const { return this->m_presentBackBuffer ? this->m_backBuffer.framebuffer : this->m_sceneFBO->getFramebuffer (); } GLuint CWallpaper::getWallpaperTexture () const { return this->m_presentBackBuffer ? this->m_backBuffer.texture : this->m_sceneFBO->getTextureID (0); } void CWallpaper::prepareBackBuffer (const glm::ivec2& size, const GLenum format) { auto& back = this->m_backBuffer; if (back.size == size && back.format == format) { return; } if (back.texture == GL_NONE) { glGenTextures (1, &back.texture); glGenFramebuffers (1, &back.framebuffer); } glBindTexture (GL_TEXTURE_2D, back.texture); glTexImage2D (GL_TEXTURE_2D, 0, static_cast (format), size.x, size.y, 0, GL_RGBA, GL_FLOAT, nullptr); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri (GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glBindFramebuffer (GL_FRAMEBUFFER, back.framebuffer); glFramebufferTexture2D (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, back.texture, 0); #if !NDEBUG glObjectLabel (GL_TEXTURE, back.texture, -1, "back buffer"); #endif back.size = size; back.format = format; } void CWallpaper::renderImageAdjustments (const glm::ivec2& size, const GLenum format) { // sub_140181F30: COL when the color options moved, LUT for a filter above 0, otherwise no material const bool color = this->m_colorEnabled; const bool lut = this->m_lutTexture != GL_NONE && this->m_lutStrength > 0.0f; if (!color && !lut) { this->m_imageAdjustmentsMaterial = nullptr; return; } if (this->m_imageAdjustmentsMaterial == nullptr || this->m_imageAdjustmentsCombos != std::pair (color, lut)) { ComboMap combos; if (color) { combos.emplace ("COL", 1); } combos.emplace ("LUT", lut ? 1 : 0); this->m_imageAdjustmentsMaterial = std::make_unique ( *this, this->m_wallpaperData.project, "materials/util/ccsimple.json", combos ); this->m_imageAdjustmentsCombos = { color, lut }; } FrameMaterial& material = *this->m_imageAdjustmentsMaterial; if (color) { material.setConstant ("params", this->m_colorParams); } if (lut) { material.setTexture (1, this->m_lutTexture, GL_TEXTURE_3D); material.setConstant ("lutparams", this->m_lutStrength); } // sub_14017FA70 copies the back buffer into _rt_FullFrameBuffer first this->prepareBackBuffer (size, format); if (this->m_presentBackBuffer) { glBindFramebuffer (GL_READ_FRAMEBUFFER, this->m_backBuffer.framebuffer); glBindFramebuffer (GL_DRAW_FRAMEBUFFER, this->m_sceneFBO->getFramebuffer ()); glBlitFramebuffer (0, 0, size.x, size.y, 0, 0, size.x, size.y, GL_COLOR_BUFFER_BIT, GL_NEAREST); } material.draw (this->m_backBuffer.framebuffer, this->m_backBuffer.size); this->m_presentBackBuffer = true; } void CWallpaper::setupShaders () { const GLuint vertexShaderID = glCreateShader (GL_VERTEX_SHADER); const char* sourcePointer = "#version 330\n" "precision highp float;\n" "in vec3 a_Position;\n" "in vec2 a_TexCoord;\n" "out vec2 v_TexCoord;\n" "void main () {\n" "gl_Position = vec4 (a_Position, 1.0);\n" "v_TexCoord = a_TexCoord;\n" "}"; glShaderSource (vertexShaderID, 1, &sourcePointer, nullptr); glCompileShader (vertexShaderID); GLint result = GL_FALSE; int infoLogLength = 0; glGetShaderiv (vertexShaderID, GL_COMPILE_STATUS, &result); glGetShaderiv (vertexShaderID, GL_INFO_LOG_LENGTH, &infoLogLength); if (infoLogLength > 0) { const auto logBuffer = new char[infoLogLength + 1]; memset (logBuffer, 0, infoLogLength + 1); glGetShaderInfoLog (vertexShaderID, infoLogLength, nullptr, logBuffer); const std::string message = logBuffer; delete[] logBuffer; sLog.exception (message); } const GLuint fragmentShaderID = glCreateShader (GL_FRAGMENT_SHADER); sourcePointer = "#version 330\n" "precision highp float;\n" "uniform sampler2D g_Texture0;\n" "uniform sampler3D g_Texture1;\n" "uniform vec4 g_Params;\n" "uniform float g_LutParams;\n" "uniform bool u_ColorEnabled;\n" "uniform bool u_LutEnabled;\n" "uniform bool u_InputLinear;\n" "uniform bool u_InputScRGB;\n" "uniform bool u_OutputPQ;\n" "uniform int u_Supersample;\n" "in vec2 v_TexCoord;\n" "out vec4 out_FragColor;\n" // BT.2408 reference white, what the PQ image description of HDR surfaces anchors SDR content to "const float referenceWhite = 203.0;\n" "const mat3 bt709to2020 = mat3 (0.6274, 0.0691, 0.0164, 0.3293, 0.9195, 0.0880, 0.0433, 0.0114, 0.8956);\n" "const mat3 bt2020to709 = mat3 (1.6605, -0.1246, -0.0182, -0.5876, 1.1329, -0.1006, -0.0728, -0.0083, " "1.1187);\n" "vec3 srgbToLinear (vec3 c) {\n" "return mix (c / 12.92, pow ((c + 0.055) / 1.055, vec3 (2.4)), step (0.04045, c));\n" "}\n" "vec3 linearToSrgb (vec3 c) {\n" "return mix (c * 12.92, 1.055 * pow (c, vec3 (1.0 / 2.4)) - 0.055, step (0.0031308, c));\n" "}\n" // mpv decodes SDR video with BT.1886, a pure 2.4 power, going back the same way keeps SDR videos // exactly as they look without --hdr "vec3 videoToLinear (vec3 c) { return pow (c, vec3 (2.4)); }\n" "vec3 linearToVideo (vec3 c) { return pow (c, vec3 (1.0 / 2.4)); }\n" "vec3 pqEncode (vec3 nits) {\n" "vec3 y = pow (clamp (nits / 10000.0, 0.0, 1.0), vec3 (0.1593017578125));\n" "return pow ((0.8359375 + 18.8515625 * y) / (1.0 + 18.6875 * y), vec3 (78.84375));\n" "}\n" "vec3 softClip (vec3 x) {\n" "return mix (x, 0.8 + 0.2 * (1.0 - exp (-(x - 0.8) / 0.2)), step (0.8, x));\n" "}\n" "vec3 hsv2rgb (vec3 c) {\n" "vec4 K = vec4 (1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0);\n" "vec3 p = abs (fract (c.xxx + K.xyz) * 6.0 - K.www);\n" "return c.z * mix (K.xxx, clamp (p - K.xxx, 0.0, 1.0), c.y);\n" "}\n" "vec3 rgb2hsv (vec3 RGB) {\n" "vec4 P = (RGB.g < RGB.b) ? vec4 (RGB.bg, -1.0, 2.0 / 3.0) : vec4 (RGB.gb, 0.0, -1.0 / 3.0);\n" "vec4 Q = (RGB.r < P.x) ? vec4 (P.xyw, RGB.r) : vec4 (RGB.r, P.yzx);\n" "float C = Q.x - min (Q.w, Q.y);\n" "float H = abs ((Q.w - Q.y) / (6.0 * C + 1e-10) + Q.z);\n" "return vec3 (H, C / (Q.x + 1e-10), Q.x);\n" "}\n" "void main () {\n" "vec4 albedo = vec4 (0.0);\n" "if (u_Supersample > 1) {\n" "vec2 stepX = dFdx (v_TexCoord);\n" "vec2 stepY = dFdy (v_TexCoord);\n" "for (int y = 0; y < u_Supersample; y++) {\n" "for (int x = 0; x < u_Supersample; x++) {\n" "vec2 offset = (vec2 (x, y) + 0.5) / float (u_Supersample) - 0.5;\n" "albedo += texture (g_Texture0, v_TexCoord + offset.x * stepX + offset.y * stepY);\n" "}\n" "}\n" "albedo /= float (u_Supersample * u_Supersample);\n" "} else {\n" "albedo = texture (g_Texture0, v_TexCoord);\n" "}\n" "if (u_InputScRGB) {\n" "albedo.rgb = u_OutputPQ ? bt709to2020 * albedo.rgb : linearToSrgb (clamp (albedo.rgb, 0.0, 1.0));\n" "}\n" "bool filtered = u_ColorEnabled || u_LutEnabled;\n" "vec3 overbright = vec3 (0.0);\n" // the filters work on SDR-encoded values like in Wallpaper Engine, what's past reference white is kept aside "if (u_InputLinear && filtered) {\n" "vec3 light = max (bt2020to709 * albedo.rgb, 0.0);\n" "overbright = max (light - 1.0, 0.0);\n" "albedo.rgb = linearToVideo (min (light, 1.0));\n" "}\n" "if (u_ColorEnabled) {\n" "albedo.rgb = mix (vec3 (0.5), albedo.rgb, g_Params.y);\n" "vec3 hsv = rgb2hsv (albedo.rgb);\n" "hsv.z *= g_Params.x;\n" "hsv.y *= g_Params.z;\n" "hsv.x += g_Params.w;\n" "albedo.rgb = hsv2rgb (hsv);\n" "}\n" "if (u_LutEnabled) {\n" "albedo.rgb = mix (albedo.rgb, texture (g_Texture1, albedo.rgb).rgb, g_LutParams);\n" "}\n" "if (u_InputLinear || u_OutputPQ) {\n" "vec3 encoded = clamp (albedo.rgb, 0.0, 1.0);\n" "vec3 linear2020 = !u_InputLinear ? bt709to2020 * srgbToLinear (encoded)\n" " : filtered ? bt709to2020 * (videoToLinear (encoded) + overbright) : albedo.rgb;\n" "albedo.rgb = u_OutputPQ ? pqEncode (max (linear2020, 0.0) * referenceWhite)\n" " : linearToVideo (min (softClip (max (bt2020to709 * linear2020, 0.0)), 1.0));\n" "}\n" "out_FragColor = albedo;\n" "}"; glShaderSource (fragmentShaderID, 1, &sourcePointer, nullptr); glCompileShader (fragmentShaderID); result = GL_FALSE; infoLogLength = 0; glGetShaderiv (fragmentShaderID, GL_COMPILE_STATUS, &result); glGetShaderiv (fragmentShaderID, GL_INFO_LOG_LENGTH, &infoLogLength); if (infoLogLength > 0) { const auto logBuffer = new char[infoLogLength + 1]; memset (logBuffer, 0, infoLogLength + 1); glGetShaderInfoLog (fragmentShaderID, infoLogLength, nullptr, logBuffer); const std::string message = logBuffer; delete[] logBuffer; sLog.exception (message); } this->m_shader = glCreateProgram (); glAttachShader (this->m_shader, vertexShaderID); glAttachShader (this->m_shader, fragmentShaderID); glLinkProgram (this->m_shader); result = GL_FALSE; infoLogLength = 0; glGetProgramiv (this->m_shader, GL_LINK_STATUS, &result); glGetProgramiv (this->m_shader, GL_INFO_LOG_LENGTH, &infoLogLength); if (infoLogLength > 0) { const auto logBuffer = new char[infoLogLength + 1]; memset (logBuffer, 0, infoLogLength + 1); glGetProgramInfoLog (this->m_shader, infoLogLength, nullptr, logBuffer); const std::string message = logBuffer; delete[] logBuffer; sLog.exception (message); } glDetachShader (this->m_shader, vertexShaderID); glDetachShader (this->m_shader, fragmentShaderID); glDeleteShader (vertexShaderID); glDeleteShader (fragmentShaderID); this->g_Texture0 = glGetUniformLocation (this->m_shader, "g_Texture0"); this->g_Texture1 = glGetUniformLocation (this->m_shader, "g_Texture1"); this->g_Params = glGetUniformLocation (this->m_shader, "g_Params"); this->g_LutParams = glGetUniformLocation (this->m_shader, "g_LutParams"); this->u_ColorEnabled = glGetUniformLocation (this->m_shader, "u_ColorEnabled"); this->u_LutEnabled = glGetUniformLocation (this->m_shader, "u_LutEnabled"); this->u_InputLinear = glGetUniformLocation (this->m_shader, "u_InputLinear"); this->u_InputScRGB = glGetUniformLocation (this->m_shader, "u_InputScRGB"); this->u_OutputPQ = glGetUniformLocation (this->m_shader, "u_OutputPQ"); this->u_Supersample = glGetUniformLocation (this->m_shader, "u_Supersample"); this->a_Position = glGetAttribLocation (this->m_shader, "a_Position"); this->a_TexCoord = glGetAttribLocation (this->m_shader, "a_TexCoord"); } void CWallpaper::setDestinationFramebuffer (GLuint framebuffer) { this->m_destFramebuffer = framebuffer; } void CWallpaper::setSpanInfo (const SpanInfo& spanInfo) { this->m_spanInfo = spanInfo; } const CWallpaper::SpanInfo* CWallpaper::getSpanInfo () const { return this->m_spanInfo.has_value () ? &this->m_spanInfo.value () : nullptr; } void CWallpaper::updateUVs (const glm::ivec4& viewport, const bool vflip) { if (this->m_state.hasChanged (viewport, vflip, this->getCanvasWidth (), this->getCanvasHeight ())) { this->m_state.updateState (viewport, vflip, this->getCanvasWidth (), this->getCanvasHeight ()); } } void CWallpaper::updateSpanBounds () { auto& span = *this->m_spanInfo; const auto& viewports = this->getContext ().getOutput ().getViewports (); glm::ivec2 low (std::numeric_limits::max ()); glm::ivec2 high (std::numeric_limits::min ()); double scale = 0.0; for (const auto& screen : span.screens) { const auto it = viewports.find (screen); if (it == viewports.end () || it->second->logicalSize.x <= 0 || it->second->logicalSize.y <= 0) { continue; } const auto* output = it->second; low = glm::min (low, output->globalPosition); high = glm::max (high, output->globalPosition + output->logicalSize); scale = std::max (scale, static_cast (output->viewport.z) / output->logicalSize.x); } if (scale <= 0.0) { return; } const glm::ivec4 bounds { low, high - low }; GLint maxTexture = 0; GLint maxViewport[2] = { 0, 0 }; glGetIntegerv (GL_MAX_TEXTURE_SIZE, &maxTexture); glGetIntegerv (GL_MAX_VIEWPORT_DIMS, maxViewport); const double limit = std::min ({ maxTexture, maxViewport[0], maxViewport[1] }); if (limit > 0.0) { scale = std::min (scale, limit / std::max (bounds.z, bounds.w)); } if (bounds != span.totalBounds || scale != span.scale) { sLog.out ( "Span ", span.screens.front (), ": ", bounds.z, "x", bounds.w, " at ", bounds.x, ",", bounds.y, ", rendered at ", scale, "x" ); } span.totalBounds = bounds; span.scale = scale; } void CWallpaper::updateSpanCursor ( const glm::ivec4& viewport, const glm::ivec2& globalPosition, const glm::ivec2& logicalSize ) { const auto& span = *this->m_spanInfo; const auto& input = this->getContext ().getInputContext ().getMouseInput (); auto desktop = input.desktopPosition (); if (!desktop.has_value () && viewport.z > 0 && viewport.w > 0) { const glm::dvec2 local = (input.position () - glm::dvec2 (viewport.x, viewport.y)) / glm::dvec2 (viewport.z, viewport.w); desktop = glm::dvec2 (globalPosition) + glm::dvec2 (local.x, 1.0 - local.y) * glm::dvec2 (logicalSize); } if (!desktop.has_value ()) { return; } // ScreenToClient on the group's window (sub_140110630), in its pixels with y up like MouseInput this->m_spanCursor = glm::dvec2 ( (desktop->x - span.totalBounds.x) * span.scale, (span.totalBounds.y + span.totalBounds.w - desktop->y) * span.scale ); } glm::dvec2 CWallpaper::cursorPosition () const { if (this->m_spanInfo.has_value ()) { return this->m_spanCursor; } return this->getContext ().getInputContext ().getMouseInput ().position (); } bool CWallpaper::pointerInRegion () const { if (!this->m_pointerRegion.has_value ()) { return true; } const auto region = this->toCursorSpace (*this->m_pointerRegion); const glm::dvec2 position = this->cursorPosition (); return position.x >= region.x && position.x < region.x + region.z && position.y >= region.y && position.y < region.y + region.w; } glm::ivec4 CWallpaper::toCursorSpace (const glm::ivec4& rect) const { if (!this->m_cursorMirrorHeight.has_value ()) { return rect; } return { rect.x, *this->m_cursorMirrorHeight - rect.y - rect.w, rect.z, rect.w }; } WallpaperEngine::Input::MouseClickStatus CWallpaper::regionButton (const Input::MouseClickStatus status, PointerPress& press) const { if (!this->m_pointerRegion.has_value ()) { return status; } if (status == Input::MouseClickStatus::Released) { press = {}; return status; } // a press belongs to the slot it started on until release if (!press.held) { press = { .held = true, .owned = this->pointerInRegion () }; } return press.owned ? status : Input::MouseClickStatus::Released; } WallpaperEngine::Input::MouseClickStatus CWallpaper::cursorLeftClick () const { const auto& input = this->getContext ().getInputContext ().getMouseInput (); return this->regionButton ( this->m_spanInfo.has_value () ? input.desktopLeftClick () : input.leftClick (), this->m_leftPress ); } WallpaperEngine::Input::MouseClickStatus CWallpaper::cursorRightClick () const { return this->regionButton ( this->getContext ().getInputContext ().getMouseInput ().rightClick (), this->m_rightPress ); } glm::vec4 CWallpaper::getOutputUVs () const { if (this->rendersAtOutputSize ()) { return this->m_state.isVFlipped () ? glm::vec4 { 0.0f, 1.0f, 0.0f, 1.0f } : glm::vec4 { 0.0f, 1.0f, 1.0f, 0.0f }; } const auto uvs = this->m_state.getTextureUVs (); return { uvs.ustart, uvs.uend, uvs.vstart, uvs.vend }; } int CWallpaper::getFramebufferWidth () const { return this->m_sceneFBO != nullptr ? static_cast (this->m_sceneFBO->getRealWidth ()) : this->getCanvasWidth (); } int CWallpaper::getFramebufferHeight () const { return this->m_sceneFBO != nullptr ? static_cast (this->m_sceneFBO->getRealHeight ()) : this->getCanvasHeight (); } void CWallpaper::render ( const glm::ivec4& viewport, const bool vflip, const glm::ivec2& globalPosition, const glm::ivec2& logicalSize ) { const uint32_t currentFrame = this->getContext ().getDriver ().getFrameCounter (); const bool needsSceneRender = (currentFrame != this->m_lastRenderedFrame); glm::ivec4 sceneViewport = viewport; // WE makes a stretch group one more monitor whose rect is the bounding box of its monitors (sub_140061B50), // drawn into one window over that rect: the scene, its cursor and the flip cover the whole group if (this->m_spanInfo.has_value ()) { if (needsSceneRender) { this->updateSpanBounds (); this->updateSpanCursor (viewport, globalPosition, logicalSize); } const auto& span = *this->m_spanInfo; sceneViewport = { 0, 0, static_cast (std::lround (span.totalBounds.z * span.scale)), static_cast (std::lround (span.totalBounds.w * span.scale)) }; } this->m_screenSize = { sceneViewport.z, sceneViewport.w }; // X11 rects count y from the top, the cursor from the bottom; a span's cursor is already in group pixels this->m_cursorMirrorHeight = vflip || this->m_spanInfo.has_value () ? std::nullopt : std::optional (this->getContext ().getOutput ().getFullHeight ()); this->m_cursorViewport = this->toCursorSpace (sceneViewport); this->m_supersampling = this->rendersAtOutputSize () ? this->supersamplingFor ({ sceneViewport.z, sceneViewport.w }) : 1; // the scene reads the visible region from these while it renders this->updateUVs (sceneViewport, vflip); #if !NDEBUG glPushDebugGroup (GL_DEBUG_SOURCE_APPLICATION, 0, -1, "Rendering scene"); #endif if (needsSceneRender) { this->renderFrame (sceneViewport); this->m_lastRenderedFrame = currentFrame; // a video learns its real size inside renderFrame, the UVs from before it would crop the first frame this->updateUVs (sceneViewport, vflip); } #if !NDEBUG glPopDebugGroup (); #endif this->present (viewport, globalPosition, logicalSize); } void CWallpaper::present (const glm::ivec4& viewport, const glm::ivec2& globalPosition, const glm::ivec2& logicalSize) { #if !NDEBUG glPushDebugGroup (GL_DEBUG_SOURCE_APPLICATION, 0, -1, "Rendering scene to output"); #endif float ustart, uend, vstart, vend; if (this->m_spanInfo.has_value ()) { const auto& span = this->m_spanInfo.value (); const auto spanW = static_cast (span.totalBounds.z); const auto spanH = static_cast (span.totalBounds.w); const auto spanX = static_cast (span.totalBounds.x); const auto spanY = static_cast (span.totalBounds.y); const glm::vec4 base = this->getOutputUVs (); const float baseUstart = base.x; const float baseUend = base.y; const float baseVstart = base.z; const float baseVend = base.w; float relLeft = (static_cast (globalPosition.x) - spanX) / spanW; float relRight = (static_cast (globalPosition.x + logicalSize.x) - spanX) / spanW; // a flipped span mirrors the whole group, the leftmost screen shows the right end of the image if (this->m_flipHorizontal) { std::tie (relLeft, relRight) = std::make_pair (1.0f - relLeft, 1.0f - relRight); } const float relTop = (static_cast (globalPosition.y) - spanY) / spanH; const float relBottom = (static_cast (globalPosition.y + logicalSize.y) - spanY) / spanH; const float baseURange = baseUend - baseUstart; const float baseVRange = baseVend - baseVstart; ustart = baseUstart + relLeft * baseURange; uend = baseUstart + relRight * baseURange; vstart = baseVstart + relTop * baseVRange; vend = baseVstart + relBottom * baseVRange; if (this->m_lastRenderedFrame < 5) { sLog.debug ( "SPAN DEBUG: viewport=", viewport.z, "x", viewport.w, " globalPos=(", globalPosition.x, ",", globalPosition.y, ")", " span=(", span.totalBounds.x, ",", span.totalBounds.y, ",", span.totalBounds.z, ",", span.totalBounds.w, ")", " rel=[", relLeft, ",", relRight, "]x[", relTop, ",", relBottom, "]", " baseUV=[", baseUstart, ",", baseUend, "]x[", baseVstart, ",", baseVend, "]", " finalUV=[", ustart, ",", uend, "]x[", vstart, ",", vend, "]" ); } } else { const glm::vec4 uvs = this->getOutputUVs (); ustart = uvs.x; uend = uvs.y; vstart = uvs.z; vend = uvs.w; if (this->m_flipHorizontal) { std::swap (ustart, uend); } } const GLfloat texCoords[] = { ustart, vstart, uend, vstart, ustart, vend, ustart, vend, uend, vstart, uend, vend, }; glViewport (viewport.x, viewport.y, viewport.z, viewport.w); glBindFramebuffer (GL_FRAMEBUFFER, this->m_destFramebuffer); glBindVertexArray (this->m_vaoBuffer); if (!WallpaperEngine::Data::Utils::sameFloat (ustart, this->m_uploadedUstart) || !WallpaperEngine::Data::Utils::sameFloat (uend, this->m_uploadedUend) || !WallpaperEngine::Data::Utils::sameFloat (vstart, this->m_uploadedVstart) || !WallpaperEngine::Data::Utils::sameFloat (vend, this->m_uploadedVend)) { glBindBuffer (GL_ARRAY_BUFFER, this->m_texCoordBuffer); glBufferSubData (GL_ARRAY_BUFFER, 0, sizeof (texCoords), texCoords); this->m_uploadedUstart = ustart; this->m_uploadedUend = uend; this->m_uploadedVstart = vstart; this->m_uploadedVend = vend; } this->drawOutputQuad (this->m_supersampling); if (this->getContext ().getApp ().getContext ().settings.render.debug.brightnessLog) { static uint32_t brightnessFrameCounter = 0; if ((brightnessFrameCounter++ % 30) == 0) { std::vector px (static_cast (viewport.z) * viewport.w * 4); glReadPixels (viewport.x, viewport.y, viewport.z, viewport.w, GL_RGBA, GL_UNSIGNED_BYTE, px.data ()); uint64_t sum = 0; for (size_t i = 0; i < px.size (); i += 4) { sum += px[i] + px[i + 1] + px[i + 2]; } const double mean = static_cast (sum) / static_cast (px.size () / 4 * 3); sLog.out ("[BRIGHTNESS] frame=", brightnessFrameCounter, " mean=", mean); } } #if !NDEBUG glPopDebugGroup (); #endif } int CWallpaper::supersamplingFor (const glm::ivec2& outputSize) { const int requested = this->getContext ().getApp ().getContext ().settings.general.supersampling; if (requested <= 1 || outputSize.x <= 0 || outputSize.y <= 0) { return 1; } GLint maxTexture = 0; GLint maxRenderbuffer = 0; GLint maxViewport[2] = { 0, 0 }; glGetIntegerv (GL_MAX_TEXTURE_SIZE, &maxTexture); glGetIntegerv (GL_MAX_RENDERBUFFER_SIZE, &maxRenderbuffer); glGetIntegerv (GL_MAX_VIEWPORT_DIMS, maxViewport); const int limit = std::min ({ maxTexture, maxRenderbuffer, maxViewport[0], maxViewport[1] }); int factor = requested; while (factor > 1 && std::max (outputSize.x, outputSize.y) * factor > limit) { factor--; } if (factor != requested && factor != this->m_supersamplingLogged) { sLog.error ( "SSAA x", requested, " would need a ", outputSize.x * requested, "x", outputSize.y * requested, " scene buffer, more than the GPU allows (", limit, "), using x", factor ); } this->m_supersamplingLogged = factor; return factor; } void CWallpaper::drawOutputQuad (const int supersample) { glDisable (GL_BLEND); glDisable (GL_DEPTH_TEST); glDisable (GL_CULL_FACE); glUseProgram (this->m_shader); glActiveTexture (GL_TEXTURE0); glBindTexture (GL_TEXTURE_2D, this->getWallpaperTexture ()); glUniform1i (this->g_Texture0, 0); if (this->m_outputSampler == GL_NONE) { glGenSamplers (1, &this->m_outputSampler); glSamplerParameteri (this->m_outputSampler, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glSamplerParameteri (this->m_outputSampler, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } const uint32_t clamp = this->m_state.getClampingMode (); const GLint wrap = (clamp & TextureFlags_ClampUVs) ? GL_CLAMP_TO_EDGE : (clamp & TextureFlags_ClampUVsBorder) ? GL_CLAMP_TO_BORDER : GL_REPEAT; glSamplerParameteri (this->m_outputSampler, GL_TEXTURE_WRAP_S, wrap); glSamplerParameteri (this->m_outputSampler, GL_TEXTURE_WRAP_T, wrap); glSamplerParameterfv (this->m_outputSampler, GL_TEXTURE_BORDER_COLOR, &this->m_cornerColor.x); glBindSampler (0, this->m_outputSampler); // a sampler2D and a sampler3D on the same unit is an invalid draw even when the LUT is never read glUniform1i (this->g_Texture1, 1); const bool adjusted = !this->drawsImageAdjustments (); const bool lutEnabled = adjusted && this->m_lutTexture != GL_NONE && this->m_lutStrength > 0.0f; glUniform1i (this->u_ColorEnabled, adjusted && this->m_colorEnabled); glUniform1i (this->u_LutEnabled, lutEnabled); glUniform1i (this->u_InputLinear, this->m_linearInput || (this->m_scRGBInput && this->m_outputHDR)); glUniform1i (this->u_InputScRGB, this->m_scRGBInput); glUniform1i (this->u_OutputPQ, this->m_outputHDR); glUniform1i (this->u_Supersample, supersample); glUniform4fv (this->g_Params, 1, &this->m_colorParams.x); glUniform1f (this->g_LutParams, this->m_lutStrength); if (lutEnabled) { glActiveTexture (GL_TEXTURE1); glBindTexture (GL_TEXTURE_3D, this->m_lutTexture); glActiveTexture (GL_TEXTURE0); } glDrawArrays (GL_TRIANGLES, 0, 6); glBindSampler (0, GL_NONE); } void CWallpaper::setPause (bool newState) { } void CWallpaper::setAudioPolicy (bool muted, std::optional ambientVolume) { } void CWallpaper::setAudioHushed (bool hushed) { } void CWallpaper::setupFramebuffers (const bool depth, const TextureFormat format) { const uint32_t width = this->getCanvasWidth (); const uint32_t height = this->getCanvasHeight (); // layers and effects sample the frame clamped to its edges like WE (2.8.42 RenderDoc: _rt_FullFrameBuffer // reads are ClampEdge), the clamp mode and corner color only apply when it goes to the output const auto sceneFBO = this->create ( "_rt_FullFrameBuffer", format, TextureFlags_ClampUVs, 1.0, { width, height }, { width, height } ); if (depth) { sceneFBO->attachDepthBuffer (); } this->m_sceneFBO = sceneFBO; } AudioContext& CWallpaper::getAudioContext () const { return this->m_audioContext; } const WallpaperState& CWallpaper::getState () const { return this->m_state; } void CWallpaper::setScalingMode (WallpaperState::TextureUVsScaling mode) { this->m_state.setTextureUVsStrategy (mode); } void CWallpaper::setZoom (float zoom) { this->m_state.setZoom (zoom); } void CWallpaper::setOffset (float offsetX, float offsetY) { this->m_state.setOffset (offsetX, offsetY); } void CWallpaper::setAlignment (const WallpaperState::Alignment& alignment) { this->m_state.setAlignment (alignment); } void CWallpaper::setCornerColor (const glm::vec4& color) { this->m_cornerColor = color; } void CWallpaper::setImageAdjustments (const ImageAdjustments& adjustments) { this->m_imageAdjustments = adjustments; // wallpaper64.exe sub_140181F30: sliders are 0-100 around 50, contrast and saturation go through a square // root and brightness through a square before reaching ccsimple const float brightness = adjustments.brightness.value_or (50.0f) / 50.0f; const float contrast = adjustments.contrast.value_or (50.0f) / 50.0f; const float saturation = adjustments.saturation.value_or (50.0f) / 50.0f; const float hue = adjustments.hue.value_or (50.0f) / 100.0f - 0.5f; this->m_colorEnabled = adjustments.colorEnabled.value_or (false) && (!WallpaperEngine::Data::Utils::sameFloat (contrast, 1.0f) || !WallpaperEngine::Data::Utils::sameFloat (brightness, 1.0f) || !WallpaperEngine::Data::Utils::sameFloat (saturation, 1.0f) || WallpaperEngine::Data::Utils::isNonZero (hue)); this->m_colorParams = { std::pow (brightness, 2.0f), std::pow (contrast, 0.5f), std::pow (saturation, 0.5f), hue }; this->m_lutStrength = adjustments.filterStrength.value_or (100.0f) / 100.0f; this->m_flipHorizontal = adjustments.flipHorizontal.value_or (false); // only scenes and videos have these in Wallpaper Engine if (this->is ()) { this->m_colorEnabled = false; this->m_flipHorizontal = false; this->loadLut (""); return; } this->loadLut (adjustments.filter.value_or ("")); } bool CWallpaper::hasImageAdjustments () const { return this->m_colorEnabled || this->m_flipHorizontal || (this->m_lutTexture != GL_NONE && this->m_lutStrength > 0.0f); } GLuint CWallpaper::renderAdjustedFramebuffer () { if (!this->hasImageAdjustments () && !this->m_linearInput && !this->m_scRGBInput) { return this->getWallpaperFramebuffer (); } const auto width = static_cast (this->getFramebufferWidth ()); const auto height = static_cast (this->getFramebufferHeight ()); if (this->m_adjustedFBO == nullptr || this->m_adjustedFBO->getRealWidth () != width || this->m_adjustedFBO->getRealHeight () != height) { this->m_adjustedFBO = std::make_unique ( "_rt_ImageAdjustments", TextureFormat_ARGB8888, TextureFlags_ClampUVs, 1.0f, width, height, width, height ); } // the output quad puts v=0 at the top, the framebuffer keeps row 0 at the bottom const float ustart = this->m_flipHorizontal ? 1.0f : 0.0f; const float uend = 1.0f - ustart; const GLfloat texCoords[] = { ustart, 1.0f, uend, 1.0f, ustart, 0.0f, ustart, 0.0f, uend, 1.0f, uend, 0.0f }; this->m_uploadedUstart = std::numeric_limits::quiet_NaN (); const GLuint previousDestination = this->m_destFramebuffer; const bool outputHDR = this->m_outputHDR; this->m_destFramebuffer = this->m_adjustedFBO->getFramebuffer (); this->m_outputHDR = false; glViewport (0, 0, static_cast (width), static_cast (height)); glBindFramebuffer (GL_FRAMEBUFFER, this->m_destFramebuffer); glBindVertexArray (this->m_vaoBuffer); glBindBuffer (GL_ARRAY_BUFFER, this->m_texCoordBuffer); glBufferSubData (GL_ARRAY_BUFFER, 0, sizeof (texCoords), texCoords); this->drawOutputQuad (1); this->m_destFramebuffer = previousDestination; this->m_outputHDR = outputHDR; return this->m_adjustedFBO->getFramebuffer (); } void CWallpaper::loadLut (const std::string& name) { if (name == this->m_lutName) { return; } this->m_lutName = name; if (this->m_lutTexture != GL_NONE) { glDeleteTextures (1, &this->m_lutTexture); this->m_lutTexture = GL_NONE; } if (name.empty ()) { return; } try { const auto stream = this->getAssetLocator ().texture ("lut/" + name); const auto texture = WallpaperEngine::Data::Parsers::TextureParser::parse (BinaryReader (stream)); const auto& mipmap = texture->images.at (0).at (0); if (!(texture->flags & TextureFlags_Volume)) { sLog.error ("Image filter ", name, " is not a volume texture"); return; } stbi_uc* decoded = nullptr; const void* pixels = mipmap->uncompressedData.get (); const size_t expected = static_cast (mipmap->width) * mipmap->height * mipmap->depth * 4; // the z slices are stacked vertically in the image, the order glTexImage3D wants if (texture->freeImageFormat != FIF_UNKNOWN) { int width, height; decoded = decodeImageRGBA (mipmap->uncompressedData.get (), mipmap->uncompressedSize, width, height); if (decoded == nullptr || static_cast (width) * height * 4 != expected) { stbi_image_free (decoded); sLog.error ("Image filter ", name, " has unexpected image data"); return; } pixels = decoded; } else if ( texture->format != TextureFormat_ARGB8888 || static_cast (mipmap->uncompressedSize) < expected ) { sLog.error ("Image filter ", name, " has an unsupported format"); return; } glGenTextures (1, &this->m_lutTexture); glBindTexture (GL_TEXTURE_3D, this->m_lutTexture); glTexParameteri (GL_TEXTURE_3D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri (GL_TEXTURE_3D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri (GL_TEXTURE_3D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE); glTexParameteri (GL_TEXTURE_3D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE); glTexParameteri (GL_TEXTURE_3D, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE); glPixelStorei (GL_UNPACK_ALIGNMENT, 4); glTexImage3D ( GL_TEXTURE_3D, 0, GL_RGBA8, static_cast (mipmap->width), static_cast (mipmap->height), static_cast (mipmap->depth), 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels ); glBindTexture (GL_TEXTURE_3D, 0); stbi_image_free (decoded); } catch (const std::exception& e) { sLog.error ("Cannot load image filter ", name, ": ", e.what ()); } } std::shared_ptr CWallpaper::findFBO (const std::string& name) const { const auto fbo = this->find (name); if (fbo == nullptr) { sLog.exception ("Cannot find FBO ", name); } return fbo; } std::shared_ptr CWallpaper::getFBO () const { return this->m_sceneFBO; } const std::filesystem::path& CWallpaper::getSceneFile () const { return this->m_wallpaperData.project.sceneFile; } std::unique_ptr CWallpaper::fromWallpaper ( const Wallpaper& wallpaper, RenderContext& context, AudioContext& audioContext, const std::filesystem::path& resolvedBackgroundPath, const WallpaperState::TextureUVsScaling& scalingMode, const uint32_t& clampMode, const glm::ivec2& maxRenderSize ) { if (wallpaper.is ()) { return std::make_unique ( wallpaper, context, audioContext, scalingMode, clampMode ); } if (wallpaper.is