Ver código fonte

fixed rotations for some objects, fixed a lot of text bugs (more fixes incoming), added more mdls support

UwU 1 mês atrás
pai
commit
b106e5c459
55 arquivos alterados com 2033 adições e 1116 exclusões
  1. 2 0
      CMakeLists.txt
  2. 11 0
      docs/investigations/puppet-and-renderer-notes.md
  3. 36 37
      src/WallpaperEngine/Application/ApplicationContext.cpp
  4. 6 8
      src/WallpaperEngine/Application/WallpaperApplication.cpp
  5. 2 3
      src/WallpaperEngine/Application/WallpaperApplication.h
  6. 2 1
      src/WallpaperEngine/Audio/Drivers/SDLAudioDriver.cpp
  7. 30 0
      src/WallpaperEngine/Data/Assets/Texture.h
  8. 7 0
      src/WallpaperEngine/Data/Model/DynamicValue.cpp
  9. 0 2
      src/WallpaperEngine/Data/Model/PropertyAnimation.h
  10. 48 4
      src/WallpaperEngine/Data/Parsers/DynamicValueParser.cpp
  11. 6 3
      src/WallpaperEngine/Data/Parsers/ObjectParser.cpp
  12. 41 1
      src/WallpaperEngine/Data/Parsers/TextureParser.cpp
  13. 1 0
      src/WallpaperEngine/Data/Parsers/TextureParser.h
  14. 2 3
      src/WallpaperEngine/Data/Parsers/WallpaperParser.cpp
  15. 18 0
      src/WallpaperEngine/FileSystem/Adapters/Directory.cpp
  16. 1 0
      src/WallpaperEngine/FileSystem/Adapters/Directory.h
  17. 14 0
      src/WallpaperEngine/FileSystem/Adapters/Package.cpp
  18. 1 0
      src/WallpaperEngine/FileSystem/Adapters/Package.h
  19. 84 0
      src/WallpaperEngine/FileSystem/Adapters/Types.h
  20. 43 2
      src/WallpaperEngine/FileSystem/Container.cpp
  21. 3 0
      src/WallpaperEngine/FileSystem/Container.h
  22. 12 10
      src/WallpaperEngine/Render/CFBO.cpp
  23. 10 8
      src/WallpaperEngine/Render/CTexture.cpp
  24. 5 7
      src/WallpaperEngine/Render/CWallpaper.cpp
  25. 3 3
      src/WallpaperEngine/Render/Camera.cpp
  26. 195 0
      src/WallpaperEngine/Render/ImageDecoder.cpp
  27. 17 0
      src/WallpaperEngine/Render/ImageDecoder.h
  28. 33 19
      src/WallpaperEngine/Render/ModelData.cpp
  29. 98 97
      src/WallpaperEngine/Render/ModelData.h
  30. 48 144
      src/WallpaperEngine/Render/Objects/CImage.cpp
  31. 2 7
      src/WallpaperEngine/Render/Objects/CImage.h
  32. 18 18
      src/WallpaperEngine/Render/Objects/CMesh.cpp
  33. 120 114
      src/WallpaperEngine/Render/Objects/CParticle.cpp
  34. 32 30
      src/WallpaperEngine/Render/Objects/CSound.cpp
  35. 38 32
      src/WallpaperEngine/Render/Objects/CText.cpp
  36. 122 117
      src/WallpaperEngine/Render/Objects/PuppetPhysics.cpp
  37. 3 1
      src/WallpaperEngine/Render/Objects/PuppetPhysics.h
  38. 37 32
      src/WallpaperEngine/Render/Objects/PuppetRig.cpp
  39. 2 3
      src/WallpaperEngine/Render/Objects/PuppetRig.h
  40. 17 20
      src/WallpaperEngine/Render/Objects/TextLayout.cpp
  41. 2 3
      src/WallpaperEngine/Render/Shaders/GLSLContext.cpp
  42. 82 29
      src/WallpaperEngine/Render/Shaders/ShaderUnit.cpp
  43. 289 21
      src/WallpaperEngine/Render/TextureCache.cpp
  44. 12 11
      src/WallpaperEngine/Render/Volumetrics.cpp
  45. 2 2
      src/WallpaperEngine/Render/Volumetrics.h
  46. 18 17
      src/WallpaperEngine/Render/WallpaperState.cpp
  47. 203 174
      src/WallpaperEngine/Render/Wallpapers/CScene.cpp
  48. 4 1
      src/WallpaperEngine/Render/Wallpapers/CScene.h
  49. 195 101
      src/WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.cpp
  50. 6 11
      src/WallpaperEngine/Scripting/AnimationSystem.cpp
  51. 1 2
      src/WallpaperEngine/Scripting/AnimationSystem.h
  52. 19 11
      src/WallpaperEngine/Scripting/SceneObject.cpp
  53. 7 2
      src/WallpaperEngine/Scripting/ScriptEngine.cpp
  54. 19 5
      src/WallpaperEngine/Scripting/ScriptPropertiesObject.cpp
  55. 4 0
      src/WallpaperEngine/Scripting/ScriptableObject.cpp

+ 2 - 0
CMakeLists.txt

