Forráskód Böngészése

plenty of new features added

UwU 1 hónapja
szülő
commit
ef7f7f5dd7
32 módosított fájl, 1527 hozzáadás és 63 törlés
  1. 2 0
      CMakeLists.txt
  2. 1 1
      README.md
  3. 11 0
      src/WallpaperEngine/Application/ApplicationContext.cpp
  4. 2 0
      src/WallpaperEngine/Application/ApplicationContext.h
  5. 1 0
      src/WallpaperEngine/Data/Assets/Texture.h
  6. 16 0
      src/WallpaperEngine/Data/Model/Effect.h
  7. 96 9
      src/WallpaperEngine/Data/Parsers/EffectParser.cpp
  8. 2 0
      src/WallpaperEngine/Data/Parsers/EffectParser.h
  9. 31 14
      src/WallpaperEngine/Data/Parsers/TextureParser.cpp
  10. 1 1
      src/WallpaperEngine/Data/Parsers/TextureParser.h
  11. 90 6
      src/WallpaperEngine/Media/DBusMediaSource.cpp
  12. 5 0
      src/WallpaperEngine/Media/DBusMediaSource.h
  13. 37 0
      src/WallpaperEngine/Render/CTexture.cpp
  14. 4 0
      src/WallpaperEngine/Render/CTexture.h
  15. 430 0
      src/WallpaperEngine/Render/GifAnimation.cpp
  16. 87 0
      src/WallpaperEngine/Render/GifAnimation.h
  17. 89 0
      src/WallpaperEngine/Render/Objects/CImage.cpp
  18. 6 0
      src/WallpaperEngine/Render/Objects/CImage.h
  19. 4 0
      src/WallpaperEngine/Render/Objects/CParticle.cpp
  20. 55 1
      src/WallpaperEngine/Render/Objects/CRenderable.cpp
  21. 10 0
      src/WallpaperEngine/Render/Objects/CRenderable.h
  22. 5 1
      src/WallpaperEngine/Render/Objects/CText.cpp
  23. 11 1
      src/WallpaperEngine/Render/Objects/Effects/CPass.cpp
  24. 65 18
      src/WallpaperEngine/Render/Objects/PuppetClipping.cpp
  25. 7 0
      src/WallpaperEngine/Render/Objects/PuppetClipping.h
  26. 112 6
      src/WallpaperEngine/Render/Objects/PuppetRig.cpp
  27. 13 0
      src/WallpaperEngine/Render/Objects/PuppetRig.h
  28. 8 1
      src/WallpaperEngine/Render/TextureCache.cpp
  29. 137 2
      src/WallpaperEngine/Render/Wallpapers/CScene.cpp
  30. 19 0
      src/WallpaperEngine/Render/Wallpapers/CScene.h
  31. 9 2
      src/WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.cpp
  32. 161 0
      tools/tex_scan.py

+ 2 - 0
CMakeLists.txt

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

+ 1 - 1
README.md

@@ -241,7 +241,7 @@ linux-wallpaperengine --disable-object Clock --disable-object 3 2370927443
 
 ## Limitations
 
-The scene renderer follows Wallpaper Engine 2.8 closely, but not everything is there yet. The full list with details is in [TODO.md](TODO.md).
+The scene renderer follows Wallpaper Engine 2.8 closely, but not everything is there yet.
 
 Platform and setup:
 

+ 11 - 0
src/WallpaperEngine/Application/ApplicationContext.cpp

@@ -1106,6 +1106,17 @@ void ApplicationContext::loadSettingsFromArgv () {
 	    this->settings.general.shadowQuality = qualityLevel (value);
 	});
 
+    configurationGroup.add_argument ("--msaa")
+	.help (
+	    "Wallpaper Engine's anti-aliasing setting: none (default), x2, x4 or x8. Like Wallpaper Engine it only "
+	    "applies "
+	    "to scenes with a 3D model object, which then draw their objects multisampled"
+	)
+	.choices ("none", "x2", "x4", "x8")
+	.action ([this] (const std::string& value) -> void {
+	    this->settings.general.msaaSamples = value == "x2" ? 2 : value == "x4" ? 4 : value == "x8" ? 8 : 0;
+	});
+
     configurationGroup.add_argument ("--disable-animations")
 	.help ("Freezes all scene animation (scripts, particles, effects and puppet meshes) at its current frame")
 	.flag ()

+ 2 - 0
src/WallpaperEngine/Application/ApplicationContext.h

@@ -124,6 +124,8 @@ public:
 	    /** WE's volumetrics and shadow quality: 0 disabled, 1 low, 2 medium, 3 high, 4 ultra */
 	    int volumetricsQuality = 2;
 	    int shadowQuality = 2;
+	    /** WE's "msaa" setting as a sample count (0 off, 2, 4, 8), only scenes with models use it, see --msaa */
+	    int msaaSamples = 0;
 	    /** Objects/layers to force-hide, matched by id or name */
 	    std::vector<std::string> disabledObjects;
 	    /** Objects/layers to force-show, matched by id or name */

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

