From 0adb0f89bcb8eff742533643e97b5c8e8d04583f Mon Sep 17 00:00:00 2001 From: shweet Date: Thu, 8 Oct 2026 17:16:49 -0400 Subject: [PATCH] Frame Blur (Flash's blur filter), child properties in Change All Frame Properties, flips under Visible Blur is a layer frame's box blur, as Flash's low-quality BlurFilter: a box that many canvas pixels wide, averaged over the frame's crop (premultiplied) by the texture shader, the quad grown by its reach. An animation layer blurs its child's draws at least as much. It interpolates, copies, batches (clamped to 0-255), saves as an editor-only Blur attribute and counts as an Isaac issue. Change All Frame Properties gains the Child section (animation, mode, start frame, random, restart), applied only to animation layers and disabled when no animation layer is targeted. Frame Properties' Flip X/Y sit below Visible instead of inside Child. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- src/canvas.cpp | 36 +++++++-- src/canvas.hpp | 11 ++- src/cli.cpp | 4 +- src/edit/content.cpp | 10 ++- src/edit/edit.hpp | 1 + src/edit/frames.cpp | 5 +- src/imgui/taskbar.cpp | 1 + src/imgui/window/animation_preview.cpp | 6 +- src/imgui/window/frame_properties.cpp | 48 ++++++----- src/imgui/window/timeline/menus.cpp | 6 +- .../wizard/change_all_frame_properties.cpp | 81 +++++++++++++++++-- .../wizard/change_all_frame_properties.hpp | 1 + src/model/common.hpp | 10 ++- src/model/draw.cpp | 1 + src/model/frames.cpp | 11 ++- src/model/frames.hpp | 2 +- src/model/model.hpp | 1 + src/model/xml.cpp | 5 +- src/model/xml.hpp | 1 + src/resource/shader.hpp | 30 +++++++ src/resource/strings.hpp | 4 + src/settings.hpp | 12 +++ tests/draw.cpp | 19 +++++ tests/operations.cpp | 24 ++++++ tests/render/render.cpp | 24 ++++++ 26 files changed, 308 insertions(+), 48 deletions(-) diff --git a/README.md b/README.md index 0cbf317..4dad572 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ This application was developed with the assistance of a large language model. - Dockable [Dear ImGui](https://github.com/ocornut/imgui) interface (windows can be detached into their own) with persistent layout, drag and drop, context menus and rebindable shortcuts. - Timeline: multi-select, cut/copy/paste (whole frames or single properties), duplicate, split, bake, drag to move/resize, and start/end markers to loop a range. - Groups for animations, layers and nulls, with group transforms baked for the game on save. -- Frame properties for crop, size, position, pivot, scale, skew, rotation, tint, color offset, region, shader, visibility, interpolation (including easing) and flips; batch changes across selections. +- Frame properties for crop, size, position, pivot, scale, skew, rotation, tint, color offset, blur (Flash's blur filter), region, shader, visibility, interpolation (including easing) and flips; batch changes across selections. - Spritesheet editor with pan, move, crop, draw, erase and color picker tools; regions; packing, merging, trimming; automatic reload when files change on disk. - Animation preview with grid, axes, pivots, borders, onionskin (with pivot paths), and another document's animation as an overlay. - Wizards: generate animations from a grid, generate regions, change all frame properties, merge animations and files. diff --git a/src/canvas.cpp b/src/canvas.cpp index 075c09d..3a36e3f 100644 --- a/src/canvas.cpp +++ b/src/canvas.cpp @@ -207,13 +207,18 @@ namespace anm2ed } void Canvas::texture_render(Shader& shader, GLuint texture, mat4 transform, vec4 tint, vec3 colorOffset, - float* vertices, vec2 textureSize, float playbackTime) const + float* vertices, vec2 textureSize, float playbackTime, TextureBlur blur) const { canvas_blend_premultiplied_set(); glUseProgram(shader.id); texture_uniforms_set(shader, transform, tint, colorOffset, textureSize, playbackTime); + // The editor's own texture shader blurs; a custom shader without these uniforms ignores them. + glUniform1f(glGetUniformLocation(shader.id, shader::UNIFORM_BLUR), blur.radius); + glUniform4fv(glGetUniformLocation(shader.id, shader::UNIFORM_REGION), 1, value_ptr(blur.region)); + glUniform2fv(glGetUniformLocation(shader.id, shader::UNIFORM_TEXEL), 1, + value_ptr(textureSize.x > 0 && textureSize.y > 0 ? 1.0f / textureSize : vec2())); glVertexAttrib4fv(2, value_ptr(tint)); glBindVertexArray(textureVAO); @@ -271,6 +276,28 @@ namespace anm2ed rect_end(rectVAO, mode, count); } + // A layer draw's crop of its spritesheet. A blurred one (Flash's BlurFilter: a box `blur` canvas pixels wide) grows by + // the box's reach, in texels at the draw's scale, and averages its crop over it. + void Canvas::layer_render(Shader& shader, GLuint texture, vec2 textureSize, const mat4& transform, + const model::Draw& draw, vec4 tint, vec3 colorOffset) const + { + auto blurred = draw; + auto& frame = blurred.frame; + TextureBlur blur{.region = vec4(frame.crop, frame.crop + frame.size) / vec4(textureSize, textureSize)}; + if (frame.blur > 0.0f && frame.size.x > 0.0f && frame.size.y > 0.0f) + { + auto canvasArea = std::abs(glm::determinant(glm::mat2(draw.parent * model::draw_quad_model_get(draw)))); + auto canvasPerTexel = std::sqrt(canvasArea / (frame.size.x * frame.size.y)); + blur.radius = canvasPerTexel > 0.0f ? std::round(frame.blur * 0.5f / canvasPerTexel) : 0.0f; + frame.crop -= blur.radius; + frame.size += blur.radius * 2.0f; + frame.pivot += blur.radius; + } + auto vertices = math::uv_vertices_get(frame.crop / textureSize, (frame.crop + frame.size) / textureSize); + texture_render(shader, texture, transform * blurred.parent * model::draw_quad_model_get(blurred), tint, colorOffset, + vertices.data(), textureSize, draw.time, blur); + } + // An animation's layers alone (no markers or helpers); spritesheet images are looked up by draw, custom shaders by id. void Canvas::layers_render(Shader& shader, const model::Model& model, const model::Animation& animation, const model::DrawOptions& options, const mat4& transform, @@ -283,12 +310,9 @@ namespace anm2ed auto& frame = draw.frame; auto image = image_get(draw); if (!image || !image->is_valid() || frame.size == vec2()) continue; - auto imageSize = vec2(image->size); - auto uvVertices = math::uv_vertices_get(frame.crop / imageSize, (frame.crop + frame.size) / imageSize); auto customShader = shader_get ? shader_get(frame.shaderId) : nullptr; - texture_render(customShader ? *customShader : shader, texture::id_get(*image), - transform * draw.parent * model::draw_quad_model_get(draw), frame.tint, frame.colorOffset, - uvVertices.data(), imageSize, draw.time); + layer_render(customShader ? *customShader : shader, texture::id_get(*image), vec2(image->size), transform, draw, + frame.tint, frame.colorOffset); } } diff --git a/src/canvas.hpp b/src/canvas.hpp index c5f4c86..fa7f59a 100644 --- a/src/canvas.hpp +++ b/src/canvas.hpp @@ -15,6 +15,13 @@ namespace anm2ed { + // A box blur `radius` texels wide each way over the texture's `region` (UV min, max); outside it is clear. + struct TextureBlur + { + float radius{}; + glm::vec4 region{}; + }; + class Canvas : public Framebuffer { public: @@ -66,7 +73,9 @@ namespace anm2ed void grid_render(resource::Shader&, float, glm::vec2, glm::ivec2 = glm::ivec2(32, 32), glm::ivec2 = {}, glm::vec4 = glm::vec4(1.0f)) const; void texture_render(resource::Shader&, GLuint, glm::mat4 = {1.0f}, glm::vec4 = glm::vec4(1.0f), glm::vec3 = {}, - float* = (float*)TEXTURE_VERTICES, glm::vec2 = {}, float = 0.0f) const; + float* = (float*)TEXTURE_VERTICES, glm::vec2 = {}, float = 0.0f, TextureBlur = {}) const; + void layer_render(resource::Shader&, GLuint, glm::vec2, const glm::mat4&, const model::Draw&, glm::vec4, + glm::vec3) const; void rect_fill_render(resource::Shader&, const glm::mat4&, const glm::mat4&, glm::vec4 = glm::vec4(1.0f)) const; void layers_render(resource::Shader&, const model::Model&, const model::Animation&, const model::DrawOptions&, const glm::mat4&, const std::function&, diff --git a/src/cli.cpp b/src/cli.cpp index 450e7a9..0ab562d 100644 --- a/src/cli.cpp +++ b/src/cli.cpp @@ -179,9 +179,9 @@ options: auto issues = model::isaac_issues_get(model); std::println("isaac issues: {} eased frames, {} group transforms, {} skewed frames, {} shader frames, {} depth " - "frames, {} trigger sounds, {} animation layers", + "frames, {} blurred frames, {} trigger sounds, {} animation layers", issues.easedFrames, issues.groupTransforms, issues.skewFrames, issues.shaderFrames, issues.depthFrames, - issues.triggerSounds, issues.animationLayers); + issues.blurFrames, issues.triggerSounds, issues.animationLayers); return 0; } diff --git a/src/edit/content.cpp b/src/edit/content.cpp index 01b48b3..bd6d06e 100644 --- a/src/edit/content.cpp +++ b/src/edit/content.cpp @@ -191,16 +191,22 @@ namespace anm2ed::edit index < 0 ? (void)wholeTracks.insert(reference) : (void)frames[reference].insert(index); } + auto is_animation_layer = [&](const Track& track) + { + auto layer = track.type == ItemType::LAYER ? item_get(model.content.layers, track.id) : nullptr; + return layer && layer->is_animation(); + }; auto whole_apply = [&](Track& track) { std::set indices{}; for (int i = 0; i < (int)track.frames.size(); ++i) indices.insert(i); - frames_change(track, change, track.type, type, indices); + frames_change(track, change, track.type, type, indices, is_animation_layer(track)); }; for (auto& [reference, indices] : frames) - if (auto track = model.track_edit(reference)) frames_change(*track, change, track->type, type, indices); + if (auto track = model.track_edit(reference)) + frames_change(*track, change, track->type, type, indices, is_animation_layer(*track)); for (auto reference : wholeTracks) if (auto track = model.track_edit(reference)) whole_apply(*track); for (auto index : targets.animations) diff --git a/src/edit/edit.hpp b/src/edit/edit.hpp index ed80c0b..2d28e68 100644 --- a/src/edit/edit.hpp +++ b/src/edit/edit.hpp @@ -81,6 +81,7 @@ namespace anm2ed::edit DURATION, SHADER, DEPTH, + BLUR, CHILD, EVENT, SOUNDS, diff --git a/src/edit/frames.cpp b/src/edit/frames.cpp index 07b620a..307e5ea 100644 --- a/src/edit/frames.cpp +++ b/src/edit/frames.cpp @@ -214,7 +214,7 @@ namespace anm2ed::edit auto isLayerOnly = property == FrameProperty::PIVOT || property == FrameProperty::CROP || property == FrameProperty::SIZE || property == FrameProperty::REGION || property == FrameProperty::SHADER || property == FrameProperty::DEPTH || - property == FrameProperty::CHILD; + property == FrameProperty::BLUR || property == FrameProperty::CHILD; return type == ItemType::LAYER || !isLayerOnly; } @@ -270,6 +270,9 @@ namespace anm2ed::edit case FrameProperty::DEPTH: target.depth = source.depth; break; + case FrameProperty::BLUR: + target.blur = source.blur; + break; case FrameProperty::CHILD: target.childAnimation = source.childAnimation; target.childMode = source.childMode; diff --git a/src/imgui/taskbar.cpp b/src/imgui/taskbar.cpp index e2d1d58..ec81dd3 100644 --- a/src/imgui/taskbar.cpp +++ b/src/imgui/taskbar.cpp @@ -387,6 +387,7 @@ namespace anm2ed::imgui {issues.skewFrames, FORMAT_ISAAC_SKEW_FRAMES}, {issues.shaderFrames, FORMAT_ISAAC_SHADER_FRAMES}, {issues.depthFrames, FORMAT_ISAAC_DEPTH_FRAMES}, + {issues.blurFrames, FORMAT_ISAAC_BLUR_FRAMES}, {issues.triggerSounds, FORMAT_ISAAC_TRIGGER_SOUNDS}, {issues.animationLayers, FORMAT_ISAAC_ANIMATION_LAYERS}}) if (count > 0) ImGui::BulletText("%s", localize_format(format, count).c_str()); diff --git a/src/imgui/window/animation_preview.cpp b/src/imgui/window/animation_preview.cpp index 2400982..07a2ec0 100644 --- a/src/imgui/window/animation_preview.cpp +++ b/src/imgui/window/animation_preview.cpp @@ -721,13 +721,11 @@ namespace anm2ed::imgui auto textureSize = vec2(layerTexture->size); auto layerModel = model::draw_quad_model_get(draw); auto layerTransform = transform * layerModel; - auto vertices = math::uv_vertices_get(frame.crop / textureSize, (frame.crop + frame.size) / textureSize); auto tint = frame.tint; tint.a = std::max(0.0f, tint.a - (alphaOffset + sampleAlpha)); auto customShader = sampleDocument.shader_get(frame.shaderId); - texture_render(customShader ? *customShader : shaderTexture, resource::texture::id_get(*layerTexture), - layerTransform, tint, frame.colorOffset + sampleColor, vertices.data(), textureSize, - draw.time); + layer_render(customShader ? *customShader : shaderTexture, resource::texture::id_get(*layerTexture), + textureSize, baseTransform, draw, tint, frame.colorOffset + sampleColor); auto color = isOnion ? onionColor : isActiveDocument && is_layer_selected(draw.id) ? SELECTED_LAYER_BORDER_COLOR diff --git a/src/imgui/window/frame_properties.cpp b/src/imgui/window/frame_properties.cpp index 814f8c3..4022418 100644 --- a/src/imgui/window/frame_properties.cpp +++ b/src/imgui/window/frame_properties.cpp @@ -277,6 +277,16 @@ namespace anm2ed::imgui const Reference&) { frame.colorOffset = colorOffset; }); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_COLOR_OFFSET)); + ImGui::BeginDisabled(type != LAYER); + auto blurEdit = + drag_float_persistent(localize.get(BASIC_BLUR), frame ? &useFrame.blur : &dummy_value(), + DRAG_SPEED, 0.0f, FRAME_BLUR_MAX, frame ? float_format_get(frame->blur) : ""); + frame_edit(blurEdit, EDIT_FRAME_BLUR, + [blur = useFrame.blur](Document&, model::Frame& frame, model::Track*, const Reference&) + { frame.blur = std::clamp(blur, 0.0f, FRAME_BLUR_MAX); }); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BLUR)); + ImGui::EndDisabled(); + ImGui::BeginDisabled(type != LAYER || isAnimationLayer); if (combo_id_mapped(localize.get(BASIC_REGION), frame ? &useFrame.regionId : &dummy_value_negative(), regions.ids, regions.labels) && @@ -328,6 +338,22 @@ namespace anm2ed::imgui } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FRAME_VISIBILITY)); + auto widgetSize = widget_size_with_row_get(2); + + for (int axis = 0; axis < (int)std::size(FLIP_BUTTONS); ++axis) + { + if (axis > 0) ImGui::SameLine(); + if (ImGui::Button(localize.get(FLIP_BUTTONS[axis].label), widgetSize) && frame) + frame_edit(edit_state::COMPLETE, FLIP_BUTTONS[axis].edit, + [axis, isPositionFlipped = ImGui::IsKeyDown(ImGuiMod_Ctrl)](Document&, model::Frame& frame, + model::Track*, const Reference&) + { + frame.scale[axis] = -frame.scale[axis]; + if (isPositionFlipped) frame.position[axis] = -frame.position[axis]; + }); + ImGui::SetItemTooltip("%s", localize.get(FLIP_BUTTONS[axis].tooltip)); + } + if (isAnimationLayer && frame) { ImGui::SeparatorText(localize.get(LABEL_CHILD)); @@ -339,9 +365,11 @@ namespace anm2ed::imgui combo_string_mapped(localize.get(LABEL_ANIMATION), &useFrame.childAnimation, values, labels); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CHILD_ANIMATION)); - const char* modeLabels[] = {localize.get(LABEL_LOOP), localize.get(LABEL_ONCE), localize.get(LABEL_HOLD)}; + std::vector modeLabels{}; + for (auto label : wizard::CHILD_MODE_LABELS) + modeLabels.push_back(localize.get(label)); auto mode = (int)useFrame.childMode; - if (ImGui::Combo(localize.get(BASIC_MODE), &mode, modeLabels, (int)std::size(modeLabels))) + if (ImGui::Combo(localize.get(BASIC_MODE), &mode, modeLabels.data(), (int)modeLabels.size())) { useFrame.childMode = (ChildMode)mode; isChildChanged = true; @@ -366,22 +394,6 @@ namespace anm2ed::imgui { edit::frame_property_copy(frame, child, edit::FrameProperty::CHILD); }); } - auto widgetSize = widget_size_with_row_get(2); - - for (int axis = 0; axis < (int)std::size(FLIP_BUTTONS); ++axis) - { - if (axis > 0) ImGui::SameLine(); - if (ImGui::Button(localize.get(FLIP_BUTTONS[axis].label), widgetSize) && frame) - frame_edit(edit_state::COMPLETE, FLIP_BUTTONS[axis].edit, - [axis, isPositionFlipped = ImGui::IsKeyDown(ImGuiMod_Ctrl)](Document&, model::Frame& frame, - model::Track*, const Reference&) - { - frame.scale[axis] = -frame.scale[axis]; - if (isPositionFlipped) frame.position[axis] = -frame.position[axis]; - }); - ImGui::SetItemTooltip("%s", localize.get(FLIP_BUTTONS[axis].tooltip)); - } - ImGui::Separator(); ImGui::Dummy(ImVec2(0.0f, ImGui::GetFrameHeight())); } diff --git a/src/imgui/window/timeline/menus.cpp b/src/imgui/window/timeline/menus.cpp index 96ed359..5420f25 100644 --- a/src/imgui/window/timeline/menus.cpp +++ b/src/imgui/window/timeline/menus.cpp @@ -3,9 +3,9 @@ namespace anm2ed::imgui { constexpr StringType FRAME_PROPERTY_LABELS[] = { - BASIC_POSITION, BASIC_SCALE, BASIC_ROTATION, BASIC_SKEW, BASIC_PIVOT, BASIC_CROP, - BASIC_SIZE, BASIC_REGION, BASIC_TINT, BASIC_COLOR_OFFSET, BASIC_VISIBLE, BASIC_INTERPOLATED, - BASIC_DURATION, BASIC_SHADER, BASIC_DEPTH, LABEL_CHILD, BASIC_EVENT, LABEL_SOUNDS}; + BASIC_POSITION, BASIC_SCALE, BASIC_ROTATION, BASIC_SKEW, BASIC_PIVOT, BASIC_CROP, BASIC_SIZE, + BASIC_REGION, BASIC_TINT, BASIC_COLOR_OFFSET, BASIC_VISIBLE, BASIC_INTERPOLATED, BASIC_DURATION, BASIC_SHADER, + BASIC_DEPTH, BASIC_BLUR, LABEL_CHILD, BASIC_EVENT, LABEL_SOUNDS}; static_assert(std::size(FRAME_PROPERTY_LABELS) == (std::size_t)edit::FrameProperty::COUNT); void TimelineContext::frame_begin() diff --git a/src/imgui/wizard/change_all_frame_properties.cpp b/src/imgui/wizard/change_all_frame_properties.cpp index 6ef6302..195a2ca 100644 --- a/src/imgui/wizard/change_all_frame_properties.cpp +++ b/src/imgui/wizard/change_all_frame_properties.cpp @@ -138,6 +138,27 @@ namespace anm2ed::imgui::wizard auto isLayerPropertyAvailable = isFramesDestination ? std::ranges::any_of(selectedFrameReferences, is_layer) : isItemsDestination ? std::ranges::any_of(selectedItemReferences, is_layer) : settings.changeIsLayers; + // Child properties reach animation layers only; their choices are every such layer's animations. + auto animation_layer_get = [&](const Reference& reference) -> const model::Layer* + { + auto layer = is_layer(reference) ? model::item_get(document.model.content.layers, reference.itemID) : nullptr; + return layer && layer->is_animation() ? layer : nullptr; + }; + std::set childAnimations{}; + bool isChildPropertyAvailable{}; + auto child_layer_add = [&](const model::Layer* layer) + { + if (!layer || !layer->is_animation()) return; + isChildPropertyAvailable = true; + for (auto& name : document.animation_names_get(layer->libraryId)) + childAnimations.insert(name); + }; + if (isFramesDestination || isItemsDestination) + for (const auto& reference : isFramesDestination ? selectedFrameReferences : selectedItemReferences) + child_layer_add(animation_layer_get(reference)); + else if (settings.changeIsLayers) + for (const auto& layer : document.model.content.layers) + child_layer_add(&layer); ComponentRow componentRows[] = { {BASIC_CROP, {&settings.changeIsCropX, &settings.changeIsCropY}, value_ptr(settings.changeCrop), true}, @@ -149,7 +170,8 @@ namespace anm2ed::imgui::wizard {BASIC_PIVOT, {&settings.changeIsPivotX, &settings.changeIsPivotY}, value_ptr(settings.changePivot), true}, {BASIC_SCALE, {&settings.changeIsScaleX, &settings.changeIsScaleY}, value_ptr(settings.changeScale), false}, {BASIC_SKEW, {&settings.changeIsSkewX, &settings.changeIsSkewY}, value_ptr(settings.changeSkew), false}, - {BASIC_ROTATION, {&settings.changeIsRotation}, &settings.changeRotation, false}}; + {BASIC_ROTATION, {&settings.changeIsRotation}, &settings.changeRotation, false}, + {BASIC_BLUR, {&settings.changeIsBlur}, &settings.changeBlur, true}}; ComponentRow colorRows[] = { {BASIC_TINT, {&settings.changeIsTintR, &settings.changeIsTintG, &settings.changeIsTintB, &settings.changeIsTintA}, @@ -235,6 +257,42 @@ namespace anm2ed::imgui::wizard bool_draw("Flip X", LABEL_FLIP_X, settings.changeIsFlipXSet, settings.changeIsFlipX); ImGui::SameLine(); bool_draw("Flip Y", LABEL_FLIP_Y, settings.changeIsFlipYSet, settings.changeIsFlipY); + + ImGui::SeparatorText(localize.get(LABEL_CHILD)); + ImGui::BeginDisabled(!isChildPropertyAvailable); + { + std::vector values{std::string{}}; + std::vector labels{localize.get(TEXT_LAYER_ANIMATION)}; + values.insert(values.end(), childAnimations.begin(), childAnimations.end()); + labels.insert(labels.end(), childAnimations.begin(), childAnimations.end()); + ImGui::PushID("Child Animation"); + property_toggle_begin(settings.changeIsChildAnimation); + combo_string_mapped(localize.get(LABEL_ANIMATION), &settings.changeChildAnimation, values, labels); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CHILD_ANIMATION)); + ImGui::EndDisabled(); + ImGui::PopID(); + + std::vector modeIds{}; + std::vector modeLabels{}; + for (int i = 0; i < (int)std::size(CHILD_MODE_LABELS); ++i) + { + modeIds.push_back(i); + modeLabels.push_back(localize.get(CHILD_MODE_LABELS[i])); + } + combo_draw("Child Mode", BASIC_MODE, settings.changeIsChildMode, settings.changeChildMode, modeIds, modeLabels); + + ImGui::PushID("Child Start"); + property_toggle_begin(settings.changeIsChildStart); + input_int_range(localize.get(LABEL_START_FRAME), settings.changeChildStart, 0, FRAME_NUM_MAX, STEP, STEP_FAST); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CHILD_START)); + ImGui::EndDisabled(); + ImGui::PopID(); + + bool_draw("Child Random", LABEL_RANDOM, settings.changeIsChildStartRandomSet, settings.changeIsChildStartRandom); + ImGui::SameLine(); + bool_draw("Child Restart", LABEL_RESTART, settings.changeIsChildRestartSet, settings.changeIsChildRestart); + } + ImGui::EndDisabled(); ImGui::PopStyleVar(); auto frame_change = [&](ChangeType changeType) @@ -254,6 +312,14 @@ namespace anm2ed::imgui::wizard if (settings.changeIsInterpolationSet) frameChange.interpolation = (Interpolation)settings.changeInterpolation; if (settings.changeIsFlipXSet) frameChange.isFlipX = settings.changeIsFlipX; if (settings.changeIsFlipYSet) frameChange.isFlipY = settings.changeIsFlipY; + if (isChildPropertyAvailable) + { + if (settings.changeIsChildAnimation) frameChange.childAnimation = settings.changeChildAnimation; + if (settings.changeIsChildMode) frameChange.childMode = (ChildMode)settings.changeChildMode; + if (settings.changeIsChildStart) frameChange.childStart = settings.changeChildStart; + if (settings.changeIsChildStartRandomSet) frameChange.isChildStartRandom = settings.changeIsChildStartRandom; + if (settings.changeIsChildRestartSet) frameChange.isChildRestart = settings.changeIsChildRestart; + } manager.command_push( {manager.selected, @@ -319,12 +385,15 @@ namespace anm2ed::imgui::wizard ImGui::Separator(); } - bool isAnyProperty = settings.changeIsDuration || settings.changeIsDepth || settings.changeIsRegion || - settings.changeIsShader || settings.changeIsVisibleSet || settings.changeIsInterpolationSet || - settings.changeIsFlipXSet || - settings.changeIsFlipYSet + bool isAnyProperty = + settings.changeIsDuration || settings.changeIsDepth || settings.changeIsRegion || settings.changeIsShader || + settings.changeIsVisibleSet || settings.changeIsInterpolationSet || settings.changeIsFlipXSet || + settings.changeIsFlipYSet || + (isChildPropertyAvailable && + (settings.changeIsChildAnimation || settings.changeIsChildMode || settings.changeIsChildStart || + settings.changeIsChildStartRandomSet || settings.changeIsChildRestartSet)) #define X(name, member, isLayerOnly, isColor, isEnabled, value) || settings.isEnabled - FRAME_CHANGE_SCALARS + FRAME_CHANGE_SCALARS #undef X ; bool isDestinationValid = isFramesDestination ? isSelectedFramesAvailable diff --git a/src/imgui/wizard/change_all_frame_properties.hpp b/src/imgui/wizard/change_all_frame_properties.hpp index 9b56b53..d0ad1ac 100644 --- a/src/imgui/wizard/change_all_frame_properties.hpp +++ b/src/imgui/wizard/change_all_frame_properties.hpp @@ -8,6 +8,7 @@ namespace anm2ed::imgui::wizard { inline constexpr StringType INTERPOLATION_LABELS[] = {BASIC_NONE, BASIC_LINEAR, BASIC_EASE_IN, BASIC_EASE_OUT, BASIC_EASE_IN_OUT}; + inline constexpr StringType CHILD_MODE_LABELS[] = {LABEL_LOOP, LABEL_ONCE, LABEL_HOLD}; class ChangeAllFrameProperties { diff --git a/src/model/common.hpp b/src/model/common.hpp index 2db7985..ed8a1f8 100644 --- a/src/model/common.hpp +++ b/src/model/common.hpp @@ -105,6 +105,7 @@ namespace anm2ed inline constexpr int FPS_MIN = 1; inline constexpr int FPS_MAX = 120; inline constexpr int FRAME_DEPTH_MAX = 100; + inline constexpr float FRAME_BLUR_MAX = 255.0f; // Flash's BlurFilter limit enum class SpritesheetMergeOrigin { @@ -189,7 +190,8 @@ namespace anm2ed X(tintA, tint.a, false, true, changeIsTintA, changeTint.a) \ X(colorOffsetR, colorOffset.r, false, true, changeIsColorOffsetR, changeColorOffset.r) \ X(colorOffsetG, colorOffset.g, false, true, changeIsColorOffsetG, changeColorOffset.g) \ - X(colorOffsetB, colorOffset.b, false, true, changeIsColorOffsetB, changeColorOffset.b) + X(colorOffsetB, colorOffset.b, false, true, changeIsColorOffsetB, changeColorOffset.b) \ + X(blur, blur, true, false, changeIsBlur, changeBlur) struct FrameChange { @@ -204,6 +206,12 @@ namespace anm2ed std::optional interpolation{}; std::optional isFlipX{}; std::optional isFlipY{}; + // An animation layer's child; a spritesheet layer's frames keep theirs. + std::optional childAnimation{}; + std::optional childMode{}; + std::optional childStart{}; + std::optional isChildStartRandom{}; + std::optional isChildRestart{}; }; struct Reference diff --git a/src/model/draw.cpp b/src/model/draw.cpp index ad1f817..e0a5b21 100644 --- a/src/model/draw.cpp +++ b/src/model/draw.cpp @@ -123,6 +123,7 @@ namespace anm2ed::model child.parent = transform * child.parent; child.frame.tint *= frame.tint; child.frame.colorOffset += frame.colorOffset; + child.frame.blur = std::max(child.frame.blur, frame.blur); // Each part blurs on its own, as the game draws it. if (child.source != &model) child.frame.shaderId = -1; layerOrders.emplace_back(layerOrder + frame.depth, frame.depth); draws.push_back(std::move(child)); diff --git a/src/model/frames.cpp b/src/model/frames.cpp index 09a1468..cdd34de 100644 --- a/src/model/frames.cpp +++ b/src/model/frames.cpp @@ -18,6 +18,7 @@ namespace anm2ed::model frame.skew = glm::mix(frame.skew, next.skew, amount); frame.colorOffset = glm::mix(frame.colorOffset, next.colorOffset, amount); frame.tint = glm::mix(frame.tint, next.tint, amount); + frame.blur = glm::mix(frame.blur, next.blur, amount); } // Splits an interpolated frame into uninterpolated frames of at most `interval`; the first keeps the frame's uid. @@ -170,7 +171,7 @@ namespace anm2ed::model } void frames_change(Track& track, FrameChange change, ItemType itemType, ChangeType changeType, - const std::set& selection) + const std::set& selection, bool isAnimationLayer) { auto apply = [&](auto& target, const auto& optionalValue) { @@ -205,6 +206,14 @@ namespace anm2ed::model if (!isLayerOnly || itemType == ItemType::LAYER) apply(frame.member, change.name); FRAME_CHANGE_SCALARS #undef X + frame.blur = std::clamp(frame.blur, 0.0f, FRAME_BLUR_MAX); + if (!isAnimationLayer) continue; + if (change.childAnimation) frame.childAnimation = *change.childAnimation; + if (change.childMode) frame.childMode = *change.childMode; + if (change.isChildStartRandom) frame.isChildStartRandom = *change.isChildStartRandom; + if (change.isChildRestart) frame.isChildRestart = *change.isChildRestart; + apply(frame.childStart, change.childStart); + frame.childStart = std::clamp(frame.childStart, 0, FRAME_NUM_MAX); } } diff --git a/src/model/frames.hpp b/src/model/frames.hpp index 705ce4c..26d0dd0 100644 --- a/src/model/frames.hpp +++ b/src/model/frames.hpp @@ -18,6 +18,6 @@ namespace anm2ed::model void frame_bake(Track&, int, int, bool, bool); void frames_generate_from_grid(Track&, glm::ivec2, glm::ivec2, glm::vec2, int, int, int); void frames_sort_by_at_frame(Track&); - void frames_change(Track&, FrameChange, ItemType, ChangeType, const std::set&); + void frames_change(Track&, FrameChange, ItemType, ChangeType, const std::set&, bool isAnimationLayer = false); glm::vec4 animation_rect(const Model&, const Animation&, bool, const LibraryGet& = {}); } diff --git a/src/model/model.hpp b/src/model/model.hpp index 5c89e9d..0174cb1 100644 --- a/src/model/model.hpp +++ b/src/model/model.hpp @@ -55,6 +55,7 @@ namespace anm2ed::model int regionId{-1}; int shaderId{-1}; int depth{}; // a layer frame draws this many layers above (or below) its place in the timeline; editor-only + float blur{}; // Flash's BlurFilter at quality 1: one box blur this many canvas pixels wide; editor-only // On an animation layer: the child animation (empty for the layer's own) and how it plays; editor-only. std::string childAnimation{}; ChildMode childMode{ChildMode::LOOP}; diff --git a/src/model/xml.cpp b/src/model/xml.cpp index 9854d02..21e389e 100644 --- a/src/model/xml.cpp +++ b/src/model/xml.cpp @@ -41,7 +41,7 @@ namespace anm2ed::model "XPivot", "YPivot", "XCrop", "YCrop", "XPosition", "YPosition", "Width", "Height", "XScale", "YScale", "SkewX", "SkewY", "ShearX", "ShearY", "RedTint", "GreenTint", "BlueTint", "AlphaTint", "RedOffset", "GreenOffset", "BlueOffset", "Interpolated", "Origin", "BakeInterpolation", "BakeDelay", "BakeCount", "OriginalDelay", "Library", "Animation", - "ChildAnimation", "ChildMode", "ChildStart", "Restart"}; + "ChildAnimation", "ChildMode", "ChildStart", "Restart", "Blur"}; // clang-format on constexpr std::string_view SOURCE_DOCUMENT_TAG = "SourceDocument"; constexpr std::string_view FRAME_RESTORE_TAG = "FrameRestore"; @@ -223,6 +223,7 @@ namespace anm2ed::model frame.regionId = int_get(element, "RegionId"); frame.shaderId = int_get(element, "ShaderId"); frame.depth = int_get(element, "Depth", 0); + frame.blur = float_get(element, "Blur"); frame.childAnimation = string_get(element, "ChildAnimation"); auto childMode = std::ranges::find(CHILD_MODE_VALUES, string_get(element, "ChildMode")); if (childMode != std::end(CHILD_MODE_VALUES)) @@ -1169,6 +1170,7 @@ namespace anm2ed::model if (writer.is(SERIALIZE_EXTENSIONS) && type == ItemType::LAYER) { if (frame.depth != 0) sink.attribute("Depth", frame.depth); + if (frame.blur != 0.0f) sink.attribute("Blur", frame.blur); if (!frame.childAnimation.empty()) sink.attribute("ChildAnimation", frame.childAnimation); if (frame.childMode != ChildMode::LOOP) sink.attribute("ChildMode", CHILD_MODE_VALUES[(int)frame.childMode]); if (frame.isChildStartRandom) @@ -1370,6 +1372,7 @@ namespace anm2ed::model issues.skewFrames += frame.skew != glm::vec2(); issues.shaderFrames += frame.shaderId != -1; issues.depthFrames += track.type == ItemType::LAYER && frame.depth != 0; + issues.blurFrames += track.type == ItemType::LAYER && frame.blur != 0.0f; issues.triggerSounds += track.type == ItemType::TRIGGER && std::ranges::any_of(frame.soundIds, [](int id) { return id != -1; }); diff --git a/src/model/xml.hpp b/src/model/xml.hpp index 06d78e3..c47d69a 100644 --- a/src/model/xml.hpp +++ b/src/model/xml.hpp @@ -16,6 +16,7 @@ namespace anm2ed::model int skewFrames{}; int shaderFrames{}; int depthFrames{}; + int blurFrames{}; int triggerSounds{}; int animationLayers{}; diff --git a/src/resource/shader.hpp b/src/resource/shader.hpp index 168aaf6..37797f8 100644 --- a/src/resource/shader.hpp +++ b/src/resource/shader.hpp @@ -78,16 +78,43 @@ namespace anm2ed::resource::shader } )"; + // u_blur > 0: Flash's low-quality BlurFilter, a box of 2 * u_blur + 1 texels averaged (premultiplied) over the + // u_region crop, clear outside it; a wide box steps over texels so a fragment reads at most BLUR_SAMPLES per axis. inline constexpr auto TEXTURE_FRAGMENT = R"( #version 330 core in vec2 i_uv_out; uniform sampler2D u_texture; uniform vec4 u_tint; uniform vec3 u_color_offset; + uniform float u_blur; + uniform vec4 u_region; + uniform vec2 u_texel; out vec4 o_fragColor; + const int BLUR_SAMPLES = 33; + vec4 texel_premultiplied_get(vec2 uv) + { + if (any(lessThan(uv, u_region.xy)) || any(greaterThanEqual(uv, u_region.zw))) return vec4(0.0); + vec4 color = texture(u_texture, uv); + return vec4(color.rgb * color.a, color.a); + } void main() { vec4 texColor = texture(u_texture, i_uv_out); + if (u_blur > 0.0) + { + int radius = int(u_blur); + int stride = max(1, (radius * 2 + BLUR_SAMPLES) / BLUR_SAMPLES); + vec4 sum = vec4(0.0); + float count = 0.0; + for (int y = -radius; y <= radius; y += stride) + for (int x = -radius; x <= radius; x += stride) + { + sum += texel_premultiplied_get(i_uv_out + vec2(x, y) * u_texel); + count += 1.0; + } + sum /= count; + texColor = sum.a > 0.0 ? vec4(sum.rgb / sum.a, sum.a) : vec4(0.0); + } texColor *= u_tint; texColor.rgb += u_color_offset; texColor.rgb *= texColor.a; @@ -231,6 +258,9 @@ namespace anm2ed::resource::shader constexpr auto UNIFORM_DASH_LENGTH = "u_dash_length"; constexpr auto UNIFORM_DASH_GAP = "u_dash_gap"; constexpr auto UNIFORM_DASH_OFFSET = "u_dash_offset"; + constexpr auto UNIFORM_BLUR = "u_blur"; + constexpr auto UNIFORM_REGION = "u_region"; + constexpr auto UNIFORM_TEXEL = "u_texel"; #define RESOURCE_SHADER_ATTRIBUTE_ALIASES \ X(0, "i_position") \ diff --git a/src/resource/strings.hpp b/src/resource/strings.hpp index 9de3737..fce7c49 100644 --- a/src/resource/strings.hpp +++ b/src/resource/strings.hpp @@ -42,6 +42,7 @@ namespace anm2ed X(BASIC_AT_FRAME, "At Frame", "En Frame", "На кадре", "触发帧", "트리거될 프레임") \ X(BASIC_BATCH, "Batch", "Lote", "Пакетный", "批量", "일괄") \ X(BASIC_BEFORE, "Before", "Antes", "До", "前一帧", "전") \ + X(BASIC_BLUR, "Blur", "Desenfoque", "Размытие", "模糊", "흐림") \ X(BASIC_BORDER, "Border", "Borde", "Границы", "边框", "경계선") \ X(BASIC_CANCEL, "Cancel", "Cancelar", "Отмена", "取消", "취소") \ X(BASIC_COLOR, "Color", "Color", "Цвет", "颜色", "색상") \ @@ -125,6 +126,7 @@ namespace anm2ed X(EDIT_END_MARKER, "Set End Marker", "Poner Marcador de Fin", "Конечный маркер", "设置结束标记", "끝 마커 설정") \ X(EDIT_FRAME_CHILD, "Frame Child", "Hijo del Frame", "Дочерняя анимация кадра", "帧子动画", "프레임 자식") \ X(EDIT_FRAME_DEPTH, "Frame Depth", "Profundidad del Frame", "Глубина кадра", "帧深度", "프레임 깊이") \ + X(EDIT_FRAME_BLUR, "Frame Blur", "Desenfoque del Frame", "Размытие кадра", "帧模糊", "프레임 흐림") \ X(EDIT_PASTE_FRAME_PROPERTY, "Paste Frame Property", "Pegar Propiedad del Frame", "Вставка свойства кадра", "粘贴帧属性", "프레임 속성 붙여넣기") \ X(EDIT_PASTE_LIBRARIES, "Paste Libraries", "Pegar Bibliotecas", "Вставить библиотеки", "粘贴库", "라이브러리 붙여넣기") \ X(EDIT_REMOVE_MARKERS, "Remove Markers", "Quitar Marcadores", "Удаление маркеров", "移除标记", "마커 제거") \ @@ -229,6 +231,7 @@ namespace anm2ed X(FORMAT_EVENT_LABEL, "Event: {0}", "Evento: {0}", "Событие: {0}", "事件: {0}", "이벤트: {0}") \ X(FORMAT_ID, "ID: {0}", "ID: {0}", "ID: {0}", "ID: {0}", "ID: {0}") \ X(FORMAT_ISAAC_ANIMATION_LAYERS, "{} layer(s) play animations, which the game doesn't support; they will draw nothing.", "{} capa(s) reproducen animaciones, que el juego no soporta; no dibujarán nada.", "{} слой(ёв) проигрывают анимации, которые игра не поддерживает; они ничего не отобразят.", "{} 个图层播放动画,游戏不支持;它们将不显示任何内容。", "{}개의 레이어가 애니메이션을 재생합니다. 게임에서 지원하지 않으므로 아무것도 그리지 않습니다.") \ + X(FORMAT_ISAAC_BLUR_FRAMES, "{} frame(s) blur their layer, which the game doesn't support; they will draw sharp.", "{} Frame(s) desenfocan su capa, que el juego no soporta; se dibujarán nítidos.", "{} кадр(ов) размывают слой, что игра не поддерживает; они будут нарисованы чётко.", "{} 个帧模糊了图层,游戏不支持,将清晰绘制。", "프레임 {}개가 게임이 지원하지 않는 레이어 흐림을 사용합니다. 선명하게 그려집니다.") \ X(FORMAT_ISAAC_DEPTH_FRAMES, "{} frame(s) change their layer's depth, which the game doesn't support; they will draw in timeline order.", "{} Frame(s) cambian la profundidad de su capa, que el juego no soporta; se dibujarán en el orden de la línea de tiempo.", "{} кадр(ов) меняют глубину слоя, что игра не поддерживает; они будут рисоваться в порядке таймлайна.", "{} 个帧改变了图层深度,游戏不支持,将按时间轴顺序绘制。", "프레임 {}개가 게임이 지원하지 않는 레이어 깊이를 바꿉니다. 타임라인 순서로 그려집니다.") \ X(FORMAT_ISAAC_EASED_FRAMES, "{} eased frame(s) will be baked into one-frame steps.", "{} Frame(s) con suavizado se convertirán en pasos de un Frame.", "{} кадр(ов) со сглаживанием будут запечены в покадровые шаги.", "{} 个缓动帧将被烘焙为逐帧步进。", "이징 프레임 {}개가 1프레임 단위로 베이크됩니다.") \ X(FORMAT_ISAAC_GROUP_TRANSFORMS, "{} group transform(s) will be baked into their items' frames.", "{} transformación(es) de grupo se aplicarán a los Frames de sus elementos.", "{} трансформаци(й) групп будут запечены в кадры их элементов.", "{} 个组变换将被烘焙到其项目的帧中。", "그룹 변형 {}개가 항목의 프레임에 베이크됩니다.") \ @@ -669,6 +672,7 @@ namespace anm2ed X(TOOLTIP_BAKE_INTO_OTHER_FRAMES_ALL, "All layer/null frames will have the selected root frames' transformations applied to them.", "Todos los frames de capas/nulls tendrán aplicadas las transformaciones de los root frames seleccionados.", "Все кадры слоев/нулей получат трансформации выбранных корневых кадров.", "所有图层/Null帧会应用所选根帧的变换.", "모든 레이어/Null 프레임에 선택된 Root 프레임의 변환을 적용합니다.") \ X(TOOLTIP_BAKE_MATCH_ROOT_INTERPOLATION, "Bake affected layer/null frames to duration 1 before applying root transforms, so they match the selected root frames' interpolation.", "Hornea los frames de capas/nulls afectados a duración 1 antes de aplicar transformaciones root, para coincidir con la interpolación root seleccionada.", "Запечь затронутые кадры слоев/нулей до длительности 1 перед применением корневых трансформаций, чтобы соответствовать интерполяции выбранных корневых кадров.", "应用根变换前,将受影响的图层/Null帧烘焙为时长1,以匹配所选根帧的插值.", "선택된 Root 프레임의 보간에 맞도록 Root 변환 적용 전에 영향받는 레이어/Null 프레임을 지속시간 1로 베이크합니다.") \ X(TOOLTIP_BAKE_USE_ROOT_PIVOT, "Scale and rotate other frames around the root frame position instead of the animation origin.", "Escala y rota otros frames alrededor de la posición del root frame en vez del origen de la animación.", "Масштабировать и вращать другие кадры вокруг позиции корневого кадра, а не начала координат анимации.", "围绕根帧位置而不是动画原点缩放和旋转其他帧.", "애니메이션 원점 대신 Root 프레임 위치를 중심으로 다른 프레임을 확대/회전합니다.") \ + X(TOOLTIP_BLUR, "Blur this layer like a Flash blur filter (low quality): one box blur this many canvas pixels wide, across and down. An animation layer blurs its child at least this much.\n(Editor only; the game draws it sharp.)", "Desenfoca esta capa como un filtro de desenfoque de Flash (calidad baja): un desenfoque de caja de este ancho en píxeles del lienzo, horizontal y vertical. Una capa de animación desenfoca a su hijo al menos esto.\n(Solo en el editor; el juego la dibuja nítida.)", "Размыть слой как фильтр размытия Flash (низкое качество): одно прямоугольное размытие такой ширины в пикселях холста, по горизонтали и вертикали. Слой анимации размывает дочернюю анимацию не меньше этого.\n(Только в редакторе; игра рисует его чётко.)", "像 Flash 模糊滤镜(低品质)一样模糊此图层:沿水平和垂直方向进行一次此宽度(画布像素)的方框模糊。动画图层至少以此程度模糊其子动画。\n(仅限编辑器;游戏会清晰绘制。)", "Flash 흐림 필터(낮은 품질)처럼 이 레이어를 흐리게 합니다. 캔버스 픽셀 기준 이 너비의 박스 흐림을 가로와 세로로 한 번 적용합니다. 애니메이션 레이어는 자식을 최소 이만큼 흐리게 합니다.\n(편집기 전용이며, 게임은 선명하게 그립니다.)") \ X(TOOLTIP_BORDER, "Toggle the visibility of borders around layers.", "Alterna la visibilidad de los bordes alrededor de las capas.", "Переключить видимость границ около слоев.", "切换动画层边框是否可见.", "레이어 주변 경계선을 표시하거나 숨깁니다.") \ X(TOOLTIP_CANCEL_ADD_ITEM, "Cancel adding an item.", "Cancelar añadir un item.", "Отменить добавление предмета.", "取消添加物品.", "항목 추가를 취소합니다.") \ X(TOOLTIP_CANCEL_BAKE_FRAMES, "Cancel baking frames.", "Cancelar hacer bake de Frames.", "Отменить запечку кадров.", "取消提前渲染.", "프레임 베이킹을 취소합니다.") \ diff --git a/src/settings.hpp b/src/settings.hpp index 4afc35b..446bca8 100644 --- a/src/settings.hpp +++ b/src/settings.hpp @@ -92,6 +92,12 @@ namespace anm2ed X(CHANGE_IS_ROTATION, changeIsRotation, STRING_UNDEFINED, BOOL, false) \ X(CHANGE_IS_DURATION, changeIsDuration, STRING_UNDEFINED, BOOL, false) \ X(CHANGE_IS_DEPTH, changeIsDepth, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_BLUR, changeIsBlur, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_CHILD_ANIMATION, changeIsChildAnimation, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_CHILD_MODE, changeIsChildMode, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_CHILD_START, changeIsChildStart, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_CHILD_START_RANDOM_SET, changeIsChildStartRandomSet, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_CHILD_RESTART_SET, changeIsChildRestartSet, STRING_UNDEFINED, BOOL, false) \ X(CHANGE_IS_TINT_R, changeIsTintR, STRING_UNDEFINED, BOOL, false) \ X(CHANGE_IS_TINT_G, changeIsTintG, STRING_UNDEFINED, BOOL, false) \ X(CHANGE_IS_TINT_B, changeIsTintB, STRING_UNDEFINED, BOOL, false) \ @@ -115,6 +121,12 @@ namespace anm2ed X(CHANGE_ROTATION, changeRotation, STRING_UNDEFINED, FLOAT, 0.0f) \ X(CHANGE_DURATION, changeDuration, STRING_UNDEFINED, INT, 0) \ X(CHANGE_DEPTH, changeDepth, STRING_UNDEFINED, INT, 0) \ + X(CHANGE_BLUR, changeBlur, STRING_UNDEFINED, FLOAT, 0.0f) \ + X(CHANGE_CHILD_ANIMATION, changeChildAnimation, STRING_UNDEFINED, STRING, "") \ + X(CHANGE_CHILD_MODE, changeChildMode, STRING_UNDEFINED, INT, 0) \ + X(CHANGE_CHILD_START, changeChildStart, STRING_UNDEFINED, INT, 0) \ + X(CHANGE_IS_CHILD_START_RANDOM, changeIsChildStartRandom, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_CHILD_RESTART, changeIsChildRestart, STRING_UNDEFINED, BOOL, false) \ X(CHANGE_TINT, changeTint, STRING_UNDEFINED, VEC4, {}) \ X(CHANGE_COLOR_OFFSET, changeColorOffset, STRING_UNDEFINED, VEC3, {}) \ X(CHANGE_REGION_ID, changeRegionId, STRING_UNDEFINED, INT, -1) \ diff --git a/tests/draw.cpp b/tests/draw.cpp index 0056fcb..d2fbc9f 100644 --- a/tests/draw.cpp +++ b/tests/draw.cpp @@ -58,6 +58,25 @@ TEST_CASE("a layer frame's depth moves it among the layers for that frame only") CHECK(model::isaac_issues_get(anm2).depthFrames == 1); } +TEST_CASE("a layer frame's blur reaches its child's draws and stays out of the game's copy") +{ + auto anm2 = model_load(file_load(TEST_DIR / "render" / "nested.anm2")); + anm2.frame_edit({0, LAYER, 1, 0})->blur = 6.0f; + bool isAnyChild{}; + for (const auto& draw : model::animation_draws_get(anm2, *anm2.animation_get(0), {})) + if (draw.type == model::DrawType::LAYER && draw.id == 1) + { + isAnyChild = true; + CHECK(draw.frame.blur >= 6.0f); + } + CHECK(isAnyChild); + + auto text = model::model_to_string(anm2); + CHECK(game_document_get(text).find("Blur") == std::string::npos); + CHECK(model_load(text).frame_get({0, LAYER, 1, 0})->blur == 6.0f); + CHECK(model::isaac_issues_get(anm2).blurFrames == 1); +} + TEST_CASE("an animation layer draws its child animation, from this file or a library") { auto anm2 = model_load(file_load(TEST_DIR / "render" / "nested.anm2")); diff --git a/tests/operations.cpp b/tests/operations.cpp index de614d2..83134b1 100644 --- a/tests/operations.cpp +++ b/tests/operations.cpp @@ -380,6 +380,30 @@ TEST_CASE("change all frame properties changes layer depth only") CHECK(model.frame_get(null)->depth == 0); } +TEST_CASE("change all frame properties blurs layers and changes only animation layers' children") +{ + auto model = model_load(file_load(TEST_DIR / "render" / "nested.anm2")); + Reference animationLayer{0, LAYER, 1, 0}; + Reference spritesheetLayer{1, LAYER, 2, 0}; + REQUIRE(model.frame_get(spritesheetLayer)); + edit::frames_change_apply(model, {.references = {animationLayer, spritesheetLayer}}, + {.blur = 8.0f, .childAnimation = "Spin", .childMode = ChildMode::ONCE, .childStart = 3}, + ChangeType::ADJUST); + auto child = *model.frame_get(animationLayer); + CHECK(child.blur == 8.0f); + CHECK(child.childAnimation == "Spin"); + CHECK(child.childMode == ChildMode::ONCE); + CHECK(child.childStart == 3); + auto sprite = *model.frame_get(spritesheetLayer); + CHECK(sprite.blur == 8.0f); + CHECK(sprite.childAnimation.empty()); + CHECK(sprite.childMode == ChildMode::LOOP); + CHECK(sprite.childStart == 0); + + edit::frames_change_apply(model, {.references = {animationLayer}}, {.blur = 1000.0f}, ChangeType::ADD); + CHECK(model.frame_get(animationLayer)->blur == FRAME_BLUR_MAX); +} + TEST_CASE("animations_merge moves triggers past the animation placed before them") { auto model_make = []() diff --git a/tests/render/render.cpp b/tests/render/render.cpp index ac14443..910c93b 100644 --- a/tests/render/render.cpp +++ b/tests/render/render.cpp @@ -157,3 +157,27 @@ TEST_CASE("animation layers draw their child animations") pixels.data())); golden_image_check("nested_frame_0.png"); } + +TEST_CASE("a blurred layer spreads past its crop like Flash's blur filter") +{ + RenderFixture fixture("spin.anm2"); + if (!fixture.gl.is_valid()) + { + MESSAGE("skipped: no OpenGL context"); + return; + } + REQUIRE(fixture.document->is_valid()); + + // The red square (16 x 16 at (-16, 0)) sharp leaves the canvas clear 2 above its top edge and solid 1 inside it; an + // 8 pixel box spreads a third of it out and takes as much from inside. + constexpr glm::vec2 OUTSIDE{-20.0f, -10.0f}, INSIDE{-20.0f, -7.0f}; + auto sharp = fixture.frame_get(0.0f); + fixture.document->model.frame_edit({0, LAYER, 0, 0})->blur = 8.0f; + fixture.animation = fixture.document->model.animation_get(0); + auto blurred = fixture.frame_get(0.0f); + CHECK(fixture.pixel_get(blurred, OUTSIDE).r > fixture.pixel_get(sharp, OUTSIDE).r + 40); + CHECK(fixture.pixel_get(blurred, INSIDE).r + 40 < fixture.pixel_get(sharp, INSIDE).r); + + REQUIRE(resource::Image::write_pixels_png(OUTPUT_DIR / "spin_blur_frame_0.png", glm::ivec2(fixture.canvas->size), + blurred.data())); +}