@@ -458,6 +458,8 @@ set(COMMON_SOURCES
     src/WallpaperEngine/Render/RenderContext.cpp
     src/WallpaperEngine/Render/TextureCache.h
     src/WallpaperEngine/Render/TextureCache.cpp
+    src/WallpaperEngine/Render/ImageDecoder.h
+    src/WallpaperEngine/Render/ImageDecoder.cpp
     src/WallpaperEngine/Render/FBOProvider.cpp
     src/WallpaperEngine/Render/FBOProvider.h
 

+ 11 - 0
docs/investigations/puppet-and-renderer-notes.md

@@ -318,3 +318,14 @@ is ~66 units off that origin, so the marks left the crease. Now `ResolvedTransfo
 of each attachment point) is applied in `updateScreenSpacePosition()` around the puppet mesh's bounds center.
 Only mikasa's eye has a non-zero rest angle among koshini, ahri, Arona, asagi and mikasa's hair, so nothing else
 changes. Sandbox headless render matches the preview lash direction; real hardware not yet confirmed.
+
+## Mikasa eye rotation (3764765600), resolved via RenderDoc (2026-10-01)
+
+The third attempt above was wrong. A RenderDoc capture of real WE 2.8.42 (eye draw: 825 indices, 444x444 texture)
+shows the eye's MVP rotated by only 2.26 degrees. The skinning matrices of mikasaback in the same frame give the
+head bones an animated delta of 2.79 degrees, so the eye's world angle is own 44.57 + bone rest -45.09 + 2.79 =
+2.27: exactly parent * attachment point * child local, nothing else. `mikasa eye.tex` is an open eye at that
+orientation (sclera, iris with the red dot, upper lash); the closed crease in mikasaback only shows during blinks.
+The extra mesh-center pivot rotation (`meshPivotAngle`) turned it 45 degrees into a horizontal lash and is removed.
+Position already matched WE (the vertex box lands on the same pixels). WE's puppet vertices are object-local and
+rotate around the object origin, our quad center.

+ 36 - 37
src/WallpaperEngine/Application/ApplicationContext.cpp

@@ -662,43 +662,42 @@ void ApplicationContext::loadSettingsFromArgv () {
 	.append ();
 
     // WE's alignment settings in its own units (sub_140181F30 divides them by 100)
-    const auto addAlignmentArgument
-	= [this, &backgroundGroup, &lastScreen] (
-	      const char* name, const char* help, const float maximum,
-	      float WallpaperEngine::Render::WallpaperState::Alignment::* field
-	  ) {
-	      backgroundGroup.add_argument (name)
-		  .help (help)
-		  .action ([this, &lastScreen, name, maximum, field] (const std::string& value) -> void {
-		      float parsed;
-
-		      try {
-			  parsed = std::stof (value);
-		      } catch (const std::exception&) {
-			  sLog.exception ("Invalid ", name, " value: ", value);
-		      }
-
-		      if (parsed < 0.0f || parsed > maximum) {
-			  sLog.exception (name, " must be between 0 and ", maximum, ": ", value);
-		      }
-
-		      parsed /= 100.0f;
-
-		      if (this->settings.render.mode == DESKTOP_BACKGROUND) {
-			  auto& alignment = this->settings.general.screenAlignments
-					       .try_emplace (lastScreen, this->settings.render.window.alignment)
-					       .first->second;
-			  alignment.*field = parsed;
-
-			  if (lastScreen.rfind ("span:", 0) == 0 && !this->settings.general.spanGroups.empty ()) {
-			      this->settings.general.spanGroups.back ().alignment.*field = parsed;
-			  }
-		      } else {
-			  this->settings.render.window.alignment.*field = parsed;
-		      }
-		  })
-		  .append ();
-	  };
+    const auto addAlignmentArgument = [this, &backgroundGroup, &lastScreen] (
+					  const char* name, const char* help, const float maximum,
+					  float WallpaperEngine::Render::WallpaperState::Alignment::* field
+				      ) {
+	backgroundGroup.add_argument (name)
+	    .help (help)
+	    .action ([this, &lastScreen, name, maximum, field] (const std::string& value) -> void {
+		float parsed;
+
+		try {
+		    parsed = std::stof (value);
+		} catch (const std::exception&) {
+		    sLog.exception ("Invalid ", name, " value: ", value);
+		}
+
+		if (parsed < 0.0f || parsed > maximum) {
+		    sLog.exception (name, " must be between 0 and ", maximum, ": ", value);
+		}
+
+		parsed /= 100.0f;
+
+		if (this->settings.render.mode == DESKTOP_BACKGROUND) {
+		    auto& alignment = this->settings.general.screenAlignments
+					  .try_emplace (lastScreen, this->settings.render.window.alignment)
+					  .first->second;
+		    alignment.*field = parsed;
+
+		    if (lastScreen.rfind ("span:", 0) == 0 && !this->settings.general.spanGroups.empty ()) {
+			this->settings.general.spanGroups.back ().alignment.*field = parsed;
+		    }
+		} else {
+		    this->settings.render.window.alignment.*field = parsed;
+		}
+	    })
+	    .append ();
+    };
 
     addAlignmentArgument (
 	"--alignment-position",

+ 6 - 8
src/WallpaperEngine/Application/WallpaperApplication.cpp

@@ -959,10 +959,9 @@ void WallpaperApplication::checkHotswapRequest () {
     if (!request.path.has_value () && !request.layersProvided && !request.volume.has_value ()
 	&& !request.xray.has_value () && !request.scaling.has_value () && !request.zoom.has_value ()
 	&& !request.offset.has_value () && !request.alignment.has_value () && !request.disableParallax.has_value ()
-	&& !request.expandCanvas.has_value ()
-	&& !request.cornerColor.has_value () && !request.imageAdjustmentsProvided && !request.speed.has_value ()
-	&& !request.audioScreen.has_value () && !request.ambientVolume.has_value () && !request.propertiesProvided
-	&& !request.audioSensitivityProvided && !request.soundVolumeProvided) {
+	&& !request.expandCanvas.has_value () && !request.cornerColor.has_value () && !request.imageAdjustmentsProvided
+	&& !request.speed.has_value () && !request.audioScreen.has_value () && !request.ambientVolume.has_value ()
+	&& !request.propertiesProvided && !request.audioSensitivityProvided && !request.soundVolumeProvided) {
 	sLog.error ("Hotswap requested but control file was empty");
 	return;
     }
@@ -1212,9 +1211,8 @@ glm::vec2 WallpaperApplication::resolveScreenOffset (const std::string& screen)
 								       : this->m_context.settings.render.window.offset;
 }
 
-WallpaperEngine::Render::WallpaperState::Alignment WallpaperApplication::resolveScreenAlignment (
-    const std::string& screen
-) const {
+WallpaperEngine::Render::WallpaperState::Alignment
+WallpaperApplication::resolveScreenAlignment (const std::string& screen) const {
     const auto it = this->m_context.settings.general.screenAlignments.find (screen);
 
     return it != this->m_context.settings.general.screenAlignments.end ()
@@ -2097,7 +2095,7 @@ void WallpaperApplication::takeScreenshot (const std::filesystem::path& filename
 	glFinish ();
 
 	// errors left over from rendering (e.g. a uniform type mismatch) would otherwise fail the readback below
-	while (glGetError () != GL_NO_ERROR) {}
+	while (glGetError () != GL_NO_ERROR) { }
 
 	const int readWidth = wallpaper->getFramebufferWidth ();
 	const int readHeight = wallpaper->getFramebufferHeight ();

+ 2 - 3
src/WallpaperEngine/Application/WallpaperApplication.h

@@ -212,9 +212,8 @@ private:
     [[nodiscard]] std::string resolveScreenBackgroundPath (const std::string& screen) const;
     [[nodiscard]] float resolveScreenZoom (const std::string& screen) const;
     [[nodiscard]] glm::vec2 resolveScreenOffset (const std::string& screen) const;
-    [[nodiscard]] WallpaperEngine::Render::WallpaperState::Alignment resolveScreenAlignment (
-	const std::string& screen
-    ) const;
+    [[nodiscard]] WallpaperEngine::Render::WallpaperState::Alignment
+    resolveScreenAlignment (const std::string& screen) const;
     [[nodiscard]] glm::vec4 resolveScreenCornerColor (const std::string& screen) const;
     /** Command line and control file settings for this screen (or span group) over what the preset carries */
     [[nodiscard]] ImageAdjustments

+ 2 - 1
src/WallpaperEngine/Audio/Drivers/SDLAudioDriver.cpp

@@ -8,7 +8,8 @@ using namespace WallpaperEngine::Audio;
 using namespace WallpaperEngine::Audio::Drivers;
 
 namespace {
-template <typename T> void scaleSamples (uint8_t* data, int bytes, int channels, int firstChannel, float left, float right) {
+template <typename T>
+void scaleSamples (uint8_t* data, int bytes, int channels, int firstChannel, float left, float right) {
     auto* samples = reinterpret_cast<T*> (data);
     const int count = bytes / static_cast<int> (sizeof (T));
 

+ 30 - 0
src/WallpaperEngine/Data/Assets/Texture.h

@@ -101,6 +101,21 @@ enum TextureFlags {
 	| TextureFlags_ClampUVsBorder | TextureFlags_Video | TextureFlags_Volume | TextureFlags_AlphaChannelPriority,
 };
 
+/**
+ * A part of a mipmap swapped in while a user property condition holds (TEXB0004, wallpaper64.exe 2.8.42
+ * sub_14015C8D0), e.g. an alternative outfit painted over the base image
+ */
+struct MipmapPatch {
+    uint32_t key = 0;
+    uint32_t x = 0;
+    uint32_t y = 0;
+    uint32_t width = 0;
+    uint32_t height = 0;
+    /** FreeImage format of the data, -1 for raw pixels like the mipmap's own */
+    int format = -1;
+    std::string data {};
+};
+
 struct Mipmap {
     uint32_t width = 0;
     uint32_t height = 0;
@@ -113,6 +128,20 @@ struct Mipmap {
     std::unique_ptr<char[]> compressedData = nullptr;
     std::unique_ptr<char[]> uncompressedData = nullptr;
     std::string json {};
+    std::vector<MipmapPatch> patches {};
+    /** RGBA pixels with the patches of the conditions that hold already applied, used instead of decoding the data */
+    std::vector<unsigned char> composedPixels {};
+};
+
+/** A TEXB0004 condition: while the user property holds, patches with this key get applied */
+struct TextureCondition {
+    /** Only the first condition that holds within a group counts */
+    uint32_t group = 0;
+    uint32_t key = 0;
+    /** Bit 0 blends the patch by its alpha, bit 1 replaces the whole mipmap with the patch's raw data */
+    uint32_t flags = 0;
+    /** {"condition": "<bool property>"} or {"condition": {"name": "<property>", "condition": "<value>"}} */
+    std::string json {};
 };
 
 struct Frame {
@@ -151,6 +180,7 @@ struct Texture {
     FIF freeImageFormat = FIF_UNKNOWN;
     bool isVideoMp4 = false;
     uint32_t imageCount = 0;
+    std::vector<TextureCondition> conditions {};
     std::map<uint32_t, MipmapList> images {};
     std::vector<FrameSharedPtr> frames {};
 

+ 7 - 0
src/WallpaperEngine/Data/Model/DynamicValue.cpp

@@ -201,6 +201,13 @@ void DynamicValue::update (const Model::Color& newValue, UpdateSource source) {
 }
 
 void DynamicValue::update (const DynamicValue& other, UpdateSource source) {
+    // WE's bool properties only take JSON bools (sub_1401E1A90), a combo's string without a condition
+    // leaves the scene's own value in place (3401903509's "visible": {"user": "diff", "value": true})
+    if (this->m_type == UnderlyingType::Boolean && !this->m_condition.has_value ()
+	&& other.getType () == UnderlyingType::String) {
+	return;
+    }
+
     // a slider bound to a vector property sets every component, but the property stays a vector
     const bool isVector = this->m_type == UnderlyingType::Vec2 || this->m_type == UnderlyingType::Vec3
 	|| this->m_type == UnderlyingType::Vec4;

+ 0 - 2
src/WallpaperEngine/Data/Model/PropertyAnimation.h

@@ -42,8 +42,6 @@ struct PropertyAnimation {
     Mode mode = Mode::Single;
     bool startPaused = false;
     bool wrapLoop = false;
-    /** Curve values are offsets on top of the property's own value instead of absolute values */
-    bool relative = false;
     std::vector<AnimationEvent> events;
     std::vector<std::string> children;
     std::optional<std::string> parent;

+ 48 - 4
src/WallpaperEngine/Data/Parsers/DynamicValueParser.cpp

@@ -1,6 +1,7 @@
 #include "DynamicValueParser.h"
 
 #include <cstdlib>
+#include <optional>
 #include <sstream>
 
 #include "UserSettingParser.h"
@@ -29,7 +30,44 @@ bool isNumericVector (const std::string& str) {
     return count >= 2;
 }
 
-std::shared_ptr<const PropertyAnimation> parseAnimation (const json& data) {
+// wallpaper64 sub_1401A4DB0: a "relative" animation is turned into an absolute one at load by adding the
+// property's value to the c0..c2 keys. Only a string value with three space separated parts qualifies, anything
+// else keeps the keys as they are
+std::optional<glm::vec3> relativeAnimationBase (const json& value) {
+    if (!value.is_string ()) {
+	return std::nullopt;
+    }
+
+    const std::string& str = value.get_ref<const std::string&> ();
+    const char* cursor = str.c_str ();
+    glm::vec3 base;
+
+    if (*cursor == '\0') {
+	return std::nullopt;
+    }
+
+    for (int component = 0; component < 2; component++) {
+	base[component] = static_cast<float> (std::atof (cursor));
+
+	while (*cursor != '\0' && *cursor != ' ') {
+	    cursor++;
+	}
+
+	if (*cursor == '\0') {
+	    return std::nullopt;
+	}
+
+	while (*cursor == ' ') {
+	    cursor++;
+	}
+    }
+
+    base[2] = static_cast<float> (std::atof (cursor));
+
+    return base;
+}
+
+std::shared_ptr<const PropertyAnimation> parseAnimation (const json& data, const json& value) {
     auto animation = std::make_shared<PropertyAnimation> ();
 
     for (size_t component = 0; component < animation->curves.size (); component++) {
@@ -40,8 +78,14 @@ std::shared_ptr<const PropertyAnimation> parseAnimation (const json& data) {
 	}
     }
 
-    if (const auto relative = data.find ("relative"); relative != data.end () && relative->is_boolean ()) {
-	animation->relative = relative->get<bool> ();
+    if (data.contains ("relative")) {
+	if (const auto base = relativeAnimationBase (value); base.has_value ()) {
+	    for (int component = 0; component < 3; component++) {
+		for (auto& key : animation->curves[component]) {
+		    key.value += (*base)[component];
+		}
+	    }
+	}
     }
 
     const auto options = data.find ("options");
@@ -264,7 +308,7 @@ DynamicValueUniquePtr DynamicValueParser::parse (const json& data, const Propert
     if (data.is_object ()) {
 	if (const auto animation = data.find ("animation");
 	    animation != data.end () && animation->is_object () && animation->contains ("c0")) {
-	    value->setAnimation (parseAnimation (*animation));
+	    value->setAnimation (parseAnimation (*animation, valueIt));
 	}
     }
 

+ 6 - 3
src/WallpaperEngine/Data/Parsers/ObjectParser.cpp

@@ -547,7 +547,7 @@ MeshUniquePtr ObjectParser::parseMesh (const JSON& it, const Project& project, O
 		   .modelData = model.is_number () ? std::optional<int> (model.get<int> ()) : std::nullopt,
 		   .skin = skinIt != it.end () && skinIt->is_number_integer () ? skinIt->get<uint32_t> () : 0,
 		   .animationLayers = animationLayers.has_value () ? parseAnimationLayers (*animationLayers, project)
-								  : std::vector<ImageAnimationLayerUniquePtr> {} }
+								   : std::vector<ImageAnimationLayerUniquePtr> {} }
     );
 }
 
@@ -1535,7 +1535,8 @@ ParticleRenderer ObjectParser::parseParticleRenderer (const JSON& it) {
     // "fixed" is screen too; "axis" "0 0 0" becomes y up
     const std::string orientation = it.optional<std::string> ("orientation", "screen");
     const auto axisIt = it.find ("axis");
-    glm::vec3 axis = axisIt != it.end () && axisIt->is_string () ? parseFloats (axisIt->get<std::string> ()) : glm::vec3 (0.0f);
+    glm::vec3 axis
+	= axisIt != it.end () && axisIt->is_string () ? parseFloats (axisIt->get<std::string> ()) : glm::vec3 (0.0f);
     glm::vec3 axisUp (0.0f, 0.0f, -1.0f);
 
     axis = axis == glm::vec3 (0.0f) ? glm::vec3 (0.0f, 1.0f, 0.0f) : glm::normalize (axis);
@@ -1556,7 +1557,9 @@ ParticleRenderer ObjectParser::parseParticleRenderer (const JSON& it) {
 	.uvSmoothing = it.optional ("uvsmoothing", true),
 	.fadeAlpha = it.optional ("fadealpha", false),
 	.fadeSize = it.optional ("fadesize", false),
-	.orientation = orientation == "upright" ? 1 : orientation == "fixed" ? 2 : 0,
+	.orientation = orientation == "upright" ? 1
+	    : orientation == "fixed"            ? 2
+						: 0,
 	.axis = axis,
 	.axisUp = axisUp,
 	.orientationFlag = (it.optional ("flags", 0) & 1) != 0,

+ 41 - 1
src/WallpaperEngine/Data/Parsers/TextureParser.cpp

@@ -23,6 +23,10 @@ TextureUniquePtr TextureParser::parse (const BinaryReader& file) {
 
 	for (uint32_t mipmap = 0; mipmap < mipmapCount; mipmap++) {
 	    mipmaps.emplace_back (parseMipmap (file, *result));
+
+	    if (!result->conditions.empty ()) {
+		parseMipmapPatches (*mipmaps.back (), file);
+	    }
 	}
 
 	result->images.emplace (image, mipmaps);
@@ -91,6 +95,29 @@ MipmapSharedPtr TextureParser::parseMipmap (const BinaryReader& file, const Text
     return result;
 }
 
+void TextureParser::parseMipmapPatches (Mipmap& mipmap, const BinaryReader& file) {
+    const uint32_t groupCount = file.nextUInt32 ();
+
+    for (uint32_t group = 0; group < groupCount; group++) {
+	const uint32_t patchCount = file.nextUInt32 ();
+
+	for (uint32_t index = 0; index < patchCount; index++) {
+	    MipmapPatch patch;
+
+	    std::ignore = file.nextUInt32 ();
+	    patch.key = file.nextUInt32 ();
+	    patch.x = file.nextUInt32 ();
+	    patch.y = file.nextUInt32 ();
+	    patch.width = file.nextUInt32 ();
+	    patch.height = file.nextUInt32 ();
+	    patch.format = file.nextInt ();
+	    patch.data.resize (file.nextUInt32 ());
+	    file.next (patch.data.data (), patch.data.size ());
+	    mipmap.patches.push_back (std::move (patch));
+	}
+    }
+}
+
 FrameSharedPtr TextureParser::parseFrameV1 (const BinaryReader& file) {
     auto result = std::make_shared<Frame> ();
 
@@ -217,7 +244,9 @@ void TextureParser::parseContainer (Texture& header, const BinaryReader& file) {
     if (strncmp (magic, "TEXB0004", 9) == 0) {
 	header.containerVersion = ContainerVersion_TEXB0004;
 	header.freeImageFormat = parseFIF (file.nextUInt32 ());
-	header.isVideoMp4 = file.nextUInt32 () == 1;
+	// wallpaper64.exe 2.8.42 sub_14015C8D0 reads this as the number of user property conditions
+	const uint32_t conditionCount = file.nextUInt32 ();
+	header.isVideoMp4 = conditionCount == 1;
 
 	if (header.freeImageFormat == FIF_UNKNOWN && header.isVideoMp4) {
 	    header.freeImageFormat = FIF_MP4;
@@ -226,6 +255,17 @@ void TextureParser::parseContainer (Texture& header, const BinaryReader& file) {
 	// TEXB0004 behaves like TEXB0003 unless it's actually an MP4
 	if (header.freeImageFormat != FIF_MP4) {
 	    header.containerVersion = ContainerVersion_TEXB0003;
+	    header.isVideoMp4 = false;
+
+	    for (uint32_t index = 0; index < conditionCount; index++) {
+		TextureCondition condition;
+
+		condition.group = file.nextUInt32 ();
+		condition.key = file.nextUInt32 ();
+		condition.flags = file.nextUInt32 ();
+		condition.json = file.nextNullTerminatedString ();
+		header.conditions.push_back (std::move (condition));
+	    }
 	}
     } else if (strncmp (magic, "TEXB0003", 9) == 0) {
 	header.containerVersion = ContainerVersion_TEXB0003;

+ 1 - 0
src/WallpaperEngine/Data/Parsers/TextureParser.h

@@ -27,6 +27,7 @@ private:
     static void parseTextureHeader (Texture& header, const BinaryReader& file);
     static void parseContainer (Texture& header, const BinaryReader& file);
     static void parseAnimations (Texture& header, const BinaryReader& file);
+    static void parseMipmapPatches (Mipmap& mipmap, const BinaryReader& file);
     static TextureFormat parseTextureFormat (uint32_t value);
     static uint32_t parseTextureFlags (uint32_t value);
     static FIF parseFIF (uint32_t value);

+ 2 - 3
src/WallpaperEngine/Data/Parsers/WallpaperParser.cpp

@@ -77,9 +77,8 @@ void dropDeepPassthroughParents (ObjectList& objects) {
 	linked[index] = parent;
 	children[parent].push_back (index);
     };
-    const auto tooDeep = [&] (int index, int parent) {
-	return ancestorsDepth (parent) + chainDepth (chainDepth, index, 0) > 3;
-    };
+    const auto tooDeep
+	= [&] (int index, int parent) { return ancestorsDepth (parent) + chainDepth (chainDepth, index, 0) > 3; };
     const auto drop = [&] (int index) {
 	sLog.out (
 	    "Object ", objects[index]->id, " loses its parent ", objects[index]->parent.value (),

+ 18 - 0
src/WallpaperEngine/FileSystem/Adapters/Directory.cpp

@@ -144,6 +144,24 @@ DirectoryAdapter::resolveWorkshopDependencyAlias (const std::filesystem::path& p
     return found;
 }
 
+std::vector<std::string> DirectoryAdapter::listFiles (const std::filesystem::path& dir) const {
+    std::vector<std::string> names;
+    std::error_code ec;
+    const auto finalpath = std::filesystem::weakly_canonical (resolveCase (this->basepath, dir), ec);
+
+    if (ec || finalpath.string ().find (this->basepath.string ()) != 0) {
+	return names;
+    }
+
+    for (const auto& entry : std::filesystem::directory_iterator (finalpath, ec)) {
+	if (entry.is_regular_file (ec)) {
+	    names.push_back (entry.path ().filename ().string ());
+	}
+    }
+
+    return names;
+}
+
 bool DirectoryFactory::handlesMountpoint (const std::filesystem::path& path) const {
     try {
 	const auto finalpath = std::filesystem::canonical (path);

+ 1 - 0
src/WallpaperEngine/FileSystem/Adapters/Directory.h

@@ -21,6 +21,7 @@ struct DirectoryAdapter final : Adapter {
     [[nodiscard]] std::filesystem::path physicalPath (const std::filesystem::path& path) const override;
     [[nodiscard]] std::optional<std::filesystem::path>
     resolveWorkshopDependencyAlias (const std::filesystem::path& path) const override;
+    [[nodiscard]] std::vector<std::string> listFiles (const std::filesystem::path& dir) const override;
 
     const std::filesystem::path basepath;
 };

+ 14 - 0
src/WallpaperEngine/FileSystem/Adapters/Package.cpp

@@ -77,6 +77,20 @@ PackageAdapter::resolveWorkshopDependencyAlias (const std::filesystem::path& pat
     return found;
 }
 
+std::vector<std::string> PackageAdapter::listFiles (const std::filesystem::path& dir) const {
+    std::vector<std::string> names;
+
+    for (const auto& file : this->package->files) {
+	const std::filesystem::path path = file->filename;
+
+	if (equalsIgnoreCase (path.parent_path ().generic_string (), dir.generic_string ())) {
+	    names.push_back (path.filename ().string ());
+	}
+    }
+
+    return names;
+}
+
 bool PackageFactory::handlesMountpoint (const std::filesystem::path& path) const {
     try {
 	const auto finalpath = std::filesystem::canonical (path);

+ 1 - 0
src/WallpaperEngine/FileSystem/Adapters/Package.h

@@ -25,6 +25,7 @@ struct PackageAdapter final : Adapter {
     [[nodiscard]] std::filesystem::path physicalPath (const std::filesystem::path& path) const override;
     [[nodiscard]] std::optional<std::filesystem::path>
     resolveWorkshopDependencyAlias (const std::filesystem::path& path) const override;
+    [[nodiscard]] std::vector<std::string> listFiles (const std::filesystem::path& dir) const override;
 
     PackageUniquePtr package;
 };

+ 84 - 0
src/WallpaperEngine/FileSystem/Adapters/Types.h

@@ -1,9 +1,13 @@
 #pragma once
 
 #include "WallpaperEngine/Data/Utils/BinaryReader.h"
+#include <algorithm>
+#include <cctype>
+#include <cstring>
 #include <filesystem>
 #include <optional>
 #include <string>
+#include <vector>
 
 namespace WallpaperEngine::FileSystem::Adapters {
 using namespace WallpaperEngine::Data::Utils;
@@ -25,6 +29,84 @@ inline bool isWorkshopDependencyAliasOf (const std::string& candidate, const std
     return !middle.empty () && middle.find ('/') == std::string::npos;
 }
 
+// The characters a long name part keeps in its Windows 8.3 short name: upper case, no spaces or dots, the ones FAT
+// doesn't allow (and every non-ASCII character, counted once per UTF-8 sequence) become '_'
+inline std::string shortNameChars (std::string_view part) {
+    std::string out;
+
+    for (const unsigned char c : part) {
+	if (c == ' ' || c == '.' || (c & 0xC0) == 0x80) {
+	    continue;
+	}
+
+	if (c >= 0x80 || std::strchr ("+,;=[]", c) != nullptr) {
+	    out += '_';
+	} else {
+	    out += static_cast<char> (std::toupper (c));
+	}
+    }
+
+    return out;
+}
+
+// Which sibling a Windows 8.3 alias like "KONACH~1.TEX" stood for on the author's disk. Scenes sometimes reference
+// those (3810078802), but packages and copies only carry the long names. Windows numbers the aliases sharing a
+// basis and extension in creation order, which isn't stored anywhere, so the siblings are taken in name order.
+inline std::optional<std::string> resolveShortNameAlias (std::vector<std::string> siblings, const std::string& wanted) {
+    const auto dot = wanted.rfind ('.');
+    const std::string stem = wanted.substr (0, dot);
+    const std::string extension = dot == std::string::npos ? "" : shortNameChars (wanted.substr (dot + 1));
+    const auto tilde = stem.rfind ('~');
+
+    if (tilde == std::string::npos || tilde == 0 || stem.size () > 8 || extension.size () > 3
+	|| tilde + 1 == stem.size ()
+	|| !std::all_of (stem.begin () + tilde + 1, stem.end (), [] (unsigned char c) { return std::isdigit (c); })) {
+	return std::nullopt;
+    }
+
+    const std::string basis = shortNameChars (stem.substr (0, tilde));
+    const int index = std::stoi (stem.substr (tilde + 1));
+
+    if (basis.empty () || index < 1) {
+	return std::nullopt;
+    }
+
+    std::erase_if (siblings, [&] (const std::string& name) {
+	const auto nameDot = name.rfind ('.');
+	const std::string nameStem = name.substr (0, nameDot);
+	const std::string nameExtension = nameDot == std::string::npos ? "" : name.substr (nameDot + 1);
+	const auto isShortName = [] (const std::string& part) {
+	    return std::ranges::equal (shortNameChars (part), part, [] (unsigned char x, unsigned char y) {
+		return x == std::toupper (y);
+	    });
+	};
+	// names that already fit 8.3 (in any case) never got an alias
+	const bool hasAlias = nameStem.size () > 8 || nameExtension.size () > 3 || !isShortName (nameStem)
+	    || !isShortName (nameExtension) || std::ranges::count (name, '.') > 1;
+
+	if (!hasAlias) {
+	    return true;
+	}
+
+	const std::string nameBasis = shortNameChars (nameStem);
+
+	return shortNameChars (nameExtension).substr (0, 3) != extension || nameBasis.substr (0, basis.size ()) != basis
+	    || (nameBasis.size () > basis.size () && basis.size () != 7 - (stem.size () - tilde - 1));
+    });
+
+    std::ranges::sort (siblings, [] (const std::string& a, const std::string& b) {
+	return std::ranges::lexicographical_compare (a, b, [] (unsigned char x, unsigned char y) {
+	    return std::toupper (x) < std::toupper (y);
+	});
+    });
+
+    if (static_cast<size_t> (index) > siblings.size ()) {
+	return std::nullopt;
+    }
+
+    return siblings[index - 1];
+}
+
 struct Adapter {
     Adapter () = default;
     virtual ~Adapter () = default;
@@ -38,6 +120,8 @@ struct Adapter {
     resolveWorkshopDependencyAlias (const std::filesystem::path& path) const {
 	return std::nullopt;
     }
+
+    [[nodiscard]] virtual std::vector<std::string> listFiles (const std::filesystem::path& dir) const { return {}; }
 };
 
 using AdapterSharedPtr = std::shared_ptr<Adapter>;

+ 43 - 2
src/WallpaperEngine/FileSystem/Container.cpp

@@ -34,7 +34,20 @@ Container::Container () {
 ReadStreamSharedPtr Container::read (const std::filesystem::path& path) const {
     const auto normalized = normalize_path (path);
 
-    ReadStreamSharedPtr result = this->resolveAdapterForFile (path).open (normalized);
+    ReadStreamSharedPtr result;
+
+    try {
+	result = this->resolveAdapterForFile (path).open (normalized);
+    } catch (std::filesystem::filesystem_error&) {
+	const auto alias = this->resolveShortNameAlias (normalized);
+
+	if (!alias.has_value ()) {
+	    throw;
+	}
+
+	sLog.out ("Using '", alias->string (), "' for the Windows short name '", normalized.string (), "'");
+	result = this->resolveAdapterForFile (*alias).open (*alias);
+    }
 
     if (result->fail ()) {
 	throw std::runtime_error ("Failed to open file: " + normalized.string ());
@@ -123,4 +136,32 @@ Container::resolveWorkshopDependencyAlias (const std::filesystem::path& path) co
     }
 
     return std::nullopt;
-}
+}
+std::optional<std::filesystem::path> Container::resolveShortNameAlias (const std::filesystem::path& path) const {
+    const auto normalized = normalize_path (path);
+    const auto wanted = normalized.filename ().string ();
+
+    if (wanted.find ('~') == std::string::npos) {
+	return std::nullopt;
+    }
+
+    for (const auto& [root, adapter] : this->m_mountpoints) {
+	if (!normalized.string ().starts_with (root.string ())) {
+	    continue;
+	}
+
+	const std::filesystem::path relative = normalized.string ().substr (root.string ().length ());
+	const auto found = Adapters::resolveShortNameAlias (adapter->listFiles (relative.parent_path ()), wanted);
+
+	if (found.has_value ()) {
+	    // relative to the mountpoint root, without a leading "/", like the adapters expect it
+	    return relative.parent_path () / *found;
+	}
+    }
+
+    if (!normalized.string ().starts_with ("/")) {
+	return this->resolveShortNameAlias ("/" + normalized.string ());
+    }
+
+    return std::nullopt;
+}

+ 3 - 0
src/WallpaperEngine/FileSystem/Container.h

@@ -62,6 +62,9 @@ public:
     [[nodiscard]] std::optional<std::filesystem::path>
     resolveWorkshopDependencyAlias (const std::filesystem::path& path) const;
 
+    /** The long-named sibling a Windows 8.3 alias (KONACH~1.tex) in path stood for, see resolveShortNameAlias */
+    [[nodiscard]] std::optional<std::filesystem::path> resolveShortNameAlias (const std::filesystem::path& path) const;
+
 private:
     /**
      * Searches for an adapter to handle the given file

+ 12 - 10
src/WallpaperEngine/Render/CFBO.cpp

@@ -45,16 +45,18 @@ CFBO::CFBO (
     if (format == TextureFormat_D32f) {
 	this->setupDepthOnly (textureWidth, textureHeight);
 	this->m_resolution = { textureWidth, textureHeight, realWidth, realHeight };
-	this->m_frames.push_back (std::make_shared<Frame> (Frame {
-	    .frameNumber = 0,
-	    .frametime = 0,
-	    .x = 0,
-	    .y = 0,
-	    .width1 = static_cast<float> (textureWidth),
-	    .width2 = static_cast<float> (realWidth),
-	    .height1 = static_cast<float> (textureHeight),
-	    .height2 = static_cast<float> (realHeight),
-	}));
+	this->m_frames.push_back (
+	    std::make_shared<Frame> (Frame {
+		.frameNumber = 0,
+		.frametime = 0,
+		.x = 0,
+		.y = 0,
+		.width1 = static_cast<float> (textureWidth),
+		.width2 = static_cast<float> (realWidth),
+		.height1 = static_cast<float> (textureHeight),
+		.height2 = static_cast<float> (realHeight),
+	    })
+	);
 	return;
     }
 

+ 10 - 8
src/WallpaperEngine/Render/CTexture.cpp

@@ -3,6 +3,8 @@
 
 #include <lz4.h>
 
+#include "ImageDecoder.h"
+
 #define STB_IMAGE_IMPLEMENTATION
 #include "RenderContext.h"
 
@@ -64,13 +66,11 @@ CTexture::CTexture (RenderContext& context, TextureUniquePtr header) :
 	    const uint32_t bufferSize = mipmap->uncompressedSize;
 	    GLenum textureFormat = GL_RGBA;
 
-	    if (this->m_header->freeImageFormat != FIF_UNKNOWN) {
-		int fileChannels;
-
-		dataptr = handle = stbi_load_from_memory (
-		    reinterpret_cast<unsigned char*> (mipmap->uncompressedData.get ()), mipmap->uncompressedSize,
-		    &width, &height, &fileChannels, 4
-		);
+	    if (!mipmap->composedPixels.empty ()) {
+		dataptr = mipmap->composedPixels.data ();
+	    } else if (this->m_header->freeImageFormat != FIF_UNKNOWN) {
+		dataptr = handle
+		    = decodeImageRGBA (mipmap->uncompressedData.get (), mipmap->uncompressedSize, width, height);
 	    } else {
 		if (this->m_header->format == TextureFormat_R8) {
 		    // 1 byte per pixel, so alignment must be set manually
@@ -102,10 +102,12 @@ CTexture::CTexture (RenderContext& context, TextureUniquePtr header) :
 		    sLog.exception ("Cannot load texture, unknown format", this->m_header->format);
 	    }
 
-	    if (this->m_header->freeImageFormat != FIF_UNKNOWN) {
+	    if (handle != nullptr) {
 		stbi_image_free (handle);
 	    }
 
+	    std::vector<unsigned char> ().swap (mipmap->composedPixels);
+
 	    level++;
 	}
     }

+ 5 - 7
src/WallpaperEngine/Render/CWallpaper.cpp

@@ -2,7 +2,7 @@
 #include <tuple>
 #include <vector>
 
-#include <stb_image.h>
+#include "ImageDecoder.h"
 
 #include "CWallpaper.h"
 #include "WallpaperEngine/Assets/AssetLoadException.h"
@@ -269,7 +269,8 @@ void CWallpaper::updateUVs (const glm::ivec4& viewport, const bool vflip) {
 
 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 };
+	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 ();
@@ -584,12 +585,9 @@ void CWallpaper::loadLut (const std::string& name) {
 
 	// the z slices are stacked vertically in the image, the order glTexImage3D wants
 	if (texture->freeImageFormat != FIF_UNKNOWN) {
-	    int width, height, channels;
+	    int width, height;
 
-	    decoded = stbi_load_from_memory (
-		reinterpret_cast<const stbi_uc*> (mipmap->uncompressedData.get ()), mipmap->uncompressedSize, &width,
-		&height, &channels, 4
-	    );
+	    decoded = decodeImageRGBA (mipmap->uncompressedData.get (), mipmap->uncompressedSize, width, height);
 
 	    if (decoded == nullptr || static_cast<size_t> (width) * height * 4 != expected) {
 		stbi_image_free (decoded);

+ 3 - 3
src/WallpaperEngine/Render/Camera.cpp

@@ -136,8 +136,7 @@ void Camera::setPerspectiveView (const glm::mat4& view, const float fov) {
     glm::mat4 layerView = view;
     layerView[3][2] = -2000.0f;
     this->m_perspectiveLayer = kFlipY
-	* glm::perspective (2.0f * std::atan (std::tan (radians / 2.0f) / 2000.0f), aspect, 5.0f, 15000.0f)
-	* layerView;
+	* glm::perspective (2.0f * std::atan (std::tan (radians / 2.0f) / 2000.0f), aspect, 5.0f, 15000.0f) * layerView;
 }
 
 void Camera::setVisibleRegion (const glm::vec4& margins, const float outputAspect) {
@@ -185,7 +184,8 @@ void Camera::updatePerspectiveLayers () {
     view[3][1] -= centerY;
     view[3][2] = -distance;
 
-    const float aspect = this->m_outputAspect > 0.0f ? this->m_outputAspect : this->m_canvasWidth / this->m_canvasHeight;
+    const float aspect
+	= this->m_outputAspect > 0.0f ? this->m_outputAspect : this->m_canvasWidth / this->m_canvasHeight;
     const glm::mat4 projection = glm::perspective (fov, aspect, 5.0f, farZ);
 
     const glm::vec3 center (width / 2.0f, height / 2.0f, 0.0f);

+ 195 - 0
src/WallpaperEngine/Render/ImageDecoder.cpp

@@ -0,0 +1,195 @@
+#include "ImageDecoder.h"
+
+#include <cstdint>
+#include <cstdlib>
+#include <cstring>
+#include <utility>
+
+namespace {
+uint16_t read16 (const uint8_t* p, bool bigEndian) { return bigEndian ? (p[0] << 8) | p[1] : (p[1] << 8) | p[0]; }
+
+uint32_t read32 (const uint8_t* p, bool bigEndian) {
+    return bigEndian ? (uint32_t (p[0]) << 24) | (p[1] << 16) | (p[2] << 8) | p[3]
+		     : (uint32_t (p[3]) << 24) | (p[2] << 16) | (p[1] << 8) | p[0];
+}
+
+int orientationFromTiff (const uint8_t* tiff, size_t size) {
+    if (size < 8) {
+	return 1;
+    }
+
+    bool bigEndian;
+
+    if (tiff[0] == 'I' && tiff[1] == 'I') {
+	bigEndian = false;
+    } else if (tiff[0] == 'M' && tiff[1] == 'M') {
+	bigEndian = true;
+    } else {
+	return 1;
+    }
+
+    const uint32_t ifd = read32 (tiff + 4, bigEndian);
+
+    if (ifd > size - 2) {
+	return 1;
+    }
+
+    const uint16_t count = read16 (tiff + ifd, bigEndian);
+
+    for (uint16_t i = 0; i < count; i++) {
+	const size_t entry = ifd + 2 + i * 12ul;
+
+	if (entry + 12 > size) {
+	    break;
+	}
+
+	// 0x0112 Orientation, SHORT
+	if (read16 (tiff + entry, bigEndian) == 0x0112 && read16 (tiff + entry + 2, bigEndian) == 3) {
+	    const int value = read16 (tiff + entry + 8, bigEndian);
+	    return value >= 1 && value <= 8 ? value : 1;
+	}
+    }
+
+    return 1;
+}
+
+int jpegOrientation (const uint8_t* data, size_t size) {
+    if (size < 4 || data[0] != 0xFF || data[1] != 0xD8) {
+	return 1;
+    }
+
+    size_t offset = 2;
+
+    while (offset + 4 <= size) {
+	if (data[offset] != 0xFF) {
+	    return 1;
+	}
+
+	const uint8_t marker = data[offset + 1];
+
+	// fill bytes
+	if (marker == 0xFF) {
+	    offset++;
+	    continue;
+	}
+
+	// start of scan or end of image, no more metadata
+	if (marker == 0xDA || marker == 0xD9) {
+	    return 1;
+	}
+
+	const size_t length = (data[offset + 2] << 8) | data[offset + 3];
+
+	if (length < 2 || offset + 2 + length > size) {
+	    return 1;
+	}
+
+	const uint8_t* segment = data + offset + 4;
+	const size_t segmentSize = length - 2;
+
+	if (marker == 0xE1 && segmentSize > 6 && memcmp (segment, "Exif\0\0", 6) == 0) {
+	    return orientationFromTiff (segment + 6, segmentSize - 6);
+	}
+
+	offset += 2 + length;
+    }
+
+    return 1;
+}
+
+int orientationOf (const void* data, size_t size) { return jpegOrientation (static_cast<const uint8_t*> (data), size); }
+
+bool swapsAxes (int orientation) { return orientation >= 5; }
+} // namespace
+
+namespace WallpaperEngine::Render {
+stbi_uc* decodeImageRGBA (const void* data, size_t size, int& width, int& height) {
+    int channels;
+    stbi_uc* pixels = stbi_load_from_memory (
+	static_cast<const stbi_uc*> (data), static_cast<int> (size), &width, &height, &channels, 4
+    );
+
+    if (pixels == nullptr) {
+	return nullptr;
+    }
+
+    const int orientation = orientationOf (data, size);
+
+    if (orientation == 1) {
+	return pixels;
+    }
+
+    const int srcWidth = width;
+    const int srcHeight = height;
+    const int dstWidth = swapsAxes (orientation) ? srcHeight : srcWidth;
+    const int dstHeight = swapsAxes (orientation) ? srcWidth : srcHeight;
+    auto* rotated = static_cast<stbi_uc*> (malloc (static_cast<size_t> (dstWidth) * dstHeight * 4));
+
+    if (rotated == nullptr) {
+	return pixels;
+    }
+
+    const auto* src = reinterpret_cast<const uint32_t*> (pixels);
+    auto* dst = reinterpret_cast<uint32_t*> (rotated);
+
+    for (int y = 0; y < dstHeight; y++) {
+	for (int x = 0; x < dstWidth; x++) {
+	    int sx, sy;
+
+	    switch (orientation) {
+		case 2:
+		    sx = srcWidth - 1 - x;
+		    sy = y;
+		    break;
+		case 3:
+		    sx = srcWidth - 1 - x;
+		    sy = srcHeight - 1 - y;
+		    break;
+		case 4:
+		    sx = x;
+		    sy = srcHeight - 1 - y;
+		    break;
+		case 5:
+		    sx = y;
+		    sy = x;
+		    break;
+		case 6:
+		    sx = y;
+		    sy = srcHeight - 1 - x;
+		    break;
+		case 7:
+		    sx = srcWidth - 1 - y;
+		    sy = srcHeight - 1 - x;
+		    break;
+		default:
+		    sx = srcWidth - 1 - y;
+		    sy = x;
+		    break;
+	    }
+
+	    dst[static_cast<size_t> (y) * dstWidth + x] = src[static_cast<size_t> (sy) * srcWidth + sx];
+	}
+    }
+
+    stbi_image_free (pixels);
+    width = dstWidth;
+    height = dstHeight;
+    return rotated;
+}
+
+bool decodedImageSize (const void* data, size_t size, int& width, int& height) {
+    int channels;
+
+    if (!stbi_info_from_memory (
+	    static_cast<const stbi_uc*> (data), static_cast<int> (size), &width, &height, &channels
+	)) {
+	return false;
+    }
+
+    if (swapsAxes (orientationOf (data, size))) {
+	std::swap (width, height);
+    }
+
+    return true;
+}
+} // namespace WallpaperEngine::Render

+ 17 - 0
src/WallpaperEngine/Render/ImageDecoder.h

@@ -0,0 +1,17 @@
+#pragma once
+
+#include <cstddef>
+#include <stb_image.h>
+
+namespace WallpaperEngine::Render {
+/**
+ * Decodes an encoded image (jpeg, png...) to RGBA8 the way WE's resourceutil64 does it: FreeImage with
+ * JPEG_EXIFROTATE, so jpegs come out in their EXIF orientation. Free the result with stbi_image_free.
+ */
+stbi_uc* decodeImageRGBA (const void* data, size_t size, int& width, int& height);
+
+/**
+ * Size of the image once decoded with decodeImageRGBA, without decoding it
+ */
+bool decodedImageSize (const void* data, size_t size, int& width, int& height);
+} // namespace WallpaperEngine::Render

+ 33 - 19
src/WallpaperEngine/Render/ModelData.cpp

@@ -10,11 +10,11 @@ using namespace WallpaperEngine::Render::ModelData;
 namespace {
 // format bit and size of every vertex component, the tables at 0x140484A20 / 0x1404849B0 (sub_1400EA5B0)
 constexpr std::pair<uint32_t, uint32_t> COMPONENTS[] = {
-    { 0x1, 12 },      { 0x10000, 16 },  { 0x2000000, 12 }, { 0x2, 12 },       { 0x4, 16 },      { 0x800000, 16 },
-    { 0x1000000, 16 }, { 0x8, 8 },       { 0x10, 12 },      { 0x20, 16 },      { 0x40, 8 },      { 0x80, 12 },
-    { 0x100, 16 },    { 0x200, 8 },     { 0x400, 12 },     { 0x800, 16 },     { 0x1000, 8 },    { 0x2000, 12 },
-    { 0x4000, 16 },   { 0x20000, 8 },   { 0x40000, 12 },   { 0x80000, 16 },   { 0x100000, 8 },  { 0x200000, 12 },
-    { 0x400000, 16 }, { 0x8000, 16 },
+    { 0x1, 12 },       { 0x10000, 16 }, { 0x2000000, 12 }, { 0x2, 12 },     { 0x4, 16 },     { 0x800000, 16 },
+    { 0x1000000, 16 }, { 0x8, 8 },      { 0x10, 12 },      { 0x20, 16 },    { 0x40, 8 },     { 0x80, 12 },
+    { 0x100, 16 },     { 0x200, 8 },    { 0x400, 12 },     { 0x800, 16 },   { 0x1000, 8 },   { 0x2000, 12 },
+    { 0x4000, 16 },    { 0x20000, 8 },  { 0x40000, 12 },   { 0x80000, 16 }, { 0x100000, 8 }, { 0x200000, 12 },
+    { 0x400000, 16 },  { 0x8000, 16 },
 };
 
 uint32_t vertexStride (uint32_t format) {
@@ -82,20 +82,34 @@ void writeInPlace (std::vector<char>& target, const std::vector<char>& source) {
 const char* WallpaperEngine::Render::ModelData::errorMessage (Error error) {
     // scenescript64 sub_1816361F0: index 0 is an empty string
     switch (error) {
-	case Error::InvalidMaterial: return "Invalid material";
-	case Error::ShaderExpectingMoreVertexData: return "Shader expecting more vertex data.";
-	case Error::InconsistentVertexBufferSize: return "Inconsistent vertex buffer size";
-	case Error::InvalidToken: return "Invalid model data token";
-	case Error::VertexBufferSizeCannotIncrease: return "Vertex buffer size cannot increase";
-	case Error::IndexBufferSizeCannotIncrease: return "Index buffer size cannot increase";
-	case Error::NotCreatedAsDynamic: return "Model data not created as dynamic";
-	case Error::BufferLockFailed: return "Buffer lock failed";
-	case Error::IncorrectIndexBufferType: return "Incorrect index buffer type";
-	case Error::CannotAddShapes: return "Cannot add shapes in IModelData.update";
-	case Error::CannotDeleteShapes: return "Cannot delete shape or buffers in IModelData.update";
-	case Error::CannotChangeMaterial: return "Material cannot be changed in IModelData.update";
-	case Error::CannotChangeVertexFormat: return "Vertex format cannot be changed in IModelData.update";
-	case Error::None: break;
+	case Error::InvalidMaterial:
+	    return "Invalid material";
+	case Error::ShaderExpectingMoreVertexData:
+	    return "Shader expecting more vertex data.";
+	case Error::InconsistentVertexBufferSize:
+	    return "Inconsistent vertex buffer size";
+	case Error::InvalidToken:
+	    return "Invalid model data token";
+	case Error::VertexBufferSizeCannotIncrease:
+	    return "Vertex buffer size cannot increase";
+	case Error::IndexBufferSizeCannotIncrease:
+	    return "Index buffer size cannot increase";
+	case Error::NotCreatedAsDynamic:
+	    return "Model data not created as dynamic";
+	case Error::BufferLockFailed:
+	    return "Buffer lock failed";
+	case Error::IncorrectIndexBufferType:
+	    return "Incorrect index buffer type";
+	case Error::CannotAddShapes:
+	    return "Cannot add shapes in IModelData.update";
+	case Error::CannotDeleteShapes:
+	    return "Cannot delete shape or buffers in IModelData.update";
+	case Error::CannotChangeMaterial:
+	    return "Material cannot be changed in IModelData.update";
+	case Error::CannotChangeVertexFormat:
+	    return "Vertex format cannot be changed in IModelData.update";
+	case Error::None:
+	    break;
     }
 
     return "";

+ 98 - 97
src/WallpaperEngine/Render/ModelData.h

@@ -17,112 +17,113 @@ namespace WallpaperEngine::Render {
  * created with the token draw them (sub_14021AD10)
  */
 namespace ModelData {
-/** Vertex format bits a script can use (scenescript64 sub_18162FD40) */
-constexpr uint32_t FORMAT_POSITION = 0x1;
-constexpr uint32_t FORMAT_NORMAL = 0x2;
-constexpr uint32_t FORMAT_TANGENT_SIGNED = 0x4;
-constexpr uint32_t FORMAT_UV = 0x8;
-constexpr uint32_t FORMAT_COLOR = 0x8000;
+    /** Vertex format bits a script can use (scenescript64 sub_18162FD40) */
+    constexpr uint32_t FORMAT_POSITION = 0x1;
+    constexpr uint32_t FORMAT_NORMAL = 0x2;
+    constexpr uint32_t FORMAT_TANGENT_SIGNED = 0x4;
+    constexpr uint32_t FORMAT_UV = 0x8;
+    constexpr uint32_t FORMAT_COLOR = 0x8000;
 
-/** The error codes of the engine calls, scenescript64 turns them into these SyntaxError messages */
-enum class Error : int {
-    None = 0,
-    InvalidMaterial = 1,
-    ShaderExpectingMoreVertexData = 2,
-    InconsistentVertexBufferSize = 3,
-    InvalidToken = 4,
-    VertexBufferSizeCannotIncrease = 5,
-    IndexBufferSizeCannotIncrease = 6,
-    NotCreatedAsDynamic = 7,
-    BufferLockFailed = 8,
-    IncorrectIndexBufferType = 9,
-    CannotAddShapes = 10,
-    CannotDeleteShapes = 11,
-    CannotChangeMaterial = 12,
-    CannotChangeVertexFormat = 13,
-};
+    /** The error codes of the engine calls, scenescript64 turns them into these SyntaxError messages */
+    enum class Error : int {
+	None = 0,
+	InvalidMaterial = 1,
+	ShaderExpectingMoreVertexData = 2,
+	InconsistentVertexBufferSize = 3,
+	InvalidToken = 4,
+	VertexBufferSizeCannotIncrease = 5,
+	IndexBufferSizeCannotIncrease = 6,
+	NotCreatedAsDynamic = 7,
+	BufferLockFailed = 8,
+	IncorrectIndexBufferType = 9,
+	CannotAddShapes = 10,
+	CannotDeleteShapes = 11,
+	CannotChangeMaterial = 12,
+	CannotChangeVertexFormat = 13,
+    };
 
-[[nodiscard]] const char* errorMessage (Error error);
+    [[nodiscard]] const char* errorMessage (Error error);
 
-/** One shape of a script configuration (scenescript64's 304 byte shape record, sub_181630720) */
-struct ShapeConfig {
-    std::vector<float> vertices;
-    bool hasVertices = false;
-    std::vector<uint32_t> indices32;
-    std::vector<uint16_t> indices16;
-    bool hasIndices32 = false;
-    bool hasIndices16 = false;
-    /** indexBuffer: null */
-    bool deleteIndices = false;
-    uint32_t format = 0;
-    std::string material;
-    bool vertexDynamic = false;
-    bool indexDynamic = false;
-    /** the shape itself was null (replaceData deletes it) */
-    bool deleteShape = false;
+    /** One shape of a script configuration (scenescript64's 304 byte shape record, sub_181630720) */
+    struct ShapeConfig {
+	std::vector<float> vertices;
+	bool hasVertices = false;
+	std::vector<uint32_t> indices32;
+	std::vector<uint16_t> indices16;
+	bool hasIndices32 = false;
+	bool hasIndices16 = false;
+	/** indexBuffer: null */
+	bool deleteIndices = false;
+	uint32_t format = 0;
+	std::string material;
+	bool vertexDynamic = false;
+	bool indexDynamic = false;
+	/** the shape itself was null (replaceData deletes it) */
+	bool deleteShape = false;
 
-    [[nodiscard]] bool hasIndices () const { return this->hasIndices32 || this->hasIndices16; }
-    [[nodiscard]] uint32_t indexCount () const {
-	return static_cast<uint32_t> (this->hasIndices32 ? this->indices32.size () : this->indices16.size ());
-    }
-};
+	[[nodiscard]] bool hasIndices () const { return this->hasIndices32 || this->hasIndices16; }
+	[[nodiscard]] uint32_t indexCount () const {
+	    return static_cast<uint32_t> (this->hasIndices32 ? this->indices32.size () : this->indices16.size ());
+	}
+    };
 
-struct Config {
-    std::vector<ShapeConfig> shapes;
-    std::optional<glm::vec3> boundsMin;
-    std::optional<glm::vec3> boundsMax;
-};
+    struct Config {
+	std::vector<ShapeConfig> shapes;
+	std::optional<glm::vec3> boundsMin;
+	std::optional<glm::vec3> boundsMax;
+    };
 
-/** A mesh with its GPU buffer record: the 200 byte mesh (sub_1401C2F10) and the 32 byte buffer entry of WE's model */
-struct Mesh {
-    std::string material;
-    uint32_t format = 0;
-    uint32_t stride = 0;
-    /** buffer +18 */
-    bool indexed = false;
-    /** mesh flag 1, 32 bit indices */
-    bool wideIndices = false;
-    /** buffer +16 / +17 */
-    bool vertexDynamic = false;
-    bool indexDynamic = false;
-    /** buffer +8 / +12: float and index counts the buffers were created with */
-    uint32_t vertexFloats = 0;
-    uint32_t indexCount = 0;
-    std::vector<char> vertices;
-    std::vector<char> indices;
-    /** bumped whenever applyData writes into the buffers */
-    uint64_t revision = 0;
-};
+    /** A mesh with its GPU buffer record: the 200 byte mesh (sub_1401C2F10) and the 32 byte buffer entry of WE's model
+     */
+    struct Mesh {
+	std::string material;
+	uint32_t format = 0;
+	uint32_t stride = 0;
+	/** buffer +18 */
+	bool indexed = false;
+	/** mesh flag 1, 32 bit indices */
+	bool wideIndices = false;
+	/** buffer +16 / +17 */
+	bool vertexDynamic = false;
+	bool indexDynamic = false;
+	/** buffer +8 / +12: float and index counts the buffers were created with */
+	uint32_t vertexFloats = 0;
+	uint32_t indexCount = 0;
+	std::vector<char> vertices;
+	std::vector<char> indices;
+	/** bumped whenever applyData writes into the buffers */
+	uint64_t revision = 0;
+    };
 
-struct Model {
-    uint32_t token = 0;
-    /** +560: the script handle and every layer using it hold one */
-    int references = 1;
-    std::vector<Mesh> meshes;
-    glm::vec3 boundsMin = glm::vec3 (0.0f);
-    glm::vec3 boundsMax = glm::vec3 (0.0f);
-    /** bumped when replaceData changes meshes, the layers using it rebuild (the listeners sub_1401D6400 calls) */
-    uint64_t structure = 0;
-};
+    struct Model {
+	uint32_t token = 0;
+	/** +560: the script handle and every layer using it hold one */
+	int references = 1;
+	std::vector<Mesh> meshes;
+	glm::vec3 boundsMin = glm::vec3 (0.0f);
+	glm::vec3 boundsMax = glm::vec3 (0.0f);
+	/** bumped when replaceData changes meshes, the layers using it rebuild (the listeners sub_1401D6400 calls) */
+	uint64_t structure = 0;
+    };
 
-/** Checks a shape's material against its vertex format: InvalidMaterial / ShaderExpectingMoreVertexData or None */
-using MaterialCheck = std::function<Error (const std::string& material, uint32_t format)>;
+    /** Checks a shape's material against its vertex format: InvalidMaterial / ShaderExpectingMoreVertexData or None */
+    using MaterialCheck = std::function<Error (const std::string& material, uint32_t format)>;
 
-class Store {
-public:
-    /** sub_14018C720, 0 and error set on failure */
-    uint32_t create (const Config& config, const MaterialCheck& check, Error& error);
-    /** sub_1401D6400: applyData (replace false) or replaceData */
-    void apply (uint32_t token, const Config& config, bool replace, const MaterialCheck& check, Error& error);
-    /** sub_14018D8B0: drops one reference */
-    void release (uint32_t token);
-    /** A layer takes a reference (sub_14021AD10), nullptr for an unknown token */
-    std::shared_ptr<Model> acquire (int token);
+    class Store {
+    public:
+	/** sub_14018C720, 0 and error set on failure */
+	uint32_t create (const Config& config, const MaterialCheck& check, Error& error);
+	/** sub_1401D6400: applyData (replace false) or replaceData */
+	void apply (uint32_t token, const Config& config, bool replace, const MaterialCheck& check, Error& error);
+	/** sub_14018D8B0: drops one reference */
+	void release (uint32_t token);
+	/** A layer takes a reference (sub_14021AD10), nullptr for an unknown token */
+	std::shared_ptr<Model> acquire (int token);
 
-private:
-    std::map<uint32_t, std::shared_ptr<Model>> m_models;
-    /** scene +7224, zeroed with the scene, the first token is 1 */
-    uint32_t m_counter = 0;
-};
+    private:
+	std::map<uint32_t, std::shared_ptr<Model>> m_models;
+	/** scene +7224, zeroed with the scene, the first token is 1 */
+	uint32_t m_counter = 0;
+    };
 } // namespace ModelData
 } // namespace WallpaperEngine::Render

+ 48 - 144
src/WallpaperEngine/Render/Objects/CImage.cpp

@@ -22,16 +22,17 @@
 #include <glm/gtx/rotate_vector.hpp>
 #undef GLM_ENABLE_EXPERIMENTAL
 
+#include "WallpaperEngine/Assets/AssetLoadException.h"
 #include "WallpaperEngine/Data/Model/DynamicValue.h"
 #include "WallpaperEngine/Data/Model/Material.h"
 #include "WallpaperEngine/Data/Model/Object.h"
 #include "WallpaperEngine/Data/Model/UserSetting.h"
 #include "WallpaperEngine/Data/Parsers/MaterialParser.h"
 #include "WallpaperEngine/Data/Utils/BinaryReader.h"
-#include "WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.h"
-#include "WallpaperEngine/Scripting/ScriptEngine.h"
 #include "WallpaperEngine/Data/Utils/MemoryStream.h"
 #include "WallpaperEngine/Logging/Log.h"
+#include "WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.h"
+#include "WallpaperEngine/Scripting/ScriptEngine.h"
 
 using namespace WallpaperEngine;
 using namespace WallpaperEngine::Render::Objects;
@@ -379,60 +380,13 @@ CImage::ResolvedTransform CImage::resolveTransform (const Object& object) const
     // Accumulate top-down: the root's local transform is already its resolved
     // transform, then fold each child onto its already-resolved parent.
     ResolvedTransform resolved = localTransform (*chain[count - 1]);
-    float meshPivotAngle = 0.0f;
     for (int i = count - 2; i >= 0; --i) {
 	ResolvedTransform local = localTransform (*chain[i]);
 
 	// scene.json's "attachment" follows a named point on the direct parent's puppet rig (see
-	// PuppetAttachmentPoint), not the parent's own origin. This mirrors the real engine's attachment
-	// resolution (confirmed via disassembly of wallpaper64.exe's sub_140148A20, the function that
-	// actually builds an object's world matrix): parentWorldMatrix * boneLocalMatrix, composed with NO
-	// Y-axis sign flip anywhere in the chain - the real engine uses one consistent Y convention all the
-	// way from JSON through every level of parent/child composition, flipping (if at all) exactly once,
-	// at the very end in the camera projection.
-	//
-	// resolveTransform's own "origin" space already works this same unflipped way for ordinary
-	// (non-attachment) children two lines below (`local.origin.y = anchorOrigin.y + offset.y`, no
-	// negation) - it's only the FINAL CImage-constructor/updateScenePosition step that ever flips Y, to
-	// go from this consistent origin-space into screen/pixel space. The bone's meshPosition, however,
-	// comes from getAttachmentPointMeshTransform() already in that same unflipped origin-space
-	// convention (see its own doc comment) - so it must be folded in raw, exactly like a normal child's
-	// local.origin is, not re-flipped a second time. Confirmed against a real wallpaper with a genuinely
-	// large bone rotation (mikasa/3764765600's "eye" attachment, ~-45 degrees): before this fix the
-	// attachment landed off the top edge of the screen entirely; with position un-negated it lands
-	// correctly on the face.
-	//
-	// anchorAngle (the bone's rotation, same sign/no-flip as position) rotates the attached child's own
-	// local-origin nudge below, via the same offset-rotation every normal child already goes through -
-	// that's required for *position* to track the bone correctly: a child's own declared origin is a
-	// small offset in the attachment point's local frame, so it has to rotate along with whatever that
-	// frame's current orientation is, same as it already scales along with the parent's current scale.
-	// It also feeds the child's own final stored angle two lines below - the mathematically consistent
-	// choice (attachmentWorldMatrix * childLocalMatrix), and the one actually confirmed working: mikasa's
-	// eye (the only attachment point found so far riding a bone with genuine non-zero rotation) is
-	// visible with this formula, just not at the correct angle (her declared local angle of ~44.6 degrees
-	// and the eye bone's ~-45 degree rotation nearly cancel to ~0 net rotation, rendering as a thin
-	// angular sliver instead of a natural lash contour - a real, unsolved cosmetic bug, tracked
-	// separately, not this line).
-	//
-	// Two variants were tried and reverted, both regressions confirmed by the user on real hardware, not
-	// just sandbox: (1) flipping only meshTransform->angle's sign within anchorAngle - since anchorAngle
-	// also drives the offset-rotation above, this swung the eye's own (~355-unit) local-origin nudge by
-	// nearly 90 degrees and pushed the object off the right edge of the screen entirely ("eyes completely
-	// disappeared"). (2) splitting a separate finalAngle that dropped the bone's rotation from the final
-	// angle entirely, reasoning that position and orientation could use different angles - this looked
-	// like a plausible eyelash contour in an isolated sandbox crop, but the eye's own detail marks (a
-	// small highlight dot, iris shading, a few lash strokes - confirmed via decode_tex.py on "mikasa
-	// eye.tex": barely 0.7% of the canvas is non-transparent) are precisely positioned to overlay a
-	// specific closed-eye crease baked into mikasaback's own texture; changing the mesh's rotation swings
-	// those small marks to different screen pixels even though the object's own bounding-box center
-	// doesn't move, and evidently rotated them off that tiny target entirely - user confirmed "eyes are
-	// still invisible" with a real screenshot showing bare skin, no eye at all, where the sandbox crop had
-	// suggested something was there. Reverted back to the single-anchorAngle formula below, which is the
-	// last state confirmed actually visible (if wrongly rotated) on real hardware - a real fix for the
-	// rotation needs to explain why a *different* angle would still hit the same crease, not just look
-	// better in isolation.
-	// meshPivotAngle: the remaining angle difference pivots around the mesh's own center, not the object origin
+	// PuppetAttachmentPoint): WE's world matrix is parentWorld * (animated bone world * point local) * childLocal
+	// (sub_140148A20), so the point's animated angle rotates the child's offset and adds to its own angle, and the
+	// mesh turns around the object origin
 	glm::vec3 anchorOrigin = resolved.origin;
 	float anchorAngle = resolved.angle;
 	glm::vec2 anchorScale = { 1.0f, 1.0f };
@@ -451,9 +405,6 @@ CImage::ResolvedTransform CImage::resolveTransform (const Object& object) const
 		    // the bone's own scale (possibly negative, i.e. a mirrored bone) carries into whatever
 		    // rides it, same as position/rotation
 		    anchorScale = meshTransform->scale;
-		    // the attachment matrix carries a static rotation that only orients the point's own frame,
-		    // so it steers the child's offset but not its orientation, and is cancelled around the mesh center
-		    meshPivotAngle += -meshTransform->restAngle;
 
 		    if (!this->m_attachmentDiagnosticLogged.contains (chain[i]->id)) {
 			this->m_attachmentDiagnosticLogged.insert (chain[i]->id);
@@ -464,8 +415,7 @@ CImage::ResolvedTransform CImage::resolveTransform (const Object& object) const
 			    " boneScale=(", meshTransform->scale.x, ",", meshTransform->scale.y, ") parentOrigin=(",
 			    resolved.origin.x, ",", resolved.origin.y, ") parentScale=", resolved.scale.x,
 			    " anchorOrigin=(", anchorOrigin.x, ",", anchorOrigin.y,
-			    ") anchorAngleDeg=", glm::degrees (anchorAngle),
-			    " restAngleDeg=", glm::degrees (meshTransform->restAngle)
+			    ") anchorAngleDeg=", glm::degrees (anchorAngle)
 			);
 		    }
 		}
@@ -479,7 +429,7 @@ CImage::ResolvedTransform CImage::resolveTransform (const Object& object) const
 	local.origin.z = resolved.origin.z + local.origin.z * resolved.scale.z;
 	local.scale.x *= anchorScale.x;
 	local.scale.y *= anchorScale.y;
-	resolved = { local.origin, local.scale * resolved.scale, local.angle + anchorAngle, meshPivotAngle };
+	resolved = { local.origin, local.scale * resolved.scale, local.angle + anchorAngle };
     }
 
     return resolved;
@@ -518,8 +468,7 @@ CImage::CImage (Wallpapers::CScene& scene, const Image& image) :
 
 	    this->registerProperty (prefix + name, *(*setting)->value);
 	    scene.getScriptEngine ().setThisObjectFactory (
-		this->getProperties ().at (prefix + name).key,
-		[this, layerIndex] (Scripting::ScriptEngine& engine) {
+		this->getProperties ().at (prefix + name).key, [this, layerIndex] (Scripting::ScriptEngine& engine) {
 		    return Scripting::Adapters::makeAnimationLayerHandle (engine, *this, layerIndex);
 		}
 	    );
@@ -534,7 +483,12 @@ CImage::CImage (Wallpapers::CScene& scene, const Image& image) :
     glm::vec2 size = this->getSize ();
     glm::vec3 scale = transform.scale;
 
-    this->detectTexture ();
+    try {
+	this->detectTexture ();
+    } catch (const Assets::AssetLoadException& e) {
+	// live WE loads the scene anyway and draws the layer empty
+	sLog.error ("Image ", image.id, " has no texture, drawing it empty: ", e.what ());
+    }
 
     const bool placeholderTexture = this->m_texture == nullptr;
 
@@ -795,7 +749,9 @@ bool CImage::hitTest (const glm::vec2& ndc) {
 	std::abs (this->m_pos.z - this->m_pos.x) / 2.0f, std::abs (this->m_pos.w - this->m_pos.y) / 2.0f
     );
 
-    return Wallpapers::CScene::quadContainsPoint (glm::translate (this->m_modelViewProjectionScreen, center), half, ndc);
+    return Wallpapers::CScene::quadContainsPoint (
+	glm::translate (this->m_modelViewProjectionScreen, center), half, ndc
+    );
 }
 
 glm::vec2 CImage::cursorLocalPosition (const glm::vec2& ndc) {
@@ -1015,7 +971,6 @@ void CImage::updatePuppetPositionBuffer (const glm::vec2& size) {
     glBufferData (GL_ARRAY_BUFFER, positions.size () * sizeof (GLfloat), positions.data (), GL_DYNAMIC_DRAW);
 }
 
-
 PuppetActiveAnimation* CImage::findPuppetAnimationLayer (size_t serial) { return this->m_rig.findLayer (serial); }
 
 size_t CImage::getPuppetAnimationLayerCount () const { return this->m_rig.getLayerCount (); }
@@ -1032,7 +987,9 @@ std::optional<size_t> CImage::createPuppetAnimationLayer (
     return this->m_rig.createLayer (animation, config, autoRemove, this->getScene ().getScene ().project);
 }
 
-bool CImage::destroyPuppetAnimationLayersByName (const std::string& name) { return this->m_rig.destroyLayersByName (name); }
+bool CImage::destroyPuppetAnimationLayersByName (const std::string& name) {
+    return this->m_rig.destroyLayersByName (name);
+}
 
 bool CImage::destroyPuppetAnimationLayer (size_t serial) { return this->m_rig.destroyLayer (serial); }
 
@@ -1099,7 +1056,6 @@ void CImage::updatePuppetSkinning () {
     this->updatePuppetPositionBuffer (this->m_size);
 }
 
-
 glm::mat4 CImage::puppetObjectWorld () const {
     // WE's bone world (image vtable slot 16, sub_1401FD3F0) also moves by the alignment offset (sub_1402066A0),
     // left out: the size it uses for puppets isn't traced yet
@@ -1116,7 +1072,9 @@ void CImage::setPuppetBoneTransform (int bone, const glm::mat4& transform) {
     this->m_rig.setBoneTransform (bone, transform, this->puppetObjectWorld ());
 }
 
-const glm::mat4& CImage::getPuppetLocalBoneTransform (int bone) const { return this->m_rig.getLocalBoneTransform (bone); }
+const glm::mat4& CImage::getPuppetLocalBoneTransform (int bone) const {
+    return this->m_rig.getLocalBoneTransform (bone);
+}
 
 void CImage::setPuppetLocalBoneTransform (int bone, const glm::mat4& transform) {
     this->m_rig.setLocalBoneTransform (bone, transform, this->puppetObjectWorld ());
@@ -1158,12 +1116,7 @@ CImage::getAttachmentPointMeshTransform (const std::string& name) const {
 	  )
 	: glm::vec2 (scaleX, glm::length (glm::vec2 (animatedWorld[1])));
 
-    const glm::mat4 bindWorld = glm::inverse (this->m_rig.bones[it->boneIndex].inverseBindWorld) * it->localTransform;
-    const float restAngle = std::atan2 (bindWorld[0][1], bindWorld[0][0]);
-
-    return AttachmentPointTransform {
-	.position = glm::vec3 (animatedWorld[3]), .angle = angle, .scale = scale, .restAngle = restAngle
-    };
+    return AttachmentPointTransform { .position = glm::vec3 (animatedWorld[3]), .angle = angle, .scale = scale };
 }
 
 void CImage::setupPuppetGeometryCallback (Effects::CPass* pass) const {
@@ -1218,30 +1171,6 @@ void CImage::setupPuppetGeometryCallback (Effects::CPass* pass) const {
 	    glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_puppetIndices);
 	    glDrawElements (GL_TRIANGLES, this->m_puppetIndexCount, GL_UNSIGNED_SHORT, nullptr);
 
-	    {
-		static int mikasaEyeDumpCounter = 0;
-		if (this->getId () == 603 && mikasaEyeDumpCounter++ == 5) {
-		    GLint vp[4] = {};
-		    glGetIntegerv (GL_VIEWPORT, vp);
-		    const int w = vp[2], h = vp[3];
-		    if (w > 0 && h > 0 && w < 8192 && h < 8192) {
-			std::vector<unsigned char> pixels (static_cast<size_t> (w) * h * 4);
-			glReadPixels (0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, pixels.data ());
-			FILE* f = fopen ("/tmp/mikasa_eye_bakepass_dump.raw", "wb");
-			if (f) {
-			    fwrite (&w, sizeof (int), 1, f);
-			    fwrite (&h, sizeof (int), 1, f);
-			    fwrite (pixels.data (), 1, pixels.size (), f);
-			    fclose (f);
-			    sLog.out (
-				"TEMP-DIAG dumped FBO contents for mikasa eye bake pass: ", w, "x", h,
-				" to /tmp/mikasa_eye_bakepass_dump.raw"
-			    );
-			}
-		    }
-		}
-	    }
-
 	    if (!this->m_puppetDrawErrorChecked) {
 		this->m_puppetDrawErrorChecked = true;
 		GLint boundFBO = 0;
@@ -1384,9 +1313,8 @@ void CImage::setup () {
     });
 
     this->m_hasPassthroughChildren = this->m_image.model->passthrough
-	&& std::ranges::any_of (this->getScene ().getScene ().objects, [this] (const auto& object) {
-	       return object->parent == this->getImage ().id;
-	   });
+	&& std::ranges::any_of (this->getScene ().getScene ().objects,
+				[this] (const auto& object) { return object->parent == this->getImage ().id; });
 
     // passthrough without effects has nothing to draw unless another layer reads its _rt_imageLayerComposite or it
     // has children to draw into its buffer
@@ -1726,9 +1654,9 @@ void CImage::setupPasses () {
 	// what WE's intermediate passes see as g_EffectModelViewProjectionMatrix: their geometry where the layer
 	// is on screen (sub_1401EBF60), the final pass keeps its own MVP
 	pass->setEffectModelViewProjectionMatrix (
-	    projection == &this->m_modelViewProjectionCopy	? &this->m_effectModelViewProjectionCopy
+	    projection == &this->m_modelViewProjectionCopy       ? &this->m_effectModelViewProjectionCopy
 		: projection == &this->m_modelViewProjectionPass ? &this->m_effectModelViewProjectionPass
-								    : nullptr
+								 : nullptr
 	);
 
 	texcoord = this->getTexCoordPass ();
@@ -1900,7 +1828,8 @@ const float& CImage::getAlpha () const {
 const glm::vec3& CImage::getColor () const {
     // a solid layer showing an image the user picked draws it untinted, its color only tints the plain
     // white fill (checked against WE with 3765586324's local file background, black and white color alike)
-    const glm::vec3 color = this->showsUserTextureOnSolidLayer () ? glm::vec3 (1.0f) : this->m_image.color->value->getVec3 ();
+    const glm::vec3 color
+	= this->showsUserTextureOnSolidLayer () ? glm::vec3 (1.0f) : this->m_image.color->value->getVec3 ();
     // the object's brightness only scales its color in HDR scene rendering (sub_140207740)
     m_colorCache = color * (this->getScene ().isHDR () ? this->m_image.brightness->value->getFloat () : 1.0f);
     return m_colorCache;
@@ -1914,7 +1843,8 @@ bool CImage::showsUserTextureOnSolidLayer () const {
     const auto& properties = this->getScene ().getScene ().project.properties;
     for (const auto& [index, propertyName] : (*this->m_image.model->material->passes.begin ())->usertextures) {
 	const auto it = properties.find (propertyName);
-	if (it != properties.end () && !it->second->is<Data::Model::PropertyUserShortcut> () && !it->second->getString ().empty ()) {
+	if (it != properties.end () && !it->second->is<Data::Model::PropertyUserShortcut> ()
+	    && !it->second->getString ().empty ()) {
 	    return true;
 	}
     }
@@ -1960,8 +1890,7 @@ void CImage::updateScenePosition (
     const glm::vec2 declared = this->getImage ().size;
     const auto& model = *this->getImage ().model;
 
-    if (!model.fullscreen && !model.autosize && !model.puppet.has_value () && declared.x > 0.0f
-	&& declared.y > 0.0f) {
+    if (!model.fullscreen && !model.autosize && !model.puppet.has_value () && declared.x > 0.0f && declared.y > 0.0f) {
 	displaySize = declared;
     }
 
@@ -1972,7 +1901,8 @@ void CImage::updateScenePosition (
     this->m_pos.z = origin.x + (scaledSize.x / 2.0f);
     this->m_pos.y = origin.y - (scaledSize.y / 2.0f);
 
-    const uint32_t alignment = Data::Parsers::ObjectParser::parseAlignment (this->getImage ().alignmentName->value->getString ());
+    const uint32_t alignment
+	= Data::Parsers::ObjectParser::parseAlignment (this->getImage ().alignmentName->value->getString ());
 
     if (alignment & ImageAlignment_Top) {
 	this->m_pos.y -= scaledSize.y / 2.0f;
@@ -2087,15 +2017,15 @@ CImage::ResolvedTransform CImage::updateGeometryBuffers () {
 }
 
 namespace {
-// keeps an edge pair (e.g. m_pos.x/.z) from sliding past the viewport once `offset` is added to both,
-// so the image never uncovers ground it doesn't have pixels for; an image too small to cover the viewport
-// on this axis has no ground to uncover, it is an object sitting on the scene and moves freely
-float clampParallaxAxis (float offset, float edgeA, float edgeB, float sceneExtent) {
+// keeps an edge pair (e.g. m_pos.x/.z) from sliding into the on-screen part of the canvas once `offset` is added
+// to both, so the image never uncovers ground it doesn't have pixels for; an image too small to cover it on this
+// axis has no ground to uncover, it is an object sitting on the scene and moves freely. Canvas cropped away by the
+// cover scaling is free to scroll in, WE has no clamp at all (sub_14018AAC0 adds the raw offset to the view)
+float clampParallaxAxis (float offset, float edgeA, float edgeB, float visibleLow, float visibleHigh) {
     const float low = std::min (edgeA, edgeB);
     const float high = std::max (edgeA, edgeB);
-    const float half = sceneExtent / 2.0f;
-    const float maxOffset = -half - low;
-    const float minOffset = half - high;
+    const float maxOffset = visibleLow - low;
+    const float minOffset = visibleHigh - high;
 
     if (minOffset > maxOffset) {
 	return offset;
@@ -2186,30 +2116,6 @@ void CImage::updateScreenSpacePosition () {
 	rotModel = glm::translate (rotModel, -this->m_sceneCenter);
     }
 
-    if (transform.meshPivotAngle != 0.0f && this->m_hasPuppetMesh) {
-	const auto& source
-	    = !this->m_puppetSkinnedPositions.empty () ? this->m_puppetSkinnedPositions : this->m_puppetRawPositions;
-	glm::vec2 boundsMin (std::numeric_limits<float>::max ());
-	glm::vec2 boundsMax (std::numeric_limits<float>::lowest ());
-	for (size_t i = 0; i + 2 < source.size (); i += 3) {
-	    boundsMin = glm::min (boundsMin, glm::vec2 (source[i], source[i + 1]));
-	    boundsMax = glm::max (boundsMax, glm::vec2 (source[i], source[i + 1]));
-	}
-
-	if (boundsMin.x <= boundsMax.x) {
-	    const glm::vec2 meshCenter = (boundsMin + boundsMax) / 2.0f;
-	    const glm::vec4 pivot (
-		this->m_pos.x + (this->m_size.x / 2.0f + meshCenter.x) * this->m_puppetScale.x,
-		this->m_pos.w + (this->m_size.y / 2.0f - meshCenter.y) * this->m_puppetScale.y, 0.0f, 1.0f
-	    );
-	    const glm::vec3 rotatedPivot = glm::vec3 (rotModel * pivot);
-	    glm::mat4 pivotRot = glm::translate (glm::mat4 (1.0f), rotatedPivot);
-	    pivotRot = glm::rotate (pivotRot, -transform.meshPivotAngle, glm::vec3 (0.0f, 0.0f, 1.0f));
-	    pivotRot = glm::translate (pivotRot, -rotatedPivot);
-	    rotModel = pivotRot * rotModel;
-	}
-    }
-
     rotModel = this->ancestorTiltCorrection () * rotModel;
 
     glm::mat4 mvp = this->getViewProjection () * rotModel;
@@ -2231,9 +2137,8 @@ void CImage::updateScreenSpacePosition () {
 	    const glm::vec3 center (
 		(this->m_pos.x + this->m_pos.z) / 2.0f, (this->m_pos.y + this->m_pos.w) / 2.0f, 0.0f
 	    );
-	    const glm::mat4 toLocal = glm::translate (
-		glm::scale (glm::mat4 (1.0f), glm::vec3 (size / extent, 0.0f)), -center
-	    );
+	    const glm::mat4 toLocal
+		= glm::translate (glm::scale (glm::mat4 (1.0f), glm::vec3 (size / extent, 0.0f)), -center);
 	    const glm::mat4 viewProjection = this->getImage ().perspective->value->getBool ()
 		? camera.getPerspectiveLayerViewProjection ()
 		: this->getScene ().getWorldViewProjection ();
@@ -2258,10 +2163,9 @@ void CImage::updateScreenSpacePosition () {
 
 	if (this->getScene ().getContext ().getApp ().getContext ().settings.mouse.clampParallaxToImageSize
 	    && !textureTiles) {
-	    const float sceneWidth = static_cast<float> (this->getScene ().getCanvasWidth ());
-	    const float sceneHeight = static_cast<float> (this->getScene ().getCanvasHeight ());
-	    x = clampParallaxAxis (x, this->m_pos.x, this->m_pos.z, sceneWidth);
-	    y = clampParallaxAxis (y, this->m_pos.y, this->m_pos.w, sceneHeight);
+	    const glm::vec4 visible = this->getScene ().getVisibleCanvasRegion ();
+	    x = clampParallaxAxis (x, this->m_pos.x, this->m_pos.z, visible.x, visible.y);
+	    y = clampParallaxAxis (y, this->m_pos.y, this->m_pos.w, visible.z, visible.w);
 	}
 
 	// WE translates the view (sub_14018AAC0), so its offset isn't turned by the layer's own rotation. The clamp's

+ 2 - 7
src/WallpaperEngine/Render/Objects/CImage.h

@@ -78,8 +78,6 @@ public:
 	glm::vec3 position;
 	float angle;
 	glm::vec2 scale;
-	/** the same attachment point's rotation in the rig's bind pose */
-	float restAngle;
     };
 
     /**
@@ -119,9 +117,8 @@ public:
     [[nodiscard]] std::optional<size_t> getPuppetAnimationLayerAt (int64_t index) const;
     [[nodiscard]] std::optional<size_t> findPuppetAnimationLayerByName (const std::string& name) const;
     /** animation is a clip name (string) or a layer config (object); config's keys go over it */
-    std::optional<size_t> createPuppetAnimationLayer (
-	const Data::JSON::JSON& animation, const Data::JSON::JSON& config, bool autoRemove
-    );
+    std::optional<size_t>
+    createPuppetAnimationLayer (const Data::JSON::JSON& animation, const Data::JSON::JSON& config, bool autoRemove);
     /** removes every layer called name */
     bool destroyPuppetAnimationLayersByName (const std::string& name);
     bool destroyPuppetAnimationLayer (size_t serial);
@@ -143,8 +140,6 @@ protected:
 	glm::vec3 origin;
 	glm::vec3 scale;
 	float angle;
-	/** part of `angle` that should pivot around the puppet mesh's own center instead of the object origin */
-	float meshPivotAngle = 0.0f;
     };
 
     [[nodiscard]] ResolvedTransform resolveTransform (const WallpaperEngine::Data::Model::Object& object) const;

+ 18 - 18
src/WallpaperEngine/Render/Objects/CMesh.cpp

@@ -5,8 +5,8 @@
 
 #include <algorithm>
 #include <cstring>
-#include <limits>
 #include <glm/gtc/matrix_transform.hpp>
+#include <limits>
 
 #include "WallpaperEngine/Data/Model/Object.h"
 #include "WallpaperEngine/Data/Parsers/MaterialParser.h"
@@ -29,11 +29,11 @@ struct VertexComponent {
 };
 
 constexpr VertexComponent VERTEX_COMPONENTS[] = {
-    { 0x1, 12 },       { 0x10000, 16 }, { 0x2000000, 12 }, { 0x2, 12 },     { 0x4, 16 },      { 0x800000, 16 },
-    { 0x1000000, 16 }, { 0x8, 8 },      { 0x10, 12 },     { 0x20, 16 },     { 0x40, 8 },
-    { 0x80, 12 },      { 0x100, 16 },   { 0x200, 8 },     { 0x400, 12 },    { 0x800, 16 },
-    { 0x1000, 8 },     { 0x2000, 12 },  { 0x4000, 16 },   { 0x20000, 8 },   { 0x40000, 12 },
-    { 0x80000, 16 },   { 0x100000, 8 }, { 0x200000, 12 }, { 0x400000, 16 }, { 0x8000, 16 },
+    { 0x1, 12 },       { 0x10000, 16 }, { 0x2000000, 12 }, { 0x2, 12 },     { 0x4, 16 },     { 0x800000, 16 },
+    { 0x1000000, 16 }, { 0x8, 8 },      { 0x10, 12 },      { 0x20, 16 },    { 0x40, 8 },     { 0x80, 12 },
+    { 0x100, 16 },     { 0x200, 8 },    { 0x400, 12 },     { 0x800, 16 },   { 0x1000, 8 },   { 0x2000, 12 },
+    { 0x4000, 16 },    { 0x20000, 8 },  { 0x40000, 12 },   { 0x80000, 16 }, { 0x100000, 8 }, { 0x200000, 12 },
+    { 0x400000, 16 },  { 0x8000, 16 },
 };
 
 constexpr uint32_t FORMAT_POSITION = 0x1;
@@ -72,7 +72,6 @@ struct CMesh::MdlMesh {
 namespace {
 using MdlMesh = CMesh::MdlMesh;
 
-
 class MdlReader {
 public:
     explicit MdlReader (const std::vector<char>& data) : m_data (data) { }
@@ -269,8 +268,9 @@ std::vector<MdlMesh> readMdlMeshes (
 	    );
 	}
 
-	// sub_140261880 from version 21: a flag byte with a u32 and a sized blob, a flag byte with a sized blob (puppets'
-	// per bone index ranges); from 23 a count of records (u64, string, u32 flags, two u32 counted u32 lists)
+	// sub_140261880 from version 21: a flag byte with a u32 and a sized blob, a flag byte with a sized blob
+	// (puppets' per bone index ranges); from 23 a count of records (u64, string, u32 flags, two u32 counted u32
+	// lists)
 	if (version >= 21) {
 	    if (reader.u8 () != 0) {
 		reader.u32 ();
@@ -378,7 +378,9 @@ void loadMorphTargets (
 	    const size_t available = positions[target].size () / sizeof (uint16_t);
 
 	    if ((flags & 0x400) == 0) {
-		std::copy_n (position, std::min<size_t> (available, 3 * vertices), halfs.begin () + static_cast<long> (out));
+		std::copy_n (
+		    position, std::min<size_t> (available, 3 * vertices), halfs.begin () + static_cast<long> (out)
+		);
 		out += 3 * vertices;
 		continue;
 	    }
@@ -440,9 +442,8 @@ public:
 	    GL_ARRAY_BUFFER, static_cast<GLsizeiptr> (this->m_mesh.vertices.size ()), this->m_mesh.vertices.data (),
 	    this->m_source != nullptr && this->m_source->vertexDynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW
 	);
-	this->m_vertexCount = this->m_mesh.stride != 0
-	    ? static_cast<GLsizei> (this->m_mesh.vertices.size () / this->m_mesh.stride)
-	    : 0;
+	this->m_vertexCount
+	    = this->m_mesh.stride != 0 ? static_cast<GLsizei> (this->m_mesh.vertices.size () / this->m_mesh.stride) : 0;
 
 	GLint previousVAO = 0;
 	glGetIntegerv (GL_VERTEX_ARRAY_BINDING, &previousVAO);
@@ -478,7 +479,8 @@ public:
 		skinning = std::cref (this->m_skinning);
 	    }
 
-	    auto* pass = new Effects::CPass (*this, this->m_fboProvider, *materialPass, skinning, std::nullopt, std::nullopt);
+	    auto* pass
+		= new Effects::CPass (*this, this->m_fboProvider, *materialPass, skinning, std::nullopt, std::nullopt);
 
 	    pass->setDestination (this->getScene ().getFBO ());
 	    pass->setInput (this->getTexture ());
@@ -775,8 +777,7 @@ CMesh::CMesh (Wallpapers::CScene& scene, const Mesh& mesh) :
 
 	    this->registerProperty (prefix + name, *(*setting)->value);
 	    scene.getScriptEngine ().setThisObjectFactory (
-		this->getProperties ().at (prefix + name).key,
-		[this, layerIndex] (Scripting::ScriptEngine& engine) {
+		this->getProperties ().at (prefix + name).key, [this, layerIndex] (Scripting::ScriptEngine& engine) {
 		    return Scripting::Adapters::makeAnimationLayerHandle (engine, *this, layerIndex);
 		}
 	    );
@@ -1066,8 +1067,7 @@ std::optional<glm::vec3> CMesh::boxEntry (const glm::vec2& ndc) const {
     }
 
     const auto& scene = this->getScene ();
-    const glm::mat4 toModel
-	= glm::inverse (scene.getWorldViewProjection () * scene.objectWorldMatrix (this->m_mesh));
+    const glm::mat4 toModel = glm::inverse (scene.getWorldViewProjection () * scene.objectWorldMatrix (this->m_mesh));
     const glm::vec4 nearPoint = toModel * glm::vec4 (ndc, -1.0f, 1.0f);
     const glm::vec4 farPoint = toModel * glm::vec4 (ndc, 1.0f, 1.0f);
     const glm::vec3 origin = glm::vec3 (nearPoint) / nearPoint.w;

+ 120 - 114
src/WallpaperEngine/Render/Objects/CParticle.cpp

@@ -1037,9 +1037,10 @@ uint32_t CParticle::emitCount (EmitterClock& clock, const ParticleEmitter& emitt
 		clock.period -= dt;
 		if (clock.period < 0.0f) {
 		    const float minDelay = std::min (emitter.minPeriodicDelay, emitter.maxPeriodicDelay);
-		    clock.period = -(WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f)
-					 * (emitter.maxPeriodicDelay - minDelay)
-				     + minDelay);
+		    clock.period
+			= -(WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f)
+				* (emitter.maxPeriodicDelay - minDelay)
+			    + minDelay);
 		}
 	    }
 	}
@@ -1154,11 +1155,12 @@ EmitterFunc CParticle::createBoxEmitter (const ParticleEmitter& emitter) {
 	    // pos = sign (u) * (|u| * (distancemax - distancemin) + distancemin), in WE's y-up space
 	    glm::vec3 randomPos;
 	    for (int axis = 0; axis < 3; axis++) {
-		const float u
-		    = (WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f) * 2.0f - 1.0f) * emitter.directions[axis];
+		const float u = (WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f) * 2.0f - 1.0f)
+		    * emitter.directions[axis];
 		const float sign = u > 0.0f ? 1.0f : (u < 0.0f ? -1.0f : 0.0f);
 		randomPos[axis] = sign
-		    * (std::abs (u) * (emitter.distanceMax[axis] - emitter.distanceMin[axis]) + emitter.distanceMin[axis]);
+		    * (std::abs (u) * (emitter.distanceMax[axis] - emitter.distanceMin[axis])
+		       + emitter.distanceMin[axis]);
 	    }
 	    randomPos.y = -randomPos.y;
 
@@ -1260,12 +1262,12 @@ void CParticle::buildImagePixels (ImageEmitter& state, const CImage& image) {
     for (int x = 0; x < columns; x++) {
 	for (int y = 0; y < rows; y++) {
 	    const glm::vec2 uv ((x + 0.5f) / columns, (y + 0.5f) / rows);
-	    const glm::vec4 albedo = (sample (uv - step) + sample (uv + step) + sample (uv + glm::vec2 (-step.x, step.y))
-				      + sample (uv + glm::vec2 (step.x, -step.y)))
+	    const glm::vec4 albedo
+		= (sample (uv - step) + sample (uv + step) + sample (uv + glm::vec2 (-step.x, step.y))
+		   + sample (uv + glm::vec2 (step.x, -step.y)))
 		* 0.25f;
-	    const auto unorm = [] (float value) {
-		return static_cast<uint8_t> (std::clamp (value * 255.0f + 0.5f, 0.0f, 255.0f));
-	    };
+	    const auto unorm
+		= [] (float value) { return static_cast<uint8_t> (std::clamp (value * 255.0f + 0.5f, 0.0f, 255.0f)); };
 	    if (unorm (albedo.a) < 0x7F) {
 		continue;
 	    }
@@ -1286,8 +1288,8 @@ EmitterFunc CParticle::createImageEmitter (const ParticleEmitter& emitter) {
     const size_t stateIndex = m_imageEmitters.size () - 1;
 
     // sub_1402378A0 emitter type 3 (layerimage) with the defaults of sub_1401B9930
-    return [this, emitter, clockIndex, stateIndex] (std::vector<ParticleInstance>& particles, uint32_t& count,
-						      float dt) {
+    return [this, emitter, clockIndex,
+	    stateIndex] (std::vector<ParticleInstance>& particles, uint32_t& count, float dt) {
 	ImageEmitter& state = m_imageEmitters[stateIndex];
 	const uint32_t toEmit = this->emitCount (m_emitterClocks[clockIndex], emitter, dt);
 
@@ -1318,7 +1320,8 @@ EmitterFunc CParticle::createImageEmitter (const ParticleEmitter& emitter) {
 	const glm::mat4 current = toParticles * world;
 	const glm::mat4 previous = toParticles * state.previousWorld;
 	const bool flat = !getScene ().getCamera ().isPerspective ();
-	const glm::vec3 offsetMin = emitter.offsetMin.value_or (flat ? glm::vec3 (-5.0f, -5.0f, 0.0f) : glm::vec3 (0.0f));
+	const glm::vec3 offsetMin
+	    = emitter.offsetMin.value_or (flat ? glm::vec3 (-5.0f, -5.0f, 0.0f) : glm::vec3 (0.0f));
 	const glm::vec3 offsetRange
 	    = emitter.offsetMax.value_or (flat ? glm::vec3 (5.0f, 5.0f, 0.0f) : glm::vec3 (0.0f)) - offsetMin;
 
@@ -1340,8 +1343,8 @@ EmitterFunc CParticle::createImageEmitter (const ParticleEmitter& emitter) {
 	    // flags 0x40000: the pixel's movement over the last frame, times a random speed
 	    p.velocity = glm::vec3 (0.0f);
 	    if ((emitter.flags & 0x40000) != 0 && m_frameDelta > 0.0f) {
-		const float speed = WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f)
-			* (emitter.speedMax - emitter.speedMin)
+		const float speed
+		    = WallpaperEngine::Maths::randomFloat (m_rng, 0.0f, 1.0f) * (emitter.speedMax - emitter.speedMin)
 		    + emitter.speedMin;
 		p.velocity = (p.position - glm::vec3 (previous * local)) / m_frameDelta * speed;
 	    }
@@ -1663,10 +1666,10 @@ InitializerFunc CParticle::createVelocityRandomInitializer (const VelocityRandom
     return [this, minValue, maxValue, exponentValue, speedOverride] (ParticleInstance& p) {
 	const bool flat = !getScene ().getCamera ().isPerspective ();
 	const glm::vec3 min = minValue != nullptr ? minValue->getVec3 ()
-	    : flat				  ? glm::vec3 (-32.0f, -32.0f, 0.0f)
+	    : flat                                ? glm::vec3 (-32.0f, -32.0f, 0.0f)
 						  : glm::vec3 (-1.0f);
 	const glm::vec3 max = maxValue != nullptr ? maxValue->getVec3 ()
-	    : flat				  ? glm::vec3 (32.0f, 32.0f, 0.0f)
+	    : flat                                ? glm::vec3 (32.0f, 32.0f, 0.0f)
 						  : glm::vec3 (1.0f);
 	const float exponent = exponentValue->getFloat ();
 
@@ -2588,20 +2591,20 @@ OperatorFunc CParticle::createOscillateAlphaOperator (const OscillateAlphaOperat
     m_usesParticleSeed = true;
 
     // case 8, blended 30 lerps the factor from 1
-    return [definition, blend] (
-	       std::vector<ParticleInstance>& particles, uint32_t count, const std::vector<ControlPointData>&, float,
-	       float
-	   ) {
-	const OscillationRanges ranges = oscillationRanges (*definition);
-	for (uint32_t i = 0; i < count; i++) {
-	    auto& p = particles[i];
-	    if (!p.alive) {
-		continue;
+    return
+	[definition, blend] (
+	    std::vector<ParticleInstance>& particles, uint32_t count, const std::vector<ControlPointData>&, float, float
+	) {
+	    const OscillationRanges ranges = oscillationRanges (*definition);
+	    for (uint32_t i = 0; i < count; i++) {
+		auto& p = particles[i];
+		if (!p.alive) {
+		    continue;
+		}
+		const float factor = oscillateFactor (p, ranges);
+		p.alpha *= blend.active ? 1.0f - (1.0f - factor) * blendWeight (blend, p) : factor;
 	    }
-	    const float factor = oscillateFactor (p, ranges);
-	    p.alpha *= blend.active ? 1.0f - (1.0f - factor) * blendWeight (blend, p) : factor;
-	}
-    };
+	};
 }
 
 OperatorFunc CParticle::createOscillateSizeOperator (const OscillateSizeOperator& op) {
@@ -2610,20 +2613,20 @@ OperatorFunc CParticle::createOscillateSizeOperator (const OscillateSizeOperator
     m_usesParticleSeed = true;
 
     // case 9, blended 31
-    return [definition, blend] (
-	       std::vector<ParticleInstance>& particles, uint32_t count, const std::vector<ControlPointData>&, float,
-	       float
-	   ) {
-	const OscillationRanges ranges = oscillationRanges (*definition);
-	for (uint32_t i = 0; i < count; i++) {
-	    auto& p = particles[i];
-	    if (!p.alive) {
-		continue;
+    return
+	[definition, blend] (
+	    std::vector<ParticleInstance>& particles, uint32_t count, const std::vector<ControlPointData>&, float, float
+	) {
+	    const OscillationRanges ranges = oscillationRanges (*definition);
+	    for (uint32_t i = 0; i < count; i++) {
+		auto& p = particles[i];
+		if (!p.alive) {
+		    continue;
+		}
+		const float factor = oscillateFactor (p, ranges);
+		p.size *= blend.active ? 1.0f - (1.0f - factor) * blendWeight (blend, p) : factor;
 	    }
-	    const float factor = oscillateFactor (p, ranges);
-	    p.size *= blend.active ? 1.0f - (1.0f - factor) * blendWeight (blend, p) : factor;
-	}
-    };
+	};
 }
 
 OperatorFunc CParticle::createOscillatePositionOperator (const OscillatePositionOperator& op) {
@@ -2654,7 +2657,7 @@ OperatorFunc CParticle::createOscillatePositionOperator (const OscillatePosition
 	const float phaseRange = phaseMaxValue->getFloat () - phaseMin;
 	const float scaleMin = scaleMinValue->getFloat ();
 	const float scaleMax = scaleMaxValue != nullptr ? scaleMaxValue->getFloat ()
-						       : (getScene ().getCamera ().isPerspective () ? 0.5f : 10.0f);
+							: (getScene ().getCamera ().isPerspective () ? 0.5f : 10.0f);
 	const float scaleRange = scaleMax - scaleMin;
 	const glm::vec3 mask = maskValue->getVec3 ();
 
@@ -3661,7 +3664,8 @@ OperatorFunc CParticle::createBoidsOperator (const BoidsOperator& op) {
 		glm::vec3 velocitySum (0.0f);
 		glm::vec3 positionSum (0.0f);
 
-		for (uint32_t other = (block * 4 + getScene ().getFrameCounter ()) % stride; other < blocks; other += stride) {
+		for (uint32_t other = (block * 4 + getScene ().getFrameCounter ()) % stride; other < blocks;
+		     other += stride) {
 		    // WE's alive mask (lifetime != 0) is taken from the neighbor block unshuffled, so it belongs to
 		    // this lane's slot there, not to the shuffled neighbor it gets applied to
 		    if (!alive[other * 4 + lane]) {
@@ -3888,9 +3892,10 @@ glm::mat4 CParticle::worldToParticles () const {
     // WE's world to this scene's space (see the bounds collision), then the system's unless it is world space
     glm::mat4 matrix = glm::scale (glm::mat4 (1.0f), glm::vec3 (1.0f, -1.0f, 1.0f));
     if (!getScene ().getCamera ().isPerspective ()) {
-	matrix = glm::translate (
-		     glm::mat4 (1.0f), glm::vec3 (-getScene ().getWidth () / 2.0f, getScene ().getHeight () / 2.0f, 0.0f)
-		 )
+	matrix
+	    = glm::translate (
+		  glm::mat4 (1.0f), glm::vec3 (-getScene ().getWidth () / 2.0f, getScene ().getHeight () / 2.0f, 0.0f)
+	      )
 	    * matrix;
     }
     if (!m_worldSpace) {
@@ -3964,8 +3969,9 @@ std::vector<CParticle::CollisionCapsule> CParticle::collisionCapsules (int index
 	    return {};
 	}
 	const glm::vec3 extents = (high - low) * 0.5f;
-	add (getScene ().objectWorldMatrix (mesh->getMesh ()) * glm::translate (glm::mat4 (1.0f), low + extents),
-	     extents);
+	add (
+	    getScene ().objectWorldMatrix (mesh->getMesh ()) * glm::translate (glm::mat4 (1.0f), low + extents), extents
+	);
     }
 
     return capsules;
@@ -3979,58 +3985,58 @@ OperatorFunc CParticle::createCollisionModelOperator (const CollisionOperator& o
     // sub_14023FBC0 case 26 with sub_1402508C0 (bounce), sub_140250E00 (slide), sub_140251320 (stop) and
     // sub_1402517D0 (delete): of the capsules a particle is inside the last one counts, it is pushed out along the
     // line from the capsule's segment. Unlike the other shapes flag 2 doesn't stop the spin
-    return [this, index, behavior, bounceValue] (
-	       std::vector<ParticleInstance>& particles, uint32_t count, const std::vector<ControlPointData>&, float,
-	       float
-	   ) {
-	const std::vector<CollisionCapsule> capsules = this->collisionCapsules (index);
-	if (capsules.empty ()) {
-	    return;
-	}
-	const float bounce = -1.0f - bounceValue->getFloat ();
+    return
+	[this, index, behavior, bounceValue] (
+	    std::vector<ParticleInstance>& particles, uint32_t count, const std::vector<ControlPointData>&, float, float
+	) {
+	    const std::vector<CollisionCapsule> capsules = this->collisionCapsules (index);
+	    if (capsules.empty ()) {
+		return;
+	    }
+	    const float bounce = -1.0f - bounceValue->getFloat ();
 
-	for (uint32_t i = 0; i < count; i++) {
-	    auto& p = particles[i];
-	    bool hit = false;
-	    glm::vec3 normal (0.0f);
-	    float depth = 0.0f;
-
-	    for (const auto& capsule : capsules) {
-		const float along
-		    = std::clamp (glm::dot (p.position - capsule.start, capsule.direction), 0.0f, capsule.length);
-		const glm::vec3 offset = p.position - (capsule.start + along * capsule.direction);
-		const float distanceSquared = glm::dot (offset, offset);
-		// on the segment itself the engine's normal would be NaN
-		if (distanceSquared < capsule.radius * capsule.radius && distanceSquared > 0.0f) {
-		    const float distance = std::sqrt (distanceSquared);
-		    hit = true;
-		    normal = offset / distance;
-		    depth = distance - capsule.radius;
+	    for (uint32_t i = 0; i < count; i++) {
+		auto& p = particles[i];
+		bool hit = false;
+		glm::vec3 normal (0.0f);
+		float depth = 0.0f;
+
+		for (const auto& capsule : capsules) {
+		    const float along
+			= std::clamp (glm::dot (p.position - capsule.start, capsule.direction), 0.0f, capsule.length);
+		    const glm::vec3 offset = p.position - (capsule.start + along * capsule.direction);
+		    const float distanceSquared = glm::dot (offset, offset);
+		    // on the segment itself the engine's normal would be NaN
+		    if (distanceSquared < capsule.radius * capsule.radius && distanceSquared > 0.0f) {
+			const float distance = std::sqrt (distanceSquared);
+			hit = true;
+			normal = offset / distance;
+			depth = distance - capsule.radius;
+		    }
 		}
-	    }
 
-	    if (!hit) {
-		continue;
-	    }
-	    if (behavior == ParticleCollisionBehavior::Delete) {
-		p.age = p.lifetime;
-		continue;
-	    }
-	    p.position -= depth * normal;
-	    const float velocity = glm::dot (p.velocity, normal);
-	    switch (behavior) {
-		case ParticleCollisionBehavior::Bounce:
-		    p.velocity += (velocity * bounce) * normal;
-		    break;
-		case ParticleCollisionBehavior::Slide:
-		    p.velocity -= velocity * normal;
-		    break;
-		default:
-		    p.velocity = glm::vec3 (0.0f);
-		    break;
+		if (!hit) {
+		    continue;
+		}
+		if (behavior == ParticleCollisionBehavior::Delete) {
+		    p.age = p.lifetime;
+		    continue;
+		}
+		p.position -= depth * normal;
+		const float velocity = glm::dot (p.velocity, normal);
+		switch (behavior) {
+		    case ParticleCollisionBehavior::Bounce:
+			p.velocity += (velocity * bounce) * normal;
+			break;
+		    case ParticleCollisionBehavior::Slide:
+			p.velocity -= velocity * normal;
+			break;
+		    default:
+			p.velocity = glm::vec3 (0.0f);
+			break;
+		}
 	    }
-	}
-    };
+	};
 }
 
 OperatorFunc CParticle::createCollisionOperator (const CollisionOperator& op) {
@@ -4468,13 +4474,14 @@ void CParticle::updateOrientation () {
     glm::vec3 up;
 
     switch (renderer.orientation) {
-	case 1: {
-	    // upright: up along the axis, facing the camera around it
-	    up = renderer.orientationFlag ? glm::vec3 (0.0f, 1.0f, 0.0f) : world * renderer.axis;
-	    const glm::vec3 right = glm::cross (cameraForward, up);
-	    forward = glm::cross (right, up);
-	    break;
-	}
+	case 1:
+	    {
+		// upright: up along the axis, facing the camera around it
+		up = renderer.orientationFlag ? glm::vec3 (0.0f, 1.0f, 0.0f) : world * renderer.axis;
+		const glm::vec3 right = glm::cross (cameraForward, up);
+		forward = glm::cross (right, up);
+		break;
+	    }
 	case 2:
 	    // fixed: the axis as forward, in the system's frame unless flags & 1
 	    forward = renderer.orientationFlag ? renderer.axis : world * renderer.axis;
@@ -4534,7 +4541,8 @@ void CParticle::updateParticleRenderVars () {
 	const float frameHeight = frame.height1 / static_cast<float> (texture->getTextureHeight (frame.frameNumber));
 	const glm::vec4* res = texture->getResolution ();
 	m_renderVar1 = glm::vec4 (
-	    frameWidth, frameHeight, static_cast<float> (m_spritesheetFrames), res->y / res->x * (frameHeight / frameWidth)
+	    frameWidth, frameHeight, static_cast<float> (m_spritesheetFrames),
+	    res->y / res->x * (frameHeight / frameWidth)
 	);
     } else {
 	float textureRatio = 1.0f;
@@ -4718,9 +4726,7 @@ void CParticle::copyRefractSource () const {
     // our copy is scene sized, the shader samples it with normalized coordinates only
     glBindFramebuffer (GL_READ_FRAMEBUFFER, source->getFramebuffer ());
     glBindFramebuffer (GL_DRAW_FRAMEBUFFER, m_refractFBO->getFramebuffer ());
-    glBlitFramebuffer (
-	0, 0, sw, sh, 0, 0, dw, dh, GL_COLOR_BUFFER_BIT, sw == dw && sh == dh ? GL_NEAREST : GL_LINEAR
-    );
+    glBlitFramebuffer (0, 0, sw, sh, 0, 0, dw, dh, GL_COLOR_BUFFER_BIT, sw == dw && sh == dh ? GL_NEAREST : GL_LINEAR);
 }
 
 void CParticle::buildRopeTrail (uint32_t& vertexIndex, uint32_t& indexOffset) {
@@ -4799,10 +4805,10 @@ void CParticle::buildRopeSegments (uint32_t& vertexIndex, uint32_t& indexOffset)
 	const auto write = [&] (const glm::vec2& corner) {
 	    float* v = &m_vertices[static_cast<size_t> (vertexIndex++) * ROPE_FLOATS_PER_VERTEX];
 	    const float values[ROPE_FLOATS_PER_VERTEX] = {
-		start.x,        start.y,        start.z,        first.size,     end.x,          end.y,
-		end.z,          lengthSlot,     before.x,       before.y,       before.z,       static_cast<float> (k),
-		after.x,        after.y,        after.z,        second.size,    second.color.r, second.color.g,
-		second.color.b, second.alpha,   corner.x,       corner.y,       first.color.r,  first.color.g,
+		start.x,        start.y,      start.z,  first.size,  end.x,          end.y,
+		end.z,          lengthSlot,   before.x, before.y,    before.z,       static_cast<float> (k),
+		after.x,        after.y,      after.z,  second.size, second.color.r, second.color.g,
+		second.color.b, second.alpha, corner.x, corner.y,    first.color.r,  first.color.g,
 		first.color.b,  first.alpha,
 	    };
 	    std::copy (std::begin (values), std::end (values), v);

+ 32 - 30
src/WallpaperEngine/Render/Objects/CSound.cpp

@@ -62,9 +62,8 @@ glm::vec2 stereoPan (const glm::vec3& direction, float distance) {
 
 CSound::CSound (Wallpapers::CScene& scene, const Sound& sound) :
     CObject (scene, sound), m_sound (sound), m_startSilent (sound.startsilent.value_or (false)) {
-    this->m_lastVolume = this->m_sound.volume && this->m_sound.volume->value
-	? this->m_sound.volume->value->getFloat ()
-	: 1.0f;
+    this->m_lastVolume
+	= this->m_sound.volume && this->m_sound.volume->value ? this->m_sound.volume->value->getFloat () : 1.0f;
     this->m_lastMaster = this->masterVolume ();
 
     // sub_1401F4F20, when the object is added to the scene
@@ -98,9 +97,11 @@ void CSound::loadVoices () {
 	try {
 	    const Audio::AudioStream probe (this->getScene ().getAudioContext (), this->getAssetLocator ().read (file));
 
-	    this->m_voices.push_back ({ .file = file,
-					.duration = static_cast<float> (probe.getDuration ()),
-					.mono = probe.getSourceChannels () == 1 });
+	    this->m_voices.push_back (
+		{ .file = file,
+		  .duration = static_cast<float> (probe.getDuration ()),
+		  .mono = probe.getSourceChannels () == 1 }
+	    );
 	} catch (const std::exception& e) {
 	    sLog.error ("Cannot load sound ", file, ": ", e.what ());
 	}
@@ -171,9 +172,7 @@ CSound::Voice& CSound::pickVoice () {
 }
 
 bool CSound::hasActiveVoice () const {
-    return std::ranges::any_of (this->m_voices, [] (const Voice& voice) {
-	return voice.state != VoiceState::Stopped;
-    });
+    return std::ranges::any_of (this->m_voices, [] (const Voice& voice) { return voice.state != VoiceState::Stopped; });
 }
 
 void CSound::play () {
@@ -226,26 +225,28 @@ void CSound::play () {
 		this->m_timer = uniform01 () * (this->m_sound.maxtime - this->m_sound.mintime) + this->m_sound.mintime
 		    + this->m_remaining;
 		break;
-	    case PlaybackMode_Single: {
-		this->stopAllVoices ();
-		this->m_timer = 0.0f;
+	    case PlaybackMode_Single:
+		{
+		    this->stopAllVoices ();
+		    this->m_timer = 0.0f;
 
-		Voice& voice = this->pickVoice ();
+		    Voice& voice = this->pickVoice ();
 
-		this->playVoice (voice, false);
-		this->m_remaining = voice.duration;
-		break;
-	    }
-	    case PlaybackMode_Loop: {
-		this->stopAllVoices ();
+		    this->playVoice (voice, false);
+		    this->m_remaining = voice.duration;
+		    break;
+		}
+	    case PlaybackMode_Loop:
+		{
+		    this->stopAllVoices ();
 
-		Voice& voice = this->pickVoice ();
+		    Voice& voice = this->pickVoice ();
 
-		this->playVoice (voice, loop);
-		// several files: the next random one starts when this one is over
-		this->m_timer = this->m_voices.size () > 1 ? voice.duration : 0.0f;
-		break;
-	    }
+		    this->playVoice (voice, loop);
+		    // several files: the next random one starts when this one is over
+		    this->m_timer = this->m_voices.size () > 1 ? voice.duration : 0.0f;
+		    break;
+		}
 	}
     }
 
@@ -299,8 +300,8 @@ void CSound::volumeChanged () {
     const auto mode = this->m_sound.playbackmode;
 
     if (mode != PlaybackMode_Single) {
-	const bool active = !(mode == PlaybackMode_Random && this->m_timer <= 0.0f) && this->hasActiveVoice ()
-	    && !this->m_paused;
+	const bool active
+	    = !(mode == PlaybackMode_Random && this->m_timer <= 0.0f) && this->hasActiveVoice () && !this->m_paused;
 
 	if (!active && !this->m_paused && !this->m_startSilent && !this->m_stopped) {
 	    this->play ();
@@ -399,7 +400,8 @@ glm::vec3 CSound::spatialPosition () const {
     // orthographic scenes only keep the direction, scaled down by the sound's depth over a quarter of the scene size
     if (camera.isOrthogonal ()) {
 	const float length = std::sqrt (glm::dot (position, position));
-	const float reach = static_cast<float> (static_cast<int> (camera.getWidth ()) + static_cast<int> (camera.getHeight ()))
+	const float reach
+	    = static_cast<float> (static_cast<int> (camera.getWidth ()) + static_cast<int> (camera.getHeight ()))
 	    * 0.25f;
 
 	position *= 1.0f / length;
@@ -416,8 +418,8 @@ glm::vec2 CSound::outputGains (const Voice& voice) const {
     // OpenAL Soft only spatializes mono sources (AL_SOURCE_SPATIALIZE_SOFT defaults to auto), the others go straight
     // to their speakers; the source gain is clamped to AL_MAX_GAIN 1 on both paths
     if (voice.mono && this->getScene ().getAudioContext ().getChannels () == 2) {
-	// WE only sets the reference distance and rolloff on spatialized sounds, the others keep OpenAL's 1 and 1 and sit
-	// on the listener
+	// WE only sets the reference distance and rolloff on spatialized sounds, the others keep OpenAL's 1 and 1 and
+	// sit on the listener
 	const float reference = this->m_sound.spatialization ? this->m_sound.mindistance : 1.0f;
 	const float rolloff = this->m_sound.spatialization ? this->m_sound.attenuation : 1.0f;
 	const float limit = std::max (reference / 1024.0f, FLT_EPSILON);

+ 38 - 32
src/WallpaperEngine/Render/Objects/CText.cpp

@@ -12,13 +12,13 @@
 #include <glm/gtc/matrix_transform.hpp>
 #include <glm/gtc/type_ptr.hpp>
 
+#include "WallpaperEngine/Assets/AssetLocator.h"
 #include "WallpaperEngine/Data/Model/DynamicValue.h"
 #include "WallpaperEngine/Data/Model/Material.h"
 #include "WallpaperEngine/Data/Model/Object.h"
 #include "WallpaperEngine/Data/Model/UserSetting.h"
 #include "WallpaperEngine/Data/Parsers/MaterialParser.h"
 #include "WallpaperEngine/Logging/Log.h"
-#include "WallpaperEngine/Assets/AssetLocator.h"
 #include "WallpaperEngine/Render/CFBO.h"
 #include "WallpaperEngine/Render/Camera.h"
 #include "WallpaperEngine/Render/TextureProvider.h"
@@ -137,7 +137,8 @@ std::string installedFamily (const std::vector<std::string>& families) {
 
 // wallpaper64.exe's fallback fonts (off_140484C40, tried per character by sub_1401AD670): Windows fonts from the
 // system font folder and the assets' Twemoji. Here the Windows fonts count when they are installed under their own
-// family, arial.ttf also through its metric compatible clones like the systemfont_arial match
+// family, arial.ttf also through its metric compatible clones like the systemfont_arial match, and the CJK ones
+// through the usual Linux CJK families since Windows always has YaHei/Malgun but Linux never does
 std::vector<TextFontSource> weFallbackFonts (const WallpaperEngine::Assets::AssetLocator& assets) {
     static std::shared_ptr<const std::vector<uint8_t>> twemoji;
     static bool twemojiRead = false;
@@ -159,10 +160,15 @@ std::vector<TextFontSource> weFallbackFonts (const WallpaperEngine::Assets::Asse
     }
 
     const std::vector<std::vector<std::string>> before = {
-	{ "Arial", "Liberation Sans", "Arimo" }, { "Segoe UI Emoji" }, { "Arial Unicode MS" }, { "Segoe UI" },
+	{ "Arial", "Liberation Sans", "Arimo" },
+	{ "Segoe UI Emoji" },
+	{ "Arial Unicode MS" },
+	{ "Segoe UI" },
     };
     const std::vector<std::vector<std::string>> after = {
-	{ "Segoe UI Symbol" }, { "Microsoft YaHei" }, { "Malgun Gothic" },
+	{ "Segoe UI Symbol" },
+	{ "Microsoft YaHei", "Noto Sans CJK SC", "Source Han Sans SC", "WenQuanYi Zen Hei", "Droid Sans Fallback" },
+	{ "Malgun Gothic", "Noto Sans CJK KR", "Source Han Sans KR" },
     };
     std::vector<TextFontSource> fonts;
 
@@ -265,15 +271,14 @@ const Material& compositeMaterial () {
     return *material;
 }
 
-// Mirrors CImage.cpp's clampParallaxAxis: keeps an edge pair from sliding past the viewport
-// once `offset` is added to both; a box too small to cover the viewport on this axis has no
+// Mirrors CImage.cpp's clampParallaxAxis: keeps an edge pair from sliding into the on-screen part
+// of the canvas once `offset` is added to both; a box too small to cover it on this axis has no
 // ground to uncover and moves freely.
-float clampParallaxAxis (float offset, float edgeA, float edgeB, float sceneExtent) {
+float clampParallaxAxis (float offset, float edgeA, float edgeB, float visibleLow, float visibleHigh) {
     const float low = std::min (edgeA, edgeB);
     const float high = std::max (edgeA, edgeB);
-    const float half = sceneExtent / 2.0f;
-    const float maxOffset = -half - low;
-    const float minOffset = half - high;
+    const float maxOffset = visibleLow - low;
+    const float minOffset = visibleHigh - high;
 
     if (minOffset > maxOffset) {
 	return offset;
@@ -351,9 +356,9 @@ CText::~CText () {
 
     this->destroyPasses ();
 
-    for (GLuint* buffer : { &m_glyphPositions, &m_glyphTexcoords, &m_colorGlyphPositions, &m_colorGlyphTexcoords,
-			    &m_backgroundPositions, &m_passSpacePosition, &m_compositePosition, &m_quadTexcoords,
-			    &m_compositeTexcoords }) {
+    for (GLuint* buffer :
+	 { &m_glyphPositions, &m_glyphTexcoords, &m_colorGlyphPositions, &m_colorGlyphTexcoords, &m_backgroundPositions,
+	   &m_passSpacePosition, &m_compositePosition, &m_quadTexcoords, &m_compositeTexcoords }) {
 	if (*buffer != 0) {
 	    glDeleteBuffers (1, buffer);
 	}
@@ -382,7 +387,8 @@ void CText::setup () {
     // sub_140186C90 flags a text (object type 4) that another object lists in its dependencies once every object
     // exists, before the first frame
     m_isDependency = std::ranges::any_of (this->getScene ().getScene ().objects, [this] (const auto& object) {
-	return object->id != m_text.id && std::ranges::find (object->dependencies, m_text.id) != object->dependencies.end ();
+	return object->id != m_text.id
+	    && std::ranges::find (object->dependencies, m_text.id) != object->dependencies.end ();
     });
 
     m_layout.setFallbackFonts (weFallbackFonts (this->getAssetLocator ()));
@@ -396,9 +402,9 @@ void CText::setup () {
     m_colorTexture = std::make_shared<TextAtlasTexture> ();
     this->m_texture = m_atlas;
 
-    for (GLuint* buffer : { &m_glyphPositions, &m_glyphTexcoords, &m_colorGlyphPositions, &m_colorGlyphTexcoords,
-			    &m_backgroundPositions, &m_passSpacePosition, &m_compositePosition, &m_quadTexcoords,
-			    &m_compositeTexcoords }) {
+    for (GLuint* buffer :
+	 { &m_glyphPositions, &m_glyphTexcoords, &m_colorGlyphPositions, &m_colorGlyphTexcoords, &m_backgroundPositions,
+	   &m_passSpacePosition, &m_compositePosition, &m_quadTexcoords, &m_compositeTexcoords }) {
 	glGenBuffers (1, buffer);
     }
 
@@ -569,8 +575,8 @@ CText::PassLayout CText::currentPassLayout () const {
     // and 0x8000, sub_140186440). Its other trigger, image flag 0x100, is never set in 2.8.42. The scene loader adds
     // 0x1010 to a text another object lists in its dependencies (sub_140186C90), the buffer is what it reads
     const bool fog = this->getScene ().hasDistanceFog () || this->getScene ().hasHeightFog ();
-    layout.buffered = (!m_text.effects.empty () || (layout.blendMode != 0 && layout.blendMode != 31) || fog
-		       || m_isDependency)
+    layout.buffered
+	= (!m_text.effects.empty () || (layout.blendMode != 0 && layout.blendMode != 31) || fog || m_isDependency)
 	&& !debug.baseOnly;
 
     // sub_140258900: text with effects renders into a buffer of its box plus padding on every side
@@ -624,8 +630,7 @@ void CText::uploadGeometry () {
 	    const auto [u0, v0, u1, v1] = std::array { quad.uv.x, quad.uv.y, quad.uv.z, quad.uv.w };
 
 	    positions.insert (
-		positions.end (),
-		{ x0, y1, 0.0f, x0, y0, 0.0f, x1, y1, 0.0f, x1, y1, 0.0f, x0, y0, 0.0f, x1, y0, 0.0f }
+		positions.end (), { x0, y1, 0.0f, x0, y0, 0.0f, x1, y1, 0.0f, x1, y1, 0.0f, x0, y0, 0.0f, x1, y0, 0.0f }
 	    );
 	    texcoords.insert (texcoords.end (), { u0, v0, u0, v1, u1, v0, u1, v0, u0, v1, u1, v1 });
 	}
@@ -722,9 +727,7 @@ CPass* CText::createFontPass (const std::shared_ptr<const CFBO>& destination, co
 	    nullptr, [this] () { glDrawArrays (GL_TRIANGLES, 0, m_colorGlyphVertexCount); }, nullptr
 	);
     } else {
-	pass->setGeometryCallback (
-	    nullptr, [this] () { glDrawArrays (GL_TRIANGLES, 0, m_glyphVertexCount); }, nullptr
-	);
+	pass->setGeometryCallback (nullptr, [this] () { glDrawArrays (GL_TRIANGLES, 0, m_glyphVertexCount); }, nullptr);
     }
 
     for (int i = 0; i < 4; i++) {
@@ -746,7 +749,8 @@ void CText::buildPasses () {
     const std::string msdfSuffix = layout.msdf ? "_msdf" : "";
 
     try {
-	m_fontMaterial = MaterialParser::load (project, "materials/fonts/basefont" + msdfSuffix + depthSuffix + ".json");
+	m_fontMaterial
+	    = MaterialParser::load (project, "materials/fonts/basefont" + msdfSuffix + depthSuffix + ".json");
 	m_colorFontMaterial = layout.color
 	    ? MaterialParser::load (project, "materials/fonts/basefontrgba" + msdfSuffix + depthSuffix + ".json")
 	    : nullptr;
@@ -849,8 +853,8 @@ void CText::buildPasses () {
     const glm::vec2 fboSize = { static_cast<float> (layout.bufferSize.x), static_cast<float> (layout.bufferSize.y) };
 
     // the same buffer setup as image layers (text and image vtables share slot 23, sub_1401EA500): scene buffers named
-    // _rt_imageLayerComposite_<id>_a/_b, which layers depending on the text sample, 16 bit float in HDR scene rendering.
-    // They keep their identity when the text box changes size, whoever resolved them keeps a working buffer
+    // _rt_imageLayerComposite_<id>_a/_b, which layers depending on the text sample, 16 bit float in HDR scene
+    // rendering. They keep their identity when the text box changes size, whoever resolved them keeps a working buffer
     const TextureFormat format = this->getScene ().isHDR () ? TextureFormat_RGBA16161616f : TextureFormat_ARGB8888;
     const auto sceneBuffer = [this, format, fboSize] (const std::string& suffix) {
 	auto& scene = this->getScene ();
@@ -1105,7 +1109,8 @@ void CText::render () {
     glPushDebugGroup (GL_DEBUG_SOURCE_APPLICATION, 0, -1, str.c_str ());
 #endif /* DEBUG */
 
-    const size_t passCount = visible ? m_passes.size () : m_passes.size () - std::min (m_passes.size (), m_compositePassCount);
+    const size_t passCount
+	= visible ? m_passes.size () : m_passes.size () - std::min (m_passes.size (), m_compositePassCount);
 
     for (size_t i = 0; i < passCount; i++) {
 	m_passes[i]->render ();
@@ -1179,8 +1184,8 @@ void CText::updateTransform () {
     // WE's world is y up from the bottom left, this space is centered and y down; the layout below is y up too
     const float scene_w = camera.getWidth ();
     const float scene_h = camera.getHeight ();
-    glm::mat4 model = flipY * glm::translate (glm::mat4 (1.0f), glm::vec3 (-scene_w * 0.5f, -scene_h * 0.5f, 0.0f))
-	* world * flipY;
+    glm::mat4 model
+	= flipY * glm::translate (glm::mat4 (1.0f), glm::vec3 (-scene_w * 0.5f, -scene_h * 0.5f, 0.0f)) * world * flipY;
 
     // Matches CImage's parallax handling (CImage.cpp:updateScreenSpacePosition): WE moves the view, so the offset
     // lands outside the text's own rotation and scale
@@ -1195,11 +1200,12 @@ void CText::updateTransform () {
 	    const float scaledHalfHeight = boxHeight * 0.5f * scale.y;
 	    const float baseX = model[3].x;
 	    const float baseY = model[3].y;
+	    const glm::vec4 visible = getScene ().getVisibleCanvasRegion ();
 	    parallaxOffset.x = clampParallaxAxis (
-		parallaxOffset.x, baseX - scaledHalfWidth, baseX + scaledHalfWidth, getScene ().getCanvasWidth ()
+		parallaxOffset.x, baseX - scaledHalfWidth, baseX + scaledHalfWidth, visible.x, visible.y
 	    );
 	    parallaxOffset.y = clampParallaxAxis (
-		parallaxOffset.y, baseY - scaledHalfHeight, baseY + scaledHalfHeight, getScene ().getCanvasHeight ()
+		parallaxOffset.y, baseY - scaledHalfHeight, baseY + scaledHalfHeight, visible.z, visible.w
 	    );
 	}
 

+ 122 - 117
src/WallpaperEngine/Render/Objects/PuppetPhysics.cpp

@@ -13,158 +13,158 @@ using JSON = WallpaperEngine::Data::JSON::JSON;
 
 namespace WallpaperEngine::Render::Objects {
 namespace {
-constexpr float kDegToRad = 0.017453292f;
-constexpr float kRadToDeg = 57.29578f;
-constexpr float kPi = 3.1415927f;
-constexpr float kTwoPi = 6.2831855f;
+    constexpr float kDegToRad = 0.017453292f;
+    constexpr float kRadToDeg = 57.29578f;
+    constexpr float kPi = 3.1415927f;
+    constexpr float kTwoPi = 6.2831855f;
 
-struct Rows {
-    glm::vec3 r[3];
-};
-
-// w, x, y, z in the vec4's x, y, z, w
-using Quat = glm::vec4;
-
-const Quat kIdentity { 1.0f, 0.0f, 0.0f, 0.0f };
+    struct Rows {
+	glm::vec3 r[3];
+    };
 
-glm::vec3 mulRow (const glm::vec3& v, const Rows& m) { return v.x * m.r[0] + v.y * m.r[1] + v.z * m.r[2]; }
+    // w, x, y, z in the vec4's x, y, z, w
+    using Quat = glm::vec4;
 
-// sub_140215380
-Quat multiply (const Quat& a, const Quat& b) {
-    return {
-	b.x * a.x - b.y * a.y - b.z * a.z - b.w * a.w,
-	b.y * a.x + a.y * b.x + b.w * a.z - a.w * b.z,
-	b.z * a.x + a.z * b.x + a.w * b.y - b.w * a.y,
-	b.w * a.x + a.w * b.x + b.z * a.y - a.z * b.y,
-    };
-}
+    const Quat kIdentity { 1.0f, 0.0f, 0.0f, 0.0f };
 
-// sub_140216070
-Quat slerp (const Quat& a, Quat b, float t) {
-    float cosine = glm::dot (a, b);
+    glm::vec3 mulRow (const glm::vec3& v, const Rows& m) { return v.x * m.r[0] + v.y * m.r[1] + v.z * m.r[2]; }
 
-    if (cosine < 0.0f) {
-	b = -b;
-	cosine = -cosine;
+    // sub_140215380
+    Quat multiply (const Quat& a, const Quat& b) {
+	return {
+	    b.x * a.x - b.y * a.y - b.z * a.z - b.w * a.w,
+	    b.y * a.x + a.y * b.x + b.w * a.z - a.w * b.z,
+	    b.z * a.x + a.z * b.x + a.w * b.y - b.w * a.y,
+	    b.w * a.x + a.w * b.x + b.z * a.y - a.z * b.y,
+	};
     }
 
-    if (cosine > 0.99999988f) {
-	return a * (1.0f - t) + b * t;
-    }
+    // sub_140216070
+    Quat slerp (const Quat& a, Quat b, float t) {
+	float cosine = glm::dot (a, b);
 
-    const float angle = std::acos (cosine);
-    const float sine = std::sin (angle);
+	if (cosine < 0.0f) {
+	    b = -b;
+	    cosine = -cosine;
+	}
 
-    return (a * std::sin ((1.0f - t) * angle) + b * std::sin (angle * t)) / sine;
-}
+	if (cosine > 0.99999988f) {
+	    return a * (1.0f - t) + b * t;
+	}
 
-// sub_140217AC0
-Quat normalize (const Quat& q) {
-    const float length = std::sqrt (glm::dot (q, q));
-    return length > 0.0f ? q * (1.0f / length) : kIdentity;
-}
+	const float angle = std::acos (cosine);
+	const float sine = std::sin (angle);
 
-// sub_1402167C0, the shortest rotation taking direction `from` onto `to`
-Quat rotationArc (const glm::vec3& from, const glm::vec3& to) {
-    const float cosine = glm::dot (from, to);
+	return (a * std::sin ((1.0f - t) * angle) + b * std::sin (angle * t)) / sine;
+    }
 
-    if (cosine >= 0.99999988f) {
-	return kIdentity;
+    // sub_140217AC0
+    Quat normalize (const Quat& q) {
+	const float length = std::sqrt (glm::dot (q, q));
+	return length > 0.0f ? q * (1.0f / length) : kIdentity;
     }
 
-    if (cosine < -0.99999988f) {
-	glm::vec3 axis (-from.y, from.x, 0.0f);
+    // sub_1402167C0, the shortest rotation taking direction `from` onto `to`
+    Quat rotationArc (const glm::vec3& from, const glm::vec3& to) {
+	const float cosine = glm::dot (from, to);
 
-	if (glm::dot (axis, axis) < 0.00000011920929f) {
-	    axis = glm::vec3 (0.0f, -from.z, from.y);
+	if (cosine >= 0.99999988f) {
+	    return kIdentity;
 	}
 
-	axis *= 1.0f / std::sqrt (glm::dot (axis, axis));
-	return { std::cos (1.5707964f), axis.x, axis.y, axis.z };
-    }
+	if (cosine < -0.99999988f) {
+	    glm::vec3 axis (-from.y, from.x, 0.0f);
 
-    const float s = std::sqrt ((cosine + 1.0f) + (cosine + 1.0f));
-    const glm::vec3 axis = glm::cross (from, to) * (1.0f / s);
+	    if (glm::dot (axis, axis) < 0.00000011920929f) {
+		axis = glm::vec3 (0.0f, -from.z, from.y);
+	    }
 
-    return { s * 0.5f, axis.x, axis.y, axis.z };
-}
+	    axis *= 1.0f / std::sqrt (glm::dot (axis, axis));
+	    return { std::cos (1.5707964f), axis.x, axis.y, axis.z };
+	}
 
-// quaternion of the Euler angles, as built inline all over sub_1401FDF90
-Quat fromEuler (const glm::vec3& angles) {
-    const glm::vec3 half = angles * 0.5f;
-    const float c1 = std::cos (half.x), s1 = std::sin (half.x);
-    const float c2 = std::cos (half.y), s2 = std::sin (half.y);
-    const float c3 = std::cos (half.z), s3 = std::sin (half.z);
+	const float s = std::sqrt ((cosine + 1.0f) + (cosine + 1.0f));
+	const glm::vec3 axis = glm::cross (from, to) * (1.0f / s);
 
-    return {
-	s2 * s1 * s3 + c2 * c1 * c3,
-	c2 * s1 * c3 - s2 * c1 * s3,
-	c2 * s1 * s3 + s2 * c1 * c3,
-	c2 * c1 * s3 - s2 * s1 * c3,
-    };
-}
+	return { s * 0.5f, axis.x, axis.y, axis.z };
+    }
 
-Rows eulerRows (const glm::vec3& angles) {
-    const float cx = std::cos (angles.x), sx = std::sin (angles.x);
-    const float cy = std::cos (angles.y), sy = std::sin (angles.y);
-    const float cz = std::cos (angles.z), sz = std::sin (angles.z);
+    // quaternion of the Euler angles, as built inline all over sub_1401FDF90
+    Quat fromEuler (const glm::vec3& angles) {
+	const glm::vec3 half = angles * 0.5f;
+	const float c1 = std::cos (half.x), s1 = std::sin (half.x);
+	const float c2 = std::cos (half.y), s2 = std::sin (half.y);
+	const float c3 = std::cos (half.z), s3 = std::sin (half.z);
+
+	return {
+	    s2 * s1 * s3 + c2 * c1 * c3,
+	    c2 * s1 * c3 - s2 * c1 * s3,
+	    c2 * s1 * s3 + s2 * c1 * c3,
+	    c2 * c1 * s3 - s2 * s1 * c3,
+	};
+    }
 
-    return { {
-	{ cy * cz, cy * sz, -sy },
-	{ sy * cz * sx - cx * sz, sy * sz * sx + cx * cz, sx * cy },
-	{ cx * cz * sy + sx * sz, cx * sz * sy - sx * cz, cx * cy },
-    } };
-}
+    Rows eulerRows (const glm::vec3& angles) {
+	const float cx = std::cos (angles.x), sx = std::sin (angles.x);
+	const float cy = std::cos (angles.y), sy = std::sin (angles.y);
+	const float cz = std::cos (angles.z), sz = std::sin (angles.z);
 
-// sub_140216280
-Rows quatRows (const Quat& q) {
-    const float w = q.x, x = q.y, y = q.z, z = q.w;
+	return { {
+	    { cy * cz, cy * sz, -sy },
+	    { sy * cz * sx - cx * sz, sy * sz * sx + cx * cz, sx * cy },
+	    { cx * cz * sy + sx * sz, cx * sz * sy - sx * cz, cx * cy },
+	} };
+    }
 
-    return { {
-	{ 1.0f - 2.0f * (z * z + y * y), 2.0f * (z * w + x * y), 2.0f * (x * z - y * w) },
-	{ 2.0f * (x * y - z * w), 1.0f - 2.0f * (z * z + x * x), 2.0f * (x * w + y * z) },
-	{ 2.0f * (y * w + x * z), 2.0f * (y * z - x * w), 1.0f - 2.0f * (y * y + x * x) },
-    } };
-}
+    // sub_140216280
+    Rows quatRows (const Quat& q) {
+	const float w = q.x, x = q.y, y = q.z, z = q.w;
 
-glm::vec3 eulerFromRows (const Rows& n) {
-    const float z = std::atan2 (n.r[0].y, n.r[0].x);
-    const float y = std::atan2 (-n.r[0].z, std::sqrt (n.r[2].z * n.r[2].z + n.r[1].z * n.r[1].z));
-    const float sz = std::sin (z), cz = std::cos (z);
-    const float x = std::atan2 (sz * n.r[2].x - cz * n.r[2].y, cz * n.r[1].y - sz * n.r[1].x);
+	return { {
+	    { 1.0f - 2.0f * (z * z + y * y), 2.0f * (z * w + x * y), 2.0f * (x * z - y * w) },
+	    { 2.0f * (x * y - z * w), 1.0f - 2.0f * (z * z + x * x), 2.0f * (x * w + y * z) },
+	    { 2.0f * (y * w + x * z), 2.0f * (y * z - x * w), 1.0f - 2.0f * (y * y + x * x) },
+	} };
+    }
 
-    return { x, y, z };
-}
+    glm::vec3 eulerFromRows (const Rows& n) {
+	const float z = std::atan2 (n.r[0].y, n.r[0].x);
+	const float y = std::atan2 (-n.r[0].z, std::sqrt (n.r[2].z * n.r[2].z + n.r[1].z * n.r[1].z));
+	const float sz = std::sin (z), cz = std::cos (z);
+	const float x = std::atan2 (sz * n.r[2].x - cz * n.r[2].y, cz * n.r[1].y - sz * n.r[1].x);
 
-float wrapAngle (float angle, bool locked) {
-    if (locked) {
-	return 0.0f;
+	return { x, y, z };
     }
 
-    if (angle < 0.0f) {
-	return std::fmod (angle - kPi, kTwoPi) + kPi;
+    float wrapAngle (float angle, bool locked) {
+	if (locked) {
+	    return 0.0f;
+	}
+
+	if (angle < 0.0f) {
+	    return std::fmod (angle - kPi, kTwoPi) + kPi;
+	}
+
+	return std::fmod (angle + kPi, kTwoPi) - kPi;
     }
 
-    return std::fmod (angle + kPi, kTwoPi) - kPi;
-}
+    glm::vec3 parseVector (const std::string& text) {
+	glm::vec3 result (0.0f);
+	const char* cursor = text.c_str ();
 
-glm::vec3 parseVector (const std::string& text) {
-    glm::vec3 result (0.0f);
-    const char* cursor = text.c_str ();
+	for (int i = 0; i < 3 && *cursor != '\0'; i++) {
+	    char* end = nullptr;
+	    result[i] = std::strtof (cursor, &end);
 
-    for (int i = 0; i < 3 && *cursor != '\0'; i++) {
-	char* end = nullptr;
-	result[i] = std::strtof (cursor, &end);
+	    if (end == cursor) {
+		break;
+	    }
 
-	if (end == cursor) {
-	    break;
+	    cursor = end;
 	}
 
-	cursor = end;
+	return result;
     }
-
-    return result;
-}
 } // namespace
 
 PuppetBonePhysics PuppetBonePhysics::parse (const std::string& text) {
@@ -265,7 +265,8 @@ glm::mat4 stepPuppetBonePhysics (
 ) {
     const uint32_t flags = physics.flags;
     const Rows current { { glm::vec3 (world[0]), glm::vec3 (world[1]), glm::vec3 (world[2]) } };
-    const Rows previous { { glm::vec3 (previousWorld[0]), glm::vec3 (previousWorld[1]), glm::vec3 (previousWorld[2]) } };
+    const Rows previous { { glm::vec3 (previousWorld[0]), glm::vec3 (previousWorld[1]),
+			    glm::vec3 (previousWorld[2]) } };
     const glm::vec3 currentOrigin (world[3]);
     const glm::vec3 previousOrigin (previousWorld[3]);
 
@@ -297,7 +298,9 @@ glm::mat4 stepPuppetBonePhysics (
     if ((flags & PuppetBonePhysics::Simulate) && (flags & PuppetBonePhysics::Rotation)) {
 	Quat& velocity = state.angularVelocity;
 
-	velocity = multiply (velocity, slerp (kIdentity, arc, std::min (distance * physics.rotationInertia * kDegToRad, 1.0f)));
+	velocity = multiply (
+	    velocity, slerp (kIdentity, arc, std::min (distance * physics.rotationInertia * kDegToRad, 1.0f))
+	);
 	velocity = multiply (
 	    velocity,
 	    slerp (kIdentity, fromEuler (-state.angles), std::min (physics.rotationStiffness * kDegToRad * dt, 1.0f))
@@ -377,7 +380,9 @@ glm::mat4 stepPuppetBonePhysics (
     };
 }
 
-void applyPuppetBoneImpulse (PuppetBonePhysicsState& state, const glm::vec3& directional, const glm::vec3& angularDegrees) {
+void applyPuppetBoneImpulse (
+    PuppetBonePhysicsState& state, const glm::vec3& directional, const glm::vec3& angularDegrees
+) {
     state.velocity += directional;
     state.angularVelocity = multiply (state.angularVelocity, fromEuler (angularDegrees * kDegToRad));
 }

+ 3 - 1
src/WallpaperEngine/Render/Objects/PuppetPhysics.h

@@ -71,5 +71,7 @@ glm::mat4 stepPuppetBonePhysics (
  * Script `applyBonePhysicsImpulse` (sub_140210990): the directional impulse is added to the translation velocity,
  * the angular one (degrees) is turned into a quaternion and multiplied onto the angular velocity.
  */
-void applyPuppetBoneImpulse (PuppetBonePhysicsState& state, const glm::vec3& directional, const glm::vec3& angularDegrees);
+void applyPuppetBoneImpulse (
+    PuppetBonePhysicsState& state, const glm::vec3& directional, const glm::vec3& angularDegrees
+);
 } // namespace WallpaperEngine::Render::Objects

+ 37 - 32
src/WallpaperEngine/Render/Objects/PuppetRig.cpp

@@ -201,7 +201,9 @@ PuppetBoneSet parsePuppetBones (const BinaryReader& reader, size_t mdlsOffset) {
     // a flag byte and then a matrix per bone and per extra record. Not the inverse bind matrices: bone 0 holds its bind
     // world and the others their bind locals (makima.body_puppet.mdl), what WE does with them isn't traced
     if (reader.next () != 0) {
-	reader.base ().seekg (static_cast<std::streamoff> ((boneCount + extraCount) * sizeof (float) * 16), std::ios::cur);
+	reader.base ().seekg (
+	    static_cast<std::streamoff> ((boneCount + extraCount) * sizeof (float) * 16), std::ios::cur
+	);
     }
 
     const uint32_t constraintCount = reader.nextUInt32 ();
@@ -574,9 +576,7 @@ std::vector<PuppetAnimationClip> parsePuppetAnimationClips (
 glm::vec3 lerp (const glm::vec3& a, const glm::vec3& b, float alpha) { return a + (b - a) * alpha; }
 } // namespace
 
-void PuppetRig::clear () {
-    *this = PuppetRig ();
-}
+void PuppetRig::clear () { *this = PuppetRig (); }
 
 void PuppetRig::load (const std::vector<char>& data, size_t mdlsOffset, uint32_t meshCount, const std::string& name) {
     this->clear ();
@@ -605,9 +605,9 @@ void PuppetRig::load (const std::vector<char>& data, size_t mdlsOffset, uint32_t
     this->hasPhysics
 	= std::ranges::any_of (this->bones, [] (const PuppetBone& bone) { return bone.physics.simulated (); });
 
-    // sub_140261880 walks the sections after MDLS in whatever order they come: every one is "TAGnnnn\0" and the absolute
-    // offset of the next one, an empty tag or the end of the file ends it. MDAT holds attachment points, MDMP morph
-    // targets (read by the model), MDLA the clips
+    // sub_140261880 walks the sections after MDLS in whatever order they come: every one is "TAGnnnn\0" and the
+    // absolute offset of the next one, an empty tag or the end of the file ends it. MDAT holds attachment points, MDMP
+    // morph targets (read by the model), MDLA the clips
     size_t offset = boneSet.nextSectionOffset;
     std::set<size_t> visited;
 
@@ -617,13 +617,15 @@ void PuppetRig::load (const std::vector<char>& data, size_t mdlsOffset, uint32_t
 	std::memcpy (&next, data.data () + offset + 9, sizeof (next));
 
 	if (tag == "MDAT") {
-	    auto attachmentSet = parsePuppetAttachmentPoints (reader, offset, static_cast<uint32_t> (this->bones.size ()));
+	    auto attachmentSet
+		= parsePuppetAttachmentPoints (reader, offset, static_cast<uint32_t> (this->bones.size ()));
 	    this->attachmentPoints = std::move (attachmentSet.points);
 	} else if (tag == "MDMP") {
 	    this->morphSection = offset;
 	} else if (tag == "MDLA") {
-	    this->clips
-		= parsePuppetAnimationClips (reader, offset, static_cast<uint32_t> (this->bones.size ()), boneSet, meshCount);
+	    this->clips = parsePuppetAnimationClips (
+		reader, offset, static_cast<uint32_t> (this->bones.size ()), boneSet, meshCount
+	    );
 	}
 
 	if (next <= offset) {
@@ -664,7 +666,8 @@ std::vector<glm::mat4> PuppetRig::skinMatrices () const {
     std::vector<glm::mat4> skin (this->bones.size ());
 
     for (size_t i = 0; i < this->bones.size (); i++) {
-	skin[i] = (i < this->boneModel.size () ? this->boneModel[i] : glm::mat4 (1.0f)) * this->bones[i].inverseBindWorld;
+	skin[i]
+	    = (i < this->boneModel.size () ? this->boneModel[i] : glm::mat4 (1.0f)) * this->bones[i].inverseBindWorld;
     }
 
     return skin;
@@ -829,16 +832,16 @@ bool PuppetRig::destroyLayersByName (const std::string& name) {
 	return false;
     }
 
-    return std::erase_if (this->layers, [&name] (const PuppetActiveAnimation& layer) {
-	       return layer.layer->name == name;
-	   })
+    return std::erase_if (
+	       this->layers, [&name] (const PuppetActiveAnimation& layer) { return layer.layer->name == name; }
+	   )
 	> 0;
 }
 
 bool PuppetRig::destroyLayer (size_t serial) {
-    return std::erase_if (this->layers, [serial] (const PuppetActiveAnimation& layer) {
-	       return layer.serial == serial;
-	   })
+    return std::erase_if (
+	       this->layers, [serial] (const PuppetActiveAnimation& layer) { return layer.serial == serial; }
+	   )
 	> 0;
 }
 
@@ -901,7 +904,8 @@ void PuppetRig::updateMorphWeights (const std::vector<PuppetLayerSample>& sample
 		    state.weights.resize (track.target + 1, 0.0f);
 		}
 
-		const float value = (1.0f - sample.alpha) * track.samples[sample.frame0] + sample.alpha * track.samples[sample.frame1];
+		const float value = (1.0f - sample.alpha) * track.samples[sample.frame0]
+		    + sample.alpha * track.samples[sample.frame1];
 		const uint64_t bit = uint64_t (1) << track.target;
 		float& weight = state.weights[track.target];
 
@@ -1019,10 +1023,14 @@ void PuppetRig::updatePose (const glm::mat4& objectWorld) {
 	    glm::length (glm::vec3 (bone.bindLocal[0])), glm::length (glm::vec3 (bone.bindLocal[1])),
 	    glm::length (glm::vec3 (bone.bindLocal[2]))
 	);
-	const glm::quat restOrientation = glm::normalize (glm::quat_cast (glm::mat3 (
-	    glm::vec3 (bone.bindLocal[0]) / restScale.x, glm::vec3 (bone.bindLocal[1]) / restScale.y,
-	    glm::vec3 (bone.bindLocal[2]) / restScale.z
-	)));
+	const glm::quat restOrientation = glm::normalize (
+	    glm::quat_cast (
+		glm::mat3 (
+		    glm::vec3 (bone.bindLocal[0]) / restScale.x, glm::vec3 (bone.bindLocal[1]) / restScale.y,
+		    glm::vec3 (bone.bindLocal[2]) / restScale.z
+		)
+	    )
+	);
 
 	glm::vec3 position = restPosition;
 	glm::vec3 scale = restScale;
@@ -1077,8 +1085,8 @@ void PuppetRig::composePose (
 
     // WE runs the physics on the bones' scene transforms (object world * bone)
     const glm::mat4& object = objectWorld;
-    const float objectScale
-	= (glm::length (glm::vec3 (object[0])) + glm::length (glm::vec3 (object[1])) + glm::length (glm::vec3 (object[2])))
+    const float objectScale = (glm::length (glm::vec3 (object[0])) + glm::length (glm::vec3 (object[1]))
+			       + glm::length (glm::vec3 (object[2])))
 	/ 3.0f;
 
     std::vector<glm::mat4> model (count);
@@ -1108,8 +1116,8 @@ void PuppetRig::composePose (
 	if (physics.simulated () && hasPrevious) {
 	    model[index] = model[index]
 		* stepPuppetBonePhysics (
-			       physics, this->physicsState[index], scene[index],
-			       this->physicsPreviousScene[index], dt, objectScale
+			       physics, this->physicsState[index], scene[index], this->physicsPreviousScene[index], dt,
+			       objectScale
 		);
 	    scene[index] = object * model[index];
 	}
@@ -1126,9 +1134,7 @@ void PuppetRig::composePose (
     this->boneScene = std::move (scene);
 }
 
-bool PuppetRig::hasPose () const {
-    return !this->bones.empty () && this->boneScene.size () == this->bones.size ();
-}
+bool PuppetRig::hasPose () const { return !this->bones.empty () && this->boneScene.size () == this->bones.size (); }
 
 int PuppetRig::findBone (const std::string& name) const {
     for (size_t i = 0; i < this->bones.size (); i++) {
@@ -1169,9 +1175,8 @@ void PuppetRig::setLocalBoneTransform (int bone, const glm::mat4& transform, con
 	}
 
 	touched.insert (index);
-	this->boneModel[index] = parent < 0 || parent >= count
-	    ? this->boneLocal[index]
-	    : this->boneModel[parent] * this->boneLocal[index];
+	this->boneModel[index]
+	    = parent < 0 || parent >= count ? this->boneLocal[index] : this->boneModel[parent] * this->boneLocal[index];
 	this->boneScene[index] = object * this->boneModel[index];
     }
 

+ 2 - 3
src/WallpaperEngine/Render/Objects/PuppetRig.h

@@ -150,9 +150,8 @@ public:
     /** Steps the layer clocks and builds this frame's pose, objectWorld is the object's world matrix */
     void updatePose (const glm::mat4& objectWorld);
     void updateMorphWeights (const std::vector<PuppetLayerSample>& samples);
-    void composePose (
-	const std::vector<int>& parents, const std::vector<glm::mat4>& locals, const glm::mat4& objectWorld
-    );
+    void
+    composePose (const std::vector<int>& parents, const std::vector<glm::mat4>& locals, const glm::mat4& objectWorld);
 
     [[nodiscard]] bool hasPose () const;
     [[nodiscard]] int findBone (const std::string& name) const;

+ 17 - 20
src/WallpaperEngine/Render/Objects/TextLayout.cpp

@@ -345,9 +345,7 @@ bool TextLayout::setPrimaryFont (std::vector<uint8_t> data, const std::string& p
     );
 }
 
-void TextLayout::setFallbackFonts (std::vector<TextFontSource> fonts) {
-    m_fallbackSources = std::move (fonts);
-}
+void TextLayout::setFallbackFonts (std::vector<TextFontSource> fonts) { m_fallbackSources = std::move (fonts); }
 
 bool TextLayout::addFace (std::shared_ptr<const std::vector<uint8_t>> data, const std::string& path) {
     if (m_library == nullptr) {
@@ -519,8 +517,8 @@ std::vector<TextLayout::ShapedGlyph> TextLayout::shape (const std::u32string& li
 	    }
 
 	    // the quad comes from the outline's box (sub_1401ADDB0, loaded without bitmaps). Segoe UI Emoji, the colour
-	    // font WE finds first on Windows, has monochrome outlines under its colour layers, Twemoji (the fallback left
-	    // on Linux) has none, which would give its emoji an empty quad: their bitmap's box stands in there
+	    // font WE finds first on Windows, has monochrome outlines under its colour layers, Twemoji (the fallback
+	    // left on Linux) has none, which would give its emoji an empty quad: their bitmap's box stands in there
 	    const GlyphBox* box = this->glyphBox (run.face, glyph);
 	    GlyphBox bounds = box != nullptr ? *box : GlyphBox {};
 
@@ -659,8 +657,8 @@ bool TextLayout::renderPlainGlyph (FT_Face face, uint32_t glyph, AtlasGlyph& out
     // colour bitmaps go to the RGBA atlas as they are, premultiplied, with red and blue swapped
     if (bitmap.pixel_mode == FT_PIXEL_MODE_BGRA) {
 	out.color = true;
-	out.bitmapBox = { slot->bitmap_left, slot->bitmap_top - out.height, slot->bitmap_left + out.width,
-			  slot->bitmap_top };
+	out.bitmapBox
+	    = { slot->bitmap_left, slot->bitmap_top - out.height, slot->bitmap_left + out.width, slot->bitmap_top };
 	out.pixels.assign (static_cast<size_t> (out.width) * out.height * 4, 0);
 
 	for (int row = 0; row < out.height; row++) {
@@ -781,9 +779,8 @@ bool TextLayout::renderColorMsdfGlyph (FT_Face face, uint32_t glyph, AtlasGlyph&
     }
 
     const float inverseRange = 1.0f / range;
-    const auto toByte = [] (float value) {
-	return static_cast<uint8_t> (std::clamp (static_cast<int> (value * 256.0f), 0, 255));
-    };
+    const auto toByte
+	= [] (float value) { return static_cast<uint8_t> (std::clamp (static_cast<int> (value * 256.0f), 0, 255)); };
 
     for (int y = 0; y < out.height; y++) {
 	const float glyphY = static_cast<float> ((static_cast<float> (y) + 0.5) / scale - translateY);
@@ -1026,9 +1023,7 @@ void TextLayout::repackAtlas (Atlas& atlas, int size) {
     atlas.pixels.assign (static_cast<size_t> (size) * size * atlas.channels, 0);
 
     if (atlas.colorScale > 0) {
-	atlas.colorPixels.assign (
-	    static_cast<size_t> (size) * atlas.colorScale * size * atlas.colorScale * 4, 0
-	);
+	atlas.colorPixels.assign (static_cast<size_t> (size) * atlas.colorScale * size * atlas.colorScale * 4, 0);
     }
 
     atlas.packOrder.clear ();
@@ -1290,15 +1285,17 @@ TextLayoutResult TextLayout::layout (const std::string& utf8, const TextLayoutPa
 		    // sub_1401B0410 puts colour glyphs into a vertex buffer of their own
 		    const float atlasSize = static_cast<float> (entry.color ? m_colorAtlas.size : m_atlas.size);
 
-		    (entry.color ? result.colorQuads : result.quads).push_back (
-			{
-			    .rect = { pen + glyph.x0 - glyph.pad + shift, lineY + glyph.y0 - glyph.pad,
-				      pen + glyph.x1 + glyph.pad + shift, lineY + glyph.y1 + glyph.pad },
-			    .uv = { static_cast<float> (entry.x) / atlasSize, static_cast<float> (entry.y) / atlasSize,
+		    (entry.color ? result.colorQuads : result.quads)
+			.push_back (
+			    {
+				.rect = { pen + glyph.x0 - glyph.pad + shift, lineY + glyph.y0 - glyph.pad,
+					  pen + glyph.x1 + glyph.pad + shift, lineY + glyph.y1 + glyph.pad },
+				.uv
+				= { static_cast<float> (entry.x) / atlasSize, static_cast<float> (entry.y) / atlasSize,
 				    static_cast<float> (entry.x + entry.width) / atlasSize,
 				    static_cast<float> (entry.y + entry.height) / atlasSize },
-			}
-		    );
+			    }
+			);
 		}
 
 		pen += glyph.advance;

+ 2 - 3
src/WallpaperEngine/Render/Shaders/GLSLContext.cpp

@@ -198,9 +198,8 @@ describeFailure (const std::string& name, const std::string& stage, const std::s
 
 namespace {
 /** Parses one stage, throwing the report describeFailure builds when glslang rejects it */
-std::unique_ptr<glslang::TShader> parseStage (
-    EShLanguage stage, const std::string& source, const std::string& name, const char* stageName
-) {
+std::unique_ptr<glslang::TShader>
+parseStage (EShLanguage stage, const std::string& source, const std::string& name, const char* stageName) {
     auto shader = std::make_unique<glslang::TShader> (stage);
 
     const char* text = source.c_str ();

+ 82 - 29
src/WallpaperEngine/Render/Shaders/ShaderUnit.cpp

@@ -39,10 +39,10 @@
 	  "#define max(x, y) max (y, x)\n"                                                                             \
 	  "#define lerp mix\n"                                                                                         \
 	  "#define frac fract\n"                                                                                       \
-	  "#define CASTI(x) (int(x))\n"                                                                               \
-	  "#define CASTU(x) (uint(x))\n"                                                                              \
-	  "#define CASTF(x) (float(x))\n"                                                                             \
-	  "#define CAST4U(x) (uvec4(x))\n"                                                                            \
+	  "#define CASTI(x) (int(x))\n"                                                                                \
+	  "#define CASTU(x) (uint(x))\n"                                                                               \
+	  "#define CASTF(x) (float(x))\n"                                                                              \
+	  "#define CAST4U(x) (uvec4(x))\n"                                                                             \
 	  "#define CAST2(x) (vec2(x))\n"                                                                               \
 	  "#define CAST3(x) (vec3(x))\n"                                                                               \
 	  "#define CAST4(x) (vec4(x))\n"                                                                               \
@@ -56,8 +56,8 @@
 	  "#define saturate(x) (clamp(x, 0.0, 1.0))\n"                                                                 \
 	  "#define texSample2D texture\n"                                                                              \
 	  "#define texSample2DLod textureLod\n"                                                                        \
-	  "#define sampler2DComparison sampler2DShadow\n"                                                             \
-	  "#define texSample2DCompare(s, u, d) vec4 (texture (s, vec3 (u, d)))\n"                                     \
+	  "#define sampler2DComparison sampler2DShadow\n"                                                              \
+	  "#define texSample2DCompare(s, u, d) vec4 (texture (s, vec3 (u, d)))\n"                                      \
 	  "#define atan2 atan\n"                                                                                       \
 	  "#define fmod(x, y) ((x)-(y)*trunc((x)/(y)))\n"                                                              \
 	  "#define ddx dFdx\n"                                                                                         \
@@ -217,7 +217,8 @@ void ShaderUnit::preprocessIncludes () {
 	    out += this->expandIncludes (line, included);
 	} else if (
 	    firstInclude != std::string::npos && depth == 0
-	    && (trimmed.starts_with ("uniform ") || trimmed.starts_with ("varying ") || trimmed.starts_with ("attribute "))
+	    && (trimmed.starts_with ("uniform ") || trimmed.starts_with ("varying ")
+		|| trimmed.starts_with ("attribute "))
 	) {
 	    hoisted += line + '\n';
 	    out += '\n';
@@ -571,16 +572,9 @@ std::string ShaderUnit::applyVectorTruncationCompatibility (std::string source)
 
     static const char* swizzles[] = { "", "", ".xy", ".xyz" };
 
-    std::string result;
-    size_t last = 0;
     bool changed = false;
 
-    for (auto it = std::sregex_iterator (source.cbegin (), source.cend (), narrowAssign); it != std::sregex_iterator ();
-	 ++it) {
-	const int targetWidth = (*it)[1].str ().back () - '0';
-	const size_t exprStart = it->position (2);
-	const std::string expr = (*it)[2].str ();
-
+    const auto truncate = [&] (const std::string& expr, const int targetWidth) {
 	// HLSL truncates a wider operand anywhere the result narrows, so plain grouping parens are
 	// looked through too: "vec2 uv = (v4 * res.xy) / 4" -> "(v4.xy * res.xy) / 4". call arguments,
 	// indices and groups that get swizzled or indexed afterwards keep their operands as they are
@@ -667,19 +661,75 @@ std::string ShaderUnit::applyVectorTruncationCompatibility (std::string source)
 	    i = end;
 	}
 
+	return fixed;
+    };
+
+    std::string result;
+    size_t last = 0;
+
+    for (auto it = std::sregex_iterator (source.cbegin (), source.cend (), narrowAssign); it != std::sregex_iterator ();
+	 ++it) {
+	const size_t exprStart = it->position (2);
+
 	result.append (source, last, exprStart - last);
-	result += fixed;
-	last = exprStart + expr.size ();
+	result += truncate ((*it)[2].str (), (*it)[1].str ().back () - '0');
+	last = exprStart + it->length (2);
+    }
+
+    result.append (source, last, std::string::npos);
+
+    // the coordinates of a 2D sample are a float2 in HLSL, "texSample2D(s, uv.xy - (k * v4))" truncates v4
+    static const std::regex sampleCall (R"(\btexSample2D(?:Lod)?\s*\()");
+    std::string sampled;
+    last = 0;
+
+    for (auto it = std::sregex_iterator (result.cbegin (), result.cend (), sampleCall); it != std::sregex_iterator ();
+	 ++it) {
+	const size_t open = it->position () + it->length () - 1;
+	size_t argStart = std::string::npos;
+	size_t argEnd = std::string::npos;
+	int nested = 0;
+
+	for (size_t i = open; i < result.size (); i++) {
+	    const char c = result[i];
+
+	    if (c == '(' || c == '[') {
+		nested++;
+	    } else if (c == ')' || c == ']') {
+		if (--nested == 0) {
+		    if (argStart != std::string::npos && argEnd == std::string::npos) {
+			argEnd = i;
+		    }
+		    break;
+		}
+	    } else if (c == ',' && nested == 1) {
+		if (argStart == std::string::npos) {
+		    argStart = i + 1;
+		} else if (argEnd == std::string::npos) {
+		    argEnd = i;
+		}
+	    } else if (c == ';' || c == '{' || c == '}') {
+		break;
+	    }
+	}
+
+	if (argStart == std::string::npos || argEnd == std::string::npos || argStart < last) {
+	    continue;
+	}
+
+	sampled.append (result, last, argStart - last);
+	sampled += truncate (result.substr (argStart, argEnd - argStart), 2);
+	last = argEnd;
     }
 
     if (!changed) {
 	return source;
     }
 
-    result.append (source, last, std::string::npos);
+    sampled.append (result, last, std::string::npos);
     sLog.out ("Applied vector truncation compatibility in shader ", this->m_file);
 
-    return result;
+    return sampled;
 }
 
 std::string ShaderUnit::applyFloatConditionCompatibility (std::string source) const {
@@ -779,7 +829,8 @@ std::string ShaderUnit::applyBoolArithmeticCompatibility (std::string source) co
     std::string result;
     size_t last = 0;
 
-    for (auto it = std::sregex_iterator (source.cbegin (), source.cend (), assign); it != std::sregex_iterator (); ++it) {
+    for (auto it = std::sregex_iterator (source.cbegin (), source.cend (), assign); it != std::sregex_iterator ();
+	 ++it) {
 	const auto target = types.find ((*it)[1].str ());
 	const auto value = types.find ((*it)[3].str ());
 	if (target == types.end () || value == types.end () || value->second != std::set<std::string> { "bool" }
@@ -1661,19 +1712,21 @@ const std::string& ShaderUnit::compile () {
 	}
     }
 
-    const std::string compat = this->applyNonConstantConstCompatibility (this->applyBoolArithmeticCompatibility (this->applyFloatConditionCompatibility (
-	this->applyVectorTruncationCompatibility (this->applyFragmentVaryingShadowCompatibility (
-	    this->applyFragmentTexCoordCompatibility (this->applyNarrowFragmentVaryingCompatibility (
-		this->applyLinkedVaryingCompatibility (this->applyNonConstantGlobalConstCompatibility (
-		    this->applyDirectiveSemicolonCompatibility (this->applyHlslAttributeCompatibility (
-			this->m_type == GLSLContext::UnitType_Geometry
-			    ? this->applyGeometryDialect (this->m_preprocessed)
-			    : this->applyGeometryOutputNames (this->m_preprocessed)
+    const std::string compat = this->applyNonConstantConstCompatibility (
+	this->applyBoolArithmeticCompatibility (this->applyFloatConditionCompatibility (
+	    this->applyVectorTruncationCompatibility (this->applyFragmentVaryingShadowCompatibility (
+		this->applyFragmentTexCoordCompatibility (this->applyNarrowFragmentVaryingCompatibility (
+		    this->applyLinkedVaryingCompatibility (this->applyNonConstantGlobalConstCompatibility (
+			this->applyDirectiveSemicolonCompatibility (this->applyHlslAttributeCompatibility (
+			    this->m_type == GLSLContext::UnitType_Geometry
+				? this->applyGeometryDialect (this->m_preprocessed)
+				: this->applyGeometryOutputNames (this->m_preprocessed)
+			))
 		    ))
 		))
 	    ))
 	))
-    )));
+    );
 
     {
 	std::lock_guard lock (cacheMutex);

+ 289 - 21
src/WallpaperEngine/Render/TextureCache.cpp

@@ -9,6 +9,7 @@
 #include "WallpaperEngine/Render/Helpers/ContextAware.h"
 
 #include "WallpaperEngine/Data/Model/Project.h"
+#include "WallpaperEngine/Data/Model/Property.h"
 #include "WallpaperEngine/Data/Parsers/TextureParser.h"
 
 #include <algorithm>
@@ -19,6 +20,12 @@
 #include <fstream>
 #include <iterator>
 
+#include "ImageDecoder.h"
+
+#include <lz4.h>
+#include <map>
+#include <ranges>
+#include <set>
 #include <stb_image.h>
 
 #define NANOSVG_IMPLEMENTATION
@@ -128,11 +135,6 @@ std::string lowerExtension (const std::string& filename) {
     return extension;
 }
 
-bool isRawImageExtension (const std::string& extension) {
-    return extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".bmp"
-	|| extension == ".tga" || extension == ".gif";
-}
-
 bool isRawVideoExtension (const std::string& extension) {
     return extension == ".mp4" || extension == ".webm" || extension == ".mkv" || extension == ".mov"
 	|| extension == ".m4v" || extension == ".avi";
@@ -142,11 +144,8 @@ bool isRawVideoExtension (const std::string& extension) {
  * Wraps a plain image/video file (what "scenetexture" properties hold once the user picks a file, as opposed
  * to the .tex assets shipped inside the scene) into the same header the .tex parser would have produced
  */
-TextureUniquePtr buildRawTexture (const std::string& filename, ReadStream& stream) {
-    const auto extension = lowerExtension (filename);
-    const bool video = isRawVideoExtension (extension);
-
-    const std::string contents ((std::istreambuf_iterator<char> (stream)), std::istreambuf_iterator<char> ());
+TextureUniquePtr buildRawTexture (const std::string& filename, const std::string& contents) {
+    const bool video = isRawVideoExtension (lowerExtension (filename));
 
     if (contents.empty ()) {
 	sLog.exception ("Cannot load ", filename, ": file is empty");
@@ -163,12 +162,7 @@ TextureUniquePtr buildRawTexture (const std::string& filename, ReadStream& strea
 	width = videoWidth > 0 ? static_cast<int> (videoWidth) : 1920;
 	height = videoHeight > 0 ? static_cast<int> (videoHeight) : 1080;
     } else {
-	int channels = 0;
-
-	if (!stbi_info_from_memory (
-		reinterpret_cast<const stbi_uc*> (contents.data ()), static_cast<int> (contents.size ()), &width,
-		&height, &channels
-	    )) {
+	if (!decodedImageSize (contents.data (), contents.size (), width, height)) {
 	    sLog.exception ("Cannot decode image ", filename, ": ", stbi_failure_reason ());
 	}
     }
@@ -256,6 +250,275 @@ TextureUniquePtr buildIconTexture (const std::filesystem::path& path) {
 
     return result;
 }
+
+// wallpaper64.exe 2.8.42 sub_140174A60: a plain name needs a boolean property that is true, the object form a string
+// property equal to its condition
+bool textureConditionHolds (const std::string& json, const Project& project) {
+    const auto parsed = JSON::parse (json, nullptr, false);
+
+    if (!parsed.is_object () || !parsed.contains ("condition")) {
+	return false;
+    }
+
+    const auto& condition = parsed["condition"];
+    std::string name;
+    const std::string* wanted = nullptr;
+
+    if (condition.is_string ()) {
+	name = condition.get<std::string> ();
+    } else if (
+	condition.is_object () && condition.contains ("name") && condition["name"].is_string ()
+	&& condition.contains ("condition") && condition["condition"].is_string ()
+    ) {
+	name = condition["name"].get<std::string> ();
+	wanted = condition["condition"].get_ptr<const std::string*> ();
+    } else {
+	return false;
+    }
+
+    const auto property = project.properties.find (name);
+
+    if (property == project.properties.end ()) {
+	return false;
+    }
+
+    if (wanted == nullptr) {
+	return property->second->getType () == DynamicValue::Boolean && property->second->getBool ();
+    }
+
+    return property->second->getType () == DynamicValue::String && property->second->getString () == *wanted;
+}
+
+// how many bytes of patch pixels blitTexturePatch reads, WE doesn't check it
+size_t texturePatchSize (const uint32_t format, const uint32_t flags, const MipmapPatch& patch) {
+    const size_t width = patch.width;
+    const size_t lastBlockRow = (patch.height - 1) / 4 * 4;
+
+    if (flags & 1) {
+	return 4 * width * patch.height;
+    }
+
+    switch (format) {
+	case TextureFormat_ARGB8888:
+	    return 4 * width * patch.height;
+	case TextureFormat_DXT5:
+	case TextureFormat_DXT3:
+	    return lastBlockRow * width + 4 * width;
+	case TextureFormat_DXT1:
+	    return ((lastBlockRow * width) >> 1) + 2 * width;
+	case TextureFormat_RG88:
+	    return 2 * width * patch.height;
+	case TextureFormat_R8:
+	    return width * patch.height;
+	default:
+	    return 0;
+    }
+}
+
+// wallpaper64.exe 2.8.42 sub_14015C480
+void blitTexturePatch (
+    const uint32_t format, const uint32_t flags, const MipmapPatch& patch, const unsigned char* source,
+    unsigned char* target, const uint32_t targetWidth
+) {
+    if (flags & 1) {
+	if (format != TextureFormat_ARGB8888) {
+	    return;
+	}
+
+	for (uint32_t row = 0; row < patch.height; row++) {
+	    for (uint32_t column = 0; column < patch.width; column++) {
+		uint32_t src;
+		uint32_t dst;
+		unsigned char* out = target + 4 * (column + patch.x + targetWidth * (row + patch.y));
+
+		memcpy (&src, source + 4 * (column + row * patch.width), 4);
+		memcpy (&dst, out, 4);
+
+		const uint32_t alpha = src >> 24;
+		const uint32_t green
+		    = static_cast<uint16_t> ((dst & 0xFF00) + ((alpha * ((src & 0xFF00) - (dst & 0xFF00))) >> 8))
+		    & 0xFF00;
+		const uint32_t redBlue
+		    = ((dst & 0xFF00FF) + ((alpha * ((src & 0xFF00FF) - (dst & 0xFF00FF))) >> 8)) & 0xFF00FF;
+		const uint32_t result = (std::max (dst >> 24, alpha) << 24) | green | redBlue;
+
+		memcpy (out, &result, 4);
+	    }
+	}
+
+	return;
+    }
+
+    const size_t width = targetWidth;
+
+    switch (format) {
+	case TextureFormat_ARGB8888:
+	    for (size_t row = 0; row < patch.height; row++) {
+		memcpy (
+		    target + 4 * (patch.x + width * (row + patch.y)), source + 4 * row * patch.width, 4 * patch.width
+		);
+	    }
+	    break;
+	case TextureFormat_DXT5:
+	case TextureFormat_DXT3:
+	    for (size_t row = 0; row < patch.height; row += 4) {
+		memcpy (target + width * (row + patch.y) + 4 * patch.x, source + row * patch.width, 4 * patch.width);
+	    }
+	    break;
+	case TextureFormat_DXT1:
+	    for (size_t row = 0; row < patch.height; row += 4) {
+		memcpy (
+		    target + ((width * (row + patch.y) + 4 * patch.x) >> 1), source + ((row * patch.width) >> 1),
+		    2 * patch.width
+		);
+	    }
+	    break;
+	case TextureFormat_RG88:
+	    for (size_t row = 0; row < patch.height; row++) {
+		memcpy (
+		    target + 2 * (patch.x + width * (row + patch.y)), source + 2 * row * patch.width, 2 * patch.width
+		);
+	    }
+	    break;
+	case TextureFormat_R8:
+	    for (size_t row = 0; row < patch.height; row++) {
+		memcpy (target + patch.x + width * (row + patch.y), source + row * patch.width, patch.width);
+	    }
+	    break;
+	default:
+	    break;
+    }
+}
+
+// TEXB0004 conditional patches: the parser (sub_14015C8D0) picks the patches of the conditions that hold, the texture
+// job (sub_1400CE760) paints them over the decoded mipmap
+void applyTexturePatches (Texture& texture, const Project& project) {
+    if (texture.conditions.empty ()) {
+	return;
+    }
+
+    std::set<uint32_t> groups;
+    std::map<uint32_t, uint32_t> selected;
+
+    for (const auto& condition : texture.conditions) {
+	if (!textureConditionHolds (condition.json, project) || !groups.insert (condition.group).second) {
+	    continue;
+	}
+
+	selected[condition.key] = condition.flags;
+    }
+
+    const bool native = texture.freeImageFormat != FIF_UNKNOWN;
+
+    for (auto& mipmaps : texture.images | std::views::values) {
+	for (const auto& mipmap : mipmaps) {
+	    std::vector<std::pair<const MipmapPatch*, uint32_t>> patches;
+
+	    for (const auto& patch : mipmap->patches) {
+		if (const auto flags = selected.find (patch.key); flags != selected.end ()) {
+		    patches.emplace_back (&patch, flags->second);
+		}
+	    }
+
+	    // only the last replacing patch matters, WE keeps the one before it too (applied, then thrown away)
+	    for (size_t index = patches.size (); index-- > 1;) {
+		if (patches[index].second & 2) {
+		    patches.erase (patches.begin (), patches.begin () + static_cast<long> (index - 1));
+		    break;
+		}
+	    }
+
+	    if (patches.empty ()) {
+		continue;
+	    }
+
+	    std::vector<unsigned char> pixels;
+
+	    if (native) {
+		int width = 0;
+		int height = 0;
+		stbi_uc* decoded
+		    = decodeImageRGBA (mipmap->uncompressedData.get (), mipmap->uncompressedSize, width, height);
+
+		if (decoded == nullptr || width != static_cast<int> (mipmap->width)
+		    || height != static_cast<int> (mipmap->height)) {
+		    stbi_image_free (decoded);
+		    continue;
+		}
+
+		pixels.assign (decoded, decoded + static_cast<size_t> (width) * height * 4);
+		stbi_image_free (decoded);
+	    } else {
+		pixels.assign (
+		    mipmap->uncompressedData.get (), mipmap->uncompressedData.get () + mipmap->uncompressedSize
+		);
+	    }
+
+	    const uint32_t format = native ? TextureFormat_ARGB8888 : texture.format;
+
+	    for (const auto& [patch, flags] : patches) {
+		if (flags & 2) {
+		    // the patch's raw data becomes the mipmap, it has to cover what the upload reads
+		    if (patch->data.size () >= pixels.size ()) {
+			pixels.assign (patch->data.begin (), patch->data.end ());
+		    }
+		    break;
+		}
+
+		if (patch->width == 0 || patch->height == 0 || patch->x + patch->width > mipmap->width
+		    || patch->y + patch->height > mipmap->height || patch->data.empty ()) {
+		    continue;
+		}
+
+		const size_t size = 4 * static_cast<size_t> (patch->width) * patch->height;
+		std::vector<unsigned char> source;
+
+		if (mipmap->compression == 1) {
+		    source.resize (size);
+
+		    if (LZ4_decompress_safe (
+			    patch->data.data (), reinterpret_cast<char*> (source.data ()),
+			    static_cast<int> (patch->data.size ()), static_cast<int> (size)
+			)
+			< 0) {
+			continue;
+		    }
+		} else if (native) {
+		    int width = 0;
+		    int height = 0;
+		    stbi_uc* decoded = decodeImageRGBA (patch->data.data (), patch->data.size (), width, height);
+
+		    if (decoded == nullptr || width != static_cast<int> (patch->width)
+			|| height != static_cast<int> (patch->height)) {
+			stbi_image_free (decoded);
+			continue;
+		    }
+
+		    source.assign (decoded, decoded + size);
+		    stbi_image_free (decoded);
+		} else {
+		    source.assign (patch->data.begin (), patch->data.end ());
+		}
+
+		if (source.size () < texturePatchSize (format, flags, *patch)
+		    || pixels.size ()
+			< texturePatchSize (format, 0, { .width = mipmap->width, .height = mipmap->height })) {
+		    continue;
+		}
+
+		blitTexturePatch (format, flags, *patch, source.data (), pixels.data (), mipmap->width);
+	    }
+
+	    if (native) {
+		mipmap->composedPixels = std::move (pixels);
+	    } else {
+		mipmap->uncompressedSize = static_cast<int> (pixels.size ());
+		mipmap->uncompressedData = std::make_unique<char[]> (pixels.size ());
+		memcpy (mipmap->uncompressedData.get (), pixels.data (), pixels.size ());
+	    }
+	}
+    }
+}
 } // namespace
 
 TextureCache::TextureCache (RenderContext& context) : Helpers::ContextAware (context) {
@@ -318,16 +581,21 @@ std::shared_ptr<const TextureProvider> TextureCache::resolve (const std::string&
 	    auto stream = BinaryReader (contents);
 
 	    parsedTexture = TextureParser::parse (stream);
+	    applyTexturePatches (*parsedTexture, project);
 	} catch (AssetLoadException&) {
-	    const auto extension = lowerExtension (filename);
+	    // WE picks the image decoder from the file contents (resourceutil64 FreeImage_GetFileTypeU), so
+	    // e.g. a user-picked .jfif loads just like a .jpg
+	    const auto raw = project.assetLocator->read (filename);
+	    const std::string contents ((std::istreambuf_iterator<char> (*raw)), std::istreambuf_iterator<char> ());
+	    int width;
+	    int height;
 
-	    if (!isRawImageExtension (extension) && !isRawVideoExtension (extension)) {
+	    if (!isRawVideoExtension (lowerExtension (filename))
+		&& !decodedImageSize (contents.data (), contents.size (), width, height)) {
 		throw;
 	    }
 
-	    const auto raw = project.assetLocator->read (filename);
-
-	    parsedTexture = buildRawTexture (filename, *raw);
+	    parsedTexture = buildRawTexture (filename, contents);
 	}
 	auto texture = std::make_shared<CTexture> (this->getContext (), std::move (parsedTexture));
 	texture->label (filename);

+ 12 - 11
src/WallpaperEngine/Render/Volumetrics.cpp

@@ -43,9 +43,9 @@ void main () {
 )";
 
 // assets/shaders/volumetricsfront.frag: from the near side of the volume to the far one (or the scene's depth in front
-// of it), the light's falloff summed over a few samples. With SHADOW each sample is compared against the light's tile of
-// _rt_shadowAtlas (g_Texture0), spots through the light's matrix scaled by 0.525 like the cookie, point lights through
-// common_pbr_2.h's CalculateProjectedCoordsPoint (copied below)
+// of it), the light's falloff summed over a few samples. With SHADOW each sample is compared against the light's tile
+// of _rt_shadowAtlas (g_Texture0), spots through the light's matrix scaled by 0.525 like the cookie, point lights
+// through common_pbr_2.h's CalculateProjectedCoordsPoint (copied below)
 const char* kFrontFragment = R"(
 #define mul(x, y) ((y) * (x))
 uniform sampler2D u_Back;
@@ -489,10 +489,11 @@ void Volumetrics::setup () {
 	vertices.emplace_back (std::sin (angle), -std::cos (angle), 0.0f);
 	vertices.emplace_back (std::sin (next), -std::cos (next), 0.0f);
 	indices.insert (
-	    indices.end (), { static_cast<GLushort> (base + 2), base, static_cast<GLushort> (base + 1),
-			      static_cast<GLushort> (base + 2), static_cast<GLushort> (base + 1),
-			      static_cast<GLushort> (base + 3), 1, static_cast<GLushort> (base + 1), base, 0,
-			      static_cast<GLushort> (base + 2), static_cast<GLushort> (base + 3) }
+	    indices.end (),
+	    { static_cast<GLushort> (base + 2), base, static_cast<GLushort> (base + 1),
+	      static_cast<GLushort> (base + 2), static_cast<GLushort> (base + 1), static_cast<GLushort> (base + 3), 1,
+	      static_cast<GLushort> (base + 1), base, 0, static_cast<GLushort> (base + 2),
+	      static_cast<GLushort> (base + 3) }
 	);
     }
 
@@ -599,9 +600,8 @@ glm::vec3 Volumetrics::approximateNormalize (const glm::vec3& vector) {
     return vector * inverse;
 }
 
-glm::mat4 Volumetrics::spotViewProjection (
-    const Data::Model::Light& light, const glm::mat4& world, const bool orthographic
-) {
+glm::mat4
+Volumetrics::spotViewProjection (const Data::Model::Light& light, const glm::mat4& world, const bool orthographic) {
     // sub_14025D420: the light looks down its x axis (view rows z, y, -x of the normalized world axes) through a
     // right handed PerspectiveFov (sub_14009A360) of twice the outer cone, aspect 1, near 0.05 (1 in orthographic
     // scenes), far the radius. Depth runs 0..1 like Direct3D, the cone mesh is built in that space
@@ -757,7 +757,8 @@ void Volumetrics::renderLight (
 
 	const glm::vec4 clip = lightViewProjection * glm::vec4 (fog.eyeWorld + forward * 0.1f, 1.0f);
 
-	inside = std::abs (clip.x) <= clip.w && std::abs (clip.y) <= clip.w && clip.z >= 0.0f && clip.z <= 2.0f * clip.w;
+	inside
+	    = std::abs (clip.x) <= clip.w && std::abs (clip.y) <= clip.w && clip.z >= 0.0f && clip.z <= 2.0f * clip.w;
     } else if (spot) {
 	// the cone is drawn from the light's clip space, whose inverse also gives the cone's radius at the far plane.
 	// The eye is inside when it's in front of the light, no further than the radius and within the cone there

+ 2 - 2
src/WallpaperEngine/Render/Volumetrics.h

@@ -14,8 +14,8 @@ class Light;
 
 namespace WallpaperEngine::Render {
 /**
- * Volumetric light of LightingV1 point and spot lights, wallpaper64.exe 2.8.42 sub_140196CE0 (one light into the light buffer)
- * and sub_140198D00 (blur, then added onto the scene before the next object that isn't a light)
+ * Volumetric light of LightingV1 point and spot lights, wallpaper64.exe 2.8.42 sub_140196CE0 (one light into the light
+ * buffer) and sub_140198D00 (blur, then added onto the scene before the next object that isn't a light)
  */
 class Volumetrics {
 public:

+ 18 - 17
src/WallpaperEngine/Render/WallpaperState.cpp

@@ -100,23 +100,24 @@ glm::vec4 WallpaperState::alignmentMargins (const int mode) const {
 	    top = y * (height - outputHeight);
 	    bottom = (1.0f - y) * (height - outputHeight);
 	    break;
-	case 4: {
-	    // free: x/y slide the native size scene from past one edge to past the other, the zoom scales the shown
-	    // region by (2 - zoom)^4, no smaller than 1% of it
-	    const float baseLeft = width - x * (outputWidth + width);
-	    const float baseTop = height - y * (outputHeight + height);
-	    const float baseRight = width - (1.0f - x) * (outputWidth + width);
-	    const float baseBottom = height - (1.0f - y) * (outputHeight + height);
-	    const float scale = std::max (-0.99f, std::pow (2.0f - this->m_alignment.zoom, 4.0f) - 1.0f);
-	    const float growY = (height - baseTop - baseBottom) * scale;
-	    const float growX = (width - baseRight - baseLeft) * scale;
-
-	    left = baseLeft - growX * x;
-	    right = baseRight - growX * (1.0f - x);
-	    top = baseTop - growY * y;
-	    bottom = baseBottom - growY * (1.0f - y);
-	    break;
-	}
+	case 4:
+	    {
+		// free: x/y slide the native size scene from past one edge to past the other, the zoom scales the shown
+		// region by (2 - zoom)^4, no smaller than 1% of it
+		const float baseLeft = width - x * (outputWidth + width);
+		const float baseTop = height - y * (outputHeight + height);
+		const float baseRight = width - (1.0f - x) * (outputWidth + width);
+		const float baseBottom = height - (1.0f - y) * (outputHeight + height);
+		const float scale = std::max (-0.99f, std::pow (2.0f - this->m_alignment.zoom, 4.0f) - 1.0f);
+		const float growY = (height - baseTop - baseBottom) * scale;
+		const float growX = (width - baseRight - baseLeft) * scale;
+
+		left = baseLeft - growX * x;
+		right = baseRight - growX * (1.0f - x);
+		top = baseTop - growY * y;
+		bottom = baseBottom - growY * (1.0f - y);
+		break;
+	    }
 	default:
 	    break;
     }

+ 203 - 174
src/WallpaperEngine/Render/Wallpapers/CScene.cpp

@@ -597,8 +597,9 @@ void CScene::paintLetterbox () const {
 
 bool CScene::isShadowCasterVisible (const CObject& object) const {
     // the object's visible check (vtable +104) and flag 2 (under a passthrough layer), like renderSceneObject
-    const auto visibility
-	= this->getContext ().getApp ().getContext ().resolveObjectVisibility (object.getId (), object.getObject ().name);
+    const auto visibility = this->getContext ().getApp ().getContext ().resolveObjectVisibility (
+	object.getId (), object.getObject ().name
+    );
 
     if (visibility.has_value () && !visibility.value ()) {
 	return false;
@@ -608,8 +609,7 @@ bool CScene::isShadowCasterVisible (const CObject& object) const {
 	return false;
     }
 
-    return !object.is<Objects::CMesh> ()
-	|| object.as<Objects::CMesh> ()->getMesh ().groupVisible->value->getBool ();
+    return !object.is<Objects::CMesh> () || object.as<Objects::CMesh> ()->getMesh ().groupVisible->value->getBool ();
 }
 
 void CScene::renderSceneObject (CObject* cur) {
@@ -910,13 +910,15 @@ void CScene::renderReflection () {
     glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
 
     // everything the scene draws goes into the reflection target, like a passthrough layer's buffer
-    this->m_layerTargets.push_back ({
-	.fbo = this->_rt_Reflection,
-	.transform = glm::mat4 (1.0f),
-	.alphaMax = false,
-	.viewProjection = this->getWorldViewProjection (),
-	.viewProjectionApplied = true,
-    });
+    this->m_layerTargets.push_back (
+	{
+	    .fbo = this->_rt_Reflection,
+	    .transform = glm::mat4 (1.0f),
+	    .alphaMax = false,
+	    .viewProjection = this->getWorldViewProjection (),
+	    .viewProjectionApplied = true,
+	}
+    );
     this->m_renderingReflection = true;
 
     // scene +456 (sub_14018FF60): images, models, text and particles in creation order, minus the ones that sample the
@@ -1440,7 +1442,7 @@ void CScene::dispatchCursorEvents () {
     // handlers are free to create layers, which would move things around under a live iteration. 3D scenes walk a
     // copy sorted by depth like the transparent pass (sub_1401865C0), 2D ones the creation order
     const auto objects = this->getCamera ().isPerspective () ? this->sortedByDepth (this->m_objectsByRenderOrder)
-								: this->m_objectsByRenderOrder;
+							     : this->m_objectsByRenderOrder;
     // WE (sub_140189E10) checks for a drag before the pass: while the button is held on something pressed,
     // only the pressed objects hear about it, and only through cursorMove
     const bool dragging = down && !this->m_cursorPressed.empty ();
@@ -1471,9 +1473,8 @@ void CScene::dispatchCursorEvents () {
 	    hit = image->hitTest (ndc);
 	    // fullscreen layers get the cursor in window pixels: WE stores ScreenToClient / client size and multiplies
 	    // it back by the client size (sub_140110630, sub_14017F1B0)
-	    local = image->getImage ().model->fullscreen
-		? glm::vec3 (this->m_mousePositionViewport, 0.0f)
-		: glm::vec3 (image->cursorLocalPosition (ndc), 0.0f);
+	    local = image->getImage ().model->fullscreen ? glm::vec3 (this->m_mousePositionViewport, 0.0f)
+							 : glm::vec3 (image->cursorLocalPosition (ndc), 0.0f);
 	    visible = image->getImage ().visible->value->getBool ();
 	} else if (cur->is<Objects::CText> ()) {
 	    auto* text = cur->as<Objects::CText> ();
@@ -1616,6 +1617,19 @@ glm::vec4 CScene::getVisibleMargins () const {
 	     (vflip ? uvs.z : 1.0f - uvs.z) * height };
 }
 
+glm::vec4 CScene::getVisibleCanvasRegion () const {
+    glm::vec4 margins = glm::max (this->getVisibleMargins (), glm::vec4 (0.0f));
+    const float halfWidth = static_cast<float> (this->getCanvasWidth ()) / 2.0f;
+    const float halfHeight = static_cast<float> (this->getCanvasHeight ()) / 2.0f;
+
+    // the margins are on screen, a mirrored projection puts the left one on the canvas' right
+    if (this->isFlippedHorizontally ()) {
+	std::swap (margins.x, margins.y);
+    }
+
+    return { -halfWidth + margins.x, halfWidth - margins.y, -halfHeight + margins.w, halfHeight - margins.z };
+}
+
 const Data::Model::Properties& CScene::getUserProperties () const {
     return this->getWallpaperData ().project.properties;
 }
@@ -2075,91 +2089,97 @@ void CScene::updateLightingV1 () {
 	const bool shadowed = shadows && light.castShadow;
 
 	switch (light.type) {
-	    case LightType::Point: {
-		if (pointsLeft == 0) {
-		    break;
-		}
-
-		pointsLeft--;
-
-		if (const int slot = pointSlot[shadowed ? 1 : 0]++; slot < lighting.points) {
-		    lighting.pointColor[slot] = glm::vec4 (color, radius);
-		    lighting.pointOrigin[slot] = glm::vec4 (origin, exponent);
-		}
-
-		if (!shadowed || pointShadowsLeft == 0) {
-		    break;
-		}
+	    case LightType::Point:
+		{
+		    if (pointsLeft == 0) {
+			break;
+		    }
 
-		// sub_14025D420: a fov a bit over 90 degrees per quality, aspect 1, near the light source size (1 in
-		// orthographic scenes), far the radius
-		pointShadowsLeft--;
+		    pointsLeft--;
 
-		const int quality = this->m_shadowQuality;
-		const float fov = quality <= 2 ? 94.0f : quality == 3 ? 92.0f : 91.2f;
-		const float near = orthographic ? 1.0f : std::max (0.05f, light.lightSourceSize->value->getFloat ());
-		const float far = std::max (radius, near + 0.01f);
-		const glm::mat4 projection = ShadowMapping::perspective (fov * 0.017453292f, 1.0f, near, far);
-		ShadowMapping::Entry shadow { .point = true, .size = tile };
+		    if (const int slot = pointSlot[shadowed ? 1 : 0]++; slot < lighting.points) {
+			lighting.pointColor[slot] = glm::vec4 (color, radius);
+			lighting.pointOrigin[slot] = glm::vec4 (origin, exponent);
+		    }
 
-		lighting.pointShadowProjection[pointShadow]
-		    = glm::vec4 (projection[2][2], projection[3][2], projection[2][3], projection[3][3]);
-		shadow.transform = &lighting.pointShadowProjectionTransform[pointShadow];
-		pointShadow++;
+		    if (!shadowed || pointShadowsLeft == 0) {
+			break;
+		    }
 
-		for (int face = 0; face < 6; face++) {
-		    shadow.viewProjection[face] = projection * pointFaceView (face, origin);
-		}
+		    // sub_14025D420: a fov a bit over 90 degrees per quality, aspect 1, near the light source size (1
+		    // in orthographic scenes), far the radius
+		    pointShadowsLeft--;
+
+		    const int quality = this->m_shadowQuality;
+		    const float fov = quality <= 2 ? 94.0f : quality == 3 ? 92.0f : 91.2f;
+		    const float near
+			= orthographic ? 1.0f : std::max (0.05f, light.lightSourceSize->value->getFloat ());
+		    const float far = std::max (radius, near + 0.01f);
+		    const glm::mat4 projection = ShadowMapping::perspective (fov * 0.017453292f, 1.0f, near, far);
+		    ShadowMapping::Entry shadow { .point = true, .size = tile };
+
+		    lighting.pointShadowProjection[pointShadow]
+			= glm::vec4 (projection[2][2], projection[3][2], projection[2][3], projection[3][3]);
+		    shadow.transform = &lighting.pointShadowProjectionTransform[pointShadow];
+		    pointShadow++;
+
+		    for (int face = 0; face < 6; face++) {
+			shadow.viewProjection[face] = projection * pointFaceView (face, origin);
+		    }
 
-		this->m_volumeShadows[&light] = { .atlasTransform = shadow.transform,
-						  .pointProjection = lighting.pointShadowProjection[pointShadow - 1] };
-		this->m_shadowEntries.push_back (shadow);
-		break;
-	    }
-	    case LightType::Spot: {
-		if (spotsLeft == 0) {
+		    this->m_volumeShadows[&light]
+			= { .atlasTransform = shadow.transform,
+			    .pointProjection = lighting.pointShadowProjection[pointShadow - 1] };
+		    this->m_shadowEntries.push_back (shadow);
 		    break;
 		}
+	    case LightType::Spot:
+		{
+		    if (spotsLeft == 0) {
+			break;
+		    }
 
-		spotsLeft--;
+		    spotsLeft--;
 
-		const int type = (light.castShadow ? 1 : 0) | (light.useCookie ? 2 : 0);
-		const int kind = type & (shadows ? 3 : 2);
+		    const int type = (light.castShadow ? 1 : 0) | (light.useCookie ? 2 : 0);
+		    const int kind = type & (shadows ? 3 : 2);
 
-		// cosines of the cone angles in the .w, the direction is the world matrix's x column as it is
-		if (const int slot = spotSlot[kind]++; slot < lighting.spots) {
-		    lighting.spotColor[slot] = glm::vec4 (color, radius);
-		    lighting.spotOrigin[slot]
-			= glm::vec4 (origin, std::cos (light.innerCone->value->getFloat () * 0.017453292f));
-		    lighting.spotDirection[slot]
-			= glm::vec4 (glm::vec3 (world[0]), std::cos (light.outerCone->value->getFloat () * 0.017453292f));
-		    lighting.spotExponent[slot] = glm::vec4 (exponent, 0.0f, 0.0f, 0.0f);
-		}
+		    // cosines of the cone angles in the .w, the direction is the world matrix's x column as it is
+		    if (const int slot = spotSlot[kind]++; slot < lighting.spots) {
+			lighting.spotColor[slot] = glm::vec4 (color, radius);
+			lighting.spotOrigin[slot]
+			    = glm::vec4 (origin, std::cos (light.innerCone->value->getFloat () * 0.017453292f));
+			lighting.spotDirection[slot] = glm::vec4 (
+			    glm::vec3 (world[0]), std::cos (light.outerCone->value->getFloat () * 0.017453292f)
+			);
+			lighting.spotExponent[slot] = glm::vec4 (exponent, 0.0f, 0.0f, 0.0f);
+		    }
 
-		if ((!shadowed && !light.useCookie) || featuresLeft == 0) {
-		    break;
-		}
+		    if ((!shadowed && !light.useCookie) || featuresLeft == 0) {
+			break;
+		    }
 
-		featuresLeft--;
+		    featuresLeft--;
 
-		const int feature = featureSlot[kind]++;
+		    const int feature = featureSlot[kind]++;
 
-		if (feature >= featureCapacity) {
-		    break;
-		}
+		    if (feature >= featureCapacity) {
+			break;
+		    }
 
-		lighting.featureProjection[feature]
-		    = reverseDepth (Volumetrics::spotViewProjection (light, world, orthographic));
+		    lighting.featureProjection[feature]
+			= reverseDepth (Volumetrics::spotViewProjection (light, world, orthographic));
 
-		if (shadowed) {
-		    ShadowMapping::Entry shadow { .size = tile, .transform = &lighting.featureProjectionTransform[feature] };
-		    shadow.viewProjection[0] = lighting.featureProjection[feature];
-		    this->m_volumeShadows[&light]
-			= { .matrix = lighting.featureProjection[feature], .atlasTransform = shadow.transform };
-		    this->m_shadowEntries.push_back (shadow);
+		    if (shadowed) {
+			ShadowMapping::Entry shadow { .size = tile,
+						      .transform = &lighting.featureProjectionTransform[feature] };
+			shadow.viewProjection[0] = lighting.featureProjection[feature];
+			this->m_volumeShadows[&light]
+			    = { .matrix = lighting.featureProjection[feature], .atlasTransform = shadow.transform };
+			this->m_shadowEntries.push_back (shadow);
+		    }
+		    break;
 		}
-		break;
-	    }
 	    case LightType::Tube:
 		if (tube < lighting.tubes) {
 		    lighting.tubeColor[tube] = glm::vec4 (color, radius);
@@ -2169,89 +2189,92 @@ void CScene::updateLightingV1 () {
 		    tube++;
 		}
 		break;
-	    case LightType::Directional: {
-		if (directionalsLeft == 0) {
-		    break;
-		}
-
-		directionalsLeft--;
+	    case LightType::Directional:
+		{
+		    if (directionalsLeft == 0) {
+			break;
+		    }
 
-		if (const int slot = directionalSlot[shadowed ? 1 : 0]++; slot < lighting.directionals) {
-		    lighting.directionalColor[slot] = glm::vec4 (color, 1.0f);
-		    lighting.directionalDirection[slot] = glm::vec4 (-glm::vec3 (world[0]), 0.0f);
-		}
+		    directionalsLeft--;
 
-		if (!shadowed || featuresLeft == 0) {
-		    break;
-		}
+		    if (const int slot = directionalSlot[shadowed ? 1 : 0]++; slot < lighting.directionals) {
+			lighting.directionalColor[slot] = glm::vec4 (color, 1.0f);
+			lighting.directionalDirection[slot] = glm::vec4 (-glm::vec3 (world[0]), 0.0f);
+		    }
 
-		featuresLeft--;
-
-		// sub_14025D370: each cascade covers a square of its distance and a depth range around the view,
-		// sub_140190C80 0x14019128b: centered half the distance ahead of the eye (the forward's part along the
-		// light only half counted, z 0 in 2D), snapped to shadow texels along the light's y and z axes. The view
-		// looks down the light's x axis (rows z, y, -x like a spot), the projection is an orthographic box
-		// (sub_14009A630) of +-distance/2 and depth +-range/2
-		const float cascade0 = light.cascadeDistance[0]->value->getFloat ();
-		const float cascade1 = light.cascadeDistance[1]->value->getFloat ();
-		const float cascade2 = light.cascadeDistance[2]->value->getFloat ();
-		const glm::vec2 ranges[3] = {
-		    { cascade0, cascade1 * 4.0f },
-		    { cascade1, cascade1 * 4.0f },
-		    { cascade2, std::max (cascade2 * 1.5f, cascade1 * 4.0f) },
-		};
-		const glm::vec3 direction = glm::normalize (glm::vec3 (world[0]));
-		const glm::vec3 y (world[1]);
-		const glm::vec3 z (world[2]);
-		const glm::vec3 rows[3] = { Volumetrics::approximateNormalize (z), Volumetrics::approximateNormalize (y),
-					    Volumetrics::approximateNormalize (-glm::vec3 (world[0])) };
-		const glm::vec3 ahead = forward - direction * (glm::dot (forward, direction) * 0.5f);
-
-		for (const glm::vec2& range : ranges) {
-		    const float half = range.x * 0.5f;
-		    glm::vec3 center = eye + ahead * half;
-
-		    if (orthographic) {
-			center.z = 0.0f;
+		    if (!shadowed || featuresLeft == 0) {
+			break;
 		    }
 
-		    const float texel = range.x / static_cast<float> (tile);
-		    const float alongZ = glm::dot (z, center);
-		    const float alongY = glm::dot (y, center);
+		    featuresLeft--;
+
+		    // sub_14025D370: each cascade covers a square of its distance and a depth range around the view,
+		    // sub_140190C80 0x14019128b: centered half the distance ahead of the eye (the forward's part along
+		    // the light only half counted, z 0 in 2D), snapped to shadow texels along the light's y and z axes.
+		    // The view looks down the light's x axis (rows z, y, -x like a spot), the projection is an
+		    // orthographic box (sub_14009A630) of +-distance/2 and depth +-range/2
+		    const float cascade0 = light.cascadeDistance[0]->value->getFloat ();
+		    const float cascade1 = light.cascadeDistance[1]->value->getFloat ();
+		    const float cascade2 = light.cascadeDistance[2]->value->getFloat ();
+		    const glm::vec2 ranges[3] = {
+			{ cascade0, cascade1 * 4.0f },
+			{ cascade1, cascade1 * 4.0f },
+			{ cascade2, std::max (cascade2 * 1.5f, cascade1 * 4.0f) },
+		    };
+		    const glm::vec3 direction = glm::normalize (glm::vec3 (world[0]));
+		    const glm::vec3 y (world[1]);
+		    const glm::vec3 z (world[2]);
+		    const glm::vec3 rows[3]
+			= { Volumetrics::approximateNormalize (z), Volumetrics::approximateNormalize (y),
+			    Volumetrics::approximateNormalize (-glm::vec3 (world[0])) };
+		    const glm::vec3 ahead = forward - direction * (glm::dot (forward, direction) * 0.5f);
+
+		    for (const glm::vec2& range : ranges) {
+			const float half = range.x * 0.5f;
+			glm::vec3 center = eye + ahead * half;
+
+			if (orthographic) {
+			    center.z = 0.0f;
+			}
 
-		    center -= y * std::fmod (alongY, texel);
-		    center -= z * std::fmod (alongZ, texel);
+			const float texel = range.x / static_cast<float> (tile);
+			const float alongZ = glm::dot (z, center);
+			const float alongY = glm::dot (y, center);
 
-		    glm::mat4 view (1.0f);
+			center -= y * std::fmod (alongY, texel);
+			center -= z * std::fmod (alongZ, texel);
 
-		    for (int row = 0; row < 3; row++) {
-			for (int column = 0; column < 3; column++) {
-			    view[column][row] = rows[row][column];
-			}
+			glm::mat4 view (1.0f);
 
-			view[3][row] = -glm::dot (rows[row], center);
-		    }
+			for (int row = 0; row < 3; row++) {
+			    for (int column = 0; column < 3; column++) {
+				view[column][row] = rows[row][column];
+			    }
 
-		    glm::mat4 projection (1.0f);
-		    projection[0][0] = 1.0f / half;
-		    projection[1][1] = 1.0f / half;
-		    projection[2][2] = 1.0f / range.y;
-		    projection[3][2] = 0.5f;
+			    view[3][row] = -glm::dot (rows[row], center);
+			}
 
-		    const int feature = featureSlot[0]++;
+			glm::mat4 projection (1.0f);
+			projection[0][0] = 1.0f / half;
+			projection[1][1] = 1.0f / half;
+			projection[2][2] = 1.0f / range.y;
+			projection[3][2] = 0.5f;
 
-		    if (feature >= featureCapacity) {
-			continue;
-		    }
+			const int feature = featureSlot[0]++;
 
-		    lighting.featureProjection[feature] = projection * view;
+			if (feature >= featureCapacity) {
+			    continue;
+			}
 
-		    ShadowMapping::Entry shadow { .size = tile, .transform = &lighting.featureProjectionTransform[feature] };
-		    shadow.viewProjection[0] = lighting.featureProjection[feature];
-		    this->m_shadowEntries.push_back (shadow);
+			lighting.featureProjection[feature] = projection * view;
+
+			ShadowMapping::Entry shadow { .size = tile,
+						      .transform = &lighting.featureProjectionTransform[feature] };
+			shadow.viewProjection[0] = lighting.featureProjection[feature];
+			this->m_shadowEntries.push_back (shadow);
+		    }
+		    break;
 		}
-		break;
-	    }
 	    default:
 		break;
 	}
@@ -2761,16 +2784,15 @@ void CScene::loadStaticCamera () {
 
 uint32_t CScene::createModelData (const ModelData::Config& config, ModelData::Error& error) {
     return this->m_modelData.create (
-	config, [this] (const std::string& material, uint32_t format) {
+	config,
+	[this] (const std::string& material, uint32_t format) {
 	    return this->checkModelDataMaterial (material, format);
 	},
 	error
     );
 }
 
-void CScene::applyModelData (
-    uint32_t token, const ModelData::Config& config, bool replace, ModelData::Error& error
-) {
+void CScene::applyModelData (uint32_t token, const ModelData::Config& config, bool replace, ModelData::Error& error) {
     this->m_modelData.apply (
 	token, config, replace,
 	[this] (const std::string& material, uint32_t format) {
@@ -2789,30 +2811,35 @@ void CScene::releaseModelData (uint32_t token) { this->m_modelData.release (toke
 ModelData::Error CScene::checkModelDataMaterial (const std::string& material, uint32_t format) {
     const auto key = std::make_pair (material, format);
 
-    if (const auto cached = this->m_modelDataMaterialChecks.find (key); cached != this->m_modelDataMaterialChecks.end ()) {
+    if (const auto cached = this->m_modelDataMaterialChecks.find (key);
+	cached != this->m_modelDataMaterialChecks.end ()) {
 	return cached->second;
     }
 
     // semantic of every vertex format bit and of every attribute name WE's shader translation knows (0x140482AF0,
     // 0x140484A90), sub_1400D7B60 only compares semantic names
     static const std::pair<uint32_t, const char*> formatSemantics[] = {
-	{ 0x1, "POSITION" },	  { 0x10000, "POSITION" }, { 0x2000000, "POSITION" }, { 0x2, "NORMAL" },
-	{ 0x4, "TANGENT" },	  { 0x800000, "BLENDINDICES" }, { 0x1000000, "BLENDWEIGHT" }, { 0x8, "TEXCOORD" },
-	{ 0x10, "TEXCOORD" },	  { 0x20, "TEXCOORD" },    { 0x40, "TEXCOORD" },      { 0x80, "TEXCOORD" },
-	{ 0x100, "TEXCOORD" },	  { 0x200, "TEXCOORD" },   { 0x400, "TEXCOORD" },     { 0x800, "TEXCOORD" },
-	{ 0x1000, "TEXCOORD" },	  { 0x2000, "TEXCOORD" },  { 0x4000, "TEXCOORD" },    { 0x20000, "TEXCOORD" },
-	{ 0x40000, "TEXCOORD" },  { 0x80000, "TEXCOORD" }, { 0x100000, "TEXCOORD" },  { 0x200000, "TEXCOORD" },
+	{ 0x1, "POSITION" },      { 0x10000, "POSITION" },      { 0x2000000, "POSITION" },    { 0x2, "NORMAL" },
+	{ 0x4, "TANGENT" },       { 0x800000, "BLENDINDICES" }, { 0x1000000, "BLENDWEIGHT" }, { 0x8, "TEXCOORD" },
+	{ 0x10, "TEXCOORD" },     { 0x20, "TEXCOORD" },         { 0x40, "TEXCOORD" },         { 0x80, "TEXCOORD" },
+	{ 0x100, "TEXCOORD" },    { 0x200, "TEXCOORD" },        { 0x400, "TEXCOORD" },        { 0x800, "TEXCOORD" },
+	{ 0x1000, "TEXCOORD" },   { 0x2000, "TEXCOORD" },       { 0x4000, "TEXCOORD" },       { 0x20000, "TEXCOORD" },
+	{ 0x40000, "TEXCOORD" },  { 0x80000, "TEXCOORD" },      { 0x100000, "TEXCOORD" },     { 0x200000, "TEXCOORD" },
 	{ 0x400000, "TEXCOORD" }, { 0x8000, "COLOR" },
     };
     static const std::map<std::string, std::string> attributeSemantics = {
-	{ "a_Position", "POSITION" },	      { "a_PositionVec4", "POSITION" },   { "a_PositionC1", "POSITION" },
-	{ "a_Normal", "NORMAL" },	      { "a_Tangent4", "TANGENT" },	  { "a_BlendIndices", "BLENDINDICES" },
-	{ "a_BlendWeights", "BLENDWEIGHT" }, { "a_TexCoord", "TEXCOORD" },	  { "a_TexCoordVec3", "TEXCOORD" },
-	{ "a_TexCoordVec4", "TEXCOORD" },    { "a_TexCoordC1", "TEXCOORD" },	  { "a_TexCoordVec3C1", "TEXCOORD" },
-	{ "a_TexCoordVec4C1", "TEXCOORD" },  { "a_TexCoordC2", "TEXCOORD" },	  { "a_TexCoordVec3C2", "TEXCOORD" },
-	{ "a_TexCoordVec4C2", "TEXCOORD" },  { "a_TexCoordC3", "TEXCOORD" },	  { "a_TexCoordVec3C3", "TEXCOORD" },
-	{ "a_TexCoordVec4C3", "TEXCOORD" },  { "a_TexCoordC4", "TEXCOORD" },	  { "a_TexCoordVec3C4", "TEXCOORD" },
-	{ "a_TexCoordVec4C4", "TEXCOORD" },  { "a_TexCoordC5", "TEXCOORD" },	  { "a_TexCoordVec3C5", "TEXCOORD" },
+	{ "a_Position", "POSITION" },        { "a_PositionVec4", "POSITION" },
+	{ "a_PositionC1", "POSITION" },      { "a_Normal", "NORMAL" },
+	{ "a_Tangent4", "TANGENT" },         { "a_BlendIndices", "BLENDINDICES" },
+	{ "a_BlendWeights", "BLENDWEIGHT" }, { "a_TexCoord", "TEXCOORD" },
+	{ "a_TexCoordVec3", "TEXCOORD" },    { "a_TexCoordVec4", "TEXCOORD" },
+	{ "a_TexCoordC1", "TEXCOORD" },      { "a_TexCoordVec3C1", "TEXCOORD" },
+	{ "a_TexCoordVec4C1", "TEXCOORD" },  { "a_TexCoordC2", "TEXCOORD" },
+	{ "a_TexCoordVec3C2", "TEXCOORD" },  { "a_TexCoordVec4C2", "TEXCOORD" },
+	{ "a_TexCoordC3", "TEXCOORD" },      { "a_TexCoordVec3C3", "TEXCOORD" },
+	{ "a_TexCoordVec4C3", "TEXCOORD" },  { "a_TexCoordC4", "TEXCOORD" },
+	{ "a_TexCoordVec3C4", "TEXCOORD" },  { "a_TexCoordVec4C4", "TEXCOORD" },
+	{ "a_TexCoordC5", "TEXCOORD" },      { "a_TexCoordVec3C5", "TEXCOORD" },
 	{ "a_TexCoordVec4C5", "TEXCOORD" },  { "a_Color", "COLOR" },
     };
     static const std::regex input (R"(\bin\s+\w+\s+(a_\w+)\s*;)");
@@ -2844,7 +2871,8 @@ ModelData::Error CScene::checkModelDataMaterial (const std::string& material, ui
 	    Shaders::Shader shader (
 		*project.assetLocator, pass.shader, combos, overrideCombos, pass.textures, overrideTextures, noConstants
 	    );
-	    const auto sources = Shaders::GLSLContext::get ().toGlsl (shader.vertex (), shader.fragment (), pass.shader);
+	    const auto sources
+		= Shaders::GLSLContext::get ().toGlsl (shader.vertex (), shader.fragment (), pass.shader);
 	    std::set<std::string> provided;
 
 	    for (const auto& [bit, semantic] : formatSemantics) {
@@ -2860,10 +2888,11 @@ ModelData::Error CScene::checkModelDataMaterial (const std::string& material, ui
 		const std::string name = (*it)[1].str ();
 		const auto semantic = attributeSemantics.find (name);
 		const std::regex use ("\\b" + name + "\\b");
-		const auto uses = std::distance (std::sregex_iterator (code.begin (), code.end (), use), std::sregex_iterator ());
+		const auto uses
+		    = std::distance (std::sregex_iterator (code.begin (), code.end (), use), std::sregex_iterator ());
 
-		// the D3D input signature only has the inputs the shader reads: live WE takes a position-only shape with
-		// util/flat.json, whose flat.vert declares a_Color but only reads it with VERTEXCOLOR
+		// the D3D input signature only has the inputs the shader reads: live WE takes a position-only shape
+		// with util/flat.json, whose flat.vert declares a_Color but only reads it with VERTEXCOLOR
 		if (uses < 2) {
 		    continue;
 		}

+ 4 - 1
src/WallpaperEngine/Render/Wallpapers/CScene.h

@@ -16,7 +16,7 @@ namespace WallpaperEngine::Render {
 class Camera;
 class CObject;
 namespace Objects {
-class CLight;
+    class CLight;
 }
 }
 
@@ -90,6 +90,9 @@ public:
     [[nodiscard]] glm::vec4 getVisibleUVs () const;
     /** getVisibleUVs as the canvas units cut off each side: left, right, bottom, top (y up) */
     [[nodiscard]] glm::vec4 getVisibleMargins () const;
+    /** The canvas part on screen in the centered y down layer space: x min, x max, y min, y max (letterbox bars left
+     * out) */
+    [[nodiscard]] glm::vec4 getVisibleCanvasRegion () const;
     [[nodiscard]] float getOutputAspect () const;
     [[nodiscard]] bool rendersAtOutputSize () const override { return true; }
     /** Pixel size of the output being drawn, what WE's window client area (and _rt_FullFrameBuffer) would be */

+ 195 - 101
src/WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.cpp

@@ -449,14 +449,15 @@ JSValue animation_layer_call (
 	    return JS_NewBool (ctx, (clock->flags & (LayerPaused | LayerStopped)) == 0);
 	case LayerGetFrame:
 	    return JS_NewFloat64 (ctx, clock->time / frameTime);
-	case LayerSetFrame: {
-	    double frame = 0.0;
-	    if (argc > 0 && JS_IsNumber (argv[0]) && JS_ToFloat64 (ctx, &frame, argv[0]) == 0) {
-		clock->time = frameTime * static_cast<float> (frame);
-		clock->flags |= LayerFrameSet;
+	case LayerSetFrame:
+	    {
+		double frame = 0.0;
+		if (argc > 0 && JS_IsNumber (argv[0]) && JS_ToFloat64 (ctx, &frame, argv[0]) == 0) {
+		    clock->time = frameTime * static_cast<float> (frame);
+		    clock->flags |= LayerFrameSet;
+		}
+		return JS_UNDEFINED;
 	    }
-	    return JS_UNDEFINED;
-	}
 	case LayerAddEndedCallback:
 	    if (argc > 0) {
 		engine->addAnimationLayerEndedCallback (*object, static_cast<size_t> (serial), argv[0]);
@@ -512,7 +513,9 @@ JSValue WallpaperEngine::Scripting::Adapters::makeAnimationLayerHandle (
     accessor ("blend", LayerGetBlend, LayerSetBlend);
 
     // lets destroyAnimationLayer() take the object back
-    JS_DefinePropertyValueStr (ctx, handle, AnimationLayerSerialKey, JS_NewInt64 (ctx, static_cast<int64_t> (serial)), 0);
+    JS_DefinePropertyValueStr (
+	ctx, handle, AnimationLayerSerialKey, JS_NewInt64 (ctx, static_cast<int64_t> (serial)), 0
+    );
 
     for (const auto& value : data) {
 	JS_FreeValue (ctx, value);
@@ -581,60 +584,63 @@ JSValue scriptableobject_animation_layer_call (
     switch (magic) {
 	case GetAnimationLayerCount:
 	    return JS_NewInt32 (ctx, rig == nullptr ? 0 : static_cast<int32_t> (rig->getLayerCount ()));
-	case GetAnimationLayer: {
-	    if (rig == nullptr || argc < 1) {
+	case GetAnimationLayer:
+	    {
+		if (rig == nullptr || argc < 1) {
+		    return JS_NULL;
+		}
+		if (JS_IsNumber (argv[0])) {
+		    int64_t index = -1;
+		    JS_ToInt64 (ctx, &index, argv[0]);
+		    return handleFor (rig->getLayerAt (index));
+		}
+		if (JS_IsString (argv[0])) {
+		    const char* name = JS_ToCString (ctx, argv[0]);
+		    const auto serial = rig->findLayerByName (name == nullptr ? "" : name);
+		    JS_FreeCString (ctx, name);
+		    return handleFor (serial);
+		}
 		return JS_NULL;
 	    }
-	    if (JS_IsNumber (argv[0])) {
-		int64_t index = -1;
-		JS_ToInt64 (ctx, &index, argv[0]);
-		return handleFor (rig->getLayerAt (index));
-	    }
-	    if (JS_IsString (argv[0])) {
-		const char* name = JS_ToCString (ctx, argv[0]);
-		const auto serial = rig->findLayerByName (name == nullptr ? "" : name);
-		JS_FreeCString (ctx, name);
-		return handleFor (serial);
-	    }
-	    return JS_NULL;
-	}
 	case CreateAnimationLayer:
-	case PlaySingleAnimation: {
-	    if (rig == nullptr || argc < 1) {
-		return JS_NULL;
+	case PlaySingleAnimation:
+	    {
+		if (rig == nullptr || argc < 1) {
+		    return JS_NULL;
+		}
+		const auto animation = animationLayerArgument (ctx, argv[0], false);
+		const auto config
+		    = argc > 1 ? animationLayerArgument (ctx, argv[1], true) : WallpaperEngine::Data::JSON::JSON ();
+		return handleFor (rig->createLayer (
+		    animation, config, magic == PlaySingleAnimation, object->getScene ().getScene ().project
+		));
 	    }
-	    const auto animation = animationLayerArgument (ctx, argv[0], false);
-	    const auto config = argc > 1 ? animationLayerArgument (ctx, argv[1], true)
-					 : WallpaperEngine::Data::JSON::JSON ();
-	    return handleFor (rig->createLayer (
-		animation, config, magic == PlaySingleAnimation, object->getScene ().getScene ().project
-	    ));
-	}
-	case DestroyAnimationLayer: {
-	    if (rig == nullptr || argc < 1) {
+	case DestroyAnimationLayer:
+	    {
+		if (rig == nullptr || argc < 1) {
+		    return JS_FALSE;
+		}
+		if (JS_IsNumber (argv[0])) {
+		    int64_t index = -1;
+		    JS_ToInt64 (ctx, &index, argv[0]);
+		    const auto serial = rig->getLayerAt (index);
+		    return JS_NewBool (ctx, serial.has_value () && rig->destroyLayer (*serial));
+		}
+		if (JS_IsString (argv[0])) {
+		    const char* name = JS_ToCString (ctx, argv[0]);
+		    const bool destroyed = rig->destroyLayersByName (name == nullptr ? "" : name);
+		    JS_FreeCString (ctx, name);
+		    return JS_NewBool (ctx, destroyed);
+		}
+		if (JS_IsObject (argv[0])) {
+		    JSValue serialValue = JS_GetPropertyStr (ctx, argv[0], AnimationLayerSerialKey);
+		    int64_t serial = -1;
+		    const bool isLayer = JS_IsNumber (serialValue) && JS_ToInt64 (ctx, &serial, serialValue) == 0;
+		    JS_FreeValue (ctx, serialValue);
+		    return JS_NewBool (ctx, isLayer && rig->destroyLayer (static_cast<size_t> (serial)));
+		}
 		return JS_FALSE;
 	    }
-	    if (JS_IsNumber (argv[0])) {
-		int64_t index = -1;
-		JS_ToInt64 (ctx, &index, argv[0]);
-		const auto serial = rig->getLayerAt (index);
-		return JS_NewBool (ctx, serial.has_value () && rig->destroyLayer (*serial));
-	    }
-	    if (JS_IsString (argv[0])) {
-		const char* name = JS_ToCString (ctx, argv[0]);
-		const bool destroyed = rig->destroyLayersByName (name == nullptr ? "" : name);
-		JS_FreeCString (ctx, name);
-		return JS_NewBool (ctx, destroyed);
-	    }
-	    if (JS_IsObject (argv[0])) {
-		JSValue serialValue = JS_GetPropertyStr (ctx, argv[0], AnimationLayerSerialKey);
-		int64_t serial = -1;
-		const bool isLayer = JS_IsNumber (serialValue) && JS_ToInt64 (ctx, &serial, serialValue) == 0;
-		JS_FreeValue (ctx, serialValue);
-		return JS_NewBool (ctx, isLayer && rig->destroyLayer (static_cast<size_t> (serial)));
-	    }
-	    return JS_FALSE;
-	}
 	default:
 	    return JS_UNDEFINED;
     }
@@ -799,7 +805,8 @@ JSValue scriptableobject_bone_call (
     auto* engine = reinterpret_cast<WallpaperEngine::Scripting::ScriptEngine*> (static_cast<intptr_t> (engineAddress));
 
     // both index lookups write -1 before looking at the layer
-    const JSValue fallback = magic == GetBoneIndex || magic == GetBoneParentIndex ? JS_NewInt32 (ctx, -1) : JS_UNDEFINED;
+    const JSValue fallback
+	= magic == GetBoneIndex || magic == GetBoneParentIndex ? JS_NewInt32 (ctx, -1) : JS_UNDEFINED;
 
     if (!object->is<CImage> ()) {
 	return fallback;
@@ -909,21 +916,23 @@ JSValue scriptableobject_bone_call (
 	    break;
 	case GetLocalBoneAngles:
 	    return makeVec3 (localBoneAngles (image->getPuppetLocalBoneTransform (bone)));
-	case SetLocalBoneAngles: {
-	    glm::mat4 local = image->getPuppetLocalBoneTransform (bone);
-	    setLocalBoneAngles (local, readVec3 (ctx, value));
-	    image->setPuppetLocalBoneTransform (bone, local);
-	    break;
-	}
+	case SetLocalBoneAngles:
+	    {
+		glm::mat4 local = image->getPuppetLocalBoneTransform (bone);
+		setLocalBoneAngles (local, readVec3 (ctx, value));
+		image->setPuppetLocalBoneTransform (bone, local);
+		break;
+	    }
 	case GetLocalBoneOrigin:
 	    return makeVec3 (glm::vec3 (image->getPuppetLocalBoneTransform (bone)[3]));
-	case SetLocalBoneOrigin: {
-	    // sub_140210250: floats 12..14, the rest stays
-	    glm::mat4 local = image->getPuppetLocalBoneTransform (bone);
-	    local[3] = glm::vec4 (readVec3 (ctx, value), local[3].w);
-	    image->setPuppetLocalBoneTransform (bone, local);
-	    break;
-	}
+	case SetLocalBoneOrigin:
+	    {
+		// sub_140210250: floats 12..14, the rest stays
+		glm::mat4 local = image->getPuppetLocalBoneTransform (bone);
+		local[3] = glm::vec4 (readVec3 (ctx, value), local[3].w);
+		image->setPuppetLocalBoneTransform (bone, local);
+		break;
+	    }
 	default:
 	    break;
     }
@@ -938,39 +947,122 @@ namespace {
 // particles (sub_14024CB00), models (sub_140227470), lights (sub_14025DA80) and cameras (sub_1401F3460) sit
 // directly on the object one. Plain groups only have the object's
 constexpr std::string_view ObjectMembers[] = {
-    "origin", "scale", "angles", "parallaxDepth", "sortorder", "name", "solid", "disablepropagation",
-    "getTransformMatrix", "rotateObjectSpace", "lookAt", "lookAtYaw", "setParent", "getParent", "getChildren",
-    "getAttachmentIndex", "getAttachmentMatrix", "getAttachmentOrigin", "getAttachmentAngles", "getAnimation",
+    "origin",
+    "scale",
+    "angles",
+    "parallaxDepth",
+    "sortorder",
+    "name",
+    "solid",
+    "disablepropagation",
+    "getTransformMatrix",
+    "rotateObjectSpace",
+    "lookAt",
+    "lookAtYaw",
+    "setParent",
+    "getParent",
+    "getChildren",
+    "getAttachmentIndex",
+    "getAttachmentMatrix",
+    "getAttachmentOrigin",
+    "getAttachmentAngles",
+    "getAnimation",
 };
 constexpr std::string_view RenderableMembers[] = {
-    "size", "color", "alpha", "brightness", "visible", "perspective", "castshadow", "copybackground",
-    "nointerpolation", "clampuvs", "ledsource", "colorBlendMode", "getEffect", "getEffectCount",
-    "transformAttachmentToTexture",
+    "size",        "color",          "alpha",          "brightness",      "visible",
+    "perspective", "castshadow",     "copybackground", "nointerpolation", "clampuvs",
+    "ledsource",   "colorBlendMode", "getEffect",      "getEffectCount",  "transformAttachmentToTexture",
 };
 constexpr std::string_view ImageMembers[] = {
-    "alignment", "getTextureAnimation", "getVideoTexture", "getAnimationLayer", "getAnimationLayerCount",
-    "createAnimationLayer", "playSingleAnimation", "destroyAnimationLayer", "getBoneCount", "getBoneTransform",
-    "setBoneTransform", "getLocalBoneTransform", "setLocalBoneTransform", "getLocalBoneAngles", "setLocalBoneAngles",
-    "getLocalBoneOrigin", "setLocalBoneOrigin", "getBlendShapeIndex", "getBlendShapeWeight", "setBlendShapeWeight",
-    "getBoneIndex", "getBoneParentIndex", "applyBonePhysicsImpulse", "resetBonePhysicsSimulation",
+    "alignment",
+    "getTextureAnimation",
+    "getVideoTexture",
+    "getAnimationLayer",
+    "getAnimationLayerCount",
+    "createAnimationLayer",
+    "playSingleAnimation",
+    "destroyAnimationLayer",
+    "getBoneCount",
+    "getBoneTransform",
+    "setBoneTransform",
+    "getLocalBoneTransform",
+    "setLocalBoneTransform",
+    "getLocalBoneAngles",
+    "setLocalBoneAngles",
+    "getLocalBoneOrigin",
+    "setLocalBoneOrigin",
+    "getBlendShapeIndex",
+    "getBlendShapeWeight",
+    "setBlendShapeWeight",
+    "getBoneIndex",
+    "getBoneParentIndex",
+    "applyBonePhysicsImpulse",
+    "resetBonePhysicsSimulation",
 };
 constexpr std::string_view TextMembers[] = {
-    "backgroundbrightness", "opaquebackground", "limitwidth", "limitrows", "limituseellipsis", "blockalign",
-    "backgroundcolor", "pointsize", "padding", "spacing", "maxwidth", "maxrows", "msdf", "outline", "blur",
-    "dropshadow", "outlinethickness", "outlinecolor", "blursize", "dropshadowsize", "dropshadowopacity",
-    "dropshadowcolor", "dropshadowoffset", "depthtest", "horizontalalign", "verticalalign", "anchor", "text", "font",
+    "backgroundbrightness",
+    "opaquebackground",
+    "limitwidth",
+    "limitrows",
+    "limituseellipsis",
+    "blockalign",
+    "backgroundcolor",
+    "pointsize",
+    "padding",
+    "spacing",
+    "maxwidth",
+    "maxrows",
+    "msdf",
+    "outline",
+    "blur",
+    "dropshadow",
+    "outlinethickness",
+    "outlinecolor",
+    "blursize",
+    "dropshadowsize",
+    "dropshadowopacity",
+    "dropshadowcolor",
+    "dropshadowoffset",
+    "depthtest",
+    "horizontalalign",
+    "verticalalign",
+    "anchor",
+    "text",
+    "font",
 };
 constexpr std::string_view ParticleMembers[] = {
     "visible", "play", "pause", "stop", "isPlaying", "emitParticles",
 };
 constexpr std::string_view ModelMembers[] = {
-    "visible", "perspective", "castshadow", "rootmotion", "getAnimationLayer", "getAnimationLayerCount",
-    "createAnimationLayer", "playSingleAnimation", "destroyAnimationLayer",
+    "visible",
+    "perspective",
+    "castshadow",
+    "rootmotion",
+    "getAnimationLayer",
+    "getAnimationLayerCount",
+    "createAnimationLayer",
+    "playSingleAnimation",
+    "destroyAnimationLayer",
 };
 constexpr std::string_view LightMembers[] = {
-    "color", "intensity", "radius", "exponent", "innercone", "outercone", "density", "volumetricsexponent",
-    "cascadedistance0", "cascadedistance1", "cascadedistance2", "lightsourcesize", "controlpoint", "light",
-    "visible", "castshadow", "usecookie", "castvolumetrics",
+    "color",
+    "intensity",
+    "radius",
+    "exponent",
+    "innercone",
+    "outercone",
+    "density",
+    "volumetricsexponent",
+    "cascadedistance0",
+    "cascadedistance1",
+    "cascadedistance2",
+    "lightsourcesize",
+    "controlpoint",
+    "light",
+    "visible",
+    "castshadow",
+    "usecookie",
+    "castvolumetrics",
 };
 constexpr std::string_view CameraMembers[] = { "visible", "fov", "zoom", "queuemode" };
 
@@ -979,7 +1071,8 @@ std::vector<std::string_view> layerMembers (const WallpaperEngine::Scripting::Sc
     using namespace WallpaperEngine::Render::Objects;
 
     std::vector<std::string_view> members (std::begin (ObjectMembers), std::end (ObjectMembers));
-    const auto add = [&members] (const auto& list) { members.insert (members.end (), std::begin (list), std::end (list)); };
+    const auto add
+	= [&members] (const auto& list) { members.insert (members.end (), std::begin (list), std::end (list)); };
 
     if (object.is<CImage> ()) {
 	add (RenderableMembers);
@@ -1053,7 +1146,9 @@ int scriptableobject_property_names (JSContext* ctx, JSPropertyEnum** tab, uint3
     auto* object = layerOf (obj);
     const auto members = object == nullptr ? std::vector<std::string_view> {} : layerMembers (*object);
 
-    *tab = static_cast<JSPropertyEnum*> (js_mallocz (ctx, sizeof (JSPropertyEnum) * std::max<size_t> (members.size (), 1)));
+    *tab = static_cast<JSPropertyEnum*> (
+	js_mallocz (ctx, sizeof (JSPropertyEnum) * std::max<size_t> (members.size (), 1))
+    );
     *length = 0;
 
     if (*tab == nullptr) {
@@ -1159,10 +1254,8 @@ JSValue scriptableobject_property_get (JSContext* ctx, JSValueConst obj_val, JSA
 	int magic;
 	int length;
     } animationLayerCalls[] = {
-	{ "getAnimationLayerCount", GetAnimationLayerCount, 0 },
-	{ "getAnimationLayer", GetAnimationLayer, 1 },
-	{ "createAnimationLayer", CreateAnimationLayer, 2 },
-	{ "playSingleAnimation", PlaySingleAnimation, 2 },
+	{ "getAnimationLayerCount", GetAnimationLayerCount, 0 }, { "getAnimationLayer", GetAnimationLayer, 1 },
+	{ "createAnimationLayer", CreateAnimationLayer, 2 },     { "playSingleAnimation", PlaySingleAnimation, 2 },
 	{ "destroyAnimationLayer", DestroyAnimationLayer, 1 },
     };
 
@@ -1284,11 +1377,12 @@ int scriptableobject_property_set (
 }
 
 ScriptableObjectAdapter::ScriptableObjectAdapter (ScriptEngine& engine, std::string name) :
-    ObjectAdapter (engine),
-    m_exoticMethods ({ .get_own_property = scriptableobject_property_own,
-		       .get_own_property_names = scriptableobject_property_names,
-		       .get_property = scriptableobject_property_get,
-		       .set_property = scriptableobject_property_set }),
+    ObjectAdapter (engine), m_exoticMethods (
+				{ .get_own_property = scriptableobject_property_own,
+				  .get_own_property_names = scriptableobject_property_names,
+				  .get_property = scriptableobject_property_get,
+				  .set_property = scriptableobject_property_set }
+			    ),
     m_name (std::move (name)) {
     this->registerType (
 	{

+ 6 - 11
src/WallpaperEngine/Scripting/AnimationSystem.cpp

@@ -168,7 +168,7 @@ void AnimationClock::applyCurrentFrame () {
     }
 }
 
-void AnimationClock::applyBinding (Binding& binding) const {
+void AnimationClock::applyBinding (const Binding& binding) const {
     const int count = componentCount (binding.value->getType ());
 
     if (count == 0) {
@@ -185,17 +185,8 @@ void AnimationClock::applyBinding (Binding& binding) const {
 	    continue;
 	}
 
-	const float sampled
+	target[component]
 	    = evaluateAnimationCurve (keys, m_frame, m_definition->fps, static_cast<int> (m_definition->length));
-
-	if (binding.data->relative) {
-	    // fold the offset in on top of whatever the value is now, so a script moving the base
-	    // value around keeps working
-	    target[component] = current[component] - binding.lastOffset[component] + sampled;
-	    binding.lastOffset[component] = sampled;
-	} else {
-	    target[component] = sampled;
-	}
     }
 
     if (target != current) {
@@ -229,13 +220,17 @@ std::vector<AnimationClock::FiredEvent> AnimationClock::tick (float deltaSeconds
     std::vector<FiredEvent> fired;
     const float length = m_definition->length;
 
+    // wallpaper64 sub_140171440 writes every bound property each frame, paused or not, so a paused timeline
+    // keeps its frame on screen even if a script assigned the property in between
     if (!m_playing || length <= 0.0f) {
+	this->applyCurrentFrame ();
 	return fired;
     }
 
     const float step = deltaSeconds * m_definition->fps * m_rate * m_direction;
 
     if (step == 0.0f) {
+	this->applyCurrentFrame ();
 	return fired;
     }
 

+ 1 - 2
src/WallpaperEngine/Scripting/AnimationSystem.h

@@ -27,7 +27,6 @@ public:
     struct Binding {
 	DynamicValue* value;
 	std::shared_ptr<const PropertyAnimation> data;
-	glm::vec4 lastOffset { 0.0f };
     };
 
     struct FiredEvent {
@@ -56,7 +55,7 @@ public:
 
 private:
     void collectEvents (float from, float to, bool includeFrom, std::vector<FiredEvent>& out) const;
-    void applyBinding (Binding& binding) const;
+    void applyBinding (const Binding& binding) const;
 
     int m_id;
     DynamicValue* m_rootValue;

+ 19 - 11
src/WallpaperEngine/Scripting/SceneObject.cpp

@@ -352,7 +352,9 @@ struct Handle {
     uint32_t token;
 };
 
-JSValue property (JSContext* ctx, JSValueConst object, const char* name) { return JS_GetPropertyStr (ctx, object, name); }
+JSValue property (JSContext* ctx, JSValueConst object, const char* name) {
+    return JS_GetPropertyStr (ctx, object, name);
+}
 
 template <typename T> bool readTypedArray (JSContext* ctx, JSValueConst value, int type, std::vector<T>& out) {
     if (JS_GetTypedArrayType (value) != type) {
@@ -379,8 +381,10 @@ template <typename T> bool readTypedArray (JSContext* ctx, JSValueConst value, i
 /** false with a pending exception */
 bool parseShape (JSContext* ctx, JSValueConst value, bool create, ModelData::ShapeConfig& shape) {
     static const std::map<std::string, uint32_t> formats = {
-	{ "position", ModelData::FORMAT_POSITION },	  { "normal", ModelData::FORMAT_NORMAL },
-	{ "tangentSigned", ModelData::FORMAT_TANGENT_SIGNED }, { "uv", ModelData::FORMAT_UV },
+	{ "position", ModelData::FORMAT_POSITION },
+	{ "normal", ModelData::FORMAT_NORMAL },
+	{ "tangentSigned", ModelData::FORMAT_TANGENT_SIGNED },
+	{ "uv", ModelData::FORMAT_UV },
 	{ "color", ModelData::FORMAT_COLOR },
     };
 
@@ -457,8 +461,9 @@ bool parseShape (JSContext* ctx, JSValueConst value, bool create, ModelData::Sha
 
     JS_FreeValue (ctx, material);
 
-    for (const auto& [name, target] : { std::pair<const char*, bool*> { "isVertexBufferDynamic", &shape.vertexDynamic },
-					std::pair<const char*, bool*> { "isIndexBufferDynamic", &shape.indexDynamic } }) {
+    for (const auto& [name, target] :
+	 { std::pair<const char*, bool*> { "isVertexBufferDynamic", &shape.vertexDynamic },
+	   std::pair<const char*, bool*> { "isIndexBufferDynamic", &shape.indexDynamic } }) {
 	JSValue flag = property (ctx, value, name);
 
 	if (JS_IsBool (flag)) {
@@ -909,10 +914,11 @@ SceneObject::SceneObject (ScriptEngine& engine, Render::Wallpapers::CScene& scen
 
     this->m_modelDataDefinition = {
 	.class_name = "IModelData",
-	.finalizer = [] (JSRuntime*, JSValueConst value) {
-	    JSClassID classId = 0;
-	    delete static_cast<ModelDataScript::Handle*> (JS_GetAnyOpaque (value, &classId));
-	},
+	.finalizer =
+	    [] (JSRuntime*, JSValueConst value) {
+		JSClassID classId = 0;
+		delete static_cast<ModelDataScript::Handle*> (JS_GetAnyOpaque (value, &classId));
+	    },
     };
     JS_NewClassID (this->m_engine.getRuntime (), &this->m_modelDataClassId);
     JS_NewClass (this->m_engine.getRuntime (), this->m_modelDataClassId, &this->m_modelDataDefinition);
@@ -1074,11 +1080,13 @@ SceneObject::SceneObject (ScriptEngine& engine, Render::Wallpapers::CScene& scen
     );
     JS_DefinePropertyValueStr (
 	this->m_engine.getContext (), this->m_instance, "getCameraTransforms",
-	JS_NewCFunction (this->m_engine.getContext (), get_camera_transforms, "getCameraTransforms", 0), JS_PROP_ENUMERABLE
+	JS_NewCFunction (this->m_engine.getContext (), get_camera_transforms, "getCameraTransforms", 0),
+	JS_PROP_ENUMERABLE
     );
     JS_DefinePropertyValueStr (
 	this->m_engine.getContext (), this->m_instance, "setCameraTransforms",
-	JS_NewCFunction (this->m_engine.getContext (), set_camera_transforms, "setCameraTransforms", 1), JS_PROP_ENUMERABLE
+	JS_NewCFunction (this->m_engine.getContext (), set_camera_transforms, "setCameraTransforms", 1),
+	JS_PROP_ENUMERABLE
     );
     JS_DefinePropertyValueStr (
 	this->m_engine.getContext (), this->m_instance, "createModelData",

+ 7 - 2
src/WallpaperEngine/Scripting/ScriptEngine.cpp

@@ -205,7 +205,10 @@ static bool jsToDynamicValue (JSContext* ctx, JSValue val, DynamicValue& source)
     }
 
     if (tag == JS_TAG_INT) {
-	if (!updateVectorFromNumber (source, static_cast<float> (JS_VALUE_GET_INT (val)))) {
+	// the property keeps its own type (scenescript64 sub_181620E10), "alpha = 1" leaves alpha a float
+	if (source.getType () == DynamicValue::Float) {
+	    source.update (static_cast<float> (JS_VALUE_GET_INT (val)), DynamicValue::UpdateSource::Script);
+	} else if (!updateVectorFromNumber (source, static_cast<float> (JS_VALUE_GET_INT (val)))) {
 	    source.update (JS_VALUE_GET_INT (val), DynamicValue::UpdateSource::Script);
 	}
 	return true;
@@ -1385,7 +1388,9 @@ void ScriptEngine::addVideoEndedCallback (VideoPlayback::MPV::GLPlayer* player,
     this->m_videoEndedCallbacks.push_back ({ player, JS_DupValue (this->m_context, callback) });
 }
 
-void ScriptEngine::addAnimationLayerEndedCallback (const ScriptableObject& owner, size_t serial, JSValueConst callback) {
+void ScriptEngine::addAnimationLayerEndedCallback (
+    const ScriptableObject& owner, size_t serial, JSValueConst callback
+) {
     if (!JS_IsFunction (this->m_context, callback)) {
 	return;
     }

+ 19 - 5
src/WallpaperEngine/Scripting/ScriptPropertiesObject.cpp

@@ -241,24 +241,38 @@ ScriptPropertiesObject::ScriptPropertiesObject (ScriptEngine& engine, Render::Wa
 
     JS_DefinePropertyValueStr (
 	this->m_engine.getContext (), this->m_creatorPrototype, "addSlider",
-	JS_NewCFunctionMagic (this->m_engine.getContext (), scriptpropertiescreator_add, "addSlider", 1, JS_CFUNC_generic_magic, 0), JS_PROP_ENUMERABLE
+	JS_NewCFunctionMagic (
+	    this->m_engine.getContext (), scriptpropertiescreator_add, "addSlider", 1, JS_CFUNC_generic_magic, 0
+	),
+	JS_PROP_ENUMERABLE
     );
     JS_DefinePropertyValueStr (
 	this->m_engine.getContext (), this->m_creatorPrototype, "addCheckbox",
-	JS_NewCFunctionMagic (this->m_engine.getContext (), scriptpropertiescreator_add, "addCheckbox", 1, JS_CFUNC_generic_magic, 0),
+	JS_NewCFunctionMagic (
+	    this->m_engine.getContext (), scriptpropertiescreator_add, "addCheckbox", 1, JS_CFUNC_generic_magic, 0
+	),
 	JS_PROP_ENUMERABLE
     );
     JS_DefinePropertyValueStr (
 	this->m_engine.getContext (), this->m_creatorPrototype, "addText",
-	JS_NewCFunctionMagic (this->m_engine.getContext (), scriptpropertiescreator_add, "addText", 1, JS_CFUNC_generic_magic, 0), JS_PROP_ENUMERABLE
+	JS_NewCFunctionMagic (
+	    this->m_engine.getContext (), scriptpropertiescreator_add, "addText", 1, JS_CFUNC_generic_magic, 0
+	),
+	JS_PROP_ENUMERABLE
     );
     JS_DefinePropertyValueStr (
 	this->m_engine.getContext (), this->m_creatorPrototype, "addCombo",
-	JS_NewCFunctionMagic (this->m_engine.getContext (), scriptpropertiescreator_add, "addCombo", 1, JS_CFUNC_generic_magic, 1), JS_PROP_ENUMERABLE
+	JS_NewCFunctionMagic (
+	    this->m_engine.getContext (), scriptpropertiescreator_add, "addCombo", 1, JS_CFUNC_generic_magic, 1
+	),
+	JS_PROP_ENUMERABLE
     );
     JS_DefinePropertyValueStr (
 	this->m_engine.getContext (), this->m_creatorPrototype, "addColor",
-	JS_NewCFunctionMagic (this->m_engine.getContext (), scriptpropertiescreator_add, "addColor", 1, JS_CFUNC_generic_magic, 0), JS_PROP_ENUMERABLE
+	JS_NewCFunctionMagic (
+	    this->m_engine.getContext (), scriptpropertiescreator_add, "addColor", 1, JS_CFUNC_generic_magic, 0
+	),
+	JS_PROP_ENUMERABLE
     );
     JS_DefinePropertyValueStr (
 	this->m_engine.getContext (), this->m_creatorPrototype, "finish",

+ 4 - 0
src/WallpaperEngine/Scripting/ScriptableObject.cpp

@@ -78,6 +78,10 @@ void ScriptableObject::registerProperty (
 	    const std::string key = existing->second.key;
 	    this->m_properties.erase (existing);
 	    this->m_properties.emplace (name, PropertyEntry { .key = key, .value = value });
+	    this->getScene ().getScriptEngine ().getAnimations ().add (
+		animationGroup.empty () ? "obj" + std::to_string (this->getId ()) : animationGroup,
+		animationKey.empty () ? name : animationKey, value
+	    );
 	    return;
 	}