diff --git a/src/document.cpp b/src/document.cpp index c585a22..3339989 100644 --- a/src/document.cpp +++ b/src/document.cpp @@ -210,11 +210,11 @@ namespace anm2ed return *this; } - bool Document::save(const std::filesystem::path& path, std::string* errorString) + bool Document::save(const std::filesystem::path& path, std::string* errorString, bool isPurgeDefaultColors) { auto absolutePath = !path.empty() ? path : this->path; auto absolutePathUtf8 = path::to_utf8(absolutePath); - if (file_write(absolutePath, errorString)) + if (file_write(absolutePath, errorString, isPurgeDefaultColors)) { this->path = absolutePath; toast_log(Level::INFO, TOAST_SAVE_DOCUMENT, absolutePathUtf8); @@ -226,7 +226,7 @@ namespace anm2ed } // Writes the document; a Rebirth document's game copy has its animation layers flattened into plain layers. - bool Document::file_write(const std::filesystem::path& path, std::string* errorString) + bool Document::file_write(const std::filesystem::path& path, std::string* errorString, bool isPurgeDefaultColors) { std::optional game{}; if (!model.isExtendedFormat && std::ranges::any_of(model.content.layers, &model::Layer::is_animation)) @@ -242,7 +242,9 @@ namespace anm2ed return spritesheetPath; }); return model::model_save(model, path, errorString, - {.isExtendedFormat = model.isExtendedFormat, .gameModel = game ? &*game : nullptr}); + {.isExtendedFormat = model.isExtendedFormat, + .isPurgeDefaultColors = isPurgeDefaultColors, + .gameModel = game ? &*game : nullptr}); } std::filesystem::path Document::autosave_path_get() @@ -260,11 +262,11 @@ namespace anm2ed return path.parent_path() / std::filesystem::path(std::u8string(fileName.begin(), fileName.end())); } - bool Document::autosave(std::string* errorString) + bool Document::autosave(std::string* errorString, bool isPurgeDefaultColors) { auto autosavePath = autosave_path_get(); auto autosavePathUtf8 = path::to_utf8(autosavePath); - if (file_write(autosavePath, errorString)) + if (file_write(autosavePath, errorString, isPurgeDefaultColors)) { for (auto id : spritesheets_autosave_dirty_get()) { diff --git a/src/document.hpp b/src/document.hpp index 43220c1..fb42465 100644 --- a/src/document.hpp +++ b/src/document.hpp @@ -130,8 +130,8 @@ namespace anm2ed Document& operator=(const Document&) = delete; Document(Document&&) noexcept; Document& operator=(Document&&) noexcept; - bool save(const std::filesystem::path& = {}, std::string* = nullptr); - bool file_write(const std::filesystem::path&, std::string* = nullptr); + bool save(const std::filesystem::path& = {}, std::string* = nullptr, bool = true); + bool file_write(const std::filesystem::path&, std::string* = nullptr, bool = true); void assets_sync(); void texture_change(int); bool texture_reload(int); @@ -228,7 +228,7 @@ namespace anm2ed void sounds_add(const std::vector&); void libraries_add(const std::vector&); - bool autosave(std::string* = nullptr); + bool autosave(std::string* = nullptr, bool = true); std::filesystem::path autosave_path_get(); std::filesystem::path path_from_autosave_get(const std::filesystem::path&); diff --git a/src/imgui/window/animation_preview.cpp b/src/imgui/window/animation_preview.cpp index b2056f0..fc77fb6 100644 --- a/src/imgui/window/animation_preview.cpp +++ b/src/imgui/window/animation_preview.cpp @@ -759,10 +759,9 @@ namespace anm2ed::imgui auto parentIndex = manager.tab_index_get(step.tabId); auto parentDocument = parentIndex == -1 ? nullptr : manager.get(parentIndex); auto parentAnimation = parentDocument ? parentDocument->model.animation_get(step.animationIndex) : nullptr; - auto placement = parentAnimation - ? model::layer_child_transform_get(parentDocument->model, *parentAnimation, - step.layer.itemID, step.frameTime, isRootTransform) - : std::nullopt; + auto placement = parentAnimation ? model::layer_child_transform_get(*parentAnimation, step.layer.itemID, + step.frameTime, isRootTransform) + : std::nullopt; if (placement && glm::determinant(*placement) != 0.0f) render(*parentDocument, *parentAnimation, PARENT_DIM_ALPHA, {.time = step.frameTime, .isRootTransform = isRootTransform}, glm::inverse(*placement), diff --git a/src/imgui/wizard/configure.cpp b/src/imgui/wizard/configure.cpp index d38957a..63833ac 100644 --- a/src/imgui/wizard/configure.cpp +++ b/src/imgui/wizard/configure.cpp @@ -89,6 +89,9 @@ namespace anm2ed::imgui::wizard ImGui::SeparatorText(localize.get(LABEL_SERIALIZATION)); ImGui::Checkbox(localize.get(LABEL_EXTENDED_FORMAT), &temporary.isFileExtendedFormat); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_EXTENDED_FORMAT)); + ImGui::SameLine(); + ImGui::Checkbox(localize.get(LABEL_PURGE_DEFAULT_COLORS), &temporary.fileIsPurgeDefaultColors); + ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_PURGE_DEFAULT_COLORS)); } ImGui::EndChild(); @@ -204,7 +207,7 @@ namespace anm2ed::imgui::wizard SnapshotStack::max_size_set(settings.fileSnapshotStackSize); imgui::theme_set((theme::Type)settings.theme); localize.language = (Language)settings.language; - manager.chords_set(settings); + manager.settings_apply(settings); for (auto& document : manager.documents) document.snapshots.apply_limit(); diff --git a/src/manager.cpp b/src/manager.cpp index f58ced3..76c7a8e 100644 --- a/src/manager.cpp +++ b/src/manager.cpp @@ -173,7 +173,7 @@ namespace anm2ed savePath.replace_extension(".anm2"); ensure_parent_directory_exists(savePath); - if (!document->save(savePath, &errorString)) return false; + if (!document->save(savePath, &errorString, isPurgeDefaultColors)) return false; const auto autosavePath = document->autosave_path_get(); autosaveFiles.erase(std::remove(autosaveFiles.begin(), autosaveFiles.end(), previousAutosavePath), @@ -196,7 +196,7 @@ namespace anm2ed { std::string errorString{}; auto autosavePath = document.autosave_path_get(); - if (!document.autosave(&errorString)) return; + if (!document.autosave(&errorString, isPurgeDefaultColors)) return; autosaveFiles.erase(std::remove(autosaveFiles.begin(), autosaveFiles.end(), autosavePath), autosaveFiles.end()); autosaveFiles.insert(autosaveFiles.begin(), autosavePath); @@ -469,8 +469,10 @@ namespace anm2ed autosave_files_write(); } - void Manager::chords_set(Settings& settings) + // What the manager keeps from the settings: shortcuts, and how documents save. + void Manager::settings_apply(Settings& settings) { + isPurgeDefaultColors = settings.fileIsPurgeDefaultColors; for (int i = 0; i < SHORTCUT_COUNT; i++) chords[i] = imgui::string_to_chord(settings.*SHORTCUT_MEMBERS[i]); } diff --git a/src/manager.hpp b/src/manager.hpp index 6e2a9b2..b82ed21 100644 --- a/src/manager.hpp +++ b/src/manager.hpp @@ -52,6 +52,7 @@ namespace anm2ed bool isAbleToRecord{}; ImGuiKeyChord chords[SHORTCUT_COUNT]{}; + bool isPurgeDefaultColors{true}; std::vector anm2DragDropPaths{}; bool isAnm2DragDrop{}; @@ -119,6 +120,6 @@ namespace anm2ed void autosave_files_write(); void autosave_files_clear(bool removeFiles = false); - void chords_set(Settings&); + void settings_apply(Settings&); }; } diff --git a/src/model/common.hpp b/src/model/common.hpp index 3b0f3e7..e6931f3 100644 --- a/src/model/common.hpp +++ b/src/model/common.hpp @@ -151,7 +151,8 @@ namespace anm2ed SERIALIZE_NESTED_GROUPS = 1 << 6, SERIALIZE_EXTENSIONS = 1 << 7, SERIALIZE_FLATTEN_SPECIAL_INTERPOLATED_FRAMES = 1 << 8, - SERIALIZE_EXTENDED_DOCUMENT = 1 << 9 + SERIALIZE_EXTENDED_DOCUMENT = 1 << 9, + SERIALIZE_PURGE_DEFAULT_COLORS = 1 << 10 }; using Flags = int; @@ -175,6 +176,7 @@ namespace anm2ed struct Options { bool isExtendedFormat{}; + bool isPurgeDefaultColors{}; // leave out tints of 255 and color offsets of 0, which readers assume const model::Model* gameModel{}; }; diff --git a/src/model/draw.cpp b/src/model/draw.cpp index 6504310..7d9336b 100644 --- a/src/model/draw.cpp +++ b/src/model/draw.cpp @@ -148,8 +148,8 @@ namespace anm2ed::model } // Where an animation layer track (`layerId`) puts its child at a time, in the animation's space. - std::optional layer_child_transform_get(const Model& model, const Animation& animation, int layerId, - float time, bool isRootTransform) + std::optional layer_child_transform_get(const Animation& animation, int layerId, float time, + bool isRootTransform) { std::optional transform{}; tracks_each(animation.layers, diff --git a/src/model/draw.hpp b/src/model/draw.hpp index 5649f4a..af35299 100644 --- a/src/model/draw.hpp +++ b/src/model/draw.hpp @@ -65,7 +65,7 @@ namespace anm2ed::model glm::mat4 frame_child_model_get(const Frame&); std::pair child_get(const Model&, const Layer&, const Frame&, const LibraryGet&); float child_time_get(const Track&, float, int, int); - std::optional layer_child_transform_get(const Model&, const Animation&, int, float, bool); + std::optional layer_child_transform_get(const Animation&, int, float, bool); float draw_scale_get(const Draw&); std::vector animation_draws_get(const Model&, const Animation&, const DrawOptions&); std::vector animation_triggers_get(const Model&, const Animation&, int, const LibraryGet& = {}); diff --git a/src/model/xml.cpp b/src/model/xml.cpp index b61a563..7241a8e 100644 --- a/src/model/xml.cpp +++ b/src/model/xml.cpp @@ -1183,10 +1183,13 @@ namespace anm2ed::model sink.attribute("SkewX", frame.skew.x); sink.attribute("SkewY", frame.skew.y); } + auto isPurged = writer.is(SERIALIZE_PURGE_DEFAULT_COLORS); for (int i = 0; i < (int)std::size(TINT_ATTRIBUTES); ++i) - sink.attribute(TINT_ATTRIBUTES[i], math::float_to_uint8(frame.tint[i])); + if (auto tint = math::float_to_uint8(frame.tint[i]); !isPurged || tint != math::float_to_uint8(1.0f)) + sink.attribute(TINT_ATTRIBUTES[i], tint); for (int i = 0; i < (int)std::size(OFFSET_ATTRIBUTES); ++i) - sink.attribute(OFFSET_ATTRIBUTES[i], math::float_to_uint8(frame.colorOffset[i])); + if (auto offset = math::float_to_uint8(frame.colorOffset[i]); !isPurged || offset != 0) + sink.attribute(OFFSET_ATTRIBUTES[i], offset); if (writer.is(SERIALIZE_EXTENSIONS) && math::float_to_uint8(frame.colorOffset.a) != 0) sink.attribute("AlphaOffset", math::float_to_uint8(frame.colorOffset.a)); sink.attribute("Rotation", frame.rotation); @@ -1764,10 +1767,11 @@ namespace anm2ed::model // A save is the game's document with the editor's own copy embedded as SourceDocument (or just the editor's copy). void document_write(Sink& sink, const Model& model, Options options) { + Flags purge = options.isPurgeDefaultColors ? SERIALIZE_PURGE_DEFAULT_COLORS : 0; if (options.isExtendedFormat) - return model_write(sink, model, SERIALIZE_ANM2ED_DEFAULT | SERIALIZE_EXTENDED_DOCUMENT); - model_write(sink, options.gameModel ? *options.gameModel : model, SERIALIZE_ISAAC_DEFAULT, - [&]() { model_write(sink, model, SERIALIZE_ANM2ED_DEFAULT, {}, SOURCE_DOCUMENT_TAG); }); + return model_write(sink, model, SERIALIZE_ANM2ED_DEFAULT | SERIALIZE_EXTENDED_DOCUMENT | purge); + model_write(sink, options.gameModel ? *options.gameModel : model, SERIALIZE_ISAAC_DEFAULT | purge, + [&]() { model_write(sink, model, SERIALIZE_ANM2ED_DEFAULT | purge, {}, SOURCE_DOCUMENT_TAG); }); } // The text of whatever `write` sends to a sink. diff --git a/src/resource/strings.hpp b/src/resource/strings.hpp index 5031273..d456fdc 100644 --- a/src/resource/strings.hpp +++ b/src/resource/strings.hpp @@ -305,6 +305,7 @@ namespace anm2ed X(LABEL_ONLY_SELECTED_ITEM, "Only Selected Item", "Solo el Elemento Seleccionado", "Только выбранный элемент", "仅选中项目", "선택한 항목만") \ X(LABEL_PIVOT_PATH, "Pivot Path", "Trayectoria del Pivote", "Путь опорной точки", "枢轴路径", "피벗 경로") \ X(LABEL_PROPERTY, "Property", "Propiedad", "Свойство", "属性", "속성") \ + X(LABEL_PURGE_DEFAULT_COLORS, "Purge Default Color Values", "Omitir Valores de Color por Defecto", "Убирать цвета по умолчанию", "清除默认颜色值", "기본 색상 값 제거") \ X(LABEL_RANDOM, "Random", "Aleatorio", "Случайно", "随机", "무작위") \ X(LABEL_REMOVE_MARKERS, "Remove Markers", "Quitar Marcadores", "Удалить маркеры", "移除标记", "마커 제거") \ X(LABEL_RESTART, "Restart", "Reiniciar", "Перезапуск", "重新开始", "다시 시작") \ @@ -706,6 +707,7 @@ namespace anm2ed X(TOOLTIP_COLOR_OFFSET, "Change the color added onto the frame.\n(Alpha is editor only; the game ignores it.)", "Cambia el color añadido al Frame.\n(El alfa es solo del editor; el juego lo ignora.)", "Изменить цвет, который добавлен на кадр.\n(Альфа только для редактора; игра её игнорирует.)", "更改添加到帧上的颜色。\n(透明度仅限编辑器;游戏会忽略它。)", "프레임에 더해지는 색상을 변경합니다.\n(알파는 에디터 전용이며 게임에서는 무시됩니다.)") \ X(TOOLTIP_ONLY_SELECTED_ITEM, "Only the selected item (root, layer or null) is onionskinned and shows its pivot path.", "Solo el elemento seleccionado (raíz, capa o null) usa papel cebolla y muestra la trayectoria de su pivote.", "Оньонскин и путь опорной точки показываются только для выбранного элемента (корень, слой или null).", "仅对选中的项目(根、图层或空节点)显示洋葱皮和枢轴路径。", "선택한 항목(루트, 레이어 또는 널)에만 전후 비교와 피벗 경로를 표시합니다.") \ X(TOOLTIP_PIVOT_PATH, "Show the path each item's pivot travels through the animation, with a dot on every frame.", "Muestra la trayectoria que recorre el pivote de cada elemento durante la animación, con un punto en cada Frame.", "Показать путь опорной точки каждого элемента в анимации, с точкой на каждом кадре.", "显示每个项目的枢轴在动画中移动的路径,每帧一个点。", "애니메이션 동안 각 항목의 피벗이 지나는 경로를 프레임마다 점으로 표시합니다.") \ + X(TOOLTIP_PURGE_DEFAULT_COLORS, "Leave tints of 255 and color offsets of 0 out of saved frames; the game and the editor read missing ones as those defaults, so files get much smaller.", "Omite de los Frames guardados los tintes de 255 y los desplazamientos de color de 0; el juego y el editor leen los que faltan como esos valores, así que los archivos son mucho más pequeños.", "Не записывать в кадры оттенки 255 и смещения цвета 0; игра и редактор считают отсутствующие значения такими же, поэтому файлы становятся намного меньше.", "保存帧时省略为 255 的色调和为 0 的颜色偏移;游戏和编辑器会将缺失值读作这些默认值,因此文件会小得多。", "저장되는 프레임에서 255인 틴트와 0인 색상 오프셋을 생략합니다. 게임과 에디터는 빠진 값을 기본값으로 읽으므로 파일이 훨씬 작아집니다.") \ 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.", "Использовать предустановленную точку отсчета для региона.", "为区域使用预设原点。", "영역에 사전 설정된 원점을 사용합니다.") \ diff --git a/src/settings.hpp b/src/settings.hpp index 983f704..9f5f538 100644 --- a/src/settings.hpp +++ b/src/settings.hpp @@ -66,6 +66,7 @@ namespace anm2ed X(FILE_IS_WARN_ISAAC, fileIsWarnIsaac, STRING_UNDEFINED, BOOL, true) \ X(FILE_IS_AUTO_RELOAD_RESOURCES, fileIsAutoReloadResources, STRING_UNDEFINED, BOOL, true) \ X(FILE_IS_EXTENDED_FORMAT, isFileExtendedFormat, STRING_UNDEFINED, BOOL, false) \ + X(FILE_IS_PURGE_DEFAULT_COLORS, fileIsPurgeDefaultColors, STRING_UNDEFINED, BOOL, true) \ X(FILE_SNAPSHOT_STACK_SIZE, fileSnapshotStackSize, STRING_UNDEFINED, INT, 50) \ \ X(KEYBOARD_REPEAT_DELAY, keyboardRepeatDelay, STRING_UNDEFINED, FLOAT, 0.300f) \ diff --git a/src/state.cpp b/src/state.cpp index 73646df..e5b1f4f 100644 --- a/src/state.cpp +++ b/src/state.cpp @@ -31,7 +31,7 @@ namespace anm2ed for (const auto& argument : arguments) manager.open(path::from_utf8(argument)); - manager.chords_set(settings); + manager.settings_apply(settings); } void State::tick(Settings& settings, float deltaSeconds) { dockspace.tick(manager, settings, deltaSeconds); } diff --git a/tests/draw.cpp b/tests/draw.cpp index d1d6cb4..bbba7bd 100644 --- a/tests/draw.cpp +++ b/tests/draw.cpp @@ -203,8 +203,8 @@ TEST_CASE("flattening animation layers bakes their children into plain layers th TEST_CASE("an animation layer's child sits where the layer's frame puts it") { auto anm2 = model_load(file_load(TEST_DIR / "render" / "nested.anm2")); - auto placement = model::layer_child_transform_get(anm2, *anm2.animation_get(0), 0, 0.0f, true); + auto placement = model::layer_child_transform_get(*anm2.animation_get(0), 0, 0.0f, true); REQUIRE(placement); CHECK(glm::vec2(*placement * glm::vec4(16.0f, 0.0f, 0.0f, 1.0f)) == glm::vec2(48.0f, 0.0f)); - CHECK_FALSE(model::layer_child_transform_get(anm2, *anm2.animation_get(0), 99, 0.0f, true)); + CHECK_FALSE(model::layer_child_transform_get(*anm2.animation_get(0), 99, 0.0f, true)); } diff --git a/tests/invariants.cpp b/tests/invariants.cpp index 7c08502..0f9dd91 100644 --- a/tests/invariants.cpp +++ b/tests/invariants.cpp @@ -43,3 +43,22 @@ TEST_CASE("a document's format is kept by what it saves") CHECK(reloaded.isExtendedFormat); CHECK(model::model_hash(reloaded) == model::model_hash(model)); } + +TEST_CASE("purged default colors read back the same") +{ + for (const auto& fixture : fixtures_get()) + { + INFO("fixture: ", fixture.string()); + auto model = model_load(file_load(fixture)); + for (auto isExtended : {false, true}) + { + auto text = model::model_to_string(model, {.isExtendedFormat = isExtended, .isPurgeDefaultColors = true}); + CHECK(text.find("Tint=\"255\"") == std::string::npos); + CHECK(text.find("Offset=\"0\"") == std::string::npos); + CHECK(text.size() <= model::model_to_string(model, {.isExtendedFormat = isExtended}).size()); + auto reloaded = model_load(text); + reloaded.isExtendedFormat = model.isExtendedFormat; + CHECK(model::model_hash(reloaded) == model::model_hash(model)); + } + } +}