Purge Default Color Values (on by default)

Saves leave out tint channels of 255 and color offsets of 0, which Isaac and
the editor read as those defaults, in both the game's copy and the editor's.
The option sits beside Extended Format in Configure's Serialization row; the
manager takes it with the other settings (chords_set is now settings_apply).
Also drops layer_child_transform_get's unused model parameter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shweetandClaude Opus 5.5 committed 2026-10-11 18:22:26 -04:00
1 parent 0857e62419
commit bec89bf48f
15 files changed
+64 -29

No files matched your search

+8 -6
View File
@@ -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<model::Model> 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())
{
+3 -3
View File
@@ -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<std::filesystem::path>&);
void libraries_add(const std::vector<std::filesystem::path>&);
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&);
+2 -3
View File
@@ -759,9 +759,8 @@ 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)
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,
+4 -1
View File
@@ -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();
+5 -3
View File
@@ -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]);
}
+2 -1
View File
@@ -52,6 +52,7 @@ namespace anm2ed
bool isAbleToRecord{};
ImGuiKeyChord chords[SHORTCUT_COUNT]{};
bool isPurgeDefaultColors{true};
std::vector<std::filesystem::path> 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&);
};
}
+3 -1
View File
@@ -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{};
};
+2 -2
View File
@@ -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<glm::mat4> layer_child_transform_get(const Model& model, const Animation& animation, int layerId,
float time, bool isRootTransform)
std::optional<glm::mat4> layer_child_transform_get(const Animation& animation, int layerId, float time,
bool isRootTransform)
{
std::optional<glm::mat4> transform{};
tracks_each(animation.layers,
+1 -1
View File
@@ -65,7 +65,7 @@ namespace anm2ed::model
glm::mat4 frame_child_model_get(const Frame&);
std::pair<const Model*, const Animation*> child_get(const Model&, const Layer&, const Frame&, const LibraryGet&);
float child_time_get(const Track&, float, int, int);
std::optional<glm::mat4> layer_child_transform_get(const Model&, const Animation&, int, float, bool);
std::optional<glm::mat4> layer_child_transform_get(const Animation&, int, float, bool);
float draw_scale_get(const Draw&);
std::vector<Draw> animation_draws_get(const Model&, const Animation&, const DrawOptions&);
std::vector<TriggerFire> animation_triggers_get(const Model&, const Animation&, int, const LibraryGet& = {});
+9 -5
View File
@@ -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.
+2
View File
@@ -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.", "Использовать предустановленную точку отсчета для региона.", "为区域使用预设原点。", "영역에 사전 설정된 원점을 사용합니다.") \
+1
View File
@@ -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) \
+1 -1
View File
@@ -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); }
+2 -2
View File
@@ -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));
}
+19
View File
@@ -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));
}
}
}