From b7c24fad99d25d9014560dca98c25a6b92dc0f10 Mon Sep 17 00:00:00 2001 From: shweet Date: Thu, 20 Aug 2026 20:03:12 -0400 Subject: [PATCH] shading and shearing --- src/anm2/anm2.cpp | 165 ++++++- src/anm2/anm2.hpp | 6 + src/dialog.hpp | 2 + src/document.cpp | 189 ++++---- src/document.hpp | 7 +- src/imgui/window/animation_preview.cpp | 128 +++-- src/imgui/window/frame_properties.cpp | 72 +-- src/imgui/window/shaders.cpp | 458 ++++++++++++------ src/imgui/window/shaders.hpp | 6 +- src/imgui/wizard/about.cpp | 5 +- .../wizard/change_all_frame_properties.cpp | 80 +-- .../wizard/generate_animation_from_grid.cpp | 3 +- src/imgui/wizard/render_animation.cpp | 4 + src/render.cpp | 8 + src/render.hpp | 1 + src/resource/icon.hpp | 10 + src/resource/strings.hpp | 22 + src/settings.hpp | 11 +- src/snapshots.cpp | 37 +- src/snapshots.hpp | 2 + src/tool.hpp | 4 + src/util/math.cpp | 14 +- src/util/math.hpp | 8 +- workshop/metadata.xml | 2 +- 24 files changed, 850 insertions(+), 394 deletions(-) diff --git a/src/anm2/anm2.cpp b/src/anm2/anm2.cpp index 5dc192d..cbd96c4 100644 --- a/src/anm2/anm2.cpp +++ b/src/anm2/anm2.cpp @@ -50,6 +50,7 @@ namespace anm2ed X("AtFrame", atFrame) \ X("EventId", eventId) \ X("RegionId", regionId) \ + X("ShaderId", shaderId) \ X("SoundId", soundId) \ X("GroupId", groupId) \ X("Index", index) @@ -72,7 +73,9 @@ namespace anm2ed X("Width", size.x) \ X("Height", size.y) \ X("XScale", scale.x) \ - X("YScale", scale.y) + X("YScale", scale.y) \ + X("ShearX", shear.x) \ + X("ShearY", shear.y) #define ANM2_COLOR_ATTRIBUTES \ X("RedTint", tint.r) \ @@ -105,6 +108,9 @@ namespace anm2ed void groups_nest(Element&); void group_frames_restore(Element&); void source_document_erase(Element&); + void shader_ids_repair(Element&); + void shader_frame_ids_repair(Element&); + void shader_ids_remap(Element&); void region_ids_remap(Element&); void region_frame_ids_repair(Element&); Element* child_first_get(Element&, ElementType); @@ -151,10 +157,7 @@ namespace anm2ed return (int)animations.children.size(); } - bool is_source_document_tag(std::string_view tag) - { - return tag == SOURCE_DOCUMENT_TAG; - } + bool is_source_document_tag(std::string_view tag) { return tag == SOURCE_DOCUMENT_TAG; } const XMLElement* source_document_get(const XMLElement* rootElement) { @@ -187,6 +190,8 @@ namespace anm2ed group_metadata_embed(anm2.root); group_frames_restore(anm2.root); groups_flatten(anm2.root); + shader_ids_repair(anm2.root); + shader_frame_ids_repair(anm2.root); region_frame_ids_repair(anm2.root); anm2.region_frames_sync(true); anm2.isValid = true; @@ -213,6 +218,8 @@ namespace anm2ed { case ElementType::SPRITESHEET: return ElementType::SPRITESHEETS; + case ElementType::SHADER: + return ElementType::SHADERS; case ElementType::LAYER_ELEMENT: return ElementType::LAYERS; case ElementType::NULL_ELEMENT: @@ -247,7 +254,7 @@ namespace anm2ed { auto base = element_make(ElementType::FRAME); return frame.position == base.position && frame.scale == base.scale && frame.rotation == base.rotation && - frame.tint == base.tint && frame.colorOffset == base.colorOffset; + frame.shear == base.shear && frame.tint == base.tint && frame.colorOffset == base.colorOffset; } bool is_root_animation_transform_default(const Element& root) @@ -628,10 +635,11 @@ namespace anm2ed bool element_write_skip(const Element& element, ElementType parentType, Flags flags) { if (!is_track_child_valid(parentType, element.type)) return true; - if ((element.type == ElementType::SHADER || element.type == ElementType::UNIFORM || - element.type == ElementType::COMPONENT) && + if ((element.type == ElementType::SHADERS || element.type == ElementType::SHADER || + element.type == ElementType::UNIFORM || element.type == ElementType::COMPONENT) && !has_flag(flags, SERIALIZE_EXTENSIONS)) return true; + if (element.type == ElementType::SHADERS && element.children.empty()) return true; if (element.type == ElementType::SOUNDS && (!has_flag(flags, SERIALIZE_SOUNDS) || element.children.empty())) return true; if ((element.type == ElementType::LAYER_ANIMATION_GROUPS || element.type == ElementType::NULL_ANIMATION_GROUPS) && @@ -668,6 +676,11 @@ namespace anm2ed out->SetAttribute("Visible", element.isVisible); out->SetAttribute("XScale", element.scale.x); out->SetAttribute("YScale", element.scale.y); + if (has_flag(flags, SERIALIZE_EXTENSIONS)) + { + out->SetAttribute("ShearX", element.shear.x); + out->SetAttribute("ShearY", element.shear.y); + } out->SetAttribute("RedTint", color_write(element.tint.r)); out->SetAttribute("GreenTint", color_write(element.tint.g)); out->SetAttribute("BlueTint", color_write(element.tint.b)); @@ -677,6 +690,8 @@ namespace anm2ed out->SetAttribute("BlueOffset", color_write(element.colorOffset.b)); out->SetAttribute("Rotation", element.rotation); interpolation_write(out, element.interpolation); + if (has_flag(flags, SERIALIZE_EXTENSIONS) && element.shaderId != -1) + out->SetAttribute("ShaderId", element.shaderId); } void element_attributes_write(XMLElement* out, const Element& element, ElementType parentType, Flags flags) @@ -697,7 +712,8 @@ namespace anm2ed } else if (element.type == ElementType::SHADER) { - if (!element.isEnabled) out->SetAttribute("Enabled", element.isEnabled); + out->SetAttribute("Id", element.id); + out->SetAttribute("Name", element.name.c_str()); path_set(out, "Vertex", element.vertex); path_set(out, "Fragment", element.fragment); } @@ -815,6 +831,7 @@ namespace anm2ed baked.rotation = glm::mix(original.rotation, nextFrame.rotation, amount); baked.position = glm::mix(original.position, nextFrame.position, amount); baked.scale = glm::mix(original.scale, nextFrame.scale, amount); + baked.shear = glm::mix(original.shear, nextFrame.shear, amount); baked.colorOffset = glm::mix(original.colorOffset, nextFrame.colorOffset, amount); baked.tint = glm::mix(original.tint, nextFrame.tint, amount); auto frame = element_to_xml(document, baked, track.type, flags); @@ -987,6 +1004,11 @@ namespace anm2ed hash_attr_append(hash, "Visible", element.isVisible); hash_attr_append(hash, "XScale", element.scale.x); hash_attr_append(hash, "YScale", element.scale.y); + if (has_flag(flags, SERIALIZE_EXTENSIONS)) + { + hash_attr_append(hash, "ShearX", element.shear.x); + hash_attr_append(hash, "ShearY", element.shear.y); + } hash_attr_append(hash, "RedTint", color_write(element.tint.r)); hash_attr_append(hash, "GreenTint", color_write(element.tint.g)); hash_attr_append(hash, "BlueTint", color_write(element.tint.b)); @@ -996,6 +1018,8 @@ namespace anm2ed hash_attr_append(hash, "BlueOffset", color_write(element.colorOffset.b)); hash_attr_append(hash, "Rotation", element.rotation); hash_interpolation_attr_append(hash, element.interpolation); + if (has_flag(flags, SERIALIZE_EXTENSIONS) && element.shaderId != -1) + hash_attr_append(hash, "ShaderId", element.shaderId); } void bake_attributes_hash_append(std::uint64_t& hash, Interpolation interpolation, int bakeDelay) @@ -1023,7 +1047,8 @@ namespace anm2ed } else if (element.type == ElementType::SHADER) { - if (!element.isEnabled) hash_attr_append(hash, "Enabled", element.isEnabled); + hash_attr_append(hash, "Id", element.id); + hash_attr_append(hash, "Name", element.name); hash_path_attr_append(hash, "Vertex", element.vertex); hash_path_attr_append(hash, "Fragment", element.fragment); } @@ -1142,6 +1167,7 @@ namespace anm2ed baked.rotation = glm::mix(original.rotation, nextFrame.rotation, amount); baked.position = glm::mix(original.position, nextFrame.position, amount); baked.scale = glm::mix(original.scale, nextFrame.scale, amount); + baked.shear = glm::mix(original.shear, nextFrame.shear, amount); baked.colorOffset = glm::mix(original.colorOffset, nextFrame.colorOffset, amount); baked.tint = glm::mix(original.tint, nextFrame.tint, amount); element_hash_append(hash, baked, track.type, flags, @@ -1575,6 +1601,13 @@ namespace anm2ed bool is_track_child_valid(ElementType parentType, ElementType childType) { + if (parentType == ElementType::CONTENT && childType == ElementType::SHADERS) return true; + if (parentType == ElementType::SHADERS) return childType == ElementType::SHADER; + if (parentType == ElementType::SHADER) return childType == ElementType::UNIFORM; + if (parentType == ElementType::UNIFORM) return childType == ElementType::COMPONENT; + if (childType == ElementType::SHADERS || childType == ElementType::SHADER || childType == ElementType::UNIFORM || + childType == ElementType::COMPONENT) + return false; if (parentType == ElementType::TRIGGERS) return childType == ElementType::TRIGGER; if (parentType == ElementType::TRIGGER) return childType == ElementType::SOUND_ELEMENT; if (parentType == ElementType::LAYER_ANIMATION_GROUPS || parentType == ElementType::NULL_ANIMATION_GROUPS) @@ -1716,6 +1749,48 @@ namespace anm2ed return nullptr; } + void shader_ids_repair(Element& root) + { + auto content = child_first_get(root, ElementType::CONTENT); + auto shaders = content ? child_first_get(*content, ElementType::SHADERS) : nullptr; + if (!shaders) return; + + std::set usedIds{}; + int nextId{}; + for (auto& shader : shaders->children) + { + if (shader.type != ElementType::SHADER) continue; + + while (usedIds.contains(nextId)) + ++nextId; + if (shader.id < 0 || usedIds.contains(shader.id)) shader.id = nextId++; + usedIds.insert(shader.id); + if (shader.name.empty()) shader.name = "New Shader"; + } + } + + void shader_frame_ids_repair(Element& root) + { + auto content = child_first_get(root, ElementType::CONTENT); + auto shaders = content ? child_first_get(*content, ElementType::SHADERS) : nullptr; + auto animations = element_first_get(root, ElementType::ANIMATIONS); + if (!animations) return; + + std::set shaderIds{}; + if (shaders) + for (const auto& shader : shaders->children) + if (shader.type == ElementType::SHADER) shaderIds.insert(shader.id); + + auto frame_repair = [&](auto&& self, Element& element) -> void + { + if (element.type == ElementType::FRAME && element.shaderId != -1 && !shaderIds.contains(element.shaderId)) + element.shaderId = -1; + for (auto& child : element.children) + self(self, child); + }; + frame_repair(frame_repair, *animations); + } + void region_frame_ids_repair(Element& root) { auto content = child_first_get(root, ElementType::CONTENT); @@ -1823,6 +1898,36 @@ namespace anm2ed } } + void shader_ids_remap(Element& root) + { + auto content = child_first_get(root, ElementType::CONTENT); + auto shaders = content ? child_first_get(*content, ElementType::SHADERS) : nullptr; + + std::unordered_map remap{}; + int nextId{}; + if (shaders) + for (auto& shader : shaders->children) + { + if (shader.type != ElementType::SHADER) continue; + remap[shader.id] = nextId; + shader.id = nextId++; + } + + auto frame_remap = [&](auto&& self, Element& element) -> void + { + if (element.type == ElementType::FRAME && element.shaderId != -1) + { + if (auto it = remap.find(element.shaderId); it != remap.end()) + element.shaderId = it->second; + else + element.shaderId = -1; + } + for (auto& child : element.children) + self(self, child); + }; + frame_remap(frame_remap, root); + } + bool is_track_group_visible(const Element& container, const Element& track) { if (track.groupId == -1) return true; @@ -1969,6 +2074,7 @@ namespace anm2ed frame.rotation = glm::mix(frame.rotation, frameNext->rotation, amount); frame.position = glm::mix(frame.position, frameNext->position, amount); frame.scale = glm::mix(frame.scale, frameNext->scale, amount); + frame.shear = glm::mix(frame.shear, frameNext->shear, amount); frame.colorOffset = glm::mix(frame.colorOffset, frameNext->colorOffset, amount); frame.tint = glm::mix(frame.tint, frameNext->tint, amount); } @@ -2058,6 +2164,7 @@ namespace anm2ed baked.rotation = glm::mix(original.rotation, next.rotation, amount); baked.position = glm::mix(original.position, next.position, amount); baked.scale = glm::mix(original.scale, next.scale, amount); + baked.shear = glm::mix(original.shear, next.shear, amount); baked.colorOffset = glm::mix(original.colorOffset, next.colorOffset, amount); baked.tint = glm::mix(original.tint, next.tint, amount); if (isRoundScale) baked.scale = glm::round(baked.scale); @@ -2218,12 +2325,15 @@ namespace anm2ed apply_scalar(frame->size.x, change.sizeX); apply_scalar(frame->size.y, change.sizeY); if (change.regionId) frame->regionId = *change.regionId; + if (change.shaderId) frame->shaderId = *change.shaderId; } apply_scalar(frame->position.x, change.positionX); apply_scalar(frame->position.y, change.positionY); apply_scalar(frame->scale.x, change.scaleX); apply_scalar(frame->scale.y, change.scaleY); + apply_scalar(frame->shear.x, change.shearX); + apply_scalar(frame->shear.y, change.shearY); apply_scalar(frame->colorOffset.x, change.colorOffsetR); apply_scalar(frame->colorOffset.y, change.colorOffsetG); apply_scalar(frame->colorOffset.z, change.colorOffsetB); @@ -2287,6 +2397,7 @@ namespace anm2ed baked.rotation = glm::mix(original.rotation, nextFrame.rotation, amount); baked.position = glm::mix(original.position, nextFrame.position, amount); baked.scale = glm::mix(original.scale, nextFrame.scale, amount); + baked.shear = glm::mix(original.shear, nextFrame.shear, amount); baked.colorOffset = glm::mix(original.colorOffset, nextFrame.colorOffset, amount); baked.tint = glm::mix(original.tint, nextFrame.tint, amount); if (isRoundScale) baked.scale = glm::round(baked.scale); @@ -2344,6 +2455,7 @@ namespace anm2ed auto content = element_make(ElementType::CONTENT); content.children.push_back(element_make(ElementType::SPRITESHEETS)); + content.children.push_back(element_make(ElementType::SHADERS)); content.children.push_back(element_make(ElementType::LAYERS)); content.children.push_back(element_make(ElementType::NULLS)); content.children.push_back(element_make(ElementType::EVENTS)); @@ -2505,6 +2617,7 @@ namespace anm2ed if (has_flag(flags, SERIALIZE_FLATTEN_SPECIAL_INTERPOLATED_FRAMES)) all_interpolated_frames_bake(normalized.root, FRAME_DURATION_MIN, false, false); region_ids_remap(normalized.root); + shader_ids_remap(normalized.root); if (has_flag(flags, SERIALIZE_GROUPS) && has_flag(flags, SERIALIZE_NESTED_GROUPS)) groups_nest(normalized.root); else @@ -2541,6 +2654,7 @@ namespace anm2ed switch (type) { case ElementType::SPRITESHEETS: + case ElementType::SHADERS: case ElementType::LAYERS: case ElementType::NULLS: case ElementType::EVENTS: @@ -2692,6 +2806,17 @@ namespace anm2ed used.insert(id); } } + else if (type == ElementType::SHADER) + { + auto layerAnimations = child_first_get(animation, ElementType::LAYER_ANIMATIONS); + if (!layerAnimations) continue; + tracks_each(*layerAnimations, ElementType::LAYER_ANIMATION, + [&](const Element& layerAnimation) + { + for (const auto& frame : layerAnimation.children) + if (frame.type == ElementType::FRAME && frame.shaderId != -1) used.insert(frame.shaderId); + }); + } else if (type == ElementType::LAYER_ELEMENT || type == ElementType::NULL_ELEMENT) { auto containerType = @@ -2763,14 +2888,17 @@ namespace anm2ed auto layer = element_get(ElementType::LAYER_ELEMENT, layerAnimation.layerId); if (!layer || layer->spritesheetId != parentId) return; for (const auto& frame : layerAnimation.children) - if (frame.type == ElementType::FRAME && frame.regionId != -1) used.insert(frame.regionId); + { + if (frame.type != ElementType::FRAME) continue; + if (frame.regionId != -1) used.insert(frame.regionId); + } }); } std::set unused{}; if (auto spritesheet = element_get(ElementType::SPRITESHEET, parentId)) - for (const auto& region : spritesheet->children) - if (region.type == ElementType::REGION && !used.contains(region.id)) unused.insert(region.id); + for (const auto& child : spritesheet->children) + if (child.type == type && !used.contains(child.id)) unused.insert(child.id); return unused; } @@ -2895,7 +3023,7 @@ namespace anm2ed { auto rootFrame = frame_generate(*root, t); transform *= math::quad_model_parent_get(rootFrame.position, {}, math::percent_to_unit(rootFrame.scale), - rootFrame.rotation); + rootFrame.rotation, math::percent_to_unit(rootFrame.shear)); } auto layerAnimations = child_first_get(animation, ElementType::LAYER_ANIMATIONS); @@ -2912,9 +3040,9 @@ namespace anm2ed if (auto groupRoot = child_first_get(*group, ElementType::ROOT_ANIMATION)) { auto groupRootFrame = frame_generate(*groupRoot, t); - itemTransform *= math::quad_model_parent_get(groupRootFrame.position, {}, - math::percent_to_unit(groupRootFrame.scale), - groupRootFrame.rotation); + itemTransform *= math::quad_model_parent_get( + groupRootFrame.position, {}, math::percent_to_unit(groupRootFrame.scale), + groupRootFrame.rotation, math::percent_to_unit(groupRootFrame.shear)); } auto frame = frame_effective(layerAnimation.layerId, frame_generate(layerAnimation, t)); @@ -2922,7 +3050,8 @@ namespace anm2ed auto layerTransform = itemTransform * math::quad_model_get(frame.size, frame.position, frame.pivot, - math::percent_to_unit(frame.scale), frame.rotation); + math::percent_to_unit(frame.scale), frame.rotation, + math::percent_to_unit(frame.shear)); for (auto& corner : CORNERS) { auto world = layerTransform * glm::vec4(corner, 0.0f, 1.0f); diff --git a/src/anm2/anm2.hpp b/src/anm2/anm2.hpp index 763a332..b7d52fd 100644 --- a/src/anm2/anm2.hpp +++ b/src/anm2/anm2.hpp @@ -22,6 +22,7 @@ X(CONTENT, "Content") \ X(SPRITESHEETS, "Spritesheets") \ X(SPRITESHEET, "Spritesheet") \ + X(SHADERS, "Shaders") \ X(SHADER, "Shader") \ X(UNIFORM, "Uniform") \ X(COMPONENT, "Component") \ @@ -214,6 +215,7 @@ namespace anm2ed { std::optional isVisible{}; std::optional interpolation{}; + std::optional shaderId{}; std::optional rotation{}; std::optional duration{}; std::optional regionId{}; @@ -227,6 +229,8 @@ namespace anm2ed std::optional sizeY{}; std::optional scaleX{}; std::optional scaleY{}; + std::optional shearX{}; + std::optional shearY{}; std::optional colorOffsetR{}; std::optional colorOffsetG{}; std::optional colorOffsetB{}; @@ -263,6 +267,7 @@ namespace anm2ed int atFrame{-1}; int eventId{-1}; int regionId{-1}; + int shaderId{-1}; int soundId{-1}; int groupId{-1}; int index{-1}; @@ -280,6 +285,7 @@ namespace anm2ed glm::vec2 position{}; glm::vec2 size{}; glm::vec2 scale{100.0f, 100.0f}; + glm::vec2 shear{}; glm::vec3 colorOffset{}; glm::vec4 tint{types::color::WHITE}; }; diff --git a/src/dialog.hpp b/src/dialog.hpp index 8072008..859de83 100644 --- a/src/dialog.hpp +++ b/src/dialog.hpp @@ -24,6 +24,7 @@ namespace anm2ed X(SOUND, {"WAV file;OGG file", "wav;ogg"}) \ X(GIF, {"GIF image", "gif"}) \ X(WEBM, {"WebM video", "webm"}) \ + X(OGV, {"OGV video", "ogv"}) \ X(MP4, {"MP4 video", "MP4"}) \ X(EXECUTABLE, EXECUTABLE_FILTER) @@ -60,6 +61,7 @@ namespace anm2ed X(REGION_EXPORT_PATH_SET, PNG) \ X(GIF_PATH_SET, GIF) \ X(WEBM_PATH_SET, WEBM) \ + X(OGV_PATH_SET, OGV) \ X(MP4_PATH_SET, MP4) enum Type diff --git a/src/document.cpp b/src/document.cpp index 97eafca..74c43c8 100644 --- a/src/document.cpp +++ b/src/document.cpp @@ -59,14 +59,16 @@ namespace anm2ed::document } } - const Element* shader_element_get(const Element& spritesheet) + const Element* shader_element_get(const Anm2& anm2, int id) { - return element_child_first_get(spritesheet, ElementType::SHADER); + auto shaders = anm2.element_get(ElementType::SHADERS); + return shaders ? element_child_id_get(*shaders, ElementType::SHADER, id) : nullptr; } - Element* shader_element_get(Element& spritesheet) + Element* shader_element_get(Anm2& anm2, int id) { - return element_child_first_get(spritesheet, ElementType::SHADER); + auto shaders = anm2.element_get(ElementType::SHADERS); + return shaders ? element_child_id_get(*shaders, ElementType::SHADER, id) : nullptr; } std::filesystem::path shader_absolute_path_get(Document& document, const std::filesystem::path& path) @@ -190,9 +192,8 @@ namespace anm2ed::document continue; } - auto uniform = - std::find_if(shader.uniforms.begin(), shader.uniforms.end(), - [&](const resource::shader::Uniform& uniform) { return uniform.name == it->name; }); + auto uniform = std::find_if(shader.uniforms.begin(), shader.uniforms.end(), + [&](const resource::shader::Uniform& uniform) { return uniform.name == it->name; }); if (uniform == shader.uniforms.end()) { it = shaderElement.children.erase(it); @@ -211,7 +212,8 @@ namespace anm2ed::document } auto componentCount = component_count_get(uniform->valueType); - auto isComponents = resource::shader::uniform_binding_get(it->binding) == resource::shader::UNIFORM_BINDING_COMPONENTS; + auto isComponents = + resource::shader::uniform_binding_get(it->binding) == resource::shader::UNIFORM_BINDING_COMPONENTS; auto removed = std::erase_if(it->children, [&](const Element& component) { @@ -515,18 +517,20 @@ namespace anm2ed } Document::Document(Document&& other) noexcept - : path(std::move(other.path)), tabId(other.tabId), snapshots(std::move(other.snapshots)), current(snapshots.current), - playback(current.playback), animation(current.animation), event(current.event), frames(current.frames), - items(current.items), layer(current.layer), merge(current.merge), null(current.null), region(current.region), - sound(current.sound), spritesheet(current.spritesheet), textures(current.textures), sounds(current.sounds), - anm2(current.anm2), reference(current.reference), groupReferences(current.groupReferences), - frameTime(current.frameTime), message(current.message), regionBySpritesheet(std::move(other.regionBySpritesheet)), - changeAllFramePropertiesRegionId(other.changeAllFramePropertiesRegionId), previewZoom(other.previewZoom), + : path(std::move(other.path)), tabId(other.tabId), snapshots(std::move(other.snapshots)), + current(snapshots.current), playback(current.playback), animation(current.animation), event(current.event), + frames(current.frames), items(current.items), layer(current.layer), merge(current.merge), null(current.null), + region(current.region), shader(current.shader), sound(current.sound), spritesheet(current.spritesheet), + textures(current.textures), sounds(current.sounds), anm2(current.anm2), reference(current.reference), + groupReferences(current.groupReferences), frameTime(current.frameTime), message(current.message), + regionBySpritesheet(std::move(other.regionBySpritesheet)), + changeAllFramePropertiesRegionId(other.changeAllFramePropertiesRegionId), + changeAllFramePropertiesShaderId(other.changeAllFramePropertiesShaderId), previewZoom(other.previewZoom), previewPan(other.previewPan), editorPan(other.editorPan), editorZoom(other.editorZoom), overlayIndex(other.overlayIndex), overlayDocumentId(other.overlayDocumentId), hash(other.hash), - saveHash(other.saveHash), autosaveHash(other.autosaveHash), - lastAutosaveTime(other.lastAutosaveTime), isValid(other.isValid), isOpen(other.isOpen), - isForceDirty(other.isForceDirty), spritesheetHashes(std::move(other.spritesheetHashes)), + saveHash(other.saveHash), autosaveHash(other.autosaveHash), lastAutosaveTime(other.lastAutosaveTime), + isValid(other.isValid), isOpen(other.isOpen), isForceDirty(other.isForceDirty), + spritesheetHashes(std::move(other.spritesheetHashes)), spritesheetSaveHashes(std::move(other.spritesheetSaveHashes)), texturePaths(std::move(other.texturePaths)), soundPaths(std::move(other.soundPaths)), shaderVertexPaths(std::move(other.shaderVertexPaths)), shaderFragmentPaths(std::move(other.shaderFragmentPaths)), shaders(std::move(other.shaders)), @@ -640,20 +644,19 @@ namespace anm2ed return true; } - bool Document::shader_reload(int id, std::string* status) + bool Document::shader_reload(int shaderId, std::string* status) { - auto spritesheet = anm2.element_get(ElementType::SPRITESHEET, id); - auto shaderElement = spritesheet ? document::shader_element_get(*spritesheet) : nullptr; - if (!shaderElement || !shaderElement->isEnabled) + auto shaderElement = document::shader_element_get(anm2, shaderId); + if (!shaderElement) { - if (status && !shaderElement) + if (status) { auto labelString = std::string(localize.get(LABEL_FRAGMENT)); *status += std::vformat(localize.get(LABEL_SHADER_PATH_EMPTY), std::make_format_args(labelString)) + "\n"; } - shaders.erase(id); - shaderVertexPaths.erase(id); - shaderFragmentPaths.erase(id); + shaders.erase(shaderId); + shaderVertexPaths.erase(shaderId); + shaderFragmentPaths.erase(shaderId); return false; } @@ -665,9 +668,9 @@ namespace anm2ed document::shader_source_load(*this, shaderElement->fragment, fragmentSource, LABEL_FRAGMENT, status); if (!isVertexLoaded || !isFragmentLoaded) { - shaders.erase(id); - shaderVertexPaths.erase(id); - shaderFragmentPaths.erase(id); + shaders.erase(shaderId); + shaderVertexPaths.erase(shaderId); + shaderFragmentPaths.erase(shaderId); return false; } @@ -682,9 +685,9 @@ namespace anm2ed } if (!result.isLinked || !result.id) { - shaders.erase(id); - shaderVertexPaths.erase(id); - shaderFragmentPaths.erase(id); + shaders.erase(shaderId); + shaderVertexPaths.erase(shaderId); + shaderFragmentPaths.erase(shaderId); return false; } @@ -693,9 +696,9 @@ namespace anm2ed runtime.uniforms = std::move(result.uniforms); if (document::shader_uniform_configs_trim(*shaderElement, runtime)) hash_set(); document::shader_uniform_configs_apply(*shaderElement, runtime); - shaders[id] = std::move(runtime); - shaderVertexPaths[id] = shaderElement->vertex; - shaderFragmentPaths[id] = shaderElement->fragment; + shaders[shaderId] = std::move(runtime); + shaderVertexPaths[shaderId] = shaderElement->vertex; + shaderFragmentPaths[shaderId] = shaderElement->fragment; return true; } @@ -717,25 +720,6 @@ namespace anm2ed textures[spritesheet.id] = resource::Texture(path::case_insensitive_find(spritesheet.path)); texturePaths[spritesheet.id] = spritesheet.path; } - - auto shaderElement = document::shader_element_get(spritesheet); - if (!shaderElement || !shaderElement->isEnabled || shaderElement->fragment.empty()) - { - shaders.erase(spritesheet.id); - shaderVertexPaths.erase(spritesheet.id); - shaderFragmentPaths.erase(spritesheet.id); - continue; - } - - auto isShaderReload = - !shaders.contains(spritesheet.id) || !shaderVertexPaths.contains(spritesheet.id) || - !shaderFragmentPaths.contains(spritesheet.id) || - shaderVertexPaths.at(spritesheet.id) != shaderElement->vertex || - shaderFragmentPaths.at(spritesheet.id) != shaderElement->fragment; - if (isShaderReload) - shader_reload(spritesheet.id); - else if (auto shader = shader_get(spritesheet.id)) - document::shader_uniform_configs_apply(*shaderElement, *shader); } for (auto it = textures.begin(); it != textures.end();) @@ -748,10 +732,39 @@ namespace anm2ed else ++it; } + } + + if (type == ALL || type == SHADERS) + { + std::set validShaderIds{}; + util::WorkingDirectory workingDirectory(directory_get()); + if (auto shaderItems = anm2.element_get(ElementType::SHADERS)) + for (auto& shaderElement : shaderItems->children) + { + if (shaderElement.type != ElementType::SHADER) continue; + + validShaderIds.insert(shaderElement.id); + if (shaderElement.fragment.empty()) + { + shaders.erase(shaderElement.id); + shaderVertexPaths.erase(shaderElement.id); + shaderFragmentPaths.erase(shaderElement.id); + continue; + } + + auto isShaderReload = !shaders.contains(shaderElement.id) || !shaderVertexPaths.contains(shaderElement.id) || + !shaderFragmentPaths.contains(shaderElement.id) || + shaderVertexPaths.at(shaderElement.id) != shaderElement.vertex || + shaderFragmentPaths.at(shaderElement.id) != shaderElement.fragment; + if (isShaderReload) + shader_reload(shaderElement.id); + else if (auto shader = shader_get(shaderElement.id)) + document::shader_uniform_configs_apply(shaderElement, *shader); + } for (auto it = shaders.begin(); it != shaders.end();) { - if (!validIds.contains(it->first)) + if (!validShaderIds.contains(it->first)) { shaderVertexPaths.erase(it->first); shaderFragmentPaths.erase(it->first); @@ -817,15 +830,17 @@ namespace anm2ed return it == sounds.end() ? nullptr : &it->second; } - resource::Shader* Document::shader_get(int id) + resource::Shader* Document::shader_get(int shaderId) { - auto it = shaders.find(id); + if (shaderId == -1) return nullptr; + auto it = shaders.find(shaderId); return it == shaders.end() || !it->second.is_valid() ? nullptr : &it->second; } - const resource::Shader* Document::shader_get(int id) const + const resource::Shader* Document::shader_get(int shaderId) const { - auto it = shaders.find(id); + if (shaderId == -1) return nullptr; + auto it = shaders.find(shaderId); return it == shaders.end() || !it->second.is_valid() ? nullptr : &it->second; } @@ -1352,12 +1367,15 @@ namespace anm2ed if (sourceSpritesheetId == baseId) return; for (auto& frame : layerAnimation.children) { - if (frame.type != ElementType::FRAME || frame.regionId == -1) continue; - if (isMakeRegions && regionIdMap.contains(sourceSpritesheetId) && - regionIdMap.at(sourceSpritesheetId).contains(frame.regionId)) - frame.regionId = regionIdMap.at(sourceSpritesheetId).at(frame.regionId); - else - frame.regionId = -1; + if (frame.type != ElementType::FRAME) continue; + if (frame.regionId != -1) + { + if (isMakeRegions && regionIdMap.contains(sourceSpritesheetId) && + regionIdMap.at(sourceSpritesheetId).contains(frame.regionId)) + frame.regionId = regionIdMap.at(sourceSpritesheetId).at(frame.regionId); + else + frame.regionId = -1; + } } }; for (auto& layerAnimation : layerAnimations->children) @@ -1631,7 +1649,8 @@ namespace anm2ed } }; - auto track_tree_remap = [&](auto&& self, Element item, int itemType, Element& container, int parentGroupId = -1) -> void + auto track_tree_remap = [&](auto&& self, Element item, int itemType, Element& container, + int parentGroupId = -1) -> void { auto trackType = itemType == LAYER ? ElementType::LAYER_ANIMATION : ElementType::NULL_ANIMATION; if (item.type == ElementType::GROUP) @@ -1716,7 +1735,8 @@ namespace anm2ed destinationContainer.children.push_back(sourceTrack); }; - auto track_container_merge = [&](Element& destinationContainer, const Element& sourceContainer, ElementType trackType) + auto track_container_merge = + [&](Element& destinationContainer, const Element& sourceContainer, ElementType trackType) { std::unordered_map groupRemap{}; for (auto item : sourceContainer.children) @@ -1724,8 +1744,7 @@ namespace anm2ed if (item.type != ElementType::GROUP) continue; auto sourceGroupId = item.id; item.id = element_child_next_id_get(destinationContainer, ElementType::GROUP); - std::erase_if(item.children, [](const Element& child) - { return child.type != ElementType::ROOT_ANIMATION; }); + std::erase_if(item.children, [](const Element& child) { return child.type != ElementType::ROOT_ANIMATION; }); if (!element_child_first_get(item, ElementType::ROOT_ANIMATION)) { auto root = element_make(ElementType::ROOT_ANIMATION); @@ -1739,8 +1758,7 @@ namespace anm2ed for (auto item : sourceContainer.children) { if (item.type != trackType) continue; - if (item.groupId != -1) - item.groupId = groupRemap.contains(item.groupId) ? groupRemap.at(item.groupId) : -1; + if (item.groupId != -1) item.groupId = groupRemap.contains(item.groupId) ? groupRemap.at(item.groupId) : -1; track_merge(destinationContainer, item); } }; @@ -1899,6 +1917,13 @@ namespace anm2ed } }; + auto shaders_set = [&]() + { + auto shaderItems = anm2.element_get(ElementType::SHADERS); + shader.labels_set(document::element_name_labels_get(shaderItems, ElementType::SHADER, true), + document::element_ids_get(shaderItems, ElementType::SHADER, true)); + }; + switch (type) { case LAYERS: @@ -1912,6 +1937,9 @@ namespace anm2ed spritesheets_set(); regions_set(); break; + case SHADERS: + shaders_set(); + break; case SOUNDS: sounds_set(); break; @@ -1927,6 +1955,7 @@ namespace anm2ed events_set(); spritesheets_set(); regions_set(); + shaders_set(); animations_set(); sounds_set(); break; @@ -2147,8 +2176,7 @@ namespace anm2ed { auto targetReference = itemReference; targetReference.animationIndex = reference.animationIndex; - if (reference.animationIndex == itemReference.animationIndex || !anm2.element_get(targetReference)) - return {}; + if (reference.animationIndex == itemReference.animationIndex || !anm2.element_get(targetReference)) return {}; itemReference = targetReference; } result.push_back(itemReference); @@ -2156,10 +2184,7 @@ namespace anm2ed return result; } - Element* Document::frame_get() - { - return anm2.element_get(reference); - } + Element* Document::frame_get() { return anm2.element_get(reference); } Element* Document::item_get() { @@ -2170,10 +2195,7 @@ namespace anm2ed Element* Document::animation_get() { return anm2.element_get(ElementType::ANIMATION, reference.animationIndex); } Element* Document::spritesheet_get() { return anm2.element_get(ElementType::SPRITESHEET, spritesheet.reference); } - void Document::spritesheet_add(const std::filesystem::path& path) - { - spritesheets_add({path}); - } + void Document::spritesheet_add(const std::filesystem::path& path) { spritesheets_add({path}); } void Document::spritesheets_add(const std::vector& paths) { @@ -2234,10 +2256,7 @@ namespace anm2ed change(Document::SPRITESHEETS); } - void Document::sound_add(const std::filesystem::path& path) - { - sounds_add({path}); - } + void Document::sound_add(const std::filesystem::path& path) { sounds_add({path}); } void Document::sounds_add(const std::vector& paths) { diff --git a/src/document.hpp b/src/document.hpp index 5f297cc..eb766bb 100644 --- a/src/document.hpp +++ b/src/document.hpp @@ -30,6 +30,7 @@ namespace anm2ed NULLS, SPRITESHEETS, TEXTURES, + SHADERS, EVENTS, ANIMATIONS, ITEMS, @@ -82,6 +83,7 @@ namespace anm2ed Storage& merge = current.merge; Storage& null = current.null; Storage& region = current.region; + Storage& shader = current.shader; Storage& sound = current.sound; Storage& spritesheet = current.spritesheet; std::map& textures = current.textures; @@ -93,6 +95,7 @@ namespace anm2ed std::string& message = current.message; std::map regionBySpritesheet{}; int changeAllFramePropertiesRegionId{-1}; + int changeAllFramePropertiesShaderId{-1}; float previewZoom{200}; glm::vec2 previewPan{}; @@ -112,8 +115,8 @@ namespace anm2ed std::unordered_map spritesheetSaveHashes{}; std::unordered_map texturePaths{}; std::unordered_map soundPaths{}; - std::unordered_map shaderVertexPaths{}; - std::unordered_map shaderFragmentPaths{}; + std::map shaderVertexPaths{}; + std::map shaderFragmentPaths{}; std::map shaders{}; bool isAnimationPreviewSet{false}; bool isSpritesheetEditorSet{false}; diff --git a/src/imgui/window/animation_preview.cpp b/src/imgui/window/animation_preview.cpp index 4a329d5..e7ae14a 100644 --- a/src/imgui/window/animation_preview.cpp +++ b/src/imgui/window/animation_preview.cpp @@ -114,13 +114,11 @@ namespace anm2ed::imgui { std::optional rect{}; - if (animation) - rect = animation_rects_merge(rect, document.anm2.animation_rect(*animation, isRootTransform)); + if (animation) rect = animation_rects_merge(rect, document.anm2.animation_rect(*animation, isRootTransform)); if (auto overlayDocument = overlay_animation_document_get(manager, document)) if (auto overlayAnimation = overlayDocument->anm2.element_get(ElementType::ANIMATION, document.overlayIndex)) - rect = animation_rects_merge(rect, - overlayDocument->anm2.animation_rect(*overlayAnimation, isRootTransform)); + rect = animation_rects_merge(rect, overlayDocument->anm2.animation_rect(*overlayAnimation, isRootTransform)); return rect; } @@ -660,10 +658,9 @@ namespace anm2ed::imgui overlayTransparency = glm::clamp(overlayTransparency, 0.0f, 100.0f); auto orderIconSize = icon_size_get(); auto orderButtonWidth = orderIconSize.x + ImGui::GetStyle().FramePadding.x * 2.0f; - auto alphaWidth = - std::max(ImGui::GetContentRegionAvail().x - (orderButtonWidth * 2.0f) - - (ImGui::GetStyle().ItemSpacing.x * 2.0f), - ImGui::GetFrameHeight()); + auto alphaWidth = std::max(ImGui::GetContentRegionAvail().x - (orderButtonWidth * 2.0f) - + (ImGui::GetStyle().ItemSpacing.x * 2.0f), + ImGui::GetFrameHeight()); auto overlayIconTint = isLightTheme ? ImVec4(0.0f, 0.0f, 0.0f, 1.0f) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f); ImGui::PushItemWidth(alphaWidth); ImGui::DragFloat("##Overlay Alpha", &overlayTransparency, DRAG_SPEED, 0, 100, "%.0f%%"); @@ -897,8 +894,8 @@ namespace anm2ed::imgui }; auto render = [&](Document& sampleDocument, Element* animation, float time, vec3 colorOffset = {}, - float alphaOffset = {}, - const std::vector* layeredOnions = nullptr, bool isIndexMode = false) + float alphaOffset = {}, const std::vector* layeredOnions = nullptr, + bool isIndexMode = false) { auto& sampleAnm2 = sampleDocument.anm2; bool isActiveDocument = &sampleDocument == &document; @@ -926,8 +923,9 @@ namespace anm2ed::imgui if (isRootTransform && root) { auto rootFrame = frame_generate(*root, t); - sampleTransform *= math::quad_model_parent_get(rootFrame.position, {}, - math::percent_to_unit(rootFrame.scale), rootFrame.rotation); + sampleTransform *= + math::quad_model_parent_get(rootFrame.position, {}, math::percent_to_unit(rootFrame.scale), + rootFrame.rotation, math::percent_to_unit(rootFrame.shear)); } return sampleTransform; }; @@ -942,7 +940,8 @@ namespace anm2ed::imgui return true; }; - auto group_root_frame_get = [](const Element& container, const Element& track, float t) -> std::optional + auto group_root_frame_get = [](const Element& container, const Element& track, + float t) -> std::optional { if (track.groupId == -1) return std::nullopt; auto group = element_child_id_get(container, ElementType::GROUP, track.groupId); @@ -951,15 +950,15 @@ namespace anm2ed::imgui return frame_generate(*root, t); }; - auto group_transform_for_time = [&](const Element& container, const Element& track, float t, - const glm::mat4& sampleTransform) + auto group_transform_for_time = + [&](const Element& container, const Element& track, float t, const glm::mat4& sampleTransform) { auto itemTransform = sampleTransform; if (isRootTransform) if (auto groupRootFrame = group_root_frame_get(container, track, t)) - itemTransform *= math::quad_model_parent_get(groupRootFrame->position, {}, - math::percent_to_unit(groupRootFrame->scale), - groupRootFrame->rotation); + itemTransform *= math::quad_model_parent_get( + groupRootFrame->position, {}, math::percent_to_unit(groupRootFrame->scale), groupRootFrame->rotation, + math::percent_to_unit(groupRootFrame->shear)); return itemTransform; }; @@ -973,7 +972,8 @@ namespace anm2ed::imgui auto rootModel = isRootTransform ? math::quad_model_get(TARGET_SIZE, {}, TARGET_SIZE * 0.5f) : math::quad_model_get(TARGET_SIZE, rootFrame.position, TARGET_SIZE * 0.5f, - math::percent_to_unit(rootFrame.scale), rootFrame.rotation); + math::percent_to_unit(rootFrame.scale), rootFrame.rotation, + math::percent_to_unit(rootFrame.shear)); auto rootTransform = sampleTransform * rootModel; vec4 color = isOnion ? vec4(sampleColor, sampleAlpha) : color::GREEN; @@ -992,9 +992,8 @@ namespace anm2ed::imgui draw_root(time, transform, {}, 0.0f, false); - auto draw_group_root = [&](Element& group, int groupType, float sampleTime, - const glm::mat4& sampleTransform, vec3 sampleColor, float sampleAlpha, - bool isOnion) + auto draw_group_root = [&](Element& group, int groupType, float sampleTime, const glm::mat4& sampleTransform, + vec3 sampleColor, float sampleAlpha, bool isOnion) { auto groupRoot = element_child_first_get(group, ElementType::ROOT_ANIMATION); if (!groupRoot) return; @@ -1004,16 +1003,17 @@ namespace anm2ed::imgui auto itemTransform = sampleTransform; if (isRootTransform) itemTransform *= math::quad_model_parent_get(rootFrame.position, {}, math::percent_to_unit(rootFrame.scale), - rootFrame.rotation); + rootFrame.rotation, math::percent_to_unit(rootFrame.shear)); auto rootModel = isRootTransform ? math::quad_model_get(TARGET_SIZE, {}, TARGET_SIZE * 0.5f) : math::quad_model_get(TARGET_SIZE, rootFrame.position, TARGET_SIZE * 0.5f, - math::percent_to_unit(rootFrame.scale), rootFrame.rotation); + math::percent_to_unit(rootFrame.scale), rootFrame.rotation, + math::percent_to_unit(rootFrame.shear)); auto rootTransform = itemTransform * rootModel; - auto isSelected = isActiveDocument && referenceItemType == ItemType::ROOT && reference.groupType == groupType && - reference.groupId == group.id; + auto isSelected = isActiveDocument && referenceItemType == ItemType::ROOT && + reference.groupType == groupType && reference.groupId == group.id; vec4 color = isOnion ? vec4(sampleColor, sampleAlpha) : isSelected ? color::RED : ROOT_COLOR; auto icon = isAltIcons ? icon::TARGET_ALT : icon::TARGET; texture_render(shaderTexture, resources.icons[icon].id, rootTransform, color); @@ -1042,8 +1042,8 @@ namespace anm2ed::imgui self(self, child, isParentVisible && layerAnimation.isVisible); return; } - if (layerAnimation.type != ElementType::LAYER_ANIMATION || !isParentVisible || - !layerAnimation.isVisible || !is_track_group_visible(*layerAnimations, layerAnimation)) + if (layerAnimation.type != ElementType::LAYER_ANIMATION || !isParentVisible || !layerAnimation.isVisible || + !is_track_group_visible(*layerAnimations, layerAnimation)) return; auto id = layerAnimation.layerId; @@ -1069,10 +1069,10 @@ namespace anm2ed::imgui auto size = frame.size; auto pivot = frame.pivot; - auto layerModel = - math::quad_model_get(size, frame.position, pivot, math::percent_to_unit(frame.scale), frame.rotation); - auto itemTransform = group_transform_for_time(*layerAnimations, layerAnimation, sampleTime, - sampleTransform); + auto layerModel = math::quad_model_get(size, frame.position, pivot, math::percent_to_unit(frame.scale), + frame.rotation, math::percent_to_unit(frame.shear)); + auto itemTransform = + group_transform_for_time(*layerAnimations, layerAnimation, sampleTime, sampleTransform); auto layerTransform = itemTransform * layerModel; auto uvMin = crop / texSize; @@ -1097,13 +1097,13 @@ namespace anm2ed::imgui frameTint.a = std::max(0.0f, frameTint.a - (alphaOffset + sampleAlpha)); auto vertices = math::uv_vertices_get(uvMin, uvMax); - auto customShader = sampleDocument.shader_get(layer->spritesheetId); + auto customShader = sampleDocument.shader_get(frame.shaderId); auto& layerShader = customShader ? *customShader : shaderTexture; texture_render(layerShader, texture.id, layerTransform, frameTint, frameColorOffset, vertices.data(), vec2(texture.size), sampleTime); - auto color = isOnion ? vec4(sampleColor, 1.0f - sampleAlpha) + auto color = isOnion ? vec4(sampleColor, 1.0f - sampleAlpha) : is_layer_animation_selected(sampleDocument, id) ? SELECTED_LAYER_BORDER_COLOR : color::RED; @@ -1112,7 +1112,8 @@ namespace anm2ed::imgui if (isPivots) { auto pivotModel = math::quad_model_get(PIVOT_SIZE, frame.position, PIVOT_SIZE * 0.5f, - math::percent_to_unit(frame.scale), frame.rotation); + math::percent_to_unit(frame.scale), frame.rotation, + math::percent_to_unit(frame.shear)); auto pivotTransform = itemTransform * pivotModel; texture_render(shaderTexture, resources.icons[icon::PIVOT].id, pivotTransform, color); @@ -1180,18 +1181,19 @@ namespace anm2ed::imgui ? color::RED : NULL_COLOR; - auto nullModel = math::quad_model_get(size, frame.position, size * 0.5f, - math::percent_to_unit(frame.scale), frame.rotation); - auto itemTransform = group_transform_for_time(*nullAnimations, nullAnimation, sampleTime, - sampleTransform); + auto nullModel = + math::quad_model_get(size, frame.position, size * 0.5f, math::percent_to_unit(frame.scale), + frame.rotation, math::percent_to_unit(frame.shear)); + auto itemTransform = + group_transform_for_time(*nullAnimations, nullAnimation, sampleTime, sampleTransform); auto nullTransform = itemTransform * nullModel; texture_render(shaderTexture, resources.icons[icon].id, nullTransform, color); if (isShowRect) { - auto rectModel = - math::quad_model_get(frame.scale, frame.position, frame.scale * 0.5f, vec2(1.0f), frame.rotation); + auto rectModel = math::quad_model_get(frame.scale, frame.position, frame.scale * 0.5f, vec2(1.0f), + frame.rotation, math::percent_to_unit(frame.shear)); auto rectTransform = itemTransform * rectModel; rect_render(shaderLine, rectTransform, rectModel, color); @@ -1404,15 +1406,13 @@ namespace anm2ed::imgui auto frame_snapshot = [&](auto message) { auto queuedFrameReferences = selectedFrameReferences; - manager.command_push({manager.selected, - [message, queuedFrameReferences](Manager&, Document& document) + manager.command_push({manager.selected, [message, queuedFrameReferences](Manager&, Document& document) { document.frames_snapshot(localize.get(message), queuedFrameReferences); }}); }; auto frame_change_apply = [&](FrameChange frameChange, ChangeType changeType = ChangeType::ADJUST) { auto queuedFrameReferences = selectedFrameReferences; - manager.command_push({manager.selected, - [=](Manager&, Document& document) + manager.command_push({manager.selected, [=](Manager&, Document& document) { std::map> groupedFrames{}; for (auto frameReference : queuedFrameReferences) @@ -1442,6 +1442,11 @@ namespace anm2ed::imgui if (!frame) return; frame_change_apply({.scaleX = scale.x - frame->scale.x, .scaleY = scale.y - frame->scale.y}, ChangeType::ADD); }; + auto frame_shear_apply = [&](vec2 shear) + { + if (!frame) return; + frame_change_apply({.shearX = shear.x - frame->shear.x, .shearY = shear.y - frame->shear.y}, ChangeType::ADD); + }; auto frames_changed = [&]() { manager.command_push( @@ -1602,6 +1607,39 @@ namespace anm2ed::imgui } } + if (isToolEnd) frames_changed(); + break; + case tool::SHEAR: + if (!item || !frame || selectedFrameReferences.empty()) break; + if (isToolBegin) frame_snapshot(EDIT_FRAME_SHEAR); + if (isToolMouseDown) + { + auto shear = frame->shear + vec2(mouseDelta.x, mouseDelta.y); + if (isMod) + { + if (std::abs(mouseDelta.x) >= std::abs(mouseDelta.y)) + shear.y = frame->shear.y; + else + shear.x = frame->shear.x; + } + frame_shear_apply(shear); + } + if (isLeftPressed) frame_change_apply({.shearX = step}, ChangeType::SUBTRACT); + if (isRightPressed) frame_change_apply({.shearX = step}, ChangeType::ADD); + if (isUpPressed) frame_change_apply({.shearY = step}, ChangeType::SUBTRACT); + if (isDownPressed) frame_change_apply({.shearY = step}, ChangeType::ADD); + + if (isToolDuring) + { + if (ImGui::BeginTooltip()) + { + ImGui::TextUnformatted( + std::vformat(localize.get(FORMAT_SHEAR), std::make_format_args(frame->shear.x, frame->shear.y)) + .c_str()); + ImGui::EndTooltip(); + } + } + if (isToolEnd) frames_changed(); break; default: diff --git a/src/imgui/window/frame_properties.cpp b/src/imgui/window/frame_properties.cpp index 10a5641..9bfa4cb 100644 --- a/src/imgui/window/frame_properties.cpp +++ b/src/imgui/window/frame_properties.cpp @@ -24,11 +24,10 @@ namespace anm2ed::imgui if (frameSelectionCount == 0 && document.reference.frameIndex >= 0) frameSelectionCount = 1; auto isSingleFrameSelection = frameSelectionCount == 1; auto isMultiFrameSelection = frameSelectionCount > 1; - auto isSingleFrameBatchMode = - isSingleFrameSelection && document.reference.itemType != TRIGGER && isBatchMode; + auto isSingleFrameBatchMode = isSingleFrameSelection && document.reference.itemType != TRIGGER && isBatchMode; auto isBatchFrameProperties = isMultiFrameSelection || isSingleFrameBatchMode; - auto windowLabel = std::string(localize.get(isBatchFrameProperties ? LABEL_CHANGE_ALL_FRAME_PROPERTIES - : LABEL_FRAME_PROPERTIES_WINDOW)); + auto windowLabel = std::string( + localize.get(isBatchFrameProperties ? LABEL_CHANGE_ALL_FRAME_PROPERTIES : LABEL_FRAME_PROPERTIES_WINDOW)); if (isBatchFrameProperties) windowLabel += "###Frame Properties"; if (ImGui::Begin(windowLabel.c_str(), &settings.windowIsFrameProperties)) @@ -38,11 +37,10 @@ namespace anm2ed::imgui auto& type = reference.itemType; auto frame = reference.frameIndex >= 0 ? anm2.element_get(reference) : nullptr; - auto frame_edit = [&](auto message, auto behavior) - { - auto queuedReference = reference; - manager.command_push({manager.selected, - [=](Manager&, Document& document) mutable + auto frame_edit = [&](auto message, auto behavior) + { + auto queuedReference = reference; + manager.command_push({manager.selected, [=](Manager&, Document& document) mutable { if (queuedReference.frameIndex < 0) return; auto frame = document.anm2.element_get(queuedReference); @@ -55,15 +53,14 @@ namespace anm2ed::imgui behavior(document, *frame, item, queuedReference); document.anm2_change(Document::FRAMES); }}); - }; + }; auto persistent_edit = [&](auto state, auto message, auto behavior) { if (state == edit::NONE) return; auto queuedReference = reference; - manager.command_push({manager.selected, - [=](Manager&, Document& document) mutable + manager.command_push({manager.selected, [=](Manager&, Document& document) mutable { if (queuedReference.frameIndex < 0) return; auto frame = document.anm2.element_get(queuedReference); @@ -72,11 +69,12 @@ namespace anm2ed::imgui auto item = document.anm2.element_get(itemReference); if (!frame) return; - if (state == edit::START) document.frames_snapshot(localize.get(message), {queuedReference}); + if (state == edit::START) + document.frames_snapshot(localize.get(message), {queuedReference}); behavior(document, *frame, item, queuedReference); if (state == edit::END) document.anm2_change(Document::FRAMES); }}); - }; + }; auto regionLabelsString = std::vector{localize.get(BASIC_NONE)}; auto regionLabels = std::vector{regionLabelsString[0].c_str()}; @@ -165,8 +163,7 @@ namespace anm2ed::imgui frame) { auto isVisible = useFrame.isVisible; - frame_edit(EDIT_TRIGGER_VISIBILITY, - [isVisible](Document&, Element& frame, Element*, const Reference&) + frame_edit(EDIT_TRIGGER_VISIBILITY, [isVisible](Document&, Element& frame, Element*, const Reference&) { frame.isVisible = isVisible; }); } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_TRIGGER_VISIBILITY)); @@ -247,8 +244,7 @@ namespace anm2ed::imgui ImGui::EndDisabled(); auto positionEdit = - drag_float2_persistent(localize.get(BASIC_POSITION), - frame ? &useFrame.position : &dummy_value(), + drag_float2_persistent(localize.get(BASIC_POSITION), frame ? &useFrame.position : &dummy_value(), DRAG_SPEED, 0.0f, 0.0f, frame ? vec2_format_get(frame->position) : ""); persistent_edit(positionEdit, EDIT_FRAME_POSITION, [position = useFrame.position](Document&, Element& frame, Element*, const Reference&) @@ -276,6 +272,14 @@ namespace anm2ed::imgui { frame.scale = scale; }); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_SCALE)); + auto shearEdit = + drag_float2_persistent(localize.get(BASIC_SHEAR), frame ? &useFrame.shear : &dummy_value(), + DRAG_SPEED, 0.0f, 0.0f, frame ? vec2_format_get(frame->shear) : ""); + persistent_edit(shearEdit, EDIT_FRAME_SHEAR, + [shear = useFrame.shear](Document&, Element& frame, Element*, const Reference&) + { frame.shear = shear; }); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_SHEAR)); + auto rotationEdit = drag_float_persistent(localize.get(BASIC_ROTATION), frame ? &useFrame.rotation : &dummy_value(), DRAG_SPEED, 0.0f, 0.0f, frame ? float_format_get(frame->rotation) : ""); @@ -290,8 +294,8 @@ namespace anm2ed::imgui frame) { auto duration = useFrame.duration; - frame_edit(EDIT_FRAME_DURATION, - [duration](Document&, Element& frame, Element*, const Reference&) { frame.duration = duration; }); + frame_edit(EDIT_FRAME_DURATION, [duration](Document&, Element& frame, Element*, const Reference&) + { frame.duration = duration; }); } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_DURATION)); @@ -311,7 +315,7 @@ namespace anm2ed::imgui ImGui::BeginDisabled(type != LAYER); if (combo_id_mapped(localize.get(BASIC_REGION), frame ? &useFrame.regionId : &dummy_value_negative(), - regionIds, regionLabels) && + regionIds, regionLabels) && frame) { auto regionId = useFrame.regionId; @@ -337,12 +341,23 @@ namespace anm2ed::imgui { frame.interpolation = static_cast(interpolationValue); }); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FRAME_INTERPOLATION)); + ImGui::BeginDisabled(type != LAYER); + if (combo_id_mapped(localize.get(BASIC_SHADER), frame ? &useFrame.shaderId : &dummy_value_negative(), + document.shader.ids, document.shader.labels) && + frame) + { + auto shaderId = useFrame.shaderId; + frame_edit(EDIT_FRAME_SHADER, [shaderId](Document&, Element& frame, Element*, const Reference&) + { frame.shaderId = shaderId; }); + } + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FRAME_SHADER)); + ImGui::EndDisabled(); + if (ImGui::Checkbox(localize.get(BASIC_VISIBLE), frame ? &useFrame.isVisible : &dummy_value()) && frame) { auto isVisible = useFrame.isVisible; - frame_edit(EDIT_FRAME_VISIBILITY, - [isVisible](Document&, Element& frame, Element*, const Reference&) + frame_edit(EDIT_FRAME_VISIBILITY, [isVisible](Document&, Element& frame, Element*, const Reference&) { frame.isVisible = isVisible; }); } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FRAME_VISIBILITY)); @@ -359,8 +374,8 @@ namespace anm2ed::imgui frame.position.x = -frame.position.x; }); else - frame_edit(EDIT_FRAME_FLIP_X, - [](Document&, Element& frame, Element*, const Reference&) { frame.scale.x = -frame.scale.x; }); + frame_edit(EDIT_FRAME_FLIP_X, [](Document&, Element& frame, Element*, const Reference&) + { frame.scale.x = -frame.scale.x; }); } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FLIP_X)); ImGui::SameLine(); @@ -374,10 +389,13 @@ namespace anm2ed::imgui frame.position.y = -frame.position.y; }); else - frame_edit(EDIT_FRAME_FLIP_Y, - [](Document&, Element& frame, Element*, const Reference&) { frame.scale.y = -frame.scale.y; }); + frame_edit(EDIT_FRAME_FLIP_Y, [](Document&, Element& frame, Element*, const Reference&) + { frame.scale.y = -frame.scale.y; }); } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FLIP_Y)); + + ImGui::Separator(); + ImGui::Dummy(ImVec2(0.0f, ImGui::GetFrameHeight())); } } ImGui::EndDisabled(); diff --git a/src/imgui/window/shaders.cpp b/src/imgui/window/shaders.cpp index 14e3a71..f5605ae 100644 --- a/src/imgui/window/shaders.cpp +++ b/src/imgui/window/shaders.cpp @@ -1,13 +1,14 @@ #include "shaders.hpp" -#include #include #include +#include #include #include "path.hpp" #include "strings.hpp" +#include "toast.hpp" #include "util/imgui/input.hpp" #include "util/imgui/layout.hpp" @@ -41,39 +42,20 @@ namespace anm2ed::imgui return document.directory_get() / loadPath; } - bool is_shader_reload_needed(Document& document, Element& spritesheet, Element* shader) + bool is_shader_reload_needed(Document& document, Element* shader) { - if (!shader || !shader->isEnabled || shader->fragment.empty()) return false; - if (!document.shader_get(spritesheet.id)) return true; - if (!document.shaderVertexPaths.contains(spritesheet.id) || !document.shaderFragmentPaths.contains(spritesheet.id)) + if (!shader || shader->fragment.empty()) return false; + if (!document.shader_get(shader->id)) return true; + if (!document.shaderVertexPaths.contains(shader->id) || !document.shaderFragmentPaths.contains(shader->id)) return true; - return document.shaderVertexPaths.at(spritesheet.id) != shader->vertex || - document.shaderFragmentPaths.at(spritesheet.id) != shader->fragment; + return document.shaderVertexPaths.at(shader->id) != shader->vertex || + document.shaderFragmentPaths.at(shader->id) != shader->fragment; } - Element* shader_spritesheet_get(Document& document) + Element* shader_element_get(Document& document, int id) { - if (document.spritesheet.selection.size() == 1) - return document.anm2.element_get(ElementType::SPRITESHEET, *document.spritesheet.selection.begin()); - return nullptr; - } - - Element* shader_element_get(Element& spritesheet, bool isCreate) - { - if (auto shader = element_child_first_get(spritesheet, ElementType::SHADER)) return shader; - if (!isCreate) return nullptr; - - spritesheet.children.push_back(element_make(ElementType::SHADER)); - return &spritesheet.children.back(); - } - - void shader_enabled_set(Document& document, Element& spritesheet, bool isEnabled) - { - if (auto shader = shader_element_get(spritesheet, true)) - { - shader->isEnabled = isEnabled; - document.change(Document::SPRITESHEETS); - } + auto shaders = document.anm2.element_get(ElementType::SHADERS); + return shaders ? element_child_id_get(*shaders, ElementType::SHADER, id) : nullptr; } std::filesystem::path shader_asset_path_get(Document& document, const std::filesystem::path& path) @@ -82,13 +64,14 @@ namespace anm2ed::imgui return path::backslash_replace(path::make_relative(loadPath, document.directory_get())); } - void shader_path_edit(Document& document, Element& spritesheet, std::filesystem::path Element::* member, + void shader_path_edit(Document& document, int shaderId, std::filesystem::path Element::* member, const std::filesystem::path& value) { - if (auto shader = shader_element_get(spritesheet, true)) + auto shader = shader_element_get(document, shaderId); + if (shader) { shader->*member = path::backslash_replace(value); - document.change(Document::SPRITESHEETS); + document.change(Document::SHADERS); } } @@ -98,34 +81,28 @@ namespace anm2ed::imgui if (!dialog.is_selected(type)) return; auto dialogPath = dialog.path; - auto spritesheetId = window.dialogSpritesheetId; - manager.command_push({manager.selected, - [dialogPath, spritesheetId, member](Manager&, Document& document) - { - auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, spritesheetId); - if (!spritesheet) return; - shader_path_edit(document, *spritesheet, member, - shader_asset_path_get(document, dialogPath)); - }}); - window.dialogSpritesheetId = -1; + auto shaderId = window.dialogShaderId; + manager.command_push( + {manager.selected, [dialogPath, shaderId, member](Manager&, Document& document) + { shader_path_edit(document, shaderId, member, shader_asset_path_get(document, dialogPath)); }}); + window.dialogShaderId = -1; dialog.reset(); } void shader_path_row_update(ShadersWindow& window, Document& document, Resources& resources, Dialog& dialog, - Element* spritesheet, std::filesystem::path Element::* member, Dialog::Type dialogType, + Element* shader, std::filesystem::path Element::* member, Dialog::Type dialogType, StringType label) { - auto shader = spritesheet ? shader_element_get(*spritesheet, false) : nullptr; auto shaderPath = shader ? shader->*member : std::filesystem::path{}; auto isDefault = shaderPath.empty(); auto displayPath = isDefault ? path::from_utf8(localize.get(BASIC_DEFAULT)) : shaderPath; - if (ImGui::ImageButton(std::format("##{} Path Set", localize.get(label)).c_str(), - resources.icons[icon::FOLDER].id, icon_size_get())) + if (ImGui::ImageButton(std::format("##{} Path Set", localize.get(label)).c_str(), resources.icons[icon::FOLDER].id, + icon_size_get())) { - if (spritesheet) + if (shader) { - window.dialogSpritesheetId = spritesheet->id; + window.dialogShaderId = shader->id; dialog.file_open(dialogType); } } @@ -139,8 +116,7 @@ namespace anm2ed::imgui ImGui::BeginDisabled(isDefault); auto isEdited = input_text_path(std::format("##{} Path", localize.get(label)).c_str(), &displayPath); ImGui::EndDisabled(); - if (isEdited && spritesheet) - shader_path_edit(document, *spritesheet, member, displayPath); + if (isEdited && shader) shader_path_edit(document, shader->id, member, displayPath); ImGui::SameLine(); ImGui::TextUnformatted(localize.get(label)); @@ -159,13 +135,14 @@ namespace anm2ed::imgui { auto component = shader_uniform_component_get(*config, index, true); if (!component) continue; - component->binding = std::string(resource::shader::uniform_binding_value_get(uniform.components[index].binding)); + component->binding = + std::string(resource::shader::uniform_binding_value_get(uniform.components[index].binding)); component->value = std::format("{:.6g}", uniform.components[index].value); } } else std::erase_if(config->children, [](const Element& child) { return child.type == ElementType::COMPONENT; }); - document.change(Document::SPRITESHEETS); + document.change(Document::SHADERS); } int shader_uniform_component_count_get(resource::shader::UniformValueType type) @@ -264,19 +241,14 @@ namespace anm2ed::imgui return isChanged; } - void shader_uniforms_update(Document& document, Element* shaderElement, resource::Shader* runtime) + void shader_uniforms_update(Document& document, Element* shaderElement, resource::Shader* runtime, ImVec2 tableSize) { - if (!shaderElement || !runtime) return; - - if (runtime->uniforms.empty()) - { - ImGui::TextUnformatted(localize.get(BASIC_NONE)); - return; - } + if (!shaderElement) return; auto flags = ImGuiTableFlags_BordersInnerV | ImGuiTableFlags_BordersOuterH | ImGuiTableFlags_RowBg | ImGuiTableFlags_Resizable | ImGuiTableFlags_SizingStretchProp | ImGuiTableFlags_ScrollY; - auto tableSize = ImGui::GetContentRegionAvail(); + if (tableSize.x <= 0.0f) tableSize.x = ImGui::GetContentRegionAvail().x; + if (tableSize.y <= 0.0f) tableSize.y = ImGui::GetContentRegionAvail().y; if (tableSize.y < ImGui::GetFrameHeight()) tableSize.y = ImGui::GetFrameHeight(); if (!ImGui::BeginTable("##Shader Uniforms", 4, flags, tableSize)) return; @@ -287,57 +259,58 @@ namespace anm2ed::imgui ImGui::TableSetupScrollFreeze(0, 1); ImGui::TableHeadersRow(); - for (auto& uniform : runtime->uniforms) - { - ImGui::PushID(uniform.name.c_str()); - ImGui::TableNextRow(); - - ImGui::TableNextColumn(); - ImGui::TextUnformatted(uniform.name.c_str()); - - ImGui::TableNextColumn(); - ImGui::TextUnformatted(resource::shader::uniform_value_type_label_get(uniform.valueType).data()); - - ImGui::TableNextColumn(); - auto bindingLabel = resource::shader::uniform_binding_label_get(uniform.binding); - ImGui::SetNextItemWidth(-1.0f); - if (ImGui::BeginCombo("##Binding", bindingLabel.data())) + if (runtime) + for (auto& uniform : runtime->uniforms) { - for (auto binding : SHADER_UNIFORM_BINDING_COMBO_ORDER) + ImGui::PushID(uniform.name.c_str()); + ImGui::TableNextRow(); + + ImGui::TableNextColumn(); + ImGui::TextUnformatted(uniform.name.c_str()); + + ImGui::TableNextColumn(); + ImGui::TextUnformatted(resource::shader::uniform_value_type_label_get(uniform.valueType).data()); + + ImGui::TableNextColumn(); + auto bindingLabel = resource::shader::uniform_binding_label_get(uniform.binding); + ImGui::SetNextItemWidth(-1.0f); + if (ImGui::BeginCombo("##Binding", bindingLabel.data())) { - if (!resource::shader::is_uniform_binding_valid(binding, uniform.valueType)) continue; - auto isSelected = uniform.binding == binding; - auto label = resource::shader::uniform_binding_label_get(binding); - if (ImGui::Selectable(label.data(), isSelected)) + for (auto binding : SHADER_UNIFORM_BINDING_COMBO_ORDER) { - uniform.binding = binding; - if (uniform.binding == resource::shader::UNIFORM_BINDING_COMPONENTS) - shader_uniform_components_from_value_set(uniform); + if (!resource::shader::is_uniform_binding_valid(binding, uniform.valueType)) continue; + auto isSelected = uniform.binding == binding; + auto label = resource::shader::uniform_binding_label_get(binding); + if (ImGui::Selectable(label.data(), isSelected)) + { + uniform.binding = binding; + if (uniform.binding == resource::shader::UNIFORM_BINDING_COMPONENTS) + shader_uniform_components_from_value_set(uniform); + shader_uniform_config_save(document, *shaderElement, uniform); + } + if (isSelected) ImGui::SetItemDefaultFocus(); + } + ImGui::EndCombo(); + } + + ImGui::TableNextColumn(); + if (uniform.binding == resource::shader::UNIFORM_BINDING_COMPONENTS) + { + if (shader_uniform_components_update(uniform)) shader_uniform_config_save(document, *shaderElement, uniform); + } + else + { + ImGui::BeginDisabled(uniform.binding != resource::shader::UNIFORM_BINDING_MANUAL); + if (shader_uniform_value_update(uniform)) + { + shader_uniform_components_from_value_set(uniform); shader_uniform_config_save(document, *shaderElement, uniform); } - if (isSelected) ImGui::SetItemDefaultFocus(); + ImGui::EndDisabled(); } - ImGui::EndCombo(); - } - ImGui::TableNextColumn(); - if (uniform.binding == resource::shader::UNIFORM_BINDING_COMPONENTS) - { - if (shader_uniform_components_update(uniform)) shader_uniform_config_save(document, *shaderElement, uniform); + ImGui::PopID(); } - else - { - ImGui::BeginDisabled(uniform.binding != resource::shader::UNIFORM_BINDING_MANUAL); - if (shader_uniform_value_update(uniform)) - { - shader_uniform_components_from_value_set(uniform); - shader_uniform_config_save(document, *shaderElement, uniform); - } - ImGui::EndDisabled(); - } - - ImGui::PopID(); - } ImGui::EndTable(); } @@ -347,83 +320,266 @@ namespace anm2ed::imgui if (ImGui::Begin(localize.get(LABEL_SHADERS_WINDOW), &settings.windowIsShaders)) { auto document = manager.get(); - auto spritesheet = document ? shader_spritesheet_get(*document) : nullptr; - auto shader = spritesheet ? shader_element_get(*spritesheet, false) : nullptr; - auto isShaderEnabled = !shader || shader->isEnabled; - auto isReloadNeeded = document && spritesheet && is_shader_reload_needed(*document, *spritesheet, shader); - - shader_dialog_update(*this, manager, dialog, Dialog::SHADER_VERTEX_PATH_SET, &Element::vertex); - shader_dialog_update(*this, manager, dialog, Dialog::SHADER_FRAGMENT_PATH_SET, &Element::fragment); - - if (!spritesheet) + if (!document) + { + ImGui::End(); + return; + } + auto shaders = document->anm2.element_get(ElementType::SHADERS); + if (!shaders) { - ImGui::TextUnformatted(localize.get(TEXT_SELECT_SPRITESHEET)); ImGui::End(); return; } + shader_dialog_update(*this, manager, dialog, Dialog::SHADER_VERTEX_PATH_SET, &Element::vertex); + shader_dialog_update(*this, manager, dialog, Dialog::SHADER_FRAGMENT_PATH_SET, &Element::fragment); + + auto shader_add = [&]() + { + manager.command_push({manager.selected, [this](Manager&, Document& document) + { + auto shaders = document.anm2.element_get(ElementType::SHADERS); + if (!shaders) return; + + auto shader = element_make(ElementType::SHADER); + shader.id = element_child_next_id_get(*shaders, ElementType::SHADER); + shader.name = localize.get(TEXT_NEW_SHADER); + + document.anm2_snapshot(localize.get(EDIT_ADD_SHADER)); + shaders->children.push_back(shader); + document.shader.selection = {shader.id}; + document.shader.reference = shader.id; + newElementId = shader.id; + document.anm2_change(Document::SHADERS); + }}); + }; + + auto unused_shaders_remove = [&]() + { + manager.command_push({manager.selected, [this](Manager&, Document& document) + { + auto shaders = document.anm2.element_get(ElementType::SHADERS); + if (!shaders) return; + auto unused = document.anm2.element_unused(ElementType::SHADER); + if (unused.empty()) return; + + document.anm2_snapshot(localize.get(EDIT_REMOVE_UNUSED_SHADERS)); + for (auto id : unused) + { + element_child_id_erase(*shaders, ElementType::SHADER, id); + document.shader.selection.erase(id); + if (document.shader.reference == id) document.shader.reference = -1; + if (popupShaderId == id) propertiesPopup.close(); + } + document.anm2_change(Document::SHADERS); + }}); + }; + + auto& selection = document->shader.selection; + auto& reference = document->shader.reference; + std::vector ids{}; + for (auto& shader : shaders->children) + if (shader.type == ElementType::SHADER) ids.push_back(shader.id); + + if (reference != -1 && !element_child_id_get(*shaders, ElementType::SHADER, reference)) reference = -1; + for (auto it = selection.begin(); it != selection.end();) + { + if (!element_child_id_get(*shaders, ElementType::SHADER, *it)) + it = selection.erase(it); + else + ++it; + } + auto contentSize = size_without_footer_get(); if (contentSize.y < ImGui::GetFrameHeight()) contentSize.y = ImGui::GetFrameHeight(); + auto tooltipWindowPadding = ImGui::GetStyle().WindowPadding; + auto tooltipItemSpacing = ImGui::GetStyle().ItemSpacing; + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); if (ImGui::BeginChild("##Shaders Child", contentSize, ImGuiChildFlags_Borders)) { - ImGui::BeginDisabled(!isShaderEnabled); - if (ImGui::BeginTabBar("##Shaders Tabs")) + auto style = ImGui::GetStyle(); + auto shaderChildSize = ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetTextLineHeightWithSpacing() * 2); + + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2()); + selection.start(ids.size()); + if (ImGui::Shortcut(ImGuiMod_Ctrl | ImGuiKey_A, ImGuiInputFlags_RouteFocused)) { - if (ImGui::BeginTabItem(localize.get(LABEL_FILES))) + selection.clear(); + for (auto id : ids) + selection.insert(id); + } + if (ImGui::Shortcut(ImGuiKey_Escape, ImGuiInputFlags_RouteFocused)) + { + selection.clear(); + reference = -1; + } + + for (auto& shader : shaders->children) + { + if (shader.type != ElementType::SHADER) continue; + auto id = shader.id; + auto isNewShader = newElementId == id; + ImGui::PushID(id); + + if (ImGui::BeginChild("##Shader Child", shaderChildSize, ImGuiChildFlags_Borders)) { - if (document) + auto isSelected = selection.contains(id); + auto cursorPos = ImGui::GetCursorPos(); + auto runtime = document->shader_get(id); + bool isValid = runtime != nullptr; + auto& shaderIcon = isValid ? resources.icons[icon::SHADER] : resources.icons[icon::NONE]; + auto tintColor = !isValid ? ImVec4(1.0f, 0.25f, 0.25f, 1.0f) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f); + + ImGui::SetNextItemSelectionUserData(id); + ImGui::SetNextItemStorageID(id); + auto isActivated = ImGui::Selectable("##Shader Selectable", isSelected, 0, shaderChildSize); + auto isClicked = + ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right); + if (isActivated || isClicked) reference = id; + if (ImGui::IsItemHovered() && ImGui::IsMouseDoubleClicked(ImGuiMouseButton_Left)) { - shader_path_row_update(*this, *document, resources, dialog, spritesheet, &Element::vertex, - Dialog::SHADER_VERTEX_PATH_SET, LABEL_VERTEX); - shader_path_row_update(*this, *document, resources, dialog, spritesheet, &Element::fragment, - Dialog::SHADER_FRAGMENT_PATH_SET, LABEL_FRAGMENT); + selection = {id}; + reference = id; + popupShaderId = id; + propertiesPopup.open(); } - if (isReloadNeeded) ImGui::TextWrapped("%s", localize.get(LABEL_SHADER_RELOAD_NEEDED)); + ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, tooltipItemSpacing); + ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, tooltipWindowPadding); + if (ImGui::BeginItemTooltip()) + { + ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); + ImGui::TextUnformatted(shader.name.c_str()); + ImGui::PopFont(); + ImGui::Text("%s: %d", localize.get(BASIC_ID), id); + ImGui::Text("%s: %s", localize.get(LABEL_VERTEX), path::to_utf8(shader.vertex).c_str()); + ImGui::Text("%s: %s", localize.get(LABEL_FRAGMENT), path::to_utf8(shader.fragment).c_str()); + if (!isValid) + { + ImGui::Spacing(); + ImGui::TextWrapped("%s", localize.get(TOOLTIP_SHADER_INVALID)); + } + ImGui::EndTooltip(); + } + ImGui::PopStyleVar(2); - ImGui::Separator(); + ImGui::SetCursorPos(cursorPos); + auto imageSize = ImVec2(shaderChildSize.y, shaderChildSize.y); + ImGui::ImageWithBg(shaderIcon.id, imageSize, ImVec2(), ImVec2(1, 1), ImVec4(), tintColor); - auto consoleSize = ImGui::GetContentRegionAvail(); - if (consoleSize.y < ImGui::GetFrameHeight()) consoleSize.y = ImGui::GetFrameHeight(); - if (ImGui::BeginChild("##Shaders Console", consoleSize, ImGuiChildFlags_Borders)) - ImGui::TextWrapped("%s", status.c_str()); - ImGui::EndChild(); - - ImGui::EndTabItem(); + ImGui::SetCursorPos(ImVec2(shaderChildSize.y + style.ItemSpacing.x, + shaderChildSize.y - shaderChildSize.y / 2 - ImGui::GetTextLineHeight() / 2)); + auto label = std::vformat(localize.get(FORMAT_SHADER), std::make_format_args(id, shader.name)); + ImGui::TextUnformatted(label.c_str()); } - if (ImGui::BeginTabItem(localize.get(LABEL_UNIFORMS))) + ImGui::EndChild(); + + if (isNewShader) { - shader_uniforms_update(*document, shader, document->shader_get(spritesheet->id)); - ImGui::EndTabItem(); + ImGui::SetScrollHereY(0.5f); + newElementId = -1; } - ImGui::EndTabBar(); + + ImGui::PopID(); } - ImGui::EndDisabled(); + + selection.finish(); + ImGui::PopStyleVar(); } ImGui::EndChild(); + ImGui::PopStyleVar(); - auto widgetSize = widget_size_with_row_get(2); - if (ImGui::Button(localize.get(isShaderEnabled ? BASIC_ENABLED : BASIC_DISABLED), widgetSize)) - { - auto spritesheetId = spritesheet->id; - auto isNextEnabled = !isShaderEnabled; - manager.command_push({manager.selected, - [spritesheetId, isNextEnabled](Manager&, Document& document) - { - auto spritesheet = document.anm2.element_get(ElementType::SPRITESHEET, spritesheetId); - if (spritesheet) shader_enabled_set(document, *spritesheet, isNextEnabled); - }}); - } + auto widgetSize = widget_size_with_row_get(3); + if (ImGui::Button(localize.get(BASIC_ADD), widgetSize)) shader_add(); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ADD_SHADER)); ImGui::SameLine(); - ImGui::BeginDisabled(!isShaderEnabled || !document); - if (ImGui::Button(localize.get(BASIC_RELOAD), widgetSize) && document) + if (ImGui::Button(localize.get(BASIC_REMOVE_UNUSED), widgetSize)) unused_shaders_remove(); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_REMOVE_UNUSED_SHADERS)); + + ImGui::SameLine(); + + ImGui::BeginDisabled(selection.empty()); + if (ImGui::Button(localize.get(BASIC_RELOAD), widgetSize)) { status.clear(); - document->shader_reload(spritesheet->id, &status); + for (auto id : selection) + { + auto shader = shader_element_get(*document, id); + if (!shader) continue; + document->shader_reload(id, &status); + toasts.push(std::vformat(localize.get(TOAST_RELOAD_SHADER), std::make_format_args(id, shader->name))); + } } + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_RELOAD_SHADERS)); ImGui::EndDisabled(); + + propertiesPopup.trigger(); + if (ImGui::BeginPopupModal(propertiesPopup.label(), &propertiesPopup.isOpen, ImGuiWindowFlags_NoResize)) + { + auto shader = shader_element_get(*document, popupShaderId); + if (!shader) + { + propertiesPopup.close(); + ImGui::EndPopup(); + propertiesPopup.end(); + ImGui::End(); + return; + } + + auto popupSize = size_without_footer_get(); + if (popupSize.y < ImGui::GetFrameHeight()) popupSize.y = ImGui::GetFrameHeight(); + if (ImGui::BeginChild("##Shader Properties Child", popupSize)) + { + if (propertiesPopup.isJustOpened) ImGui::SetKeyboardFocusHere(); + if (input_text_string(localize.get(BASIC_NAME), &shader->name)) document->change(Document::SHADERS); + + ImGui::SeparatorText(localize.get(LABEL_FILES)); + + shader_path_row_update(*this, *document, resources, dialog, shader, &Element::vertex, + Dialog::SHADER_VERTEX_PATH_SET, LABEL_VERTEX); + shader_path_row_update(*this, *document, resources, dialog, shader, &Element::fragment, + Dialog::SHADER_FRAGMENT_PATH_SET, LABEL_FRAGMENT); + + if (is_shader_reload_needed(*document, shader)) + ImGui::TextWrapped("%s", localize.get(LABEL_SHADER_RELOAD_NEEDED)); + + ImGui::SeparatorText(localize.get(LABEL_UNIFORMS)); + + auto runtime = document->shader_get(shader->id); + auto tableSize = ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetTextLineHeightWithSpacing() * 8.0f); + auto outputReserve = ImGui::GetTextLineHeightWithSpacing() * 6.0f; + auto availableHeight = ImGui::GetContentRegionAvail().y; + if (availableHeight - outputReserve < tableSize.y) tableSize.y = availableHeight - outputReserve; + if (tableSize.y < ImGui::GetFrameHeight()) tableSize.y = ImGui::GetFrameHeight(); + shader_uniforms_update(*document, shader, runtime, tableSize); + + ImGui::SeparatorText(localize.get(LABEL_OUTPUT)); + + auto consoleSize = ImGui::GetContentRegionAvail(); + if (consoleSize.y < ImGui::GetFrameHeight()) consoleSize.y = ImGui::GetFrameHeight(); + if (ImGui::BeginChild("##Shaders Output", consoleSize, ImGuiChildFlags_Borders)) + ImGui::TextWrapped("%s", status.c_str()); + ImGui::EndChild(); + } + ImGui::EndChild(); + + auto popupWidgetSize = widget_size_with_row_get(2); + if (ImGui::Button(localize.get(BASIC_CONFIRM), popupWidgetSize)) + { + status.clear(); + document->shader_reload(shader->id, &status); + propertiesPopup.close(); + } + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_RELOAD_SHADERS)); + ImGui::SameLine(); + if (ImGui::Button(localize.get(BASIC_CANCEL), popupWidgetSize)) propertiesPopup.close(); + + ImGui::EndPopup(); + } + propertiesPopup.end(); } ImGui::End(); } diff --git a/src/imgui/window/shaders.hpp b/src/imgui/window/shaders.hpp index 21601db..860f368 100644 --- a/src/imgui/window/shaders.hpp +++ b/src/imgui/window/shaders.hpp @@ -4,6 +4,7 @@ #include "manager.hpp" #include "resources.hpp" #include "settings.hpp" +#include "util/imgui/popup.hpp" namespace anm2ed::imgui { @@ -11,7 +12,10 @@ namespace anm2ed::imgui { public: std::string status{}; - int dialogSpritesheetId{-1}; + int dialogShaderId{-1}; + int popupShaderId{-1}; + int newElementId{-1}; + PopupHelper propertiesPopup{PopupHelper(LABEL_SHADER_PROPERTIES, POPUP_NORMAL)}; void update(Manager&, Settings&, Resources&, Dialog&); }; } diff --git a/src/imgui/wizard/about.cpp b/src/imgui/wizard/about.cpp index f18231f..24de14a 100644 --- a/src/imgui/wizard/about.cpp +++ b/src/imgui/wizard/about.cpp @@ -210,7 +210,8 @@ namespace anm2ed::imgui::wizard if (textureSize.x <= 0.0f || textureSize.y <= 0.0f) return; auto transform = baseTransform * math::quad_model_get(frame.size, frame.position, frame.pivot, - math::percent_to_unit(frame.scale), frame.rotation); + math::percent_to_unit(frame.scale), frame.rotation, + math::percent_to_unit(frame.shear)); auto uvVertices = math::uv_vertices_get(frame.crop / textureSize, (frame.crop + frame.size) / textureSize); auto tint = frame.tint * rootFrame.tint; auto colorOffset = frame.colorOffset + rootFrame.colorOffset; @@ -252,7 +253,7 @@ namespace anm2ed::imgui::wizard { rootFrame = frame_generate(*root, state.time); transform *= math::quad_model_parent_get(rootFrame.position, {}, math::percent_to_unit(rootFrame.scale), - rootFrame.rotation); + rootFrame.rotation, math::percent_to_unit(rootFrame.shear)); } if (auto layerAnimations = element_child_first_get(*animation, ElementType::LAYER_ANIMATIONS)) diff --git a/src/imgui/wizard/change_all_frame_properties.cpp b/src/imgui/wizard/change_all_frame_properties.cpp index e3bf9ff..13bda08 100644 --- a/src/imgui/wizard/change_all_frame_properties.cpp +++ b/src/imgui/wizard/change_all_frame_properties.cpp @@ -39,6 +39,8 @@ namespace anm2ed::imgui::wizard auto& isPivotY = settings.changeIsPivotY; auto& isScaleX = settings.changeIsScaleX; auto& isScaleY = settings.changeIsScaleY; + auto& isShearX = settings.changeIsShearX; + auto& isShearY = settings.changeIsShearY; auto& isRotation = settings.changeIsRotation; auto& isDuration = settings.changeIsDuration; auto& isTintR = settings.changeIsTintR; @@ -53,16 +55,19 @@ namespace anm2ed::imgui::wizard auto& isFlipXSet = settings.changeIsFlipXSet; auto& isFlipYSet = settings.changeIsFlipYSet; auto& isRegion = settings.changeIsRegion; + auto& isShader = settings.changeIsShader; auto& crop = settings.changeCrop; auto& size = settings.changeSize; auto& position = settings.changePosition; auto& pivot = settings.changePivot; auto& scale = settings.changeScale; + auto& shear = settings.changeShear; auto& rotation = settings.changeRotation; auto& duration = settings.changeDuration; auto& tint = settings.changeTint; auto& colorOffset = settings.changeColorOffset; auto& regionId = document.changeAllFramePropertiesRegionId; + auto& shaderId = document.changeAllFramePropertiesShaderId; auto& isVisible = settings.changeIsVisible; auto& interpolation = settings.changeInterpolation; auto& isFlipX = settings.changeIsFlipX; @@ -114,15 +119,12 @@ namespace anm2ed::imgui::wizard isItemsDestination = destination == CHANGE_DESTINATION_ITEMS; } - auto isLayerPropertyAvailable = isFramesDestination - ? std::ranges::any_of(selectedFrameReferences, - [](const Reference& reference) - { return reference.itemType == LAYER; }) - : isItemsDestination - ? std::ranges::any_of(selectedItemReferences, - [](const Reference& reference) - { return reference.itemType == LAYER; }) - : isLayers; + auto isLayerPropertyAvailable = + isFramesDestination ? std::ranges::any_of(selectedFrameReferences, [](const Reference& reference) + { return reference.itemType == LAYER; }) + : isItemsDestination ? std::ranges::any_of(selectedItemReferences, [](const Reference& reference) + { return reference.itemType == LAYER; }) + : isLayers; #define PROPERTIES_WIDGET(body, checkboxLabel, isEnabled) \ ImGui::Checkbox(checkboxLabel, &isEnabled); \ @@ -152,18 +154,15 @@ namespace anm2ed::imgui::wizard ImGui::PushItemWidth(width); - PROPERTIES_WIDGET(ImGui::DragInt(valueRLabel, &valueAlt.r, DRAG_SPEED, 0, 0, "R:%d"), checkboxRLabel, - isREnabled); + PROPERTIES_WIDGET(ImGui::DragInt(valueRLabel, &valueAlt.r, DRAG_SPEED, 0, 0, "R:%d"), checkboxRLabel, isREnabled); ImGui::SameLine(); - PROPERTIES_WIDGET(ImGui::DragInt(valueGLabel, &valueAlt.g, DRAG_SPEED, 0, 0, "G:%d"), checkboxGLabel, - isGEnabled); + PROPERTIES_WIDGET(ImGui::DragInt(valueGLabel, &valueAlt.g, DRAG_SPEED, 0, 0, "G:%d"), checkboxGLabel, isGEnabled); ImGui::SameLine(); - PROPERTIES_WIDGET(ImGui::DragInt(valueBLabel, &valueAlt.b, DRAG_SPEED, 0, 0, "B:%d"), checkboxBLabel, - isBEnabled); + PROPERTIES_WIDGET(ImGui::DragInt(valueBLabel, &valueAlt.b, DRAG_SPEED, 0, 0, "B:%d"), checkboxBLabel, isBEnabled); ImGui::PopItemWidth(); @@ -196,22 +195,18 @@ namespace anm2ed::imgui::wizard ImGui::PushItemWidth(width); - PROPERTIES_WIDGET(ImGui::DragInt(valueRLabel, &valueAlt.r, DRAG_SPEED, 0, 0, "R:%d"), checkboxRLabel, - isREnabled); + PROPERTIES_WIDGET(ImGui::DragInt(valueRLabel, &valueAlt.r, DRAG_SPEED, 0, 0, "R:%d"), checkboxRLabel, isREnabled); ImGui::SameLine(); - PROPERTIES_WIDGET(ImGui::DragInt(valueGLabel, &valueAlt.g, DRAG_SPEED, 0, 0, "G:%d"), checkboxGLabel, - isGEnabled); + PROPERTIES_WIDGET(ImGui::DragInt(valueGLabel, &valueAlt.g, DRAG_SPEED, 0, 0, "G:%d"), checkboxGLabel, isGEnabled); ImGui::SameLine(); - PROPERTIES_WIDGET(ImGui::DragInt(valueBLabel, &valueAlt.b, DRAG_SPEED, 0, 0, "B:%d"), checkboxBLabel, - isBEnabled); + PROPERTIES_WIDGET(ImGui::DragInt(valueBLabel, &valueAlt.b, DRAG_SPEED, 0, 0, "B:%d"), checkboxBLabel, isBEnabled); ImGui::SameLine(); - PROPERTIES_WIDGET(ImGui::DragInt(valueALabel, &valueAlt.a, DRAG_SPEED, 0, 0, "A:%d"), checkboxALabel, - isAEnabled); + PROPERTIES_WIDGET(ImGui::DragInt(valueALabel, &valueAlt.a, DRAG_SPEED, 0, 0, "A:%d"), checkboxALabel, isAEnabled); ImGui::PopItemWidth(); @@ -220,10 +215,9 @@ namespace anm2ed::imgui::wizard value = vec4(uint8_to_float(valueAlt.r), uint8_to_float(valueAlt.g), uint8_to_float(valueAlt.b), uint8_to_float(valueAlt.a)); - ImVec4 buttonColor = {isREnabled ? glm::clamp(value.r, 0.0f, 1.0f) : 0, - isGEnabled ? glm::clamp(value.g, 0.0f, 1.0f) : 0, - isBEnabled ? glm::clamp(value.b, 0.0f, 1.0f) : 0, - isAEnabled ? glm::clamp(value.a, 0.0f, 1.0f) : 1}; + ImVec4 buttonColor = { + isREnabled ? glm::clamp(value.r, 0.0f, 1.0f) : 0, isGEnabled ? glm::clamp(value.g, 0.0f, 1.0f) : 0, + isBEnabled ? glm::clamp(value.b, 0.0f, 1.0f) : 0, isAEnabled ? glm::clamp(value.a, 0.0f, 1.0f) : 1}; ImGui::ColorButton(label, buttonColor); ImGui::SameLine(); @@ -275,6 +269,8 @@ namespace anm2ed::imgui::wizard float2_value("##Is Scale X", "##Is Scale Y", "##Scale X", localize.get(BASIC_SCALE), isScaleX, isScaleY, scale); + float2_value("##Is Shear X", "##Is Shear Y", "##Shear X", localize.get(BASIC_SHEAR), isShearX, isShearY, shear); + float_value("##Is Rotation", localize.get(BASIC_ROTATION), isRotation, rotation); duration_value("##Is Duration", localize.get(BASIC_DURATION), isDuration, duration); @@ -320,6 +316,15 @@ namespace anm2ed::imgui::wizard enum_value("##Is Interpolation", localize.get(BASIC_INTERPOLATED), isInterpolationSet, interpolation, interpolationIds, interpolationLabels); + ImGui::BeginDisabled(!isLayerPropertyAvailable); + auto shaderIds = !document.shader.ids.empty() ? document.shader.ids : fallbackIds; + auto shaderLabels = !document.shader.labels.empty() ? document.shader.labels : fallbackLabels; + if (!isLayerPropertyAvailable || std::find(shaderIds.begin(), shaderIds.end(), shaderId) == shaderIds.end()) + shaderId = -1; + PROPERTIES_WIDGET(combo_id_mapped(localize.get(BASIC_SHADER), &shaderId, shaderIds, shaderLabels), "##Is Shader", + isShader); + ImGui::EndDisabled(); + bool_value("##Is Visible", localize.get(BASIC_VISIBLE), isVisibleSet, isVisible); bool_value("##Is Flip X", localize.get(LABEL_FLIP_X), isFlipXSet, isFlipX); @@ -351,9 +356,12 @@ namespace anm2ed::imgui::wizard if (isPivotY) frameChange.pivotY = pivot.y; if (isScaleX) frameChange.scaleX = scale.x; if (isScaleY) frameChange.scaleY = scale.y; + if (isShearX) frameChange.shearX = shear.x; + if (isShearY) frameChange.shearY = shear.y; if (isRotation) frameChange.rotation = std::make_optional(rotation); if (isDuration) frameChange.duration = std::make_optional(duration); if (isRegion) frameChange.regionId = std::make_optional(regionId); + if (isShader) frameChange.shaderId = std::make_optional(shaderId); if (isTintR) frameChange.tintR = color_value_get(tint.r); if (isTintG) frameChange.tintG = color_value_get(tint.g); if (isTintB) frameChange.tintB = color_value_get(tint.b); @@ -378,8 +386,7 @@ namespace anm2ed::imgui::wizard auto queuedIsLayers = isLayers; auto queuedIsNulls = isNulls; - manager.command_push({manager.selected, - [=](Manager&, Document& document) + manager.command_push({manager.selected, [=](Manager&, Document& document) { auto all_frames_selection = [](const Element& item) { @@ -452,7 +459,8 @@ namespace anm2ed::imgui::wizard if (queuedIsLayers) { - auto layerAnimations = element_child_first_get(*animation, ElementType::LAYER_ANIMATIONS); + auto layerAnimations = + element_child_first_get(*animation, ElementType::LAYER_ANIMATIONS); if (layerAnimations) { auto item_change = [&](auto&& self, Element& item) -> void @@ -476,7 +484,8 @@ namespace anm2ed::imgui::wizard if (queuedIsNulls) { - auto nullAnimations = element_child_first_get(*animation, ElementType::NULL_ANIMATIONS); + auto nullAnimations = + element_child_first_get(*animation, ElementType::NULL_ANIMATIONS); if (nullAnimations) { auto item_change = [&](auto&& self, Element& item) -> void @@ -543,10 +552,11 @@ namespace anm2ed::imgui::wizard } bool isAnyProperty = isCropX || isCropY || isSizeX || isSizeY || isPositionX || isPositionY || isPivotX || - isPivotY || isScaleX || isScaleY || isRotation || isDuration || isTintR || isTintG || - isTintB || isTintA || isColorOffsetR || isColorOffsetG || isColorOffsetB || isRegion || - isVisibleSet || isInterpolationSet || isFlipXSet || isFlipYSet; - bool isDestinationValid = isFramesDestination ? isSelectedFramesAvailable + isPivotY || isScaleX || isScaleY || isShearX || isShearY || isRotation || isDuration || + isTintR || isTintG || isTintB || isTintA || isColorOffsetR || isColorOffsetG || + isColorOffsetB || isRegion || isShader || isVisibleSet || isInterpolationSet || isFlipXSet || + isFlipYSet; + bool isDestinationValid = isFramesDestination ? isSelectedFramesAvailable : isItemsDestination ? isSelectedItemsAvailable : isSelectedAnimationsAvailable && (isRoot || isLayers || isNulls); diff --git a/src/imgui/wizard/generate_animation_from_grid.cpp b/src/imgui/wizard/generate_animation_from_grid.cpp index 07a34c4..286531f 100644 --- a/src/imgui/wizard/generate_animation_from_grid.cpp +++ b/src/imgui/wizard/generate_animation_from_grid.cpp @@ -104,7 +104,8 @@ namespace anm2ed::imgui::wizard auto uvMax = (frame.crop + frame.size) / textureSize; mat4 transform = transform_get(zoom) * math::quad_model_get(frame.size, frame.position, frame.pivot, - math::percent_to_unit(frame.scale), frame.rotation); + math::percent_to_unit(frame.scale), frame.rotation, + math::percent_to_unit(frame.shear)); auto vertices = math::uv_vertices_get(uvMin, uvMax); texture_render(shaderTexture, sourceTexture->id, transform, frame.tint, frame.colorOffset, vertices.data()); diff --git a/src/imgui/wizard/render_animation.cpp b/src/imgui/wizard/render_animation.cpp index 26b1352..b3f3f6e 100644 --- a/src/imgui/wizard/render_animation.cpp +++ b/src/imgui/wizard/render_animation.cpp @@ -122,6 +122,9 @@ namespace anm2ed::imgui::wizard case render::WEBM: dialogType = Dialog::WEBM_PATH_SET; break; + case render::OGV: + dialogType = Dialog::OGV_PATH_SET; + break; case render::MP4: dialogType = Dialog::MP4_PATH_SET; break; @@ -346,6 +349,7 @@ namespace anm2ed::imgui::wizard break; case render::GIF: case render::WEBM: + case render::OGV: case render::MP4: if (!ffmpeg_valid_check()) return false; break; diff --git a/src/render.cpp b/src/render.cpp index e323531..6a1398a 100644 --- a/src/render.cpp +++ b/src/render.cpp @@ -82,6 +82,9 @@ namespace anm2ed case render::WEBM: audioOutputArguments = "-c:a libopus -b:a 160k -shortest"; break; + case render::OGV: + audioOutputArguments = "-c:a libvorbis -q:a 4 -shortest"; + break; case render::MP4: audioOutputArguments = "-c:a aac -b:a 192k -shortest"; break; @@ -121,6 +124,11 @@ namespace anm2ed if (!audioOutputArguments.empty()) command += " " + audioOutputArguments; command += std::format(" \"{}\"", pathString); break; + case render::OGV: + command += " -vf \"format=yuv420p,scale=trunc(iw/2)*2:trunc(ih/2)*2\" -c:v libtheora -q:v 7"; + if (!audioOutputArguments.empty()) command += " " + audioOutputArguments; + command += std::format(" \"{}\"", pathString); + break; case render::MP4: command += " -vf \"format=yuv420p,scale=trunc(iw/2)*2:trunc(ih/2)*2\" -c:v libx265 -crf 20 -preset slow" " -tag:v hvc1 -movflags +faststart"; diff --git a/src/render.hpp b/src/render.hpp index b6e52e4..95c2c20 100644 --- a/src/render.hpp +++ b/src/render.hpp @@ -13,6 +13,7 @@ namespace anm2ed::render X(SPRITESHEET, "Spritesheet (PNG)", ".png") \ X(GIF, "GIF", ".gif") \ X(WEBM, "WebM", ".webm") \ + X(OGV, "OGV", ".ogv") \ X(MP4, "MP4", ".mp4") enum Type diff --git a/src/resource/icon.hpp b/src/resource/icon.hpp index d8c42e9..61a6b9e 100644 --- a/src/resource/icon.hpp +++ b/src/resource/icon.hpp @@ -113,6 +113,10 @@ namespace anm2ed::resource::icon )"; + inline constexpr auto SHEAR_DATA = R"( + + )"; + inline constexpr auto CROP_DATA = R"( )"; @@ -179,6 +183,10 @@ namespace anm2ed::resource::icon inline constexpr auto SOUND_DATA = R"( +)"; + + inline constexpr auto SHADER_DATA = R"( + )"; #define SVG_LIST \ @@ -191,6 +199,7 @@ namespace anm2ed::resource::icon X(LAYER, LAYER_DATA, SIZE_NORMAL) \ X(NULL_, NULL_DATA, SIZE_NORMAL) \ X(SOUND, SOUND_DATA, SIZE_NORMAL) \ + X(SHADER, SHADER_DATA, SIZE_NORMAL) \ X(TRIGGERS, TRIGGERS_DATA, SIZE_NORMAL) \ X(VISIBLE, VISIBLE_DATA, SIZE_NORMAL) \ X(INVISIBLE, INVISIBLE_DATA, SIZE_NORMAL) \ @@ -206,6 +215,7 @@ namespace anm2ed::resource::icon X(MOVE, MOVE_DATA, SIZE_NORMAL) \ X(ROTATE, ROTATE_DATA, SIZE_NORMAL) \ X(SCALE, SCALE_DATA, SIZE_NORMAL) \ + X(SHEAR, SHEAR_DATA, SIZE_NORMAL) \ X(CROP, CROP_DATA, SIZE_NORMAL) \ X(DRAW, DRAW_DATA, SIZE_NORMAL) \ X(ERASE, ERASE_DATA, SIZE_NORMAL) \ diff --git a/src/resource/strings.hpp b/src/resource/strings.hpp index dc9ce50..d80ff77 100644 --- a/src/resource/strings.hpp +++ b/src/resource/strings.hpp @@ -92,6 +92,8 @@ namespace anm2ed X(BASIC_ROTATION, "Rotation", "Rotacion", "Поворот", "旋转", "회전") \ X(BASIC_SAVE, "Save", "Guardar", "Сохранить", "保存", "저장") \ X(BASIC_SCALE, "Scale", "Escalar", "Масштаб", "缩放", "크기") \ + X(BASIC_SHEAR, "Shear", "Shear", "Shear", "Shear", "Shear") \ + X(BASIC_SHADER, "Shader", "Shader", "Shader", "Shader", "Shader") \ X(BASIC_SET_FILE_PATH, "Set File Path", "Set File Path", "Set File Path", "Set File Path", "Set File Path") \ X(BASIC_SINGLE, "Single", "Individual", "Один", "单个", "단일") \ X(BASIC_SIZE, "Size", "Tamaño", "Размер", "大小", "비율") \ @@ -111,6 +113,7 @@ namespace anm2ed X(EDIT_ADD_NULL, "Add Null", "Añadir Null", "Добавить нуль", "添加Null", "Null 추가") \ X(EDIT_ADD_SPRITESHEET, "Add Spritesheet", "Añadir Spritesheet", "Добавить спрайт-лист", "添加图集", "스프라이트 시트 추가") \ X(EDIT_ADD_SOUND, "Add Sound", "Añadir Sonido", "Добавить звук", "添加声音", "사운드 추가") \ + X(EDIT_ADD_SHADER, "Add Shader", "Add Shader", "Add Shader", "Add Shader", "Add Shader") \ X(EDIT_ADD_TRIGGER_SOUND, "Add Trigger Sound", "Añadir Sonido del Trigger", "Добавить звук триггера", "添加事件触发器声音", "트리거 사운드 추가") \ X(EDIT_REMOVE_TRIGGER_SOUND, "Remove Trigger Sound", "Remover Sonido del Trigger", "Удалить звук триггера", "移除事件触发器声音", "트리거 사운드 제거") \ X(EDIT_ANIMATION_LENGTH, "Animation Length", "Duracion De Animacion", "Длина анимации", "动画时长", "애니메이션 길이") \ @@ -143,6 +146,8 @@ namespace anm2ed X(EDIT_FRAME_POSITION, "Frame Position", "Posicion de Frame", "Позиция кадра", "帧位置", "프레임 위치") \ X(EDIT_FRAME_ROTATION, "Frame Rotation", "Rotacion de Frame", "Поворот кадра", "帧旋转", "프레임 회전") \ X(EDIT_FRAME_SCALE, "Frame Scale", "Escala de Frame", "Масштаб кадра", "帧缩放", "프레임 비율") \ + X(EDIT_FRAME_SHADER, "Frame Shader", "Frame Shader", "Frame Shader", "Frame Shader", "Frame Shader") \ + X(EDIT_FRAME_SHEAR, "Frame Shear", "Frame Shear", "Frame Shear", "Frame Shear", "Frame Shear") \ X(EDIT_FRAME_SIZE, "Frame Size", "Tamaño de Frame", "Размер кадра", "帧大小", "프레임 크기") \ X(EDIT_FRAME_TINT, "Frame Tint", "Matiz de Frame", "Оттенок кадра", "帧色调", "프레임 색조") \ X(EDIT_FRAME_VISIBILITY, "Frame Visibility", "Visibilidad de Frame", "Видимость кадра", "帧可见", "프레임 표시") \ @@ -170,6 +175,7 @@ namespace anm2ed X(EDIT_PASTE_SPRITESHEETS, "Paste Spritesheet(s)", "Pegar Spritesheet(s)", "Вставить спрайт-листы", "粘贴图集", "스프라이트 시트 붙여넣기") \ X(EDIT_RELOAD_SPRITESHEETS, "Reload Spritesheet(s)", "Recargar Spritesheet(s)", "Перезагрузить спрайт-листы", "重新加载图集", "스프라이트 시트 다시 불러오기") \ X(EDIT_RELOAD_SOUNDS, "Reload Sound(s)", "Recargar Sonido(s)", "Перезагрузить звук(и)", "重新加载声音", "사운드 다시 불러오기") \ + X(EDIT_RELOAD_SHADERS, "Reload Shader(s)", "Reload Shader(s)", "Reload Shader(s)", "Reload Shader(s)", "Reload Shader(s)") \ X(EDIT_REMOVE_ANIMATIONS, "Remove Animation(s)", "Remover Animacion(es)", "Удалить анимации", "删除动画层", "애니메이션 제거") \ X(EDIT_REVERSE_FRAMES, "Reverse Frame(s)", "Invertir Frame(s)", "Развернуть кадры", "反转帧", "프레임 역순") \ X(EDIT_REMOVE_ITEMS, "Remove Item(s)", "Remover Item(s)", "Удалить предметы", "删除物品", "항목 제거") \ @@ -178,6 +184,7 @@ namespace anm2ed X(EDIT_REMOVE_UNUSED_LAYERS, "Remove Unused Layers", "Remover Capas No Utilizadas", "Удалить неизпользуемые слои", "删除未使用的动画层", "미사용 레이어 제거") \ X(EDIT_REMOVE_UNUSED_NULLS, "Remove Unused Nulls", "Remover Nulls No Utilizados", "Удалить неизпользуемые нули", "删除未使用的Null", "미사용 Null 제거") \ X(EDIT_REMOVE_UNUSED_SOUNDS, "Remove Unused Sounds", "Remover Sonidos No Utilizados", "Удалить неизпользуемые звуки", "删除未使用的声音", "미사용 사운드 제거") \ + X(EDIT_REMOVE_UNUSED_SHADERS, "Remove Unused Shaders", "Remove Unused Shaders", "Remove Unused Shaders", "Remove Unused Shaders", "Remove Unused Shaders") \ X(EDIT_REMOVE_UNUSED_SPRITESHEETS, "Remove Unused Spritesheets", "Remover Spritesheets No Utilizadas", "Удалить неизпользуемые спрайт-листы", "删除未使用的图集", "미사용 스프라이트 시트 제거") \ X(EDIT_RENAME_GROUP, "Rename Group", "Renombrar grupo", "Переименовать группу", "重命名组", "그룹 이름 바꾸기") \ X(EDIT_RENAME_EVENT, "Rename Event", "Renombrar Evento", "Переименовать событие", "重命名事件", "이벤트 이름 바꾸기") \ @@ -186,6 +193,7 @@ namespace anm2ed X(EDIT_SET_SPRITESHEET_FILE_PATH, "Set Spritesheet File Path", "Set Spritesheet File Path", "Set Spritesheet File Path", "Set Spritesheet File Path", "Set Spritesheet File Path") \ X(EDIT_SET_LAYER_PROPERTIES, "Set Layer Properties", "Establecer Propiedades de Capa", "Установить свойства слоя", "更改动画层属性", "레이어 속성 설정") \ X(EDIT_SET_REGION_PROPERTIES, "Set Region Properties", "Establecer propiedades de región", "Установить свойства региона", "更改区域属性", "영역 속성 설정") \ + X(EDIT_SET_SHADER_PROPERTIES, "Set Shader Properties", "Set Shader Properties", "Set Shader Properties", "Set Shader Properties", "Set Shader Properties") \ X(EDIT_TRIM_REGIONS, "Trim Regions", "Recortar regiones", "Обрезать регионы", "修剪区域", "영역 트리밍") \ X(EDIT_SET_NULL_PROPERTIES, "Set Null Properties", "Establecer Propiedades Null", "Установить свойства нуля", "更改Null属性", "Null 속성 설정") \ X(EDIT_SCAN_AND_SET_REGIONS, "Scan and Set Regions", "Escanear y establecer regiones", "Сканировать и установить регионы", "扫描并设置区域", "영역 스캔 및 설정") \ @@ -221,11 +229,13 @@ namespace anm2ed X(FORMAT_SIZE_SPACED, "Size: ({0:3}, {1:3})", "Tamaño: ({0:3}, {1:3})", "Размер: ({0:3}, {1:3})", "大小: ({0:3}, {1:3})", "크기: ({0:3}, {1:3})") \ X(FORMAT_ROTATION, "Rotation: {0}", "Rotacion: {0}", "Поворот: {0}", "旋转: {0}", "회전: {0}") \ X(FORMAT_SCALE, "Scale: ({0}, {1})", "Escalar: ({0}, {1})", "Масштаб: ({0}, {1})", "缩放: ({0}, {1})", "비율: ({0}, {1})") \ + X(FORMAT_SHEAR, "Shear: ({0}, {1})", "Shear: ({0}, {1})", "Shear: ({0}, {1})", "Shear: ({0}, {1})", "Shear: ({0}, {1})") \ X(FORMAT_SIZE, "Size: ({0}, {1})", "Tamaño: ({0}, {1})", "Размер: ({0}, {1})", "大小: ({0}, {1})", "크기: ({0}, {1})") \ X(FORMAT_SOUND_LABEL, "Sound: {0}", "Sonido: {0}", "Звук: {0}", "声音: {0}", "사운드: {0}") \ X(FORMAT_SPRITESHEET, "#{0} {1}", "#{0} {1}", "#{0} {1}", "#{0} {1}", "#{0} {1}") \ X(FORMAT_SPRITESHEET_NOT_SAVED, "{0} (Not Saved)", "{0} (No guardado)", "{0} (Не сохранено)", "{0} (未保存)", "{0} (저장되지 않음)") \ X(FORMAT_SOUND, "#{0} {1}", "#{0} {1}", "#{0} {1}", "#{0} {1}", "#{0} {1}") \ + X(FORMAT_SHADER, "#{0} {1}", "#{0} {1}", "#{0} {1}", "#{0} {1}", "#{0} {1}") \ X(FORMAT_REGION, "#{0} {1}", "#{0} {1}", "#{0} {1}", "#{0} {1}", "#{0} {1}") \ X(FORMAT_TRANSFORM, "Transform: {0}", "Transformar: {0}", "Трансформация: {0}", "变换: {0}", "변환: {0}") \ X(FORMAT_RECT, "Rect: {0}", "Rect: {0}", "Прямоугольник: {0}", "矩形: {0}", "사각형: {0}") \ @@ -329,6 +339,7 @@ namespace anm2ed X(LABEL_MANAGER_ANM2_DRAG_DROP, "Anm2 Drag Drop", "Arrastrar y Soltar Anm2", "Anm2 Drag Drop", "Anm2 拖放", "Anm2 드래그 앤 드롭") \ X(LABEL_GROUP_PROPERTIES, "Group Properties", "Propiedades de grupo", "Свойства группы", "组属性", "그룹 속성") \ X(LABEL_REGION_PROPERTIES, "Region Properties", "Propiedades de región", "Свойства региона", "区域属性", "영역 속성") \ + X(LABEL_SHADER_PROPERTIES, "Shader Properties", "Shader Properties", "Shader Properties", "Shader Properties", "Shader Properties") \ X(LABEL_EXPORT_REGION, "Export Region", "Export Region", "Export Region", "Export Region", "Export Region") \ X(LABEL_EXPORT_MAKE_SPRITESHEET, "Make Spritesheet", "Make Spritesheet", "Make Spritesheet", "Make Spritesheet", "Make Spritesheet") \ X(LABEL_EXPORT_REMOVE_CURRENT_REGION, "Remove Region from Current Spritesheet", "Remove Region from Current Spritesheet", "Remove Region from Current Spritesheet", "Remove Region from Current Spritesheet", "Remove Region from Current Spritesheet") \ @@ -360,6 +371,7 @@ namespace anm2ed X(LABEL_OPEN_RECENT, "Open Recent", "Abrir Reciente", "Открыть недавние", "打开最近", "최근 파일 열기") \ X(LABEL_OPTIONS, "Options", "Opciones", "Настройки", "选项", "설정") \ X(LABEL_OUTPUT_DIRECTORY, "Directory", "Directorio", "Директория", "目录", "디렉터리") \ + X(LABEL_OUTPUT, "Output", "Output", "Output", "Output", "Output") \ X(LABEL_OUTPUT_PATH, "Path", "Ruta", "Путь", "路径", "경로") \ X(LABEL_OVERLAY, "Overlay", "Overlay", "Наложение", "动画叠加", "오버레이") \ X(LABEL_OVERWRITE_CONFIRMATION, "Are you sure? This will overwrite the existing file.", "¿Estas Seguro? Esto sobreescribira el archivo existente.", "Вы уверены? Это перезапишет существующий файл.", "你确定吗? 这样会覆盖原本的文件.", "저장하시겠습니까? 기존 파일을 덮어쓰게 됩니다.") \ @@ -485,6 +497,7 @@ namespace anm2ed X(SHORTCUT_STRING_SAVE, "Save", "Guardar", "Сохранить", "保存", "저장") \ X(SHORTCUT_STRING_SAVE_AS, "Save As", "Guardar Como", "Сохранить как", "保存为", "다른 이름으로 저장") \ X(SHORTCUT_STRING_SCALE, "Scale", "Escalar", "Изменить масштаб", "缩放", "비율") \ + X(SHORTCUT_STRING_SHEAR, "Shear", "Shear", "Shear", "Shear", "Shear") \ X(SHORTCUT_STRING_SPLIT, "Split", "Dividir", "", "", "") \ X(SHORTCUT_STRING_BAKE, "Bake", "Bake", "Запечь", "提前渲染", "베이크") \ X(SHORTCUT_STRING_SHORTEN_FRAME, "Shorten Frame", "Acortar Frame", "Укоротить кадр", "缩短帧时长", "프레임 단축") \ @@ -502,6 +515,7 @@ namespace anm2ed X(TEXT_NEW_EVENT, "New Event", "Nuevo Evento", "Новое событие", "新事件", "새 이벤트") \ X(TEXT_NEW_GROUP, "New Group", "Nuevo grupo", "Новая группа", "新组", "새 그룹") \ X(TEXT_NEW_REGION, "New Region", "Nueva Región", "Новый регион", "新区域", "새 영역") \ + X(TEXT_NEW_SHADER, "New Shader", "New Shader", "New Shader", "New Shader", "New Shader") \ X(TEXT_REGION_IN_USE, "A spritesheet region is in use; remove region to edit.", "Se está usando una región del spritesheet; elimina la región para editar.", "Регион спрайт-листа используется; удалите регион для редактирования.", "图集中有区域正在使用;移除区域后才能编辑。", "스프라이트 시트 영역이 사용 중입니다. 편집하려면 영역을 제거하세요.") \ X(TEXT_RECORDING_PROGRESS, "Once recording is complete, rendering may take some time.\nPlease be patient...", "Una vez que el grabado este completo, renderizar puede tomar algo de tiempo. \nPor favor se paciente...", "Когда запись завершена, рендеринг может занять некоторое время.\nПожалуйста потерпите...", "录制完成时,渲染可能会花一些时间.\n请耐心等待...", "녹화가 완료되면 렌더링에 시간이 걸릴 수 있습니다.\n잠시만 기다려 주세요...") \ X(TEXT_OPEN_DIRECTORY, "Double-click to open directory in file explorer.", "Haz doble click para abrir el directiorio en el buscador de archivos.", "Дважды нажмите, чтобы открыть директорию в проводнике.", "双击以在文件管理器中打开目录。", "더블 클릭하여 파일 탐색기로 디렉터리를 엽니다.") \ @@ -536,6 +550,7 @@ namespace anm2ed X(ERROR_FILE_NOT_FOUND, "File not found!", "¡Archivo no encontrado!", "Файл не найден!", "找不到文件!", "파일을 찾을 수 없습니다!") \ X(ERROR_FILE_PERMISSIONS, "File does not have write permissions!", "¡El archivo no tiene permisos de escritura!", "У файла нет прав на запись!", "文件没有写入权限!", "파일에 쓰기 권한이 없습니다!") \ X(TOAST_RELOAD_SPRITESHEET, "Reloaded spritesheet #{0}: {1}", "Se ha recargado spritesheet #{0}: {1}", "Спрайт-лист #{0} перезагружен: {1}", "重新加载了图集 #{0}: {1}", "{0}번 스프라이트 시트 다시 불러옴: {1}") \ + X(TOAST_RELOAD_SHADER, "Reloaded shader #{0}: {1}", "Reloaded shader #{0}: {1}", "Reloaded shader #{0}: {1}", "Reloaded shader #{0}: {1}", "Reloaded shader #{0}: {1}") \ X(TOAST_MERGE_SPRITESHEETS, "Merged selected spritesheets.", "Spritesheets seleccionados combinados.", "Выбранные спрайт-листы объединены.", "已合并所选图集。", "선택된 스프라이트 시트를 병합했습니다.") \ X(TOAST_MERGE_SPRITESHEETS_FAILED, "Failed to merge selected spritesheets.", "No se pudieron combinar los spritesheets seleccionados.", "Не удалось объединить выбранные спрайт-листы.", "合并所选图集失败。", "선택된 스프라이트 시트 병합에 실패했습니다.") \ X(TOAST_PACK_SPRITESHEET, "Packed spritesheet.", "Spritesheet empaquetado.", "Спрайт-лист упакован.", "图集已打包。", "스프라이트 시트를 패킹했습니다.") \ @@ -561,6 +576,7 @@ namespace anm2ed X(TOAST_UNDO, "Undo: {0}", "Deshacer: {0}", "Отмена: {0}", "撤销: {0}", "실행 취소: {0}") \ X(TOOLTIP_ADD_ANIMATION, "Add a new animation.", "Añadir nueva animacion.", "Добавить новую анимацию.", "添加一个新动画.", "새 애니메이션을 추가합니다.") \ X(TOOLTIP_ADD_REGION, "Add a new region to the spritesheet.\nRegions are parts of a spritesheet that can be defined and labeled to be reused in frames.", "Añadir una nueva región al spritesheet.\nLas regiones son partes de un spritesheet que pueden definirse y etiquetarse para reutilizarse en frames.", "Добавить новый регион в спрайт-лист.\nРегионы — это части спрайт-листа, которые можно определить и подписать, чтобы повторно использовать их в кадрах.", "添加一个新的区域到图集。\n区域是图集的一部分,可以被定义并标记以便在帧中重复使用。", "스프라이트 시트에 새 영역을 추가합니다.\n영역은 스프라이트 시트의 일부로, 정의하고 라벨을 붙여 프레임에서 재사용할 수 있습니다.") \ + X(TOOLTIP_ADD_SHADER, "Add a new shader to the document.", "Add a new shader to the document.", "Add a new shader to the document.", "Add a new shader to the document.", "Add a new shader to the document.") \ X(TOOLTIP_ADD_EVENT, "Add an event.", "Añadir un evento.", "Добавить событие.", "添加一个事件.", "이벤트를 추가합니다.") \ X(TOOLTIP_ADD_ITEM, "Add the item, with the settings specified.", "Añadir el Item, con las configuraciones especificadas.", "Добавить предмет с указанными настройками.", "按照指定的设置添加物品.", "지정된 설정으로 항목을 추가합니다.") \ X(TOOLTIP_ADD_LAYER, "Add a layer.", "Añadir una capa.", "Добавить слой.", "添加一个动画层.", "레이어를 추가합니다.") \ @@ -595,6 +611,7 @@ namespace anm2ed X(TOOLTIP_CLOSE_SETTINGS, "Close without updating settings.", "Cerrar sin actualizar las configuraciones.", "Закрыть без обновления настройки.", "关闭但不保存设置.", "설정을 갱신하지 않고 닫습니다.") \ X(TOOLTIP_COLOR_OFFSET, "Change the color added onto the frame.", "Cambia el color añadido al Frame.", "Изменить цвет, который добавлен на кадр.", "更改覆盖在帧上的颜色.", "프레임에 더해지는 색을 변경합니다.") \ X(TOOLTIP_REGION, "Set the spritesheet region the frame will use.", "Establece la región del spritesheet que usará el frame.", "Установить регион спрайт-листа, который будет использовать кадр.", "设置帧将使用的图集区域.", "프레임이 사용할 스프라이트 시트 영역을 설정합니다.") \ + X(TOOLTIP_FRAME_SHADER, "Set the shader this frame uses. None uses the default shader.", "Set the shader this frame uses. None uses the default shader.", "Set the shader this frame uses. None uses the default shader.", "Set the shader this frame uses. None uses the default shader.", "Set the shader this frame uses. None uses the default shader.") \ X(TOOLTIP_REGION_PROPERTIES_ORIGIN, "Use a preset origin for the region.", "Usa un origen predefinido para la región.", "Использовать предустановленную точку отсчета для региона.", "为区域使用预设原点。", "영역에 사전 설정된 원점을 사용합니다.") \ X(TOOLTIP_MERGE_PRESET_APPEND_AS_NEW, "Add incoming content as new entries. Matching names are renamed before import.", "Add incoming content as new entries. Matching names are renamed before import.", "Add incoming content as new entries. Matching names are renamed before import.", "Add incoming content as new entries. Matching names are renamed before import.", "Add incoming content as new entries. Matching names are renamed before import.") \ X(TOOLTIP_MERGE_PRESET_MERGE_BY_NAME, "Keep existing content and update matching names with incoming definitions and tracks.", "Keep existing content and update matching names with incoming definitions and tracks.", "Keep existing content and update matching names with incoming definitions and tracks.", "Keep existing content and update matching names with incoming definitions and tracks.", "Keep existing content and update matching names with incoming definitions and tracks.") \ @@ -679,9 +696,11 @@ namespace anm2ed X(TOOLTIP_RENDER_FPS, "Set the exported animation frame rate.", "Set the exported animation frame rate.", "Set the exported animation frame rate.", "Set the exported animation frame rate.", "Set the exported animation frame rate.") \ X(TOOLTIP_RELOAD_SPRITESHEETS, "Reloads the selected spritesheets.", "Recarga la spritesheet seleccionada.", "Перезагружает выбранные спрайт-листы.", "重新加载所选图集.", "선택한 스프라이트 시트를 다시 불러옵니다.") \ X(TOOLTIP_RELOAD_SOUNDS, "Reloads the selected sounds.", "Recarga los sonidos seleccionados.", "Перезагружает выбранные звуки.", "重新加载所选声音.", "선택한 사운드를 다시 불러옵니다.") \ + X(TOOLTIP_RELOAD_SHADERS, "Reloads the selected shaders.", "Reloads the selected shaders.", "Reloads the selected shaders.", "Reloads the selected shaders.", "Reloads the selected shaders.") \ X(TOOLTIP_REMOVE_ANIMATION, "Remove the selected animation(s).", "Remueve la(s) animacion(es) seleccionada(s).", "Удалить выбранные анимации.", "去除所选动画.", "선택한 애니메이션을 제거합니다.") \ X(TOOLTIP_REMOVE_ITEMS, "Remove the selected item(s).", "Remueve el/los item(s) seleccionado(s).", "Удалить выбранные предметы.", "去除所选物品.", "선택한 항목을 제거합니다.") \ X(TOOLTIP_REMOVE_UNUSED_REGIONS, "Remove unused regions (i.e., ones not used by any frame in any animation.)", "Remueve regiones no utilizadas (es decir, aquellas no usadas por ningun frame en ninguna animacion.)", "Удалить неиспользуемые регионы (т. е. те, которые не используются ни одним кадром ни в одной анимации.)", "移除未使用的区域(即未被任何动画中的任何帧使用的区域。)", "사용되지 않는 영역(어떤 애니메이션의 어떤 프레임에서도 사용되지 않는 것)를 제거합니다.") \ + X(TOOLTIP_REMOVE_UNUSED_SHADERS, "Remove unused shaders (i.e., ones not used by any frame in any animation.)", "Remove unused shaders (i.e., ones not used by any frame in any animation.)", "Remove unused shaders (i.e., ones not used by any frame in any animation.)", "Remove unused shaders (i.e., ones not used by any frame in any animation.)", "Remove unused shaders (i.e., ones not used by any frame in any animation.)") \ X(TOOLTIP_EXPORT_MAKE_SPRITESHEET, "Make a new spritesheet from this region.", "Make a new spritesheet from this region.", "Make a new spritesheet from this region.", "Make a new spritesheet from this region.", "Make a new spritesheet from this region.") \ X(TOOLTIP_EXPORT_REMOVE_CURRENT_REGION, "The region will be removed from the current spritesheet.", "The region will be removed from the current spritesheet.", "The region will be removed from the current spritesheet.", "The region will be removed from the current spritesheet.", "The region will be removed from the current spritesheet.") \ X(TOOLTIP_TRIM_REGIONS, "Trim region to non-transparent content.", "Recorta la región al contenido no transparente.", "Обрезать регион до непрозрачного содержимого.", "将区域裁剪到非透明内容。", "영역을 불투명 콘텐츠에 맞게 자릅니다.") \ @@ -702,6 +721,7 @@ namespace anm2ed X(TOOLTIP_ROWS, "Set how many rows the spritesheet will have.", "Ajusta cuantas filas tendra el spritsheet.", "Установить сколько рядов будет иметь спрайт-лист.", "设置图集的行数量.", "스프라이트 시트의 행 수를 설정합니다.") \ X(TOOLTIP_SAVE_SPRITESHEETS, "Save the selected spritesheets.", "Guarda los spritesheets seleccionados.", "Сохранить выбранные спрайт-листы.", "保存所选图集.", "선택한 스프라이트 시트를 저장합니다.") \ X(TOOLTIP_SCALE, "Change the scale of the frame, in percent.", "Cambia la escala del Frame, en porcentaje.", "Изменить масштаб кадра.", "修改此帧的缩放.", "프레임의 비율을 변경합니다.") \ + X(TOOLTIP_SHEAR, "Change the shear of the frame, in percent.\nShearing is not supported in The Binding of Isaac: Rebirth.", "Change the shear of the frame, in percent.\nShearing is not supported in The Binding of Isaac: Rebirth.", "Change the shear of the frame, in percent.\nShearing is not supported in The Binding of Isaac: Rebirth.", "Change the shear of the frame, in percent.\nShearing is not supported in The Binding of Isaac: Rebirth.", "Change the shear of the frame, in percent.\nShearing is not supported in The Binding of Isaac: Rebirth.") \ X(TOOLTIP_SCALE_OUTPUT, "Set the output scale of the animation.", "Ajusta la escala de salida de la animacion.", "Установить масштаб анимации при выводе.", "设置输出动画的缩放.", "애니메이션의 출력 비율을 설정합니다.") \ X(TOOLTIP_SETTINGS_SAVE, "Use the configured settings.", "Usa las opciones configuradas.", "Использовать настроенные настройки.", "应用更改的设置.", "구성된 설정을 사용합니다.") \ X(TOOLTIP_SET_DEFAULT_ANIMATION, "Set the selected animation as the default.", "Ajusta la animacion seleccionada como predeterminada.", "Установить выбранную анимацию как анимацию по умолчанию.", "把当前所选动画设置为默认动画.", "선택한 애니메이션을 기본 애니메이션으로 설정합니다.") \ @@ -711,6 +731,7 @@ namespace anm2ed X(TOOLTIP_SOUND, "Toggle sounds playing with triggers.\nSet a trigger's sounds in Frame Properties.", "Alterna los sonidos reproducidos con triggers.\nConfigura los sonidos de un trigger en Propiedades de Frame.", "Переключить воспроизведение звуков у триггеров.\nНастраивайте звуки триггера в свойствах кадра.", "切换是否在触发器触发时播放声音.\n可在帧属性中设置触发器的声音.", "트리거와 함께 사운드를 재생할지 정합니다.\n트리거 사운드는 프레임 속성에서 설정하세요.") \ X(TEXT_SOUND_PLAY, "Click to play.", "Click para reproducir.", "Нажмите, чтобы возпроизвести.", "点击播放.", "클릭하여 재생합니다.") \ X(TOOLTIP_SOUND_INVALID, "This sound could not be loaded. Replace the file.", "Este sonido no se pudo cargar. Reemplaza el archivo.", "Этот звук не удалось загрузить. Замените файл.", "无法加载此声音。请替换文件。", "이 사운드를 불러올 수 없습니다. 파일을 교체하세요.") \ + X(TOOLTIP_SHADER_INVALID, "The shader has errors. Reload it to see details.", "The shader has errors. Reload it to see details.", "The shader has errors. Reload it to see details.", "The shader has errors. Reload it to see details.", "The shader has errors. Reload it to see details.") \ X(TOOLTIP_SOUND_ADD, "Add a sound.", "Añadir un sonido.", "Добавить звук.", "添加一个声音.", "사운드를 추가합니다.") \ X(TOOLTIP_SPRITESHEET_BORDER, "Toggle a border appearing around the spritesheet.", "Alterna un borde apareciendo alrededor del spritesheet", "Переключить показ границ около спрайт-листа.", "切换是否显示在图集的边框.", "스프라이트 시트 주변에 경계선을 표시하거나 숨깁니다.") \ X(TOOLTIP_SPRITESHEET_INVALID, "This spritesheet isn't valid!\nLoad an existing, valid texture.", "¡Este spritesheet no es valido!\nCarga una textura que exista y sea valida.", "Этот спрайт-лист невалиден!\nЗагрузите существующую, валидную текстуру.", "此图集无效!\n请加载一个已存在并有效的纹理/图集.", "이 스프라이트 시트는 유효하지 않습니다!\n유효한 텍스처를 불러오세요.") \ @@ -729,6 +750,7 @@ namespace anm2ed X(TOOLTIP_TOOL_REDO, "Redoes the last action.", "Rehace la accion anterior.", "Повторяет последнее действие.", "重做上一个操作.", "마지막 작업을 다시 실행합니다.") \ X(TOOLTIP_TOOL_ROTATE, "Use the rotate tool.\nWill rotate the selected item as the cursor is dragged, or directional keys are pressed.\n(Animation Preview only.)", "Usa la herramienta rotar.\nRotara el item seleccionado mientras el puntero es arrastrado, o las teclas direccionales son presionadas\n(Solo en la vista previa de animacion)", "Использовать инструмент поворота.\nПовернет выбранный предмет при перемещении курсора или при нажатии клавишей со стрелками.\n(Только в предпросмотре анимации.)", "使用旋转工具.\n将随着光标拖动或方向键按下来旋转选中的物品.\n(仅应用于动画预览.)", "회전 도구를 사용합니다.\n커서를 드래그하거나 방향키를 눌러 선택한 항목을 회전합니다.\n(애니메이션 미리보기 전용)") \ X(TOOLTIP_TOOL_SCALE, "Use the scale tool.\nWill scale the selected item as the cursor is dragged, or directional keys are pressed.\nHold SHIFT to lock scaling to one dimension.\n(Animation Preview only.)", "Usa la herramienta escalar.\nEscalara el item seleccionado mientras el puntero es arrastrado, o las teclas direccionales son presionadas\nManten SHIFT para fijar el escalado a solo una dimension.\n(Solo en la Vista previa de Animacion.)", "Использовать инструмент масштабирования.\nВыбранный элемент будет масштабироваться при перетаскивании курсора или нажатии клавиш со стрелками.\nУдерживайте клавишу SHIFT, чтобы заблокировать масштабирование в одном измерении.\n(Только в предпросмотре анимации.)", "使用缩放工具.\n将随着光标拖动或方向键按下来缩放选中的物品.\n按住 SHIFT 可将缩放锁定为单一维度(单一坐标轴).\n(仅应用与动画预览.)", "비율 도구를 사용합니다.\n커서를 드래그하거나 방향키를 눌러 선택한 항목의 비율을 조정합니다.\nSHIFT 키를 누르면 한 축으로 고정됩니다.\n(애니메이션 미리보기 전용)") \ + X(TOOLTIP_TOOL_SHEAR, "Use the shear tool.\nWill shear the selected item as the cursor is dragged, or directional keys are pressed.\nHold SHIFT to lock shearing to one dimension.\nShearing is not supported in The Binding of Isaac: Rebirth.\n(Animation Preview only.)", "Use the shear tool.\nWill shear the selected item as the cursor is dragged, or directional keys are pressed.\nHold SHIFT to lock shearing to one dimension.\nShearing is not supported in The Binding of Isaac: Rebirth.\n(Animation Preview only.)", "Use the shear tool.\nWill shear the selected item as the cursor is dragged, or directional keys are pressed.\nHold SHIFT to lock shearing to one dimension.\nShearing is not supported in The Binding of Isaac: Rebirth.\n(Animation Preview only.)", "Use the shear tool.\nWill shear the selected item as the cursor is dragged, or directional keys are pressed.\nHold SHIFT to lock shearing to one dimension.\nShearing is not supported in The Binding of Isaac: Rebirth.\n(Animation Preview only.)", "Use the shear tool.\nWill shear the selected item as the cursor is dragged, or directional keys are pressed.\nHold SHIFT to lock shearing to one dimension.\nShearing is not supported in The Binding of Isaac: Rebirth.\n(Animation Preview only.)") \ X(TOOLTIP_TOOL_UNDO, "Undoes the last action.", "Deshace la accion anterior.", "Отменяет последнее действие.", "重做上一个操作.", "마지막 작업을 취소합니다.") \ X(TOOLTIP_TO_ANIMATION_RANGE, "Set the range to the normal range of the animation.", "Ajusta el rango a el rango normal de la animacion.", "Установить диапазон равным обычному диапазону анимации.", "将范围设置为动画的正常范围.", "렌더링 범위를 애니메이션의 범위로 설정합니다.") \ X(TOOLTIP_TO_SELECTED_FRAMES, "If frames are selected, use that range for the rendered animation.", "Si los Frames son seleccionados, usa ese rango para la animacion renderizada.", "Если кадры выбраны, использовать этот диапазон для рендерированной анимации.", "只渲染选择范围内的帧.", "프레임이 선택된 경우 그 영역만 렌더링 범위로 사용합니다.") \ diff --git a/src/settings.hpp b/src/settings.hpp index a5d35f6..5d6b93f 100644 --- a/src/settings.hpp +++ b/src/settings.hpp @@ -86,6 +86,8 @@ namespace anm2ed X(CHANGE_IS_PIVOT_Y, changeIsPivotY, STRING_UNDEFINED, BOOL, false) \ X(CHANGE_IS_SCALE_X, changeIsScaleX, STRING_UNDEFINED, BOOL, false) \ X(CHANGE_IS_SCALE_Y, changeIsScaleY, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_SHEAR_X, changeIsShearX, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_SHEAR_Y, changeIsShearY, STRING_UNDEFINED, BOOL, false) \ X(CHANGE_IS_ROTATION, changeIsRotation, STRING_UNDEFINED, BOOL, false) \ X(CHANGE_IS_DURATION, changeIsDuration, STRING_UNDEFINED, BOOL, false) \ X(CHANGE_IS_TINT_R, changeIsTintR, STRING_UNDEFINED, BOOL, false) \ @@ -101,11 +103,13 @@ namespace anm2ed X(CHANGE_IS_FLIP_X_SET, changeIsFlipXSet, STRING_UNDEFINED, BOOL, false) \ X(CHANGE_IS_FLIP_Y_SET, changeIsFlipYSet, STRING_UNDEFINED, BOOL, false) \ X(CHANGE_IS_REGION, changeIsRegion, STRING_UNDEFINED, BOOL, false) \ + X(CHANGE_IS_SHADER, changeIsShader, STRING_UNDEFINED, BOOL, false) \ X(CHANGE_CROP, changeCrop, STRING_UNDEFINED, VEC2, {}) \ X(CHANGE_SIZE, changeSize, STRING_UNDEFINED, VEC2, {}) \ X(CHANGE_POSITION, changePosition, STRING_UNDEFINED, VEC2, {}) \ X(CHANGE_PIVOT, changePivot, STRING_UNDEFINED, VEC2, {}) \ X(CHANGE_SCALE, changeScale, STRING_UNDEFINED, VEC2, {}) \ + X(CHANGE_SHEAR, changeShear, STRING_UNDEFINED, VEC2, {}) \ X(CHANGE_ROTATION, changeRotation, STRING_UNDEFINED, FLOAT, 0.0f) \ X(CHANGE_DURATION, changeDuration, STRING_UNDEFINED, INT, 0) \ X(CHANGE_TINT, changeTint, STRING_UNDEFINED, VEC4, {}) \ @@ -201,8 +205,8 @@ namespace anm2ed X(RENDER_ROWS, renderRows, STRING_UNDEFINED, INT, 0) \ X(RENDER_COLUMNS, renderColumns, STRING_UNDEFINED, INT, 0) \ X(RENDER_FORMAT, renderFormat, STRING_UNDEFINED, PATH, "{}.png") \ - X(RENDER_IS_USE_ANIMATION_BOUNDS, renderIsUseAnimationBounds, STRING_UNDEFINED, BOOL, true) \ - X(RENDER_IS_USE_ISOLATED_ANIMATION, renderIsUseIsolatedAnimation, STRING_UNDEFINED, BOOL, false) \ + X(RENDER_IS_USE_ANIMATION_BOUNDS, renderIsUseAnimationBounds, STRING_UNDEFINED, BOOL, true) \ + X(RENDER_IS_USE_ISOLATED_ANIMATION, renderIsUseIsolatedAnimation, STRING_UNDEFINED, BOOL, false) \ X(RENDER_SCALE, renderScale, STRING_UNDEFINED, FLOAT, 1.0f) \ X(RENDER_FPS_MODE, renderFpsMode, STRING_UNDEFINED, INT, render::FPS_ANIMATION) \ X(RENDER_FFMPEG_PATH, renderFFmpegPath, STRING_UNDEFINED, PATH, FFMPEG_PATH_DEFAULT) @@ -236,6 +240,7 @@ namespace anm2ed X(SHORTCUT_MOVE, shortcutMove, SHORTCUT_STRING_MOVE, STRING, "V") \ X(SHORTCUT_ROTATE, shortcutRotate, SHORTCUT_STRING_ROTATE, STRING, "R") \ X(SHORTCUT_SCALE, shortcutScale, SHORTCUT_STRING_SCALE, STRING, "S") \ + X(SHORTCUT_SHEAR, shortcutShear, SHORTCUT_STRING_SHEAR, STRING, "H") \ X(SHORTCUT_CROP, shortcutCrop, SHORTCUT_STRING_CROP, STRING, "C") \ X(SHORTCUT_DRAW, shortcutDraw, SHORTCUT_STRING_DRAW, STRING, "B") \ X(SHORTCUT_ERASE, shortcutErase, SHORTCUT_STRING_ERASE, STRING, "E") \ @@ -277,7 +282,7 @@ namespace anm2ed X(WINDOW_NULLS, windowIsNulls, LABEL_NULLS_WINDOW, BOOL, true) \ X(WINDOW_ONIONSKIN, windowIsOnionskin, LABEL_ONIONSKIN_WINDOW, BOOL, true) \ X(WINDOW_PREVIEW, windowIsSpritesheets, LABEL_SPRITESHEETS_WINDOW, BOOL, true) \ - X(WINDOW_SHADERS, windowIsShaders, LABEL_SHADERS_WINDOW, BOOL, true) \ + X(WINDOW_SHADERS, windowIsShaders, LABEL_SHADERS_WINDOW, BOOL, true) \ X(WINDOW_SOUNDS, windowIsSounds, LABEL_SOUNDS_WINDOW, BOOL, true) \ X(WINDOW_SPRITESHEET_EDITOR, windowIsSpritesheetEditor, LABEL_SPRITESHEET_EDITOR_WINDOW, BOOL, true) \ X(WINDOW_TIMELINE, windowIsTimeline, LABEL_TIMELINE_WINDOW, BOOL, true) \ diff --git a/src/snapshots.cpp b/src/snapshots.cpp index eb833f1..d5c75c5 100644 --- a/src/snapshots.cpp +++ b/src/snapshots.cpp @@ -20,9 +20,9 @@ namespace anm2ed::snapshots bool is_storage_equal(const Storage& left, const Storage& right) { - return left.reference == right.reference && left.hovered == right.hovered && left.labelsString == right.labelsString && - left.ids == right.ids && static_cast&>(left.selection) == - static_cast&>(right.selection) && + return left.reference == right.reference && left.hovered == right.hovered && + left.labelsString == right.labelsString && left.ids == right.ids && + static_cast&>(left.selection) == static_cast&>(right.selection) && left.references == right.references; } @@ -77,16 +77,18 @@ namespace anm2ed::snapshots left.createdBy == right.createdBy && left.createdOn == right.createdOn && left.path == right.path && left.vertex == right.vertex && left.fragment == right.fragment && left.binding == right.binding && left.value == right.value && left.defaultAnimation == right.defaultAnimation && left.id == right.id && - left.layerId == right.layerId && left.nullId == right.nullId && - left.spritesheetId == right.spritesheetId && left.fps == right.fps && left.version == right.version && - left.frameNum == right.frameNum && left.duration == right.duration && left.atFrame == right.atFrame && - left.eventId == right.eventId && left.regionId == right.regionId && left.soundId == right.soundId && + left.layerId == right.layerId && left.nullId == right.nullId && left.spritesheetId == right.spritesheetId && + left.fps == right.fps && left.version == right.version && left.frameNum == right.frameNum && + left.duration == right.duration && left.atFrame == right.atFrame && left.eventId == right.eventId && + left.regionId == right.regionId && left.shaderId == right.shaderId && left.soundId == right.soundId && left.groupId == right.groupId && left.index == right.index && left.isLoop == right.isLoop && - left.isVisible == right.isVisible && left.isShowRect == right.isShowRect && left.isExpanded == right.isExpanded && - left.isEnabled == right.isEnabled && left.interpolation == right.interpolation && left.origin == right.origin && - left.rotation == right.rotation && left.soundIds == right.soundIds && is_vec2_equal(left.pivot, right.pivot) && - is_vec2_equal(left.crop, right.crop) && is_vec2_equal(left.position, right.position) && - is_vec2_equal(left.size, right.size) && is_vec2_equal(left.scale, right.scale) && + left.isVisible == right.isVisible && left.isShowRect == right.isShowRect && + left.isExpanded == right.isExpanded && left.isEnabled == right.isEnabled && + left.interpolation == right.interpolation && left.origin == right.origin && + left.rotation == right.rotation && left.soundIds == right.soundIds && + is_vec2_equal(left.pivot, right.pivot) && is_vec2_equal(left.crop, right.crop) && + is_vec2_equal(left.position, right.position) && is_vec2_equal(left.size, right.size) && + is_vec2_equal(left.scale, right.scale) && is_vec2_equal(left.shear, right.shear) && is_vec3_equal(left.colorOffset, right.colorOffset) && is_vec4_equal(left.tint, right.tint); } @@ -317,7 +319,6 @@ namespace anm2ed SNAPSHOT_STEP_STATE_FIELDS SNAPSHOT_STEP_RESOURCE_FIELDS #undef X - } bool SnapshotStack::is_empty() { return stack.empty(); } @@ -462,11 +463,11 @@ namespace anm2ed } #define X(type, name) \ - if (step.name) \ - { \ - step.name->redo = snapshot.name; \ - if (snapshots::is_value_equal(step.name->undo, step.name->redo)) step.name.reset(); \ - } + if (step.name) \ + { \ + step.name->redo = snapshot.name; \ + if (snapshots::is_value_equal(step.name->undo, step.name->redo)) step.name.reset(); \ + } SNAPSHOT_STEP_STATE_FIELDS SNAPSHOT_STEP_RESOURCE_FIELDS #undef X diff --git a/src/snapshots.hpp b/src/snapshots.hpp index 5dbb7b8..3ed285d 100644 --- a/src/snapshots.hpp +++ b/src/snapshots.hpp @@ -60,6 +60,7 @@ namespace anm2ed Storage merge{}; Storage null{}; Storage region{}; + Storage shader{}; Storage sound{}; Storage spritesheet{}; std::map textures{}; @@ -84,6 +85,7 @@ namespace anm2ed X(Storage, merge) \ X(Storage, null) \ X(Storage, region) \ + X(Storage, shader) \ X(Storage, sound) \ X(Storage, spritesheet) \ X(Reference, reference) \ diff --git a/src/tool.hpp b/src/tool.hpp index 74266c7..55ebf22 100644 --- a/src/tool.hpp +++ b/src/tool.hpp @@ -12,6 +12,7 @@ namespace anm2ed::tool MOVE, ROTATE, SCALE, + SHEAR, CROP, DRAW, ERASE, @@ -50,6 +51,9 @@ namespace anm2ed::tool {ImGuiMouseCursor_ResizeNESW, resource::icon::SCALE, SHORTCUT_SCALE, ANIMATION_PREVIEW, "##Scale", TOOLTIP_TOOL_SCALE}, + {ImGuiMouseCursor_ResizeNESW, resource::icon::SHEAR, SHORTCUT_SHEAR, ANIMATION_PREVIEW, "##Shear", + TOOLTIP_TOOL_SHEAR}, + {ImGuiMouseCursor_Arrow, resource::icon::CROP, SHORTCUT_CROP, SPRITESHEET_EDITOR, "##Crop", TOOLTIP_TOOL_CROP}, {ImGuiMouseCursor_Arrow, resource::icon::DRAW, SHORTCUT_DRAW, SPRITESHEET_EDITOR, "##Draw", diff --git a/src/util/math.cpp b/src/util/math.cpp index e9649dc..dfffa8f 100644 --- a/src/util/math.cpp +++ b/src/util/math.cpp @@ -43,7 +43,15 @@ namespace anm2ed::util::math return formatString.c_str(); } - mat4 quad_model_get(vec2 size, vec2 position, vec2 pivot, vec2 scale, float rotation) + mat4 shear_get(vec2 shear) + { + mat4 result(1.0f); + result[1][0] = shear.x; + result[0][1] = shear.y; + return result; + } + + mat4 quad_model_get(vec2 size, vec2 position, vec2 pivot, vec2 scale, float rotation, vec2 shear) { vec2 scaleAbsolute = glm::abs(scale); vec2 scaleSign = glm::sign(scale); @@ -56,12 +64,13 @@ namespace anm2ed::util::math model = glm::translate(model, vec3(pivotScaled, 0.0f)); model = glm::scale(model, vec3(scaleSign, 1.0f)); model = glm::rotate(model, glm::radians(rotation) * handedness, vec3(0, 0, 1)); + model *= shear_get(shear); model = glm::translate(model, vec3(-pivotScaled, 0.0f)); model = glm::scale(model, vec3(sizeScaled, 1.0f)); return model; } - mat4 quad_model_parent_get(vec2 position, vec2 pivot, vec2 scale, float rotation) + mat4 quad_model_parent_get(vec2 position, vec2 pivot, vec2 scale, float rotation, vec2 shear) { vec2 scaleSign = glm::sign(scale); vec2 scaleAbsolute = glm::abs(scale); @@ -71,6 +80,7 @@ namespace anm2ed::util::math local = glm::translate(local, vec3(pivot, 0.0f)); local = glm::scale(local, vec3(scaleSign, 1.0f)); local = glm::rotate(local, glm::radians(rotation) * handedness, vec3(0, 0, 1)); + local *= shear_get(shear); local = glm::translate(local, vec3(-pivot, 0.0f)); local = glm::scale(local, vec3(scaleAbsolute, 1.0f)); diff --git a/src/util/math.hpp b/src/util/math.hpp index 59d3ef8..e5f8066 100644 --- a/src/util/math.hpp +++ b/src/util/math.hpp @@ -27,10 +27,12 @@ namespace anm2ed::util::math const char* vec2_format_get(glm::vec2&); - glm::mat4 quad_model_get(glm::vec2 = {}, glm::vec2 = {}, glm::vec2 = {}, glm::vec2 = glm::vec2(1.0f), float = {}); - glm::mat4 quad_model_parent_get(glm::vec2 = {}, glm::vec2 = {}, glm::vec2 = glm::vec2(1.0f), float = {}); + glm::mat4 quad_model_get(glm::vec2 = {}, glm::vec2 = {}, glm::vec2 = {}, glm::vec2 = glm::vec2(1.0f), float = {}, + glm::vec2 = {}); + glm::mat4 quad_model_parent_get(glm::vec2 = {}, glm::vec2 = {}, glm::vec2 = glm::vec2(1.0f), float = {}, + glm::vec2 = {}); float random(); float random_in_range(float min, float max); void random_seed_set(); -} \ No newline at end of file +} diff --git a/workshop/metadata.xml b/workshop/metadata.xml index fbff99e..d10d6cb 100644 --- a/workshop/metadata.xml +++ b/workshop/metadata.xml @@ -51,6 +51,6 @@ Alternatively, if you have subscribed to the mod, you can find the latest releas [h3]Happy animating![/h3] [img]https://files.catbox.moe/4auc1c.gif[/img] - 2.27 + 2.28 Public