@@ -175,6 +175,7 @@ struct Texture {
     TextureFormat format = TextureFormat_UNKNOWN;
     FIF freeImageFormat = FIF_UNKNOWN;
     bool isVideoMp4 = false;
+    bool isAnimatedGif = false;
     uint32_t imageCount = 0;
     std::vector<TextureCondition> conditions {};
     std::map<uint32_t, MipmapList> images {};

+ 16 - 0
src/WallpaperEngine/Data/Model/Effect.h

@@ -1,5 +1,6 @@
 #pragma once
 
+#include <glm/vec4.hpp>
 #include <optional>
 #include <string>
 
@@ -13,6 +14,20 @@ struct FBO {
     std::string format;
     float scale;
     bool unique;
+    /** "clear": up to four numbers, what the buffer is cleared to when made and by a clear function */
+    glm::vec4 clearColor = {};
+    /** "clear" was empty or had all four numbers (wallpaper64.exe 2.8.42 sub_1401E7170, FBO flag 2) */
+    bool clearOnCreate = false;
+};
+
+/**
+ * An effect.json "functions" entry, run by IEffect.executeMaterialFunction. WE only keeps "clear" actions that
+ * name at least one of the effect's buffers
+ */
+struct EffectFunction {
+    std::string name;
+    /** indices into the effect's fbos of the names listed, WE only uses how many there are */
+    std::vector<int> fbos;
 };
 
 struct EffectPass {
@@ -34,5 +49,6 @@ struct Effect {
     std::vector<std::string> dependencies;
     std::vector<EffectPassUniquePtr> passes;
     std::vector<FBOUniquePtr> fbos;
+    std::vector<EffectFunction> functions;
 };
 } // namespace WallpaperEngine::Data::Model

+ 96 - 9
src/WallpaperEngine/Data/Parsers/EffectParser.cpp

@@ -1,6 +1,9 @@
 #include "EffectParser.h"
 #include "MaterialParser.h"
 
+#include <algorithm>
+#include <cstdlib>
+
 #include "WallpaperEngine/Data/Model/DynamicValue.h"
 #include "WallpaperEngine/Data/Model/Effect.h"
 #include "WallpaperEngine/Data/Model/Material.h"
@@ -19,8 +22,9 @@ EffectUniquePtr EffectParser::load (const Project& project, const std::string& f
 EffectUniquePtr EffectParser::parse (const JSON& it, const Project& project) {
     const auto dependencies = it.optional ("dependencies");
     const auto fbos = it.optional ("fbos");
+    const auto functions = it.optional ("functions");
 
-    return std::make_unique<Effect> (Effect {
+    auto result = std::make_unique<Effect> (Effect {
 	.name = it.optional<std::string> ("name", ""),
 	.description = it.optional<std::string> ("description", ""),
 	.group = it.optional<std::string> ("group", ""),
@@ -29,6 +33,58 @@ EffectUniquePtr EffectParser::parse (const JSON& it, const Project& project) {
 	.passes = parseEffectPasses (it.require ("passes", "Effect file must have passes"), project),
 	.fbos = fbos.has_value () ? parseFBOs (*fbos) : std::vector<FBOUniquePtr> {},
     });
+
+    if (functions.has_value ()) {
+	result->functions = parseFunctions (*functions, result->fbos);
+    }
+
+    return result;
+}
+
+// wallpaper64.exe 2.8.42 sub_1401E7170: an object member per function, only "action": "clear" with an "fbos" array
+// is kept, and only when one of its names is one of the effect's buffers
+std::vector<EffectFunction> EffectParser::parseFunctions (const JSON& it, const std::vector<FBOUniquePtr>& fbos) {
+    std::vector<EffectFunction> result = {};
+
+    if (!it.is_object ()) {
+	return result;
+    }
+
+    for (const auto& [name, function] : it.items ()) {
+	if (name.empty () || !function.is_object ()) {
+	    continue;
+	}
+
+	const auto action = function.find ("action");
+	const auto names = function.find ("fbos");
+
+	if (action == function.end () || !action->is_string () || action->get<std::string> () != "clear"
+	    || names == function.end () || !names->is_array ()) {
+	    continue;
+	}
+
+	EffectFunction entry { .name = name };
+
+	for (const auto& fboName : *names) {
+	    if (!fboName.is_string ()) {
+		continue;
+	    }
+
+	    const auto found = std::ranges::find_if (fbos, [&fboName] (const auto& fbo) {
+		return fbo->name == fboName.get<std::string> ();
+	    });
+
+	    if (found != fbos.end ()) {
+		entry.fbos.push_back (static_cast<int> (found - fbos.begin ()));
+	    }
+	}
+
+	if (!entry.fbos.empty ()) {
+	    result.push_back (std::move (entry));
+	}
+    }
+
+    return result;
 }
 
 std::vector<std::string> EffectParser::parseDependencies (const JSON& it) {
@@ -102,14 +158,45 @@ std::vector<FBOUniquePtr> EffectParser::parseFBOs (const JSON& it) {
     }
 
     for (const auto& cur : it) {
-	result.push_back (
-	    std::make_unique<FBO> (FBO {
-		.name = cur.require<std::string> ("name", "FBO must have a name"),
-		.format = cur.optional<std::string> ("format", "rgba8888"),
-		.scale = cur.optional ("scale", 1.0f),
-		.unique = cur.optional ("unique", false),
-	    })
-	);
+	auto fbo = std::make_unique<FBO> (FBO {
+	    .name = cur.require<std::string> ("name", "FBO must have a name"),
+	    .format = cur.optional<std::string> ("format", "rgba8888"),
+	    .scale = cur.optional ("scale", 1.0f),
+	    .unique = cur.optional ("unique", false),
+	});
+
+	// sub_1401E7170 reads "clear" with atof, one number per run of spaces; an empty string or all four numbers
+	// also clear the buffer when it is made
+	if (const auto clear = cur.find ("clear"); clear != cur.end () && clear->is_string ()) {
+	    const auto text = clear->get<std::string> ();
+	    const char* cursor = text.c_str ();
+	    bool complete = text.empty ();
+
+	    for (int component = 0; !complete && component < 4; component++) {
+		fbo->clearColor[component] = static_cast<float> (std::atof (cursor));
+
+		if (component == 3) {
+		    complete = true;
+		    break;
+		}
+
+		while (*cursor != '\0' && *cursor != ' ') {
+		    cursor++;
+		}
+
+		if (*cursor == '\0') {
+		    break;
+		}
+
+		while (*cursor == ' ') {
+		    cursor++;
+		}
+	    }
+
+	    fbo->clearOnCreate = complete;
+	}
+
+	result.push_back (std::move (fbo));
     }
 
     return result;

+ 2 - 0
src/WallpaperEngine/Data/Parsers/EffectParser.h

@@ -1,6 +1,7 @@
 #pragma once
 
 #include "WallpaperEngine/Data/JSON.h"
+#include "WallpaperEngine/Data/Model/Effect.h"
 #include "WallpaperEngine/Data/Model/Types.h"
 
 namespace WallpaperEngine::Data::Parsers {
@@ -17,5 +18,6 @@ private:
     static std::vector<EffectPassUniquePtr> parseEffectPasses (const JSON& it, const Project& project);
     static std::map<int, std::string> parseBinds (const JSON& it);
     static std::vector<FBOUniquePtr> parseFBOs (const JSON& it);
+    static std::vector<EffectFunction> parseFunctions (const JSON& it, const std::vector<FBOUniquePtr>& fbos);
 };
 } // namespace WallpaperEngine::Data::Parsers

+ 31 - 14
src/WallpaperEngine/Data/Parsers/TextureParser.cpp

@@ -14,8 +14,16 @@ using namespace WallpaperEngine::Data::Parsers;
 TextureUniquePtr TextureParser::parse (const BinaryReader& file) {
     auto result = std::make_unique<Texture> ();
 
-    parseTextureHeader (*result, file);
-    parseContainer (*result, file);
+    // wallpaper64.exe sub_14015E580: TEXV0004 is a version 0 TEXI header followed by a version 0 TEXB body (one
+    // image, mips like TEXB0001) with no section tags and no TEXS
+    const bool legacy = parseTextureHeader (*result, file);
+
+    if (legacy) {
+	result->containerVersion = ContainerVersion_TEXB0001;
+	result->imageCount = 1;
+    } else {
+	parseContainer (*result, file);
+    }
 
     for (uint32_t image = 0; image < result->imageCount; image++) {
 	const uint32_t mipmapCount = file.nextUInt32 ();
@@ -32,7 +40,7 @@ TextureUniquePtr TextureParser::parse (const BinaryReader& file) {
 	result->images.emplace (image, mipmaps);
     }
 
-    if (!result->isAnimated ()) {
+    if (legacy || !result->isAnimated ()) {
 	return result;
     }
 
@@ -126,8 +134,8 @@ FrameSharedPtr TextureParser::parseFrameV1 (const BinaryReader& file) {
     result->x = static_cast<float> (file.nextUInt32 ());
     result->y = static_cast<float> (file.nextUInt32 ());
     result->width1 = static_cast<float> (file.nextUInt32 ());
-    std::ignore = file.nextUInt32 (); // unknown
-    std::ignore = file.nextUInt32 (); // unknown
+    result->width2 = static_cast<float> (file.nextUInt32 ());
+    result->height2 = static_cast<float> (file.nextUInt32 ());
     result->height1 = static_cast<float> (file.nextUInt32 ());
 
     return result;
@@ -203,19 +211,23 @@ TextureFormat TextureParser::parseTextureFormat (uint32_t value) {
     }
 }
 
-void TextureParser::parseTextureHeader (Texture& header, const BinaryReader& file) {
+bool TextureParser::parseTextureHeader (Texture& header, const BinaryReader& file) {
     char magic[9] = { 0 };
 
     file.next (magic, 9);
 
-    if (strncmp (magic, "TEXV0005", 9) != 0) {
+    const bool legacy = strncmp (magic, "TEXV0004", 9) == 0;
+
+    if (!legacy && strncmp (magic, "TEXV0005", 9) != 0) {
 	sLog.exception ("unexpected texture container type: ", std::string_view (magic, 9));
     }
 
-    file.next (magic, 9);
+    if (!legacy) {
+	file.next (magic, 9);
 
-    if (strncmp (magic, "TEXI0001", 9) != 0) {
-	sLog.exception ("unexpected texture sub-container type: ", std::string_view (magic, 9));
+	if (strncmp (magic, "TEXI0001", 9) != 0) {
+	    sLog.exception ("unexpected texture sub-container type: ", std::string_view (magic, 9));
+	}
     }
 
     header.format = parseTextureFormat (file.nextUInt32 ());
@@ -230,7 +242,12 @@ void TextureParser::parseTextureHeader (Texture& header, const BinaryReader& fil
 	header.depth = file.nextUInt32 ();
     }
 
-    std::ignore = file.nextUInt32 ();
+    // only TEXI version 1 and up has this field
+    if (!legacy) {
+	std::ignore = file.nextUInt32 ();
+    }
+
+    return legacy;
 }
 
 void TextureParser::parseContainer (Texture& header, const BinaryReader& file) {
@@ -308,10 +325,10 @@ void TextureParser::parseAnimations (Texture& header, const BinaryReader& file)
 	}
     }
 
-    // TEXS0001/TEXS0002 don't carry gif dimensions in the header, derive them from the first frame
+    // wallpaper64.exe 2.8.42 sub_14015E1D0: before TEXS0003 the frame size is the TEXI image size
     if (header.animatedVersion == AnimatedVersion_TEXS0001 || header.animatedVersion == AnimatedVersion_TEXS0002) {
-	header.gifWidth = (*header.frames.begin ())->width1;
-	header.gifHeight = (*header.frames.begin ())->height1;
+	header.gifWidth = header.width;
+	header.gifHeight = header.height;
     }
 }
 

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

@@ -24,7 +24,7 @@ public:
     static TextureMap parseTextureMap (const JSON& it);
 
 private:
-    static void parseTextureHeader (Texture& header, const BinaryReader& file);
+    static bool 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);

+ 90 - 6
src/WallpaperEngine/Media/DBusMediaSource.cpp

@@ -29,6 +29,41 @@ DBusHandlerResult dbus_message_filter (DBusConnection* connection, DBusMessage*
     dbus_message_iter_next (&iter);
     dbus_message_iter_recurse (&iter, &changed);
 
+    // signals come from every MPRIS player on the bus: only the followed one updates the track, another one takes
+    // over only by starting to play, idle players (a browser with nothing loaded) are ignored
+    const char* sender = dbus_message_get_sender (message);
+
+    if (!mediaSource->isCurrentPlayer (sender)) {
+	DBusMessageIter scan = changed;
+	bool startedPlaying = false;
+
+	while (dbus_message_iter_get_arg_type (&scan) == DBUS_TYPE_DICT_ENTRY) {
+	    DBusMessageIter entry;
+	    dbus_message_iter_recurse (&scan, &entry);
+
+	    const char* key = nullptr;
+	    dbus_message_iter_get_basic (&entry, &key);
+
+	    if (key != nullptr && std::string_view (key) == "PlaybackStatus") {
+		DBusMessageIter value;
+		dbus_message_iter_next (&entry);
+		dbus_message_iter_recurse (&entry, &value);
+
+		const char* status = nullptr;
+		dbus_message_iter_get_basic (&value, &status);
+		startedPlaying = status != nullptr && std::string_view (status) == "Playing";
+	    }
+
+	    dbus_message_iter_next (&scan);
+	}
+
+	if (startedPlaying && sender != nullptr) {
+	    mediaSource->switchPlayer (sender);
+	}
+
+	return DBUS_HANDLER_RESULT_HANDLED;
+    }
+
     while (dbus_message_iter_get_arg_type (&changed) == DBUS_TYPE_DICT_ENTRY) {
 	DBusMessageIter entry;
 	dbus_message_iter_recurse (&changed, &entry);
@@ -187,10 +222,6 @@ void DBusMediaSource::parsePlaybackStatus (DBusMessageIter& variant, const char*
     PlaybackState newState = this->m_mediaInfo.playbackState;
 
     if (statusStr == "Playing") {
-	if (sender != nullptr) {
-	    this->m_currentPlayer = sender;
-	}
-
 	newState = PlaybackState::Playing;
     } else if (statusStr == "Paused") {
 	newState = PlaybackState::Paused;
@@ -204,6 +235,46 @@ void DBusMediaSource::parsePlaybackStatus (DBusMessageIter& variant, const char*
     }
 }
 
+bool DBusMediaSource::isCurrentPlayer (const char* sender) const {
+    return sender != nullptr && this->m_currentPlayer.has_value () && *this->m_currentPlayer == sender;
+}
+
+void DBusMediaSource::switchPlayer (const std::string& player) {
+    this->m_currentPlayer = player;
+    this->m_mediaInfo.playbackState = PlaybackState::Playing;
+    this->initialStatusFetch ();
+    this->fireMetadataListeners ();
+}
+
+std::optional<std::string> DBusMediaSource::uniqueName (const std::string& name) {
+    const char* nameText = name.c_str ();
+    DBusError err;
+    dbus_error_init (&err);
+
+    DBusMessage* msg = dbus_message_new_method_call (
+	"org.freedesktop.DBus", "/org/freedesktop/DBus", "org.freedesktop.DBus", "GetNameOwner"
+    );
+    Data::Utils::ScopeGuard guard ([msg] { dbus_message_unref (msg); });
+    dbus_message_append_args (msg, DBUS_TYPE_STRING, &nameText, DBUS_TYPE_INVALID);
+
+    DBusMessage* reply = dbus_connection_send_with_reply_and_block (this->m_connection, msg, -1, &err);
+
+    if (reply == nullptr) {
+	dbus_error_free (&err);
+	return std::nullopt;
+    }
+
+    Data::Utils::ScopeGuard replyGuard ([reply] { dbus_message_unref (reply); });
+    const char* owner = nullptr;
+
+    if (!dbus_message_get_args (reply, &err, DBUS_TYPE_STRING, &owner, DBUS_TYPE_INVALID) || owner == nullptr) {
+	dbus_error_free (&err);
+	return std::nullopt;
+    }
+
+    return std::string (owner);
+}
+
 void DBusMediaSource::parsePosition (DBusMessageIter& variant) {
     int64_t position = 0;
     dbus_message_iter_get_basic (&variant, &position);
@@ -311,9 +382,22 @@ void DBusMediaSource::detectPlayer () {
 	DBusMessageIter variant;
 	dbus_message_iter_recurse (&outer, &variant);
 
-	this->parsePlaybackStatus (variant, player.c_str ());
+	const char* status = nullptr;
+
+	if (dbus_message_iter_get_arg_type (&variant) != DBUS_TYPE_STRING) {
+	    continue;
+	}
+
+	dbus_message_iter_get_basic (&variant, &status);
+
+	if (status == nullptr || std::string_view (status) != "Playing") {
+	    continue;
+	}
 
-	if (this->m_currentPlayer.has_value ()) {
+	// signals carry the unique bus name, keep that one so they can be told apart
+	if (const auto owner = this->uniqueName (player)) {
+	    this->m_currentPlayer = *owner;
+	    this->parsePlaybackStatus (variant, owner->c_str ());
 	    break;
 	}
     }

+ 5 - 0
src/WallpaperEngine/Media/DBusMediaSource.h

@@ -15,10 +15,15 @@ public:
 
     void update () override;
 
+    [[nodiscard]] bool isCurrentPlayer (const char* sender) const;
+    void switchPlayer (const std::string& player);
+
 protected:
     void performUpdate () override;
     void initialStatusFetch ();
     void detectPlayer ();
+    /** The unique bus name owning a well-known MPRIS name */
+    std::optional<std::string> uniqueName (const std::string& name);
 
     DBusMessage* dbusMessage (
 	const char* bus_name, const char* path, const char* interface, const char* method, const char* iface = nullptr,

+ 37 - 0
src/WallpaperEngine/Render/CTexture.cpp

@@ -12,6 +12,9 @@
 
 using namespace WallpaperEngine::Render;
 
+extern float g_Time;
+extern float g_TimeLast;
+
 CTexture::CTexture (RenderContext& context, TextureUniquePtr header) :
     Helpers::ContextAware (context), m_header (std::move (header)) {
     this->setupResolution ();
@@ -53,6 +56,26 @@ CTexture::CTexture (RenderContext& context, TextureUniquePtr header) :
     this->m_textureID = new GLuint[this->m_header->imageCount];
     glGenTextures (this->m_header->imageCount, this->m_textureID);
 
+    // WE decodes the first frame when the texture is made, a GIF it can't play fails to load there, here it falls
+    // back to the still image below
+    if (this->m_header->isAnimatedGif) {
+	const auto& mipmap = *this->m_header->images.begin ()->second.begin ();
+
+	this->m_gif = GifAnimation::open (mipmap->uncompressedData.get (), mipmap->uncompressedSize);
+
+	if (this->m_gif != nullptr && this->m_gif->advance (0.0f)) {
+	    this->setupOpenGLParameters (0);
+	    glTexImage2D (
+		GL_TEXTURE_2D, 0, GL_RGBA8, this->m_gif->width (), this->m_gif->height (), 0, GL_RGBA, GL_UNSIGNED_BYTE,
+		this->m_gif->pixels ()
+	    );
+	    this->m_gifTime = g_Time;
+	    return;
+	}
+
+	this->m_gif.reset ();
+    }
+
     for (const auto& [index, mipmaps] : this->m_header->images) {
 	this->setupOpenGLParameters (index);
 
@@ -258,6 +281,20 @@ void CTexture::update () const {
     if (this->m_player) {
 	this->m_player->render ();
     }
+
+    // wallpaper64.exe 2.8.42 sub_1400EE9E0: once per frame AdvanceGIF with the frame's duration, a new frame is
+    // copied over the whole texture
+    if (this->m_gif && this->m_gifTime != g_Time) {
+	this->m_gifTime = g_Time;
+
+	if (this->m_gif->advance (std::max (g_Time - g_TimeLast, 0.0f))) {
+	    glBindTexture (GL_TEXTURE_2D, this->m_textureID[0]);
+	    glTexSubImage2D (
+		GL_TEXTURE_2D, 0, 0, 0, this->m_gif->width (), this->m_gif->height (), GL_RGBA, GL_UNSIGNED_BYTE,
+		this->m_gif->pixels ()
+	    );
+	}
+    }
 }
 
 bool CTexture::isReady () const { return true; }

+ 4 - 0
src/WallpaperEngine/Render/CTexture.h

@@ -1,5 +1,6 @@
 #pragma once
 
+#include "GifAnimation.h"
 #include "Helpers/ContextAware.h"
 #include "TextureProvider.h"
 #include "WallpaperEngine/Data/Assets/Texture.h"
@@ -58,5 +59,8 @@ private:
     GLuint* m_textureID = nullptr;
     glm::vec4 m_resolution {};
     GLPlayerUniquePtr m_player;
+    std::unique_ptr<GifAnimation> m_gif;
+    /** g_Time of the last GIF step, a texture shared by several layers steps once per frame */
+    mutable float m_gifTime = 0.0f;
 };
 } // namespace WallpaperEngine::Assets

+ 430 - 0
src/WallpaperEngine/Render/GifAnimation.cpp

@@ -0,0 +1,430 @@
+#include "GifAnimation.h"
+
+#include <algorithm>
+#include <cstring>
+
+using namespace WallpaperEngine::Render;
+
+namespace {
+bool isGif (const uint8_t* data, size_t size) {
+    return size >= 6 && data[0] == 'G' && data[1] == 'I' && data[2] == 'F' && data[3] == '8'
+	&& (data[4] == '9' || data[4] == '7') && data[5] == 'a';
+}
+} // namespace
+
+std::unique_ptr<GifAnimation> GifAnimation::open (const void* data, const size_t size) {
+    const auto* bytes = static_cast<const uint8_t*> (data);
+
+    if (!isGif (bytes, size)) {
+	return nullptr;
+    }
+
+    auto result = std::unique_ptr<GifAnimation> (new GifAnimation ());
+
+    result->m_data.assign (bytes, bytes + size);
+
+    return result;
+}
+
+bool GifAnimation::canvasSize (const void* data, const size_t size, int& width, int& height) {
+    const auto* bytes = static_cast<const uint8_t*> (data);
+
+    if (!isGif (bytes, size) || size < 10) {
+	return false;
+    }
+
+    width = bytes[6] | (bytes[7] << 8);
+    height = bytes[8] | (bytes[9] << 8);
+
+    return width > 0 && height > 0;
+}
+
+uint8_t GifAnimation::get8 () { return m_cursor < m_data.size () ? m_data[m_cursor++] : 0; }
+
+int GifAnimation::get16le () {
+    const int low = get8 ();
+    return low | (get8 () << 8);
+}
+
+void GifAnimation::skip (const int count) {
+    m_cursor = count < 0 ? m_data.size () : std::min (m_data.size (), m_cursor + count);
+}
+
+// resourceutil64 sub_180006D90
+bool GifAnimation::readHeader () {
+    if (get8 () != 'G' || get8 () != 'I' || get8 () != 'F' || get8 () != '8') {
+	return false;
+    }
+
+    const uint8_t version = get8 ();
+
+    if ((version != '7' && version != '9') || get8 () != 'a') {
+	return false;
+    }
+
+    m_width = get16le ();
+    m_height = get16le ();
+    m_flags = get8 ();
+    m_bgIndex = get8 ();
+    get8 (); // aspect ratio
+    m_transparent = -1;
+
+    if (m_width > 0x1000000 || m_height > 0x1000000) {
+	return false;
+    }
+
+    // unlike stb_image, a background index of 0 or past the global table counts as none
+    const int count = 2 << (m_flags & 7);
+
+    if ((m_flags & 0x80) == 0) {
+	m_bgIndex = -1;
+    } else {
+	readColorTable (m_palette, count, -1);
+
+	if (m_bgIndex == 0 || m_bgIndex >= count) {
+	    m_bgIndex = -1;
+	}
+    }
+
+    return true;
+}
+
+// sub_180006C40, entries are stored BGRA
+void GifAnimation::readColorTable (uint8_t (*palette)[4], const int count, const int transparent) {
+    for (int i = 0; i < count; i++) {
+	palette[i][2] = get8 ();
+	palette[i][1] = get8 ();
+	palette[i][0] = get8 ();
+	palette[i][3] = transparent == i ? 0 : 255;
+    }
+}
+
+// sub_180007230
+void GifAnimation::outputCode (const uint16_t code) {
+    if (m_codes[code].prefix >= 0) {
+	outputCode (m_codes[code].prefix);
+    }
+
+    if (m_curY >= m_maxY) {
+	return;
+    }
+
+    const int index = m_curX + m_curY;
+    uint8_t* pixel = &m_out[index];
+
+    m_history[index / 4] = 1;
+
+    const uint8_t* color = &m_colorTable[m_codes[code].suffix * 4];
+
+    if (color[3] > 128) {
+	pixel[0] = color[2];
+	pixel[1] = color[1];
+	pixel[2] = color[0];
+	pixel[3] = color[3];
+    }
+
+    m_curX += 4;
+
+    if (m_curX >= m_maxX) {
+	m_curX = m_startX;
+	m_curY += m_step;
+
+	while (m_curY >= m_maxY && m_parse > 0) {
+	    m_step = (1 << m_parse) * m_lineSize;
+	    m_curY = m_startY + (m_step >> 1);
+	    --m_parse;
+	}
+    }
+}
+
+bool GifAnimation::decodeRaster () {
+    const uint8_t lzwSize = get8 ();
+
+    if (lzwSize > 12) {
+	return false;
+    }
+
+    const int clear = 1 << lzwSize;
+    bool first = true;
+    int codeSize = lzwSize + 1;
+    int codeMask = (1 << codeSize) - 1;
+    int bits = 0;
+    int validBits = 0;
+
+    for (int code = 0; code < clear; code++) {
+	m_codes[code].prefix = -1;
+	m_codes[code].first = static_cast<uint8_t> (code);
+	m_codes[code].suffix = static_cast<uint8_t> (code);
+    }
+
+    int avail = clear + 2;
+    int oldCode = -1;
+    int length = 0;
+
+    for (;;) {
+	if (validBits < codeSize) {
+	    if (length == 0) {
+		length = get8 ();
+
+		if (length == 0) {
+		    return true;
+		}
+	    }
+
+	    --length;
+	    bits |= get8 () << validBits;
+	    validBits += 8;
+	    continue;
+	}
+
+	const int code = bits & codeMask;
+
+	bits >>= codeSize;
+	validBits -= codeSize;
+
+	if (code == clear) {
+	    codeSize = lzwSize + 1;
+	    codeMask = (1 << codeSize) - 1;
+	    avail = clear + 2;
+	    oldCode = -1;
+	    first = false;
+	} else if (code == clear + 1) {
+	    skip (length);
+
+	    while ((length = get8 ()) > 0) {
+		skip (length);
+	    }
+
+	    return true;
+	} else if (code <= avail) {
+	    if (first) {
+		return false;
+	    }
+
+	    if (oldCode >= 0) {
+		Code& entry = m_codes[avail++];
+
+		if (avail > 8192) {
+		    return false;
+		}
+
+		entry.prefix = static_cast<int16_t> (oldCode);
+		entry.first = m_codes[oldCode].first;
+		entry.suffix = code == avail ? entry.first : m_codes[code].first;
+	    } else if (code == avail) {
+		return false;
+	    }
+
+	    outputCode (static_cast<uint16_t> (code));
+
+	    if ((avail & codeMask) == 0 && avail <= 0x0FFF) {
+		codeSize++;
+		codeMask = (1 << codeSize) - 1;
+	    }
+
+	    oldCode = code;
+	} else {
+	    return false;
+	}
+    }
+}
+
+// sub_180007800, stbi__gif_load_next with a restart flag
+GifAnimation::Result GifAnimation::loadNext (const uint8_t* twoBack, const bool restart) {
+    bool firstFrame = false;
+
+    if (m_out.empty () || restart) {
+	if (!readHeader ()) {
+	    return Result::Error;
+	}
+
+	const size_t count = static_cast<size_t> (m_width) * m_height;
+
+	m_out.assign (count * 4, 0);
+	m_history.assign (count, 0);
+	firstFrame = true;
+    } else {
+	int dispose = (m_eflags >> 2) & 7;
+	const size_t count = static_cast<size_t> (m_width) * m_height;
+
+	if ((m_eflags & 0x1C) == 12 && twoBack == nullptr) {
+	    dispose = 2;
+	}
+
+	if (dispose == 3) {
+	    for (size_t i = 0; i < count; i++) {
+		if (m_history[i]) {
+		    memcpy (&m_out[i * 4], &twoBack[i * 4], 4);
+		}
+	    }
+	} else if (dispose == 2) {
+	    // no saved background like newer stb_image: the palette entry is copied as stored (BGRA)
+	    const uint8_t* fill = nullptr;
+
+	    if (m_bgIndex >= 0) {
+		fill = m_transparent < 0 ? m_palette[m_bgIndex] : m_palette[m_transparent];
+	    }
+
+	    for (size_t i = 0; i < count; i++) {
+		if (!m_history[i]) {
+		    continue;
+		}
+
+		if (fill == nullptr) {
+		    memset (&m_out[i * 4], 0, 4);
+		} else {
+		    memcpy (&m_out[i * 4], fill, 4);
+		}
+	    }
+	}
+    }
+
+    std::fill (m_history.begin (), m_history.end (), 0);
+
+    for (;;) {
+	if (m_cursor >= m_data.size ()) {
+	    return Result::Error;
+	}
+
+	const uint8_t tag = get8 ();
+
+	if (tag == 0x21) {
+	    const uint8_t extension = get8 ();
+
+	    if (extension == 0xF9) {
+		const uint8_t length = get8 ();
+
+		if (length != 4) {
+		    skip (length);
+		    continue;
+		}
+
+		m_eflags = get8 ();
+		m_delay = 10 * get16le ();
+
+		if (m_transparent >= 0) {
+		    m_palette[m_transparent][3] = 255;
+		}
+
+		if (m_eflags & 1) {
+		    m_transparent = get8 ();
+		    m_palette[m_transparent][3] = 0;
+		} else {
+		    skip (1);
+		    m_transparent = -1;
+		}
+	    }
+
+	    int length;
+
+	    while ((length = get8 ()) != 0) {
+		skip (length);
+	    }
+
+	    continue;
+	}
+
+	if (tag == 0x3B) {
+	    return Result::Trailer;
+	}
+
+	if (tag != 0x2C) {
+	    return Result::Error;
+	}
+
+	const int x = get16le ();
+	const int y = get16le ();
+	const int w = get16le ();
+	const int h = get16le ();
+
+	if (x + w > m_width || y + h > m_height) {
+	    return Result::Error;
+	}
+
+	m_lineSize = m_width * 4;
+	m_startX = x * 4;
+	m_startY = y * m_lineSize;
+	m_maxX = m_startX + w * 4;
+	m_maxY = m_startY + h * m_lineSize;
+	m_curX = m_startX;
+	m_curY = w == 0 ? m_maxY : m_startY;
+
+	const int localFlags = get8 ();
+
+	if (localFlags & 0x40) {
+	    m_step = 8 * m_lineSize;
+	    m_parse = 3;
+	} else {
+	    m_step = m_lineSize;
+	    m_parse = 0;
+	}
+
+	if (localFlags & 0x80) {
+	    readColorTable (m_localPalette, 2 << (localFlags & 7), m_eflags & 1 ? m_transparent : -1);
+	    m_colorTable = &m_localPalette[0][0];
+	} else if (m_flags & 0x80) {
+	    m_colorTable = &m_palette[0][0];
+	} else {
+	    return Result::Error;
+	}
+
+	if (!decodeRaster ()) {
+	    return Result::Error;
+	}
+
+	// first frame without transparency: pixels it doesn't draw get the background entry, alpha as stored
+	if (firstFrame && m_bgIndex >= 0 && (m_eflags & 1) == 0) {
+	    for (size_t i = 0; i < m_history.size (); i++) {
+		if (!m_history[i]) {
+		    memcpy (&m_out[i * 4], m_palette[m_bgIndex], 4);
+		}
+	    }
+	}
+
+	return Result::Frame;
+    }
+}
+
+bool GifAnimation::advance (const float dt) {
+    if (!m_first && m_timer > 0.0f) {
+	m_timer -= dt;
+
+	if (m_timer > 0.0f) {
+	    return false;
+	}
+    }
+
+    m_first = false;
+
+    const uint8_t* twoBack = m_twoBack.empty () ? nullptr : m_twoBack.data ();
+    Result result = loadNext (twoBack, false);
+
+    if (result == Result::Trailer) {
+	m_cursor = 0;
+	result = loadNext (twoBack, true);
+    }
+
+    if (result != Result::Frame) {
+	return false;
+    }
+
+    const bool sameSize = m_lastWidth == 0 || (m_lastWidth == m_width && m_lastHeight == m_height);
+
+    m_lastWidth = m_width;
+    m_lastHeight = m_height;
+    m_timer += static_cast<float> (m_delay) / 1000.0f;
+
+    const int dispose = m_eflags & 0x1C;
+
+    if (dispose == 0 || dispose == 4) {
+	if (m_twoBack.empty ()) {
+	    m_twoBack.resize (m_out.size ());
+	}
+
+	if (sameSize) {
+	    memcpy (m_twoBack.data (), m_out.data (), m_out.size ());
+	}
+    }
+
+    return true;
+}

+ 87 - 0
src/WallpaperEngine/Render/GifAnimation.h

@@ -0,0 +1,87 @@
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+#include <memory>
+#include <vector>
+
+namespace WallpaperEngine::Render {
+/**
+ * Animated GIF player for user-picked .gif image properties, a port of WE 2.8.42's resourceutil64 GIF exports
+ * (PrepareGIF/OpenGIF/AdvanceGIF/FreeGIF). Their decoder is an older stb_image variant: frames come out at the
+ * logical screen size, disposal 2 fills with a palette colour instead of the previous background, and the
+ * stream rewinds to the first frame after the trailer.
+ */
+class GifAnimation {
+public:
+    /** nullptr when the data isn't a GIF (PrepareGIF's stbi__gif_test) */
+    static std::unique_ptr<GifAnimation> open (const void* data, size_t size);
+
+    /**
+     * AdvanceGIF: steps the frame timer by dt seconds and decodes the next frame once it runs out. The first call
+     * always decodes. Returns true when pixels () holds a new frame
+     */
+    bool advance (float dt);
+
+    [[nodiscard]] const uint8_t* pixels () const { return m_out.data (); }
+    [[nodiscard]] int width () const { return m_width; }
+    [[nodiscard]] int height () const { return m_height; }
+
+    /** Logical screen size from the GIF header, without decoding anything */
+    static bool canvasSize (const void* data, size_t size, int& width, int& height);
+
+private:
+    struct Code {
+	int16_t prefix;
+	uint8_t first;
+	uint8_t suffix;
+    };
+
+    enum class Result { Frame, Trailer, Error };
+
+    GifAnimation () = default;
+
+    uint8_t get8 ();
+    int get16le ();
+    void skip (int count);
+
+    bool readHeader ();
+    void readColorTable (uint8_t (*palette)[4], int count, int transparent);
+    Result loadNext (const uint8_t* twoBack, bool restart);
+    bool decodeRaster ();
+    void outputCode (uint16_t code);
+
+    std::vector<uint8_t> m_data;
+    size_t m_cursor = 0;
+
+    int m_width = 0;
+    int m_height = 0;
+    std::vector<uint8_t> m_out;
+    std::vector<uint8_t> m_history;
+    int m_flags = 0;
+    int m_bgIndex = -1;
+    int m_transparent = -1;
+    int m_eflags = 0;
+    uint8_t m_palette[256][4] {};
+    uint8_t m_localPalette[256][4] {};
+    Code m_codes[8192] {};
+    const uint8_t* m_colorTable = nullptr;
+    int m_parse = 0;
+    int m_step = 0;
+    int m_startX = 0;
+    int m_startY = 0;
+    int m_maxX = 0;
+    int m_maxY = 0;
+    int m_curX = 0;
+    int m_curY = 0;
+    int m_lineSize = 0;
+    int m_delay = 0;
+
+    /** the last frame whose disposal keeps it (0 or 1), what disposal 3 restores to */
+    std::vector<uint8_t> m_twoBack;
+    float m_timer = 0.0f;
+    bool m_first = true;
+    int m_lastWidth = 0;
+    int m_lastHeight = 0;
+};
+} // namespace WallpaperEngine::Render

+ 89 - 0
src/WallpaperEngine/Render/Objects/CImage.cpp

@@ -881,6 +881,30 @@ bool CImage::loadPuppetMesh (const glm::vec2& size) {
 	const size_t indexEnd = layout->block.headerOffset + meshHeaderSize + layout->block.vertexBytes
 	    + sizeof (uint32_t) + layout->block.indexBytes;
 	this->m_puppetClipping.reset ();
+	this->m_puppetParts.clear ();
+	this->m_puppetPartOrder.clear ();
+	this->m_puppetMeshIndices.clear ();
+
+	// the mesh header's first field holds its flags, 8 animates the order the parts are drawn in
+	uint32_t meshFlags = 0;
+	std::memcpy (&meshFlags, data.data () + layout->block.headerOffset, sizeof (meshFlags));
+
+	if (meshFlags & 8) {
+	    try {
+		this->m_puppetParts = PuppetClipping::readParts (data, indexEnd, version, mesh->indices.size ());
+	    } catch (const std::exception& ex) {
+		sLog.error ("Ignoring the part ranges of ", *this->getImage ().model->puppet, ": ", ex.what ());
+	    }
+
+	    if (!this->m_puppetParts.empty ()) {
+		this->m_puppetMeshIndices = mesh->indices;
+		this->m_puppetPartOrder.resize (this->m_puppetParts.size ());
+
+		for (uint32_t index = 0; index < this->m_puppetPartOrder.size (); index++) {
+		    this->m_puppetPartOrder[index] = index;
+		}
+	    }
+	}
 
 	try {
 	    auto clipping = PuppetClipping::read (data, indexEnd, version, mesh->indices.size ());
@@ -933,6 +957,7 @@ bool CImage::loadPuppetMesh (const glm::vec2& size) {
 		}
 
 		this->m_rig.load (data, mdlsOffset, meshCount, *this->getImage ().model->puppet);
+		this->m_rig.drawOrderEnabled = !this->m_puppetParts.empty ();
 		this->m_rig.addSceneLayers (this->getImage ().animationLayers);
 	    } catch (const std::exception& ex) {
 		sLog.error (
@@ -1052,11 +1077,70 @@ void CImage::updatePuppetPose () {
     }
 
     this->m_rig.updatePose (this->puppetObjectWorld ());
+    this->updatePuppetDrawOrder ();
     this->m_rig.finishEndedLayers ([this] (size_t serial) {
 	this->getScene ().getScriptEngine ().dispatchAnimationLayerEnded (*this, serial);
     });
 }
 
+void CImage::updatePuppetDrawOrder () {
+    if (!this->m_rig.drawOrderTouched || this->m_puppetParts.empty ()) {
+	return;
+    }
+
+    // a part's key is (int) (its order + its bone's MDLS order, made when the parts are, + the bone's animated value)
+    const auto& boneOrder = this->m_rig.boneDrawOrder;
+    const auto& animated = this->m_rig.drawOrder;
+    std::vector<int> keys (this->m_puppetParts.size (), 0);
+
+    for (size_t index = 0; index < this->m_puppetParts.size (); index++) {
+	const auto& part = this->m_puppetParts[index];
+	const int base = static_cast<int> (part.order) + (part.bone < boneOrder.size () ? boneOrder[part.bone] : 0);
+	keys[index] = static_cast<int> (
+	    static_cast<float> (base) + (part.bone < animated.size () ? animated[part.bone] : 0.0f)
+	);
+    }
+
+    const auto byKey = [&keys] (uint32_t a, uint32_t b) { return keys[a] < keys[b]; };
+
+    if (std::ranges::is_sorted (this->m_puppetPartOrder, byKey)) {
+	return;
+    }
+
+    // MSVC's std::sort (sub_1402154D0) is an insertion sort up to 32 elements, which keeps equal keys in order
+    std::ranges::stable_sort (this->m_puppetPartOrder, byKey);
+
+    if (this->m_puppetClipping.has_value ()) {
+	this->m_puppetClipping->order = this->m_puppetPartOrder;
+
+	if (this->m_puppetClipping->build (this->m_puppetMeshIndices)) {
+	    glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_puppetClipIndices);
+	    glBufferData (
+		GL_ELEMENT_ARRAY_BUFFER, this->m_puppetClipping->indices.size () * sizeof (GLushort),
+		this->m_puppetClipping->indices.data (), GL_DYNAMIC_DRAW
+	    );
+	}
+
+	return;
+    }
+
+    std::vector<uint16_t> indices;
+    indices.reserve (this->m_puppetMeshIndices.size ());
+
+    for (const uint32_t index : this->m_puppetPartOrder) {
+	const auto& part = this->m_puppetParts[index];
+	indices.insert (
+	    indices.end (), this->m_puppetMeshIndices.begin () + part.firstIndex,
+	    this->m_puppetMeshIndices.begin () + part.firstIndex + part.indexCount
+	);
+    }
+
+    glBindBuffer (GL_ELEMENT_ARRAY_BUFFER, this->m_puppetIndices);
+    glBufferData (GL_ELEMENT_ARRAY_BUFFER, indices.size () * sizeof (GLushort), indices.data (), GL_DYNAMIC_DRAW);
+    this->m_puppetIndexCount = static_cast<GLsizei> (indices.size ());
+    this->m_puppetDrawCount = this->m_puppetIndexCount;
+}
+
 void CImage::updatePuppetSkinning () {
     if (!this->m_rig.poseAnimated || this->m_rig.boneModel.size () != this->m_rig.bones.size ()) {
 	return;
@@ -1637,6 +1721,7 @@ bool CImage::followsOutputSize () const {
 
 void CImage::addEffectPasses (const ImageEffect& effect) {
     const auto fboProvider = std::make_shared<FBOProvider> (this);
+    std::vector<std::shared_ptr<CFBO>> buffers;
 
     for (const auto& fbo : effect.effect->fbos) {
 	const auto created = fboProvider->create (
@@ -1649,8 +1734,12 @@ void CImage::addEffectPasses (const ImageEffect& effect) {
 	if (this->followsOutputSize ()) {
 	    this->getScene ().followOutputSize (created, fbo->scale);
 	}
+
+	buffers.push_back (created);
     }
 
+    this->registerEffectBuffers (effect, std::move (buffers));
+
     auto curEffect = effect.effect->passes.begin ();
     auto endEffect = effect.effect->passes.end ();
     auto curOverride = effect.passOverrides.begin ();

+ 6 - 0
src/WallpaperEngine/Render/Objects/CImage.h

@@ -197,6 +197,8 @@ private:
     void setupPuppetGeometryCallback (Effects::CPass* pass) const;
     /** The mask and clipping target passes of a puppet with clipping records, once the mesh pass exists */
     void setupPuppetClipping ();
+    /** sub_1401FDF90 end: sorts the parts by order + their bone's animated draw order, rebuilds the indices */
+    void updatePuppetDrawOrder ();
     /** The mesh pass's draw split up like WE's command list (sub_140208670) */
     void renderPuppetClipped (Effects::CPass* meshPass);
     /** sub_14020D6A0: one record's mask into _rt_FullAlphaMask, or multiplied into it through the intermediate */
@@ -236,6 +238,10 @@ private:
     bool m_puppetDrawKeep = false;
     std::optional<PuppetClipping> m_puppetClipping = std::nullopt;
     GLuint m_puppetClipIndices = GL_NONE;
+    /** mesh flag 8: the part ranges, the order the animated draw order put them in and the file's indices */
+    std::vector<PuppetClipping::Part> m_puppetParts = {};
+    std::vector<uint32_t> m_puppetPartOrder = {};
+    std::vector<uint16_t> m_puppetMeshIndices = {};
     /** clippingmaskimage4 per record, each with its mask texture */
     std::vector<Effects::CPass*> m_puppetClipMaskPasses = {};
     /** the mesh pass's material with CLIPPINGUVS and CLIPPINGTARGET */

+ 4 - 0
src/WallpaperEngine/Render/Objects/CParticle.cpp

@@ -4828,6 +4828,10 @@ void CParticle::copyRefractSource () const {
 	}
     }
 
+    if (source == getScene ().getFBO ()) {
+	getScene ().resolveMultisample ();
+    }
+
     const GLint sw = static_cast<GLint> (source->getRealWidth ());
     const GLint sh = static_cast<GLint> (source->getRealHeight ());
     const GLint dw = static_cast<GLint> (m_refractFBO->getRealWidth ());

+ 55 - 1
src/WallpaperEngine/Render/Objects/CRenderable.cpp

@@ -1,5 +1,6 @@
 #include "CRenderable.h"
 
+#include "WallpaperEngine/Data/Model/Effect.h"
 #include "WallpaperEngine/Data/Model/Material.h"
 #include "WallpaperEngine/Data/Model/Object.h"
 #include "WallpaperEngine/Data/Parsers/MaterialParser.h"
@@ -37,4 +38,57 @@ void CRenderable::setup () {
 
 std::shared_ptr<const TextureProvider> CRenderable::getTexture () const { return this->m_texture; }
 
-double CRenderable::getAnimationTime () const { return this->m_animationTime; }
+double CRenderable::getAnimationTime () const { return this->m_animationTime; }
+
+namespace {
+void clearBuffer (const CFBO& buffer, const glm::vec4& color) {
+    GLint previousFramebuffer = 0;
+    GLfloat previousClearColor[4] = {};
+    GLboolean previousColorMask[4] = {};
+    glGetIntegerv (GL_FRAMEBUFFER_BINDING, &previousFramebuffer);
+    glGetFloatv (GL_COLOR_CLEAR_VALUE, previousClearColor);
+    glGetBooleanv (GL_COLOR_WRITEMASK, previousColorMask);
+
+    glBindFramebuffer (GL_FRAMEBUFFER, buffer.getFramebuffer ());
+    glColorMask (GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
+    glClearColor (color.r, color.g, color.b, color.a);
+    glClear (GL_COLOR_BUFFER_BIT);
+
+    glClearColor (previousClearColor[0], previousClearColor[1], previousClearColor[2], previousClearColor[3]);
+    glColorMask (previousColorMask[0], previousColorMask[1], previousColorMask[2], previousColorMask[3]);
+    glBindFramebuffer (GL_FRAMEBUFFER, previousFramebuffer);
+}
+} // namespace
+
+void CRenderable::registerEffectBuffers (const ImageEffect& effect, std::vector<std::shared_ptr<CFBO>> buffers) {
+    for (size_t index = 0; index < buffers.size () && index < effect.effect->fbos.size (); index++) {
+	if (effect.effect->fbos[index]->clearOnCreate) {
+	    clearBuffer (*buffers[index], effect.effect->fbos[index]->clearColor);
+	}
+    }
+
+    this->m_effectBuffers.insert_or_assign (&effect, std::move (buffers));
+}
+
+bool CRenderable::executeEffectFunction (const ImageEffect& effect, const std::string& name) const {
+    const auto buffers = this->m_effectBuffers.find (&effect);
+
+    if (buffers == this->m_effectBuffers.end ()) {
+	return false;
+    }
+
+    const auto& functions = effect.effect->functions;
+    const auto function
+	= std::ranges::find_if (functions, [&name] (const EffectFunction& cur) { return cur.name == name; });
+
+    if (function == functions.end ()) {
+	return true;
+    }
+
+    // WE's own slip: the loop counter picks the buffer, not the index the name resolved to
+    for (size_t index = 0; index < function->fbos.size () && index < buffers->second.size (); index++) {
+	clearBuffer (*buffers->second[index], effect.effect->fbos[index]->clearColor);
+    }
+
+    return true;
+}

+ 10 - 0
src/WallpaperEngine/Render/Objects/CRenderable.h

@@ -34,6 +34,15 @@ public:
      *  shared clock (renderer +4908, sub_14015F0D0) */
     [[nodiscard]] virtual std::optional<int> getTextureFrameOverride () const { return std::nullopt; }
 
+    /** The buffers made for an effect's fbos, in their order; ones with a complete "clear" are cleared now */
+    void registerEffectBuffers (const ImageEffect& effect, std::vector<std::shared_ptr<CFBO>> buffers);
+    /**
+     * IEffect.executeMaterialFunction (wallpaper64.exe 2.8.42 sub_1401EE3A0): a "clear" function clears as many of
+     * the effect's buffers as it names, but always the first ones, each to its own clear color. False when the effect
+     * isn't one of this object's
+     */
+    bool executeEffectFunction (const ImageEffect& effect, const std::string& name) const;
+
 protected:
     void detectTexture ();
 
@@ -41,5 +50,6 @@ protected:
 
     std::shared_ptr<const TextureProvider> m_texture = nullptr;
     const Material& m_material;
+    std::map<const ImageEffect*, std::vector<std::shared_ptr<CFBO>>> m_effectBuffers = {};
 };
 }

+ 5 - 1
src/WallpaperEngine/Render/Objects/CText.cpp

@@ -915,10 +915,14 @@ void CText::buildPasses () {
 	}
 
 	const auto fboProvider = std::make_shared<FBOProvider> (this);
+	std::vector<std::shared_ptr<CFBO>> buffers;
+
 	for (const auto& fbo : effect->effect->fbos) {
-	    fboProvider->create (*fbo, TextureFlags_ClampUVs, fboSize);
+	    buffers.push_back (fboProvider->create (*fbo, TextureFlags_ClampUVs, fboSize));
 	}
 
+	this->registerEffectBuffers (*effect, std::move (buffers));
+
 	auto curOverride = effect->passOverrides.begin ();
 	const auto endOverride = effect->passOverrides.end ();
 

+ 11 - 1
src/WallpaperEngine/Render/Objects/Effects/CPass.cpp

@@ -292,7 +292,11 @@ void CPass::setupRenderFramebuffer () const {
 	: nullptr;
     const auto& target = layerTarget != nullptr ? layerTarget->fbo : this->m_drawTo;
 
-    glBindFramebuffer (GL_FRAMEBUFFER, target->getFramebuffer ());
+    glBindFramebuffer (
+	GL_FRAMEBUFFER,
+	target == this->m_renderable.getScene ().getFBO () ? this->m_renderable.getScene ().getSceneDrawFramebuffer ()
+							   : target->getFramebuffer ()
+    );
 
     // Private per-object FBOs are never cleared elsewhere, so a blending pass would otherwise
     // accumulate stale alpha across frames. The shared scene FBO must not be cleared here though,
@@ -490,6 +494,12 @@ void CPass::bindTextureUnit (int index, const std::shared_ptr<const TextureProvi
 	return;
     }
 
+    // reading the scene buffer while the objects draw multisampled gets what they drew so far, WE resolves the bound
+    // target into _rt_FullFrameBuffer (sub_1400D3310)
+    if (texture == this->m_renderable.getScene ().getFBO ()) {
+	this->m_renderable.getScene ().resolveMultisample ();
+    }
+
     glActiveTexture (GL_TEXTURE0 + index);
     glBindTexture (GL_TEXTURE_2D, texture->getTextureID (frame));
 }

+ 65 - 18
src/WallpaperEngine/Render/Objects/PuppetClipping.cpp

@@ -94,14 +94,9 @@ void linkParents (std::vector<PuppetClipping::Record>& records) {
 }
 } // namespace
 
-std::optional<PuppetClipping>
-PuppetClipping::read (const std::vector<char>& data, size_t offset, int version, size_t indexCount) {
-    if (version < 23) {
-	return std::nullopt;
-    }
-
-    Reader reader (data, offset);
-    PuppetClipping clipping;
+namespace {
+std::vector<PuppetClipping::Part> readPartRanges (Reader& reader, size_t indexCount) {
+    std::vector<PuppetClipping::Part> parts;
 
     if (reader.value<uint8_t> () != 0) {
 	reader.value<uint32_t> ();
@@ -112,8 +107,8 @@ PuppetClipping::read (const std::vector<char>& data, size_t offset, int version,
 	const auto bytes = reader.value<uint32_t> ();
 
 	for (uint32_t index = 0; index < bytes / 16; index++) {
-	    reader.value<uint32_t> ();
-	    reader.value<uint32_t> ();
+	    const auto bone = reader.value<uint32_t> ();
+	    const auto order = reader.value<uint32_t> ();
 	    const auto first = reader.value<uint32_t> ();
 	    const auto count = reader.value<uint32_t> ();
 
@@ -121,12 +116,37 @@ PuppetClipping::read (const std::vector<char>& data, size_t offset, int version,
 		throw std::runtime_error ("puppet part range is past the index buffer");
 	    }
 
-	    clipping.parts.push_back ({ .firstIndex = first, .indexCount = count });
+	    parts.push_back ({ .bone = bone, .order = order, .firstIndex = first, .indexCount = count });
 	}
 
 	reader.skip (bytes % 16);
     }
 
+    return parts;
+}
+} // namespace
+
+std::vector<PuppetClipping::Part>
+PuppetClipping::readParts (const std::vector<char>& data, size_t offset, int version, size_t indexCount) {
+    if (version < 21) {
+	return {};
+    }
+
+    Reader reader (data, offset);
+    return readPartRanges (reader, indexCount);
+}
+
+std::optional<PuppetClipping>
+PuppetClipping::read (const std::vector<char>& data, size_t offset, int version, size_t indexCount) {
+    if (version < 23) {
+	return std::nullopt;
+    }
+
+    Reader reader (data, offset);
+    PuppetClipping clipping;
+
+    clipping.parts = readPartRanges (reader, indexCount);
+
     const auto count = reader.value<uint32_t> ();
 
     for (uint32_t index = 0; index < count; index++) {
@@ -171,9 +191,36 @@ bool PuppetClipping::build (const std::vector<uint16_t>& meshIndices) {
     constexpr uint32_t Source = 0x8;
 
     const auto partCount = static_cast<int> (this->parts.size ());
+
+    if (this->order.size () != this->parts.size ()) {
+	this->order.resize (this->parts.size ());
+
+	for (uint32_t index = 0; index < this->order.size (); index++) {
+	    this->order[index] = index;
+	}
+    }
+
+    // sub_14020B720 walks the parts in their drawing order and finds them in the records by range index, so
+    // everything below works on positions in that order
+    std::vector<uint32_t> positionOf (this->parts.size (), 0);
+
+    for (uint32_t position = 0; position < this->order.size (); position++) {
+	positionOf[this->order[position]] = position;
+    }
+
+    std::vector<Record> records = this->records;
+
+    for (auto& record : records) {
+	for (auto* list : { &record.targets, &record.sources }) {
+	    for (auto& part : *list) {
+		part = positionOf[part];
+	    }
+	}
+    }
+
     std::vector<uint32_t> partFlags (this->parts.size (), 0);
 
-    for (const auto& record : this->records) {
+    for (const auto& record : records) {
 	for (const auto part : record.targets) {
 	    partFlags[part] |= Target;
 	}
@@ -192,11 +239,11 @@ bool PuppetClipping::build (const std::vector<uint16_t>& meshIndices) {
 	std::vector<uint32_t> targets;
     };
 
-    std::vector<Entry> entries (this->records.size ());
+    std::vector<Entry> entries (records.size ());
     std::set<uint32_t> hiddenSources;
 
-    for (size_t index = 0; index < this->records.size (); index++) {
-	const auto& record = this->records[index];
+    for (size_t index = 0; index < records.size (); index++) {
+	const auto& record = records[index];
 	auto& entry = entries[index];
 	entry.record = static_cast<uint32_t> (index);
 
@@ -229,7 +276,7 @@ bool PuppetClipping::build (const std::vector<uint16_t>& meshIndices) {
 
     // a nested mask can only be drawn once its ancestors' sources are
     for (size_t index = 0; index < entries.size (); index++) {
-	for (int parent = this->records[index].parent; parent != -1; parent = this->records[parent].parent) {
+	for (int parent = records[index].parent; parent != -1; parent = records[parent].parent) {
 	    entries[index].lastSource = std::max (entries[index].lastSource, entries[parent].lastSource);
 	}
     }
@@ -244,7 +291,7 @@ bool PuppetClipping::build (const std::vector<uint16_t>& meshIndices) {
 	Draw draw { .offset = static_cast<uint32_t> (this->indices.size ()), .count = 0 };
 
 	for (const auto part : list) {
-	    const auto& range = this->parts[part];
+	    const auto& range = this->parts[this->order[part]];
 	    this->indices.insert (
 		this->indices.end (), meshIndices.begin () + range.firstIndex,
 		meshIndices.begin () + range.firstIndex + range.indexCount
@@ -293,7 +340,7 @@ bool PuppetClipping::build (const std::vector<uint16_t>& meshIndices) {
 	    flush ();
 
 	    std::vector<int> chain;
-	    for (int parent = this->records[entry.record].parent; parent != -1; parent = this->records[parent].parent) {
+	    for (int parent = records[entry.record].parent; parent != -1; parent = records[parent].parent) {
 		chain.push_back (parent);
 	    }
 

+ 7 - 0
src/WallpaperEngine/Render/Objects/PuppetClipping.h

@@ -24,6 +24,9 @@ struct PuppetClipping {
     };
 
     struct Part {
+	/** bone whose MDLA v6 draw order track moves the part (mesh flag 8) */
+	uint32_t bone = 0;
+	uint32_t order = 0;
 	uint32_t firstIndex = 0;
 	uint32_t indexCount = 0;
     };
@@ -60,11 +63,15 @@ struct PuppetClipping {
      */
     static std::optional<PuppetClipping>
     read (const std::vector<char>& data, size_t offset, int version, size_t indexCount);
+    /** Only the part ranges (MDLV 21+), what the animated draw order sorts */
+    static std::vector<Part> readParts (const std::vector<char>& data, size_t offset, int version, size_t indexCount);
 
     /** Splits the mesh's indices into WE's draws and fills commands, false when the records can't be drawn here */
     bool build (const std::vector<uint16_t>& meshIndices);
 
     std::vector<Part> parts;
+    /** parts in drawing order (indices into parts), file order unless the draw order animates; build () walks it */
+    std::vector<uint32_t> order;
     std::vector<Record> records;
     std::vector<uint16_t> indices;
     std::vector<Draw> draws;

+ 112 - 6
src/WallpaperEngine/Render/Objects/PuppetRig.cpp

@@ -113,8 +113,11 @@ struct PuppetBoneSet {
     // MDLS v2+ records after the bones, every MDLA clip carries one track per entry of each
     uint32_t extraCount = 0;
     uint32_t constraintCount = 0;
+    std::vector<int> drawOrder;
 };
 
+void parsePuppetCapsules (const BinaryReader& reader, PuppetBoneSet& result, size_t nextSectionOffset);
+
 // Parses the MDLS bones (local bind-pose transforms, parent hierarchy and the per-bone physics JSON) and the
 // counts of the records after them that size the MDLA tracks. Inverse-bind matrices are derived from the bind
 // pose by walking the parent chain; the file's own copy is skipped.
@@ -265,12 +268,42 @@ PuppetBoneSet parsePuppetBones (const BinaryReader& reader, size_t mdlsOffset) {
 	}
     }
 
-    if (!reader.base ().good () || static_cast<size_t> (reader.base ().tellg ()) >= nextSectionOffset
-	|| reader.next () == 0) {
+    if (!reader.base ().good () || static_cast<size_t> (reader.base ().tellg ()) >= nextSectionOffset) {
 	reader.base ().clear ();
 	return result;
     }
 
+    if (reader.next () != 0) {
+	parsePuppetCapsules (reader, result, nextSectionOffset);
+    }
+
+    // then a flag byte and a per bone int (kept below the bone count, consumer not traced) and from MDLS v3 another
+    // flag byte and the bones' draw order
+    const auto atEnd = [&reader, nextSectionOffset] () {
+	return !reader.base ().good () || static_cast<size_t> (reader.base ().tellg ()) >= nextSectionOffset;
+    };
+
+    if (!atEnd () && reader.next () != 0) {
+	skip (static_cast<std::streamoff> (sizeof (uint32_t) * result.bones.size ()));
+    }
+
+    if (version >= 3 && !atEnd () && reader.next () != 0) {
+	result.drawOrder.resize (result.bones.size ());
+
+	for (int& order : result.drawOrder) {
+	    order = reader.nextInt ();
+	}
+    }
+
+    if (!reader.base ().good () || static_cast<size_t> (reader.base ().tellg ()) > nextSectionOffset) {
+	reader.base ().clear ();
+	result.drawOrder.clear ();
+    }
+
+    return result;
+}
+
+void parsePuppetCapsules (const BinaryReader& reader, PuppetBoneSet& result, size_t nextSectionOffset) {
     // a vec3 of extents and the capsule's frame in bone space (row-vector, row-major like the bind matrices)
     for (auto& bone : result.bones) {
 	for (int axis = 0; axis < 3; axis++) {
@@ -293,8 +326,6 @@ PuppetBoneSet parsePuppetBones (const BinaryReader& reader, size_t mdlsOffset) {
 	    bone.hasCapsule = false;
 	}
     }
-
-    return result;
 }
 
 // Resolves each bone's world transform by walking up the parent chain: the MDL format doesn't
@@ -464,10 +495,12 @@ std::vector<PuppetAnimationClip> parsePuppetAnimationClips (
 
 	clip.boneTracks.resize (boneCount);
 	clip.boneAnimated.assign (boneCount, true);
+	clip.boneFlags.assign (boneCount, 0);
 
 	for (uint32_t boneIndex = 0; boneIndex < boneCount && valid; boneIndex++) {
 	    // bit 0 keeps the bone out of this clip, the blend masks it (2.8.42 sub_140261880)
-	    clip.boneAnimated[boneIndex] = (reader.nextUInt32 () & 1) == 0;
+	    clip.boneFlags[boneIndex] = reader.nextUInt32 ();
+	    clip.boneAnimated[boneIndex] = (clip.boneFlags[boneIndex] & 1) == 0;
 	    const uint32_t trackBytes = reader.nextUInt32 ();
 
 	    if (trackBytes != sampleCount * 9 * sizeof (float)) {
@@ -544,8 +577,30 @@ std::vector<PuppetAnimationClip> parsePuppetAnimationClips (
 	    reader.base ().seekg (sizeof (uint32_t) * 6, std::ios::cur);
 	}
 
+	// a flag byte and one float track per bone, the bones' draw order offsets (clip +264)
 	if (version >= 6 && valid && reader.next () != 0) {
-	    skipFlaggedTracks (boneCount, sizeof (float));
+	    clip.drawOrderTracks.resize (boneCount);
+
+	    for (uint32_t boneIndex = 0; boneIndex < boneCount && valid; boneIndex++) {
+		(void)reader.nextUInt32 ();
+		const uint32_t trackBytes = reader.nextUInt32 ();
+
+		if (trackBytes != sampleCount * sizeof (float)) {
+		    valid = false;
+		    break;
+		}
+
+		auto& track = clip.drawOrderTracks[boneIndex];
+		track.resize (sampleCount);
+
+		for (float& sample : track) {
+		    sample = reader.nextFloat ();
+		}
+	    }
+
+	    if (!valid) {
+		clip.drawOrderTracks.clear ();
+	    }
 	}
 
 	clip.flags = flags;
@@ -681,6 +736,7 @@ void PuppetRig::load (const std::vector<char>& data, size_t mdlsOffset, uint32_t
     }
 
     this->bones = std::move (boneSet.bones);
+    this->boneDrawOrder = std::move (boneSet.drawOrder);
     this->boneModel = worldBind;
     this->physicsState.assign (this->bones.size (), {});
     this->hasPhysics
@@ -1211,6 +1267,56 @@ void PuppetRig::updatePose (const glm::mat4& objectWorld, PuppetRootMotionHost*
     // root motion may have moved the object, WE takes the world matrix again for the bones
     this->composePose (animatedParents, animatedLocals, host != nullptr ? host->rootMotionWorld () : objectWorld);
     this->updateMorphWeights (samples);
+    this->updateDrawOrder (samples);
+}
+
+void PuppetRig::updateDrawOrder (const std::vector<PuppetLayerSample>& samples) {
+    this->drawOrderTouched = false;
+
+    if (!this->drawOrderEnabled) {
+	return;
+    }
+
+    // every frame starts from the MDLS orders; a layer at full weight sets its clip's value for the frame it is on
+    // (no interpolation), a blended one lerps towards it by its weight, an additive one moves by (value - MDLS
+    // order) * weight without passing the value
+    this->drawOrder.assign (this->bones.size (), 0.0f);
+
+    for (size_t bone = 0; bone < this->bones.size () && bone < this->boneDrawOrder.size (); bone++) {
+	this->drawOrder[bone] = static_cast<float> (this->boneDrawOrder[bone]);
+    }
+
+    for (const auto& sample : samples) {
+	const auto& tracks = sample.clip->drawOrderTracks;
+	const bool direct = sample.weight == 1.0f && !sample.additive;
+
+	for (size_t bone = 0; bone < tracks.size () && bone < this->drawOrder.size (); bone++) {
+	    if (bone < sample.clip->boneFlags.size () && (sample.clip->boneFlags[bone] & 3) == 1) {
+		continue;
+	    }
+
+	    if (sample.frame0 >= tracks[bone].size ()) {
+		continue;
+	    }
+
+	    const float value = tracks[bone][sample.frame0];
+	    float& order = this->drawOrder[bone];
+
+	    if (direct) {
+		order = value;
+	    } else if (!sample.additive) {
+		order = (1.0f - sample.weight) * order + sample.weight * value;
+	    } else {
+		const float rest
+		    = bone < this->boneDrawOrder.size () ? static_cast<float> (this->boneDrawOrder[bone]) : 0.0f;
+		order = std::clamp (
+		    order + (value - rest) * sample.weight, std::min (order, value), std::max (order, value)
+		);
+	    }
+
+	    this->drawOrderTouched = true;
+	}
+    }
 }
 
 void PuppetRig::applyRootMotion (

+ 13 - 0
src/WallpaperEngine/Render/Objects/PuppetRig.h

@@ -57,6 +57,10 @@ struct PuppetAnimationClip {
     std::vector<std::vector<PuppetKeyframe>> boneTracks;
     /** per bone, false when its track flags have bit 0 set: the clip leaves that bone alone */
     std::vector<bool> boneAnimated;
+    /** per bone, the raw track flags; the float tracks below skip a bone when (flags & 3) == 1 */
+    std::vector<uint32_t> boneFlags;
+    /** MDLA v6, [bone][sample]: what gets added to the parts' draw order of that bone (mesh flag 8) */
+    std::vector<std::vector<float>> drawOrderTracks;
 
     /** a morph target's weight over the clip, one sample per frame like the bone tracks */
     struct MorphTrack {
@@ -192,6 +196,8 @@ public:
      */
     void updatePose (const glm::mat4& objectWorld, PuppetRootMotionHost* host = nullptr);
     void updateMorphWeights (const std::vector<PuppetLayerSample>& samples);
+    /** sub_1401FDF90 for meshes with flag 8: every bone's draw order from MDLS, moved by the layers' v6 tracks */
+    void updateDrawOrder (const std::vector<PuppetLayerSample>& samples);
     /** sub_140225900 for one model layer after its blend, rest is what the layers above leave of it */
     void applyRootMotion (
 	PuppetActiveAnimation& layer, const PuppetLayerSample& sample, std::vector<glm::vec3>& positions,
@@ -225,6 +231,13 @@ public:
     /** per mesh, rebuilt by every updatePose () (sub_14021C480) */
     std::vector<PuppetMorphWeights> morphWeights = {};
     size_t morphSection = 0;
+    /** MDLS v3+ per bone order (instance +496), added to the order of every part of that bone */
+    std::vector<int> boneDrawOrder = {};
+    /** set by the image for a mesh with flag 8: the pose update then keeps drawOrder (instance +640) */
+    bool drawOrderEnabled = false;
+    std::vector<float> drawOrder = {};
+    /** a layer wrote drawOrder this frame, the parts get sorted again */
+    bool drawOrderTouched = false;
     /** the bones in model space (WE images P+712), starts at the bind pose */
     std::vector<glm::mat4> boneModel = {};
     /** this frame's local matrices (P+784) and scene matrices (P+832), empty until the first update */

+ 8 - 1
src/WallpaperEngine/Render/TextureCache.cpp

@@ -20,6 +20,7 @@
 #include <fstream>
 #include <iterator>
 
+#include "GifAnimation.h"
 #include "ImageDecoder.h"
 
 #include <lz4.h>
@@ -167,6 +168,11 @@ TextureUniquePtr buildRawTexture (const std::string& filename, const std::string
 	}
     }
 
+    // wallpaper64.exe 2.8.42 sub_1400EB570 animates a file by its extension, a GIF under any other name loads as a
+    // still image. The texture is the GIF's logical screen and gets texture flag 1, point sampling
+    const bool animatedGif = !video && lowerExtension (filename) == ".gif"
+	&& GifAnimation::canvasSize (contents.data (), contents.size (), width, height);
+
     auto mipmap = std::make_shared<Mipmap> ();
 
     mipmap->width = width;
@@ -179,13 +185,14 @@ TextureUniquePtr buildRawTexture (const std::string& filename, const std::string
 
     result->containerVersion = ContainerVersion_TEXB0003;
     result->format = TextureFormat_ARGB8888;
-    result->flags = TextureFlags_ClampUVs;
+    result->flags = animatedGif ? TextureFlags_ClampUVs | TextureFlags_NoInterpolation : TextureFlags_ClampUVs;
     result->width = width;
     result->height = height;
     result->textureWidth = width;
     result->textureHeight = height;
     result->freeImageFormat = video ? FIF_MP4 : FIF_PNG;
     result->isVideoMp4 = video;
+    result->isAnimatedGif = animatedGif;
     result->imageCount = 1;
     result->images.emplace (0, MipmapList { mipmap });
 

+ 137 - 2
src/WallpaperEngine/Render/Wallpapers/CScene.cpp

@@ -119,6 +119,12 @@ CScene::CScene (
 
     this->followOutputSize (this->find ("_rt_FullFrameBuffer"), 1);
 
+    // wallpaper64.exe 2.8.42 sub_14010DF40 flags a scene when an object has a "model", only then the device gets the
+    // msaa setting's sample count (sub_140110630, sub_14012AC60) and sub_140181AF0 makes the multisampled target
+    if (hasModels) {
+	this->m_msaaSamples = this->getContext ().getApp ().getContext ().settings.general.msaaSamples;
+    }
+
     const uint32_t sceneWidth = this->m_camera->getCanvasWidth ();
     const uint32_t sceneHeight = this->m_camera->getCanvasHeight ();
 
@@ -238,6 +244,7 @@ CScene::~CScene () {
     }
 
     this->releaseHDRBloom ();
+    this->releaseMultisample ();
 
     for (const GLuint program : { this->m_bloomDownsample, this->m_bloomDownsampleThreshold, this->m_bloomUpsample,
 				  this->m_bloomUpsampleCubic, this->m_bloomCombine }) {
@@ -495,6 +502,14 @@ void CScene::renderFrameSteps (const glm::ivec4& viewport) {
     glBindFramebuffer (GL_FRAMEBUFFER, this->getWallpaperFramebuffer ());
     glViewport (0, 0, this->m_sceneFBO->getRealWidth (), this->m_sceneFBO->getRealHeight ());
 
+    // sub_140183550: the objects draw into _rt_FullFrameBufferMultiSampled, which resolves into the scene buffer
+    // once they are done
+    this->m_msaaActive = this->m_msaaSamples > 1 && this->prepareMultisample ();
+
+    if (this->m_msaaActive) {
+	glBindFramebuffer (GL_FRAMEBUFFER, this->m_msaaFramebuffer);
+    }
+
     // passes leave their own depthwrite and color mask behind, and glClear skips masked channels. Layer
     // composites write rgb only, so the alpha would otherwise never get reset to 1 and fullscreen layers,
     // which copy the scene and blend back with its alpha, would come out invisible
@@ -529,6 +544,12 @@ void CScene::renderFrameSteps (const glm::ivec4& viewport) {
 
     this->m_volumetrics->composite ();
 
+    if (this->m_msaaActive) {
+	this->resolveMultisample ();
+	this->m_msaaActive = false;
+	glBindFramebuffer (GL_FRAMEBUFFER, this->m_sceneFBO->getFramebuffer ());
+    }
+
     if (this->m_bloomObject == nullptr) {
 	this->updateMipMappedFrameBuffer ();
     }
@@ -580,7 +601,7 @@ void CScene::paintLetterbox () const {
     const GLint top = std::clamp (rowOf (height), 0, static_cast<GLint> (bufferHeight));
     const glm::vec4& color = this->getCornerColor ();
 
-    glBindFramebuffer (GL_FRAMEBUFFER, this->m_sceneFBO->getFramebuffer ());
+    glBindFramebuffer (GL_FRAMEBUFFER, this->getSceneDrawFramebuffer ());
     glColorMask (GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE);
     glClearColor (color.r, color.g, color.b, color.a);
     glEnable (GL_SCISSOR_TEST);
@@ -1002,6 +1023,119 @@ void CScene::renderReflection () {
     }
 }
 
+void CScene::executeEffectFunction (const ImageEffect& effect, const std::string& name) const {
+    for (const auto* object : this->m_objects | std::views::values) {
+	if (object->is<Objects::CRenderable> ()
+	    && object->as<Objects::CRenderable> ()->executeEffectFunction (effect, name)) {
+	    return;
+	}
+    }
+}
+
+GLuint CScene::getSceneDrawFramebuffer () const {
+    return this->m_msaaActive ? this->m_msaaFramebuffer : this->m_sceneFBO->getFramebuffer ();
+}
+
+bool CScene::prepareMultisample () {
+    const glm::ivec2 size (this->m_sceneFBO->getRealWidth (), this->m_sceneFBO->getRealHeight ());
+
+    if (this->m_msaaFramebuffer != GL_NONE && size == this->m_msaaSize) {
+	return true;
+    }
+
+    this->releaseMultisample ();
+    this->m_msaaSize = size;
+
+    // same color format as the scene buffer (sub_140181AF0: RGBA8, RGBA16F in HDR), a resolve needs it
+    GLint colorFormat = GL_RGBA8;
+    GLint maxSamples = 0;
+    glBindTexture (GL_TEXTURE_2D, this->m_sceneFBO->getTextureID (0));
+    glGetTexLevelParameteriv (GL_TEXTURE_2D, 0, GL_TEXTURE_INTERNAL_FORMAT, &colorFormat);
+    glGetIntegerv (GL_MAX_SAMPLES, &maxSamples);
+
+    // the device check (CheckMultisampleQualityLevels in sub_14012AC60) falls back to one sample, no MSAA
+    if (this->m_msaaSamples > maxSamples) {
+	sLog.error (
+	    "MSAA x", this->m_msaaSamples, " is not supported here (at most ", maxSamples, "), drawing without"
+	);
+	this->m_msaaSamples = 0;
+	return false;
+    }
+
+    glGenRenderbuffers (1, &this->m_msaaColor);
+    glBindRenderbuffer (GL_RENDERBUFFER, this->m_msaaColor);
+    glRenderbufferStorageMultisample (GL_RENDERBUFFER, this->m_msaaSamples, colorFormat, size.x, size.y);
+
+    if (this->m_sceneFBO->getDepthbuffer () != GL_NONE) {
+	glGenRenderbuffers (1, &this->m_msaaDepth);
+	glBindRenderbuffer (GL_RENDERBUFFER, this->m_msaaDepth);
+	glRenderbufferStorageMultisample (GL_RENDERBUFFER, this->m_msaaSamples, GL_DEPTH_COMPONENT24, size.x, size.y);
+    }
+
+    glBindRenderbuffer (GL_RENDERBUFFER, 0);
+    glGenFramebuffers (1, &this->m_msaaFramebuffer);
+    glBindFramebuffer (GL_FRAMEBUFFER, this->m_msaaFramebuffer);
+    glFramebufferRenderbuffer (GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, this->m_msaaColor);
+
+    if (this->m_msaaDepth != GL_NONE) {
+	glFramebufferRenderbuffer (GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, this->m_msaaDepth);
+    }
+
+    const bool complete = glCheckFramebufferStatus (GL_FRAMEBUFFER) == GL_FRAMEBUFFER_COMPLETE;
+
+    glBindFramebuffer (GL_FRAMEBUFFER, this->m_sceneFBO->getFramebuffer ());
+
+    if (!complete) {
+	sLog.error ("Cannot create the MSAA x", this->m_msaaSamples, " scene buffer, drawing without");
+	this->releaseMultisample ();
+	this->m_msaaSamples = 0;
+	return false;
+    }
+
+#if !NDEBUG
+    glObjectLabel (GL_FRAMEBUFFER, this->m_msaaFramebuffer, -1, "_rt_FullFrameBufferMultiSampled");
+#endif
+
+    return true;
+}
+
+void CScene::releaseMultisample () {
+    if (this->m_msaaFramebuffer != GL_NONE) {
+	glDeleteFramebuffers (1, &this->m_msaaFramebuffer);
+    }
+
+    if (this->m_msaaColor != GL_NONE) {
+	glDeleteRenderbuffers (1, &this->m_msaaColor);
+    }
+
+    if (this->m_msaaDepth != GL_NONE) {
+	glDeleteRenderbuffers (1, &this->m_msaaDepth);
+    }
+
+    this->m_msaaFramebuffer = this->m_msaaColor = this->m_msaaDepth = GL_NONE;
+}
+
+void CScene::resolveMultisample () const {
+    if (!this->m_msaaActive) {
+	return;
+    }
+
+    GLint readFramebuffer = 0;
+    GLint drawFramebuffer = 0;
+    glGetIntegerv (GL_READ_FRAMEBUFFER_BINDING, &readFramebuffer);
+    glGetIntegerv (GL_DRAW_FRAMEBUFFER_BINDING, &drawFramebuffer);
+
+    const GLbitfield mask = GL_COLOR_BUFFER_BIT | (this->m_msaaDepth != GL_NONE ? GL_DEPTH_BUFFER_BIT : 0);
+
+    glBindFramebuffer (GL_READ_FRAMEBUFFER, this->m_msaaFramebuffer);
+    glBindFramebuffer (GL_DRAW_FRAMEBUFFER, this->m_sceneFBO->getFramebuffer ());
+    glBlitFramebuffer (
+	0, 0, this->m_msaaSize.x, this->m_msaaSize.y, 0, 0, this->m_msaaSize.x, this->m_msaaSize.y, mask, GL_NEAREST
+    );
+    glBindFramebuffer (GL_READ_FRAMEBUFFER, readFramebuffer);
+    glBindFramebuffer (GL_DRAW_FRAMEBUFFER, drawFramebuffer);
+}
+
 void CScene::updateMipMappedFrameBuffer () const {
     if (this->_rt_MipMappedFrameBuffer == nullptr) {
 	return;
@@ -1010,11 +1144,12 @@ void CScene::updateMipMappedFrameBuffer () const {
     const auto width = static_cast<GLint> (this->m_sceneFBO->getRealWidth ());
     const auto height = static_cast<GLint> (this->m_sceneFBO->getRealHeight ());
 
+    this->resolveMultisample ();
     glBindFramebuffer (GL_READ_FRAMEBUFFER, this->m_sceneFBO->getFramebuffer ());
     glBindFramebuffer (GL_DRAW_FRAMEBUFFER, this->_rt_MipMappedFrameBuffer->getFramebuffer ());
     glBlitFramebuffer (0, 0, width, height, 0, 0, width, height, GL_COLOR_BUFFER_BIT, GL_NEAREST);
     this->_rt_MipMappedFrameBuffer->generateMipmaps ();
-    glBindFramebuffer (GL_FRAMEBUFFER, this->m_sceneFBO->getFramebuffer ());
+    glBindFramebuffer (GL_FRAMEBUFFER, this->getSceneDrawFramebuffer ());
 }
 
 void CScene::releaseHDRBloom () {

+ 19 - 0
src/WallpaperEngine/Render/Wallpapers/CScene.h

@@ -162,6 +162,15 @@ public:
 	bool viewProjectionApplied = false;
     };
     [[nodiscard]] const LayerTarget* getLayerTarget () const;
+    /**
+     * While the objects draw multisampled (_rt_FullFrameBufferMultiSampled), the framebuffer that stands in for the
+     * scene buffer, otherwise the scene buffer's own
+     */
+    [[nodiscard]] GLuint getSceneDrawFramebuffer () const;
+    /** Resolves the multisampled objects into the scene buffer, for anything about to read it (WE sub_1400D3310) */
+    void resolveMultisample () const;
+    /** IEffect.executeMaterialFunction on whichever object owns the effect */
+    void executeEffectFunction (const ImageEffect& effect, const std::string& name) const;
     /** Under a passthrough layer, which draws the object into its own buffer instead of the scene (object flag 2) */
     [[nodiscard]] bool isDrawnByPassthroughLayer (const CObject& object) const;
     /** Draws the objects under a passthrough layer into target, WE's order and visibility rules (sub_1401ECB20) */
@@ -309,6 +318,9 @@ private:
     void updateMipMappedFrameBuffer () const;
     /** The scene mirrored on the world's y = 0 plane into _rt_Reflection, before the main pass */
     void renderReflection ();
+    /** Sizes _rt_FullFrameBufferMultiSampled like the scene buffer, false when the driver can't make it */
+    bool prepareMultisample ();
+    void releaseMultisample ();
     /** --corner-color over the parts of the output a letterboxing alignment leaves uncovered */
     void paintLetterbox () const;
     void updateFog (const glm::vec3& eye);
@@ -421,6 +433,13 @@ private:
     std::shared_ptr<CFBO> _rt_FullAlphaMask = nullptr;
     std::shared_ptr<CFBO> _rt_FullAlphaMaskIntermediate = nullptr;
     std::set<int> m_reflectionReceivers = {};
+    /** Sample count of _rt_FullFrameBufferMultiSampled, 0 without it */
+    int m_msaaSamples = 0;
+    bool m_msaaActive = false;
+    GLuint m_msaaFramebuffer = GL_NONE;
+    GLuint m_msaaColor = GL_NONE;
+    GLuint m_msaaDepth = GL_NONE;
+    glm::ivec2 m_msaaSize = {};
     bool m_renderingReflection = false;
     struct OutputSizedBuffer {
 	std::weak_ptr<CFBO> fbo;

+ 9 - 2
src/WallpaperEngine/Scripting/Adapters/ScriptableObjectAdapter.cpp

@@ -440,6 +440,7 @@ void textureanimation_call (const v8::FunctionCallbackInfo<v8::Value>& info, int
 enum EffectCall {
     EffectGetMaterialCount,
     EffectGetAnimation,
+    EffectExecuteMaterialFunction,
 };
 
 // IEffect methods; getMaterialCount (sub_1401EE1A0) counts the effect's materials, one per pass
@@ -450,6 +451,10 @@ void effect_method (const v8::FunctionCallbackInfo<v8::Value>& info, int call) {
 	info.GetReturnValue ().Set (
 	    effect->effect != nullptr ? static_cast<int32_t> (effect->effect->passes.size ()) : 0
 	);
+    } else if (call == EffectExecuteMaterialFunction && effect->effect != nullptr) {
+	const std::string name = info[0]->IsString () ? JS::toString (info.GetIsolate (), info[0]) : std::string ();
+
+	engineOf (info).getScene ().executeEffectFunction (*effect, name);
     }
 }
 
@@ -1808,8 +1813,8 @@ v8::Local<v8::Value> ScriptableObjectAdapter::effect (ImageEffect& effect) {
 	return it->second.Get (isolate);
     }
 
-    // IEffect (wallpaper64 2.8.42 sub_1401EFCA0) in the order live WE lists it. getMaterial, setMaterialProperty and
-    // executeMaterialFunction aren't there yet
+    // IEffect (wallpaper64 2.8.42 sub_1401EFCA0) in the order live WE lists it. getMaterial and setMaterialProperty
+    // aren't there yet
     auto& engine = this->m_engine;
     std::vector<NativeProperty> properties = {
 	{ .name = "name",
@@ -1833,6 +1838,8 @@ v8::Local<v8::Value> ScriptableObjectAdapter::effect (ImageEffect& effect) {
 
     const auto data = JS::external (isolate, &effect);
     const std::vector<std::pair<std::string, v8::Local<v8::Function>>> methods = {
+	{ "executeMaterialFunction",
+	  JS::function (context, JS::bind<effect_method, EffectExecuteMaterialFunction>, data) },
 	{ "getMaterialCount", JS::function (context, JS::bind<effect_method, EffectGetMaterialCount>, data) },
 	{ "getAnimation", JS::function (context, JS::bind<effect_method, EffectGetAnimation>, data) },
     };

+ 161 - 0
tools/tex_scan.py

@@ -0,0 +1,161 @@
+#!/usr/bin/env python3
+"""Counts what the installed .tex files use, read like wallpaper64.exe 2.8.42's loader (sub_14015E580).
+
+Usage:
+    tex_scan.py [workshop dir] [more dirs...]
+
+Defaults to the Steam workshop folder of Wallpaper Engine plus WE's own assets. Looks at every .tex inside
+scene.pkg/general.pkg files and loose .tex files. Prints the container/section versions (TEXV, TEXI, TEXB, TEXS),
+texture formats, flag bits and FreeImage types, each with up to five items that have it. Use it before porting
+a texture feature to see whether the library has it at all.
+"""
+import os
+import struct
+import sys
+from collections import defaultdict
+
+DEFAULT_DIRS = [
+    '/workspace/SteamLibrary/steamapps/workshop/content/431960',
+    '/workspace/SteamLibrary/steamapps/common/wallpaper_engine/assets',
+]
+
+FORMATS = {
+    0: 'ARGB8888', 1: 'RGB888', 2: 'RGB565', 4: 'DXT5', 6: 'DXT3', 7: 'DXT1', 8: 'RG88', 9: 'R8',
+    10: 'RG1616f', 11: 'R16f', 12: 'BC7', 13: 'RGBa1010102', 14: 'RGBA16161616f', 15: 'RGB161616f',
+}
+
+
+def cstring(data, pos):
+    end = data.find(b'\0', pos)
+    if end < 0:
+        return None, len(data)
+    return data[pos:end].decode('latin-1'), end + 1
+
+
+def u32(data, pos):
+    if pos + 4 > len(data):
+        return 0, pos
+    return struct.unpack_from('<I', data, pos)[0], pos + 4
+
+
+def scan_tex(data, found, item):
+    def note(key):
+        if len(found[key]) < 5:
+            found[key].add(item)
+        counts[key] += 1
+
+    magic, pos = cstring(data, 0)
+    note(f'container {magic}')
+
+    if magic not in ('TEXV0005', 'TEXV0004'):
+        return
+
+    # TEXV0004: version 0 TEXI fields and version 0 TEXB body, no tags
+    if magic == 'TEXV0004':
+        sections = [('TEXI', 0), ('TEXB', 0)]
+    else:
+        sections = None
+
+    def read_texi(pos, version):
+        fmt, pos = u32(data, pos)
+        flags, pos = u32(data, pos)
+        pos += 16
+        if flags & 0x40:
+            pos += 4
+        if version >= 1:
+            pos += 4
+        note(f'format {fmt} {FORMATS.get(fmt, "?")}')
+        for bit in range(32):
+            if flags & (1 << bit):
+                note(f'flag 0x{1 << bit:x}')
+        return pos, flags
+
+    flags = 0
+
+    if sections:
+        pos, flags = read_texi(pos, 0)
+        note('TEXB version 0 (TEXV0004)')
+        return
+
+    while pos < len(data):
+        tag, pos = cstring(data, pos)
+        if not tag or len(tag) < 4:
+            break
+        version = int(tag[4:]) if tag[4:].isdigit() else -1
+        if tag.startswith('TEXI'):
+            note(f'section {tag}')
+            pos, flags = read_texi(pos, version)
+        elif tag.startswith('TEXB'):
+            note(f'section {tag}')
+            if version >= 1:
+                images, pos = u32(data, pos)
+                if images > 1:
+                    note('several images')
+            if version >= 3:
+                fif, pos = u32(data, pos)
+                note(f'freeimage {fif:#x}' if fif != 0xFFFFFFFF else 'freeimage none')
+            if version >= 4:
+                conditions, pos = u32(data, pos)
+                if conditions:
+                    note(f'TEXB0004 conditions={min(conditions, 2)}{"+" if conditions > 2 else ""}')
+            # the mip data follows, TEXS comes after it but its offset isn't stored: look for the tag
+            texs = data.find(b'TEXS', pos)
+            if texs < 0:
+                break
+            pos = texs
+        elif tag.startswith('TEXS'):
+            note(f'section {tag}')
+            break
+        else:
+            note(f'unknown section {tag}')
+            break
+
+
+counts = defaultdict(int)
+
+
+def scan_pkg(path, found, item):
+    with open(path, 'rb') as f:
+        data = f.read()
+    n, pos = u32(data, 0)
+    header = data[4:4 + n].decode('latin-1', 'replace')
+    if not header.startswith('PKGV'):
+        return
+    pos = 4 + n
+    count, pos = u32(data, pos)
+    entries = []
+    for _ in range(count):
+        n, pos = u32(data, pos)
+        name = data[pos:pos + n].decode('utf-8', 'replace')
+        pos += n
+        offset, pos = u32(data, pos)
+        length, pos = u32(data, pos)
+        entries.append((name, offset, length))
+    base = pos
+    for name, offset, length in entries:
+        if name.lower().endswith('.tex'):
+            scan_tex(data[base + offset:base + offset + length], found, item)
+
+
+def main():
+    dirs = sys.argv[1:] or DEFAULT_DIRS
+    found = defaultdict(set)
+
+    for root_dir in dirs:
+        for root, _, files in os.walk(root_dir):
+            rel = os.path.relpath(root, root_dir)
+            item = rel.split(os.sep)[0] if rel != '.' else os.path.basename(root_dir)
+            for name in files:
+                path = os.path.join(root, name)
+                if name.endswith('.pkg'):
+                    scan_pkg(path, found, item)
+                elif name.lower().endswith('.tex'):
+                    with open(path, 'rb') as f:
+                        scan_tex(f.read(), found, item)
+
+    for key in sorted(counts):
+        print(f'{counts[key]:7d}  {key:32s} {" ".join(sorted(found[key]))}')
+
+
+if __name__ == '__main__':
+    main()