Save files whole or not at all, and keep a render's sounds alive

file_text_save writes a temporary file beside its target, checks every write
and the close, then renames it over the target. A full disk or quota error
no longer leaves a truncated save reported as a success (which then deleted
the autosave). Documents, autosaves, settings and PNGs all save through it.

A recording copies each trigger sound once, so a library reloaded mid-render
leaves its audio mix nothing freed to read. A recording's finish reports
whether its output was made, which animation_record now returns in place of
whether the path existed. A PNG sequence format without a placeholder
numbers each frame after its name instead of writing one file over and over,
and pixel buffers are sized in integers (a float count could run short).
This commit is contained in:
shweet committed 2026-11-22 19:46:22 -05:00
1 parent 71b0ef683b
commit 068d189e6a
11 files changed
+96 -44

No files matched your search

+14 -6
View File
@@ -2,6 +2,8 @@
#include <array> #include <array>
constexpr std::string_view TEMPORARY_EXTENSION = ".tmp";
File::File(const std::filesystem::path& path, const char* mode) File::File(const std::filesystem::path& path, const char* mode)
{ {
open(path, mode); open(path, mode);
@@ -73,11 +75,17 @@ bool file_text_load(const std::filesystem::path& path, std::string* output, cons
} }
} }
bool file_text_save(const std::filesystem::path& path, std::string_view data, const char* mode) bool file_text_save(const std::filesystem::path& path, std::string_view data)
{ {
File file(path, mode); auto temporaryPath = path;
if (!file) temporaryPath += TEMPORARY_EXTENSION;
return false; File file(temporaryPath, "wb");
auto isWritten = file && std::fwrite(data.data(), 1, data.size(), file.get()) == data.size();
return std::fwrite(data.data(), 1, data.size(), file.get()) == data.size(); isWritten = file.close() == 0 && isWritten;
std::error_code error;
if (isWritten)
std::filesystem::rename(temporaryPath, path, error);
if (!isWritten || error)
std::filesystem::remove(temporaryPath, error);
return isWritten && !error;
} }
+2 -1
View File
@@ -21,4 +21,5 @@ private:
}; };
bool file_text_load(const std::filesystem::path&, std::string*, const char* mode = "rb"); bool file_text_load(const std::filesystem::path&, std::string*, const char* mode = "rb");
bool file_text_save(const std::filesystem::path&, std::string_view, const char* mode = "wb"); // Written to a temporary file beside it, then renamed over it: a failed or cut-short write leaves the old file whole.
bool file_text_save(const std::filesystem::path&, std::string_view);
+1 -2
View File
@@ -29,7 +29,6 @@ void Framebuffer::set()
gl.FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0); gl.FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, texture, 0);
gl.BindFramebuffer(GL_FRAMEBUFFER, 0); gl.BindFramebuffer(GL_FRAMEBUFFER, 0);
} }
@@ -43,7 +42,7 @@ void Framebuffer::size_set(Vec2 size)
std::vector<uint8_t> Framebuffer::pixels_get() const std::vector<uint8_t> Framebuffer::pixels_get() const
{ {
auto count = size.x * size.y * IMAGE_CHANNELS; auto count = (std::size_t)size.x * (std::size_t)size.y * IMAGE_CHANNELS;
std::vector<uint8_t> pixels(count); std::vector<uint8_t> pixels(count);
gl.ReadBuffer(GL_COLOR_ATTACHMENT0); gl.ReadBuffer(GL_COLOR_ATTACHMENT0);
+5 -9
View File
@@ -142,7 +142,7 @@ Image Image::vector_render(float scale) const
size_t Image::pixel_size_get() const size_t Image::pixel_size_get() const
{ {
return size.x * size.y * IMAGE_CHANNELS; return (size_t)size.x * (size_t)size.y * IMAGE_CHANNELS;
} }
Image::Image(const uint8_t* data, IVec2 size, bool isLinear) : isLinear(isLinear) Image::Image(const uint8_t* data, IVec2 size, bool isLinear) : isLinear(isLinear)
@@ -191,16 +191,12 @@ bool Image::write_pixels_png(const std::filesystem::path& path, IVec2 size, cons
if (!data || size.x <= 0 || size.y <= 0) if (!data || size.x <= 0 || size.y <= 0)
return false; return false;
File file(path, "wb"); std::string png;
if (auto handle = file.get())
{
auto write_func = [](void* context, void* bytes, int count) { auto write_func = [](void* context, void* bytes, int count) {
fwrite(bytes, 1, count, static_cast<FILE*>(context)); ((std::string*)context)->append((char*)bytes, count);
}; };
return stbi_write_png_to_func(write_func, handle, size.x, size.y, IMAGE_CHANNELS, data, return stbi_write_png_to_func(write_func, &png, size.x, size.y, IMAGE_CHANNELS, data, size.x * IMAGE_CHANNELS) &&
size.x * IMAGE_CHANNELS) != 0; file_text_save(path, png);
}
return false;
} }
// Copies a size-sized block between images. Pixels outside either image are skipped. // Copies a size-sized block between images. Pixels outside either image are skipped.
+1 -1
View File
@@ -70,7 +70,7 @@ static void path_list_save(const std::filesystem::path& path, const std::vector<
std::ostringstream file; std::ostringstream file;
for (auto& entry : entries) for (auto& entry : entries)
file << path_to_utf8(entry) << '\n'; file << path_to_utf8(entry) << '\n';
if (!file_text_save(path, file.str(), "wb")) if (!file_text_save(path, file.str()))
logger.warning(std::format("Could not write {} to: {}. Skipping...", name, path_to_utf8(path))); logger.warning(std::format("Could not write {} to: {}. Skipping...", name, path_to_utf8(path)));
} }
+1 -9
View File
@@ -1837,15 +1837,7 @@ bool model_load_string(Model& model, std::string_view text, std::string* errorSt
bool model_save(const Model& model, const std::filesystem::path& path, std::string* errorString, Options options) bool model_save(const Model& model, const std::filesystem::path& path, std::string* errorString, Options options)
{ {
auto text = model_to_string(model, options); if (file_text_save(path, model_to_string(model, options)))
File file(path, "wb");
if (!file)
{
if (errorString)
*errorString = "File permissions.";
return false;
}
if (std::fwrite(text.data(), 1, text.size(), file.get()) == text.size())
return true; return true;
if (errorString) if (errorString)
*errorString = "Could not write the file."; *errorString = "Could not write the file.";
+25 -13
View File
@@ -65,7 +65,7 @@ bool animation_render(const std::filesystem::path& ffmpegPath, const std::filesy
auto data = (const char*)audio.data(); auto data = (const char*)audio.data();
auto byteCount = audio.size() * sizeof(float); auto byteCount = audio.size() * sizeof(float);
if (file_text_save(audioPath, std::string_view(data, byteCount), "wb")) if (file_text_save(audioPath, std::string_view(data, byteCount)))
{ {
auto audioDurationFilter = std::string{}; auto audioDurationFilter = std::string{};
auto frameCount = (double)std::max((int)framePaths.size(), 1); auto frameCount = (double)std::max((int)framePaths.size(), 1);
@@ -187,9 +187,13 @@ static std::filesystem::path frame_filename_get(const std::filesystem::path& for
auto fallback = path_from_utf8(std::format("frame_{:06}.png", index)); auto fallback = path_from_utf8(std::format("frame_{:06}.png", index));
if (type != RENDER_PNGS) if (type != RENDER_PNGS)
return fallback; return fallback;
// A format without a placeholder numbers its frames after its name.
auto formatUtf8 = path_to_utf8(format);
if (formatUtf8.find('{') == std::string::npos)
formatUtf8 = path_to_utf8(format.stem()) + "_{:06}" + path_to_utf8(format.extension());
try try
{ {
auto filename = path_from_utf8(std::vformat(path_to_utf8(format), std::make_format_args(index))).filename(); auto filename = path_from_utf8(std::vformat(formatUtf8, std::make_format_args(index))).filename();
if (filename.empty()) if (filename.empty())
return fallback; return fallback;
if (filename.extension().empty()) if (filename.extension().empty())
@@ -313,6 +317,7 @@ bool Recorder::start(const RecorderOptions& recorderOptions)
count = frame_count_get(options.start, options.end, options.animationFps, options.fps); count = frame_count_get(options.start, options.end, options.animationFps, options.fps);
frames.clear(); frames.clear();
sounds.clear(); sounds.clear();
soundCopies.clear();
soundTime = -1; soundTime = -1;
directory = frames_directory_create(options); directory = frames_directory_create(options);
return !directory.empty(); return !directory.empty();
@@ -337,6 +342,8 @@ bool Recorder::is_sound_frame() const
bool Recorder::frame_capture(std::vector<uint8_t> pixels, IVec2 size, std::vector<const AudioData*> frameSounds) bool Recorder::frame_capture(std::vector<uint8_t> pixels, IVec2 size, std::vector<const AudioData*> frameSounds)
{ {
soundTime = (int)std::floor(time_get()); soundTime = (int)std::floor(time_get());
for (auto& sound : frameSounds)
sound = &soundCopies.try_emplace(sound->uid, *sound).first->second;
sounds.push_back(std::move(frameSounds)); sounds.push_back(std::move(frameSounds));
if (options.isIsolated || options.isBounded) if (options.isIsolated || options.isBounded)
pixels_unpremultiply(pixels); pixels_unpremultiply(pixels);
@@ -348,12 +355,13 @@ bool Recorder::frame_capture(std::vector<uint8_t> pixels, IVec2 size, std::vecto
return true; return true;
} }
void Recorder::finish() bool Recorder::finish()
{ {
auto pathString = path_to_utf8(options.path); auto pathString = path_to_utf8(options.path);
auto isFinished = !frames.empty();
if (options.type == RENDER_PNGS) if (options.type == RENDER_PNGS)
toast_log(frames.empty() ? Level::ERROR : Level::INFO, toast_log(isFinished ? Level::INFO : Level::ERROR,
frames.empty() ? TOAST_EXPORT_RENDERED_FRAMES_FAILED : TOAST_EXPORT_RENDERED_FRAMES, pathString); isFinished ? TOAST_EXPORT_RENDERED_FRAMES : TOAST_EXPORT_RENDERED_FRAMES_FAILED, pathString);
else if (options.type == RENDER_SPRITESHEET) else if (options.type == RENDER_SPRITESHEET)
{ {
auto layout = spritesheet_layout_get(options.rows, options.columns, (int)frames.size()); auto layout = spritesheet_layout_get(options.rows, options.columns, (int)frames.size());
@@ -361,7 +369,10 @@ void Recorder::finish()
if (frames.empty()) if (frames.empty())
toast_log(Level::WARNING, TOAST_SPRITESHEET_NO_FRAMES); toast_log(Level::WARNING, TOAST_SPRITESHEET_NO_FRAMES);
else if (!first.is_valid()) else if (!first.is_valid())
{
isFinished = false;
toast_log(Level::ERROR, TOAST_SPRITESHEET_EMPTY); toast_log(Level::ERROR, TOAST_SPRITESHEET_EMPTY);
}
else else
{ {
Image sheet = {}; Image sheet = {};
@@ -370,20 +381,21 @@ void Recorder::finish()
for (int i = 0; i < (int)frames.size() && i < layout.rows * layout.columns; ++i) for (int i = 0; i < (int)frames.size() && i < layout.rows * layout.columns; ++i)
if (auto frame = Image(frames[i]); frame.size == first.size) if (auto frame = Image(frames[i]); frame.size == first.size)
sheet.paste(frame, first.size * IVec2(i % layout.columns, i / layout.columns)); sheet.paste(frame, first.size * IVec2(i % layout.columns, i / layout.columns));
auto isSaved = sheet.write_png(options.path); isFinished = sheet.write_png(options.path);
toast_log(isSaved ? Level::INFO : Level::ERROR, toast_log(isFinished ? Level::INFO : Level::ERROR,
isSaved ? TOAST_EXPORT_SPRITESHEET : TOAST_EXPORT_SPRITESHEET_FAILED, pathString); isFinished ? TOAST_EXPORT_SPRITESHEET : TOAST_EXPORT_SPRITESHEET_FAILED, pathString);
} }
} }
else else
{ {
auto audio = auto audio =
options.isSound && options.type != RENDER_GIF ? audio_mix(sounds, options.fps) : std::vector<float>(); options.isSound && options.type != RENDER_GIF ? audio_mix(sounds, options.fps) : std::vector<float>();
auto isRendered = animation_render(options.ffmpegPath, options.path, frames, audio, options.type, options.fps); isFinished = animation_render(options.ffmpegPath, options.path, frames, audio, options.type, options.fps);
toast_log(isRendered ? Level::INFO : Level::ERROR, toast_log(isFinished ? Level::INFO : Level::ERROR,
isRendered ? TOAST_EXPORT_RENDERED_ANIMATION : TOAST_EXPORT_RENDERED_ANIMATION_FAILED, pathString); isFinished ? TOAST_EXPORT_RENDERED_ANIMATION : TOAST_EXPORT_RENDERED_ANIMATION_FAILED, pathString);
} }
cancel(); cancel();
return isFinished;
} }
// Stops. The temporary frame folder is removed (a PNG sequence's own folder is kept). // Stops. The temporary frame folder is removed (a PNG sequence's own folder is kept).
@@ -395,6 +407,7 @@ void Recorder::cancel()
directory.clear(); directory.clear();
frames.clear(); frames.clear();
sounds.clear(); sounds.clear();
soundCopies.clear();
index = count = 0; index = count = 0;
} }
@@ -415,8 +428,7 @@ bool animation_record(const RecorderOptions& recorderOptions, Canvas& canvas, Sh
recorder.cancel(); recorder.cancel();
return false; return false;
} }
recorder.finish(); return recorder.finish();
return is_path_exist(options.path);
} }
constexpr float BAKE_MARGIN = 1.0f; constexpr float BAKE_MARGIN = 1.0f;
+5 -1
View File
@@ -3,6 +3,7 @@
#include <algorithm> #include <algorithm>
#include <cmath> #include <cmath>
#include <filesystem> #include <filesystem>
#include <map>
#include <vector> #include <vector>
#include "audio_data.h" #include "audio_data.h"
@@ -170,13 +171,16 @@ public:
float time_get() const; float time_get() const;
bool is_sound_frame() const; bool is_sound_frame() const;
bool frame_capture(std::vector<uint8_t>, IVec2, std::vector<const AudioData*> = {}); bool frame_capture(std::vector<uint8_t>, IVec2, std::vector<const AudioData*> = {});
void finish(); // False when the output couldn't be made.
bool finish();
void cancel(); void cancel();
private: private:
std::filesystem::path directory; std::filesystem::path directory;
std::vector<std::filesystem::path> frames; std::vector<std::filesystem::path> frames;
// Each frame's trigger sounds, pointing into soundCopies (by uid), so they outlive a reload during the render.
std::vector<std::vector<const AudioData*>> sounds; std::vector<std::vector<const AudioData*>> sounds;
std::map<std::uint64_t, AudioData> soundCopies;
int soundTime = -1; int soundTime = -1;
}; };
+1 -1
View File
@@ -322,7 +322,7 @@ void Settings::save(const std::filesystem::path& path, const std::string& imguiD
logger.error(std::format("Failed while writing settings file: {}", pathUtf8)); logger.error(std::format("Failed while writing settings file: {}", pathUtf8));
return; return;
} }
if (!file_text_save(path, file.str(), "wb")) if (!file_text_save(path, file.str()))
{ {
logger.error(std::format("Failed to save settings file: {}", pathUtf8)); logger.error(std::format("Failed to save settings file: {}", pathUtf8));
return; return;
+16
View File
@@ -2,6 +2,7 @@
#include "asset_store.h" #include "asset_store.h"
#include "audio_data.h" #include "audio_data.h"
#include "file.h"
#include "font.h" #include "font.h"
#include "friends.h" #include "friends.h"
#include "icon.h" #include "icon.h"
@@ -135,3 +136,18 @@ TEST_CASE("Embedded resources load")
for (auto& font : FONTS) for (auto& font : FONTS)
CHECK(font->size > 0); CHECK(font->size > 0);
} }
TEST_CASE("a save replaces its file whole, or leaves it as it was")
{
auto path = std::filesystem::temp_directory_path() / "anm2ed_save_test.txt";
auto text = std::string{};
REQUIRE(file_text_save(path, "first"));
CHECK(file_text_save(path, "second"));
CHECK(file_text_load(path, &text));
CHECK(text == "second");
CHECK_FALSE(file_text_save(path / "inside_a_file.txt", "third"));
CHECK(file_text_load(path, &text));
CHECK(text == "second");
CHECK_FALSE(std::filesystem::exists(path.string() + ".tmp"));
std::filesystem::remove(path);
}
+25 -1
View File
@@ -6,7 +6,6 @@
#include <algorithm> #include <algorithm>
#include <cstdlib> #include <cstdlib>
#include <format>
#include <fstream> #include <fstream>
#include "audio.h" #include "audio.h"
@@ -133,6 +132,31 @@ TEST_CASE("a recorded spritesheet holds every frame")
golden_image_check("spin_sheet.png"); golden_image_check("spin_sheet.png");
} }
TEST_CASE("a PNG sequence without a placeholder numbers each frame")
{
RenderFixture fixture("spin.anm2");
if (!fixture.gl.is_valid())
{
MESSAGE("skipped: no OpenGL context");
return;
}
auto directory = OUTPUT_DIR / "spin_sequence";
std::filesystem::remove_all(directory);
RecorderOptions options{.type = RENDER_PNGS,
.path = directory,
.format = "spin.png",
.start = 0,
.end = fixture.animation->frameNum - 1,
.animationFps = fixture.document->model.info.fps,
.fps = fixture.document->model.info.fps};
REQUIRE(animation_record(options, *fixture.canvas, *fixture.shader, *fixture.document, *fixture.animation,
fixture.bounds, SCALE, BACKGROUND, true));
auto count = std::ranges::distance(std::filesystem::directory_iterator(directory));
CHECK(count == fixture.animation->frameNum);
CHECK(std::filesystem::exists(directory / "spin_000000.png"));
}
TEST_CASE("animation layers draw their child animations") TEST_CASE("animation layers draw their child animations")
{ {
RenderFixture fixture("nested.anm2"); RenderFixture fixture("nested.anm2");