diff --git a/src/asset_store.cpp b/src/asset_store.cpp index 786792a..d7a23d9 100644 --- a/src/asset_store.cpp +++ b/src/asset_store.cpp @@ -2,25 +2,23 @@ #include -namespace anm2ed::resource -{ constexpr std::uint64_t FNV_OFFSET = 14695981039346656037ull; constexpr std::uint64_t FNV_PRIME = 1099511628211ull; - std::uint64_t bytes_hash(std::span bytes, std::uint64_t hash = FNV_OFFSET) + static std::uint64_t bytes_hash(std::span bytes, std::uint64_t hash = FNV_OFFSET) { for (auto byte : bytes) hash = (hash ^ byte) * FNV_PRIME; return hash; } - template std::span value_bytes_get(const Value& value) + template static std::span value_bytes_get(const Value& value) { return {reinterpret_cast(&value), sizeof(value)}; } // Content hash; 0 stays free to mean "no asset". - std::uint64_t hash_finish(std::uint64_t hash) { return hash ? hash : 1; } + static std::uint64_t hash_finish(std::uint64_t hash) { return hash ? hash : 1; } std::uint64_t AssetStore::image_add(Image image) { @@ -51,4 +49,3 @@ namespace anm2ed::resource auto it = audio.find(hash); return it == audio.end() ? nullptr : &it->second; } -} diff --git a/src/asset_store.h b/src/asset_store.h index 53c2caa..955906b 100644 --- a/src/asset_store.h +++ b/src/asset_store.h @@ -6,8 +6,6 @@ #include "audio_data.h" #include "image.h" -namespace anm2ed::resource -{ // Immutable images and sounds keyed by content hash. Undo history records keys, never pixels or bytes, and // entries live until the document closes so any step can be restored. class AssetStore @@ -21,4 +19,3 @@ namespace anm2ed::resource const Image* image_get(std::uint64_t) const; const AudioData* audio_get(std::uint64_t) const; }; -} diff --git a/src/audio.cpp b/src/audio.cpp index 94fae17..9926967 100644 --- a/src/audio.cpp +++ b/src/audio.cpp @@ -6,9 +6,7 @@ #include #include -namespace anm2ed::resource::audio -{ - struct Entry + struct AudioEntry { MIX_Audio* audio{}; std::vector tracks{}; // one per overlapping play, reused once finished @@ -17,9 +15,9 @@ namespace anm2ed::resource::audio }; // Sums the squares of the left/right samples the track plays, for its levels. - void SDLCALL levels_update(void* userdata, MIX_Track*, const SDL_AudioSpec* spec, float* pcm, int samples) + static void SDLCALL levels_update(void* userdata, MIX_Track*, const SDL_AudioSpec* spec, float* pcm, int samples) { - auto entry = (Entry*)userdata; + auto entry = (AudioEntry*)userdata; auto channels = std::max(spec->channels, 1); float squares[2]{}; for (int i = 0; i < samples; ++i) @@ -30,31 +28,31 @@ namespace anm2ed::resource::audio entry->sampleCount += samples / channels; } - std::unordered_map entries{}; + static std::unordered_map entries{}; - MIX_Mixer* mixer_get() + static MIX_Mixer* audio_mixer_get() { static auto mixer = MIX_CreateMixerDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, nullptr); return mixer; } - Entry* entry_get(const AudioData& data) + static AudioEntry* entry_get(const AudioData& data) { if (!data.is_valid()) return nullptr; auto [it, isNew] = entries.try_emplace(data.uid); if (isNew) if (auto io = SDL_IOFromConstMem(data.bytes.data(), data.bytes.size())) - it->second.audio = MIX_LoadAudio_IO(mixer_get(), io, true, true); + it->second.audio = MIX_LoadAudio_IO(audio_mixer_get(), io, true, true); return it->second.audio ? &it->second : nullptr; } - bool is_on_mixer(MIX_Track* track, MIX_Mixer* mixer) { return !mixer || MIX_GetTrackMixer(track) == mixer; } + static bool is_on_mixer(MIX_Track* track, MIX_Mixer* mixer) { return !mixer || MIX_GetTrackMixer(track) == mixer; } // A sound can play over itself: while a track is still playing it, another track takes the new play. - void play(const AudioData& data, bool isLoop, MIX_Mixer* mixer) + void audio_play(const AudioData& data, bool isLoop, MIX_Mixer* mixer) { auto entry = entry_get(data); - auto targetMixer = mixer ? mixer : mixer_get(); + auto targetMixer = mixer ? mixer : audio_mixer_get(); if (!entry || !targetMixer) return; auto free = std::ranges::find_if(entry->tracks, [&](MIX_Track* track) @@ -74,14 +72,14 @@ namespace anm2ed::resource::audio if (options) SDL_DestroyProperties(options); } - void stop(const AudioData& data, MIX_Mixer* mixer) + void audio_stop(const AudioData& data, MIX_Mixer* mixer) { if (auto it = entries.find(data.uid); it != entries.end()) for (auto track : it->second.tracks) if (is_on_mixer(track, mixer)) MIX_StopTrack(track, 0); } - void track_detach(const AudioData& data, MIX_Mixer* mixer) + void audio_track_detach(const AudioData& data, MIX_Mixer* mixer) { auto it = entries.find(data.uid); if (it == entries.end()) return; @@ -94,14 +92,14 @@ namespace anm2ed::resource::audio }); } - bool is_playing(const AudioData& data) + bool is_audio_playing(const AudioData& data) { auto it = entries.find(data.uid); return it != entries.end() && std::ranges::any_of(it->second.tracks, MIX_TrackPlaying); } // The left/right loudness (RMS, 0-1) of what the track played since the last call. - glm::vec2 levels_get(const AudioData& data) + glm::vec2 audio_levels_get(const AudioData& data) { auto it = entries.find(data.uid); if (it == entries.end()) return {}; @@ -109,4 +107,3 @@ namespace anm2ed::resource::audio auto count = (float)std::max(entry.sampleCount.exchange(0), 1); return {std::sqrt(entry.squares[0].exchange(0.0f) / count), std::sqrt(entry.squares[1].exchange(0.0f) / count)}; } -} diff --git a/src/audio.h b/src/audio.h index b305eed..8bcfe0f 100644 --- a/src/audio.h +++ b/src/audio.h @@ -6,11 +6,8 @@ #include "audio_data.h" // Playback of AudioData; decoded audio and tracks are cached per AudioData uid. -namespace anm2ed::resource::audio -{ - void play(const AudioData&, bool = false, MIX_Mixer* = nullptr); - void stop(const AudioData&, MIX_Mixer* = nullptr); - void track_detach(const AudioData&, MIX_Mixer* = nullptr); - bool is_playing(const AudioData&); - glm::vec2 levels_get(const AudioData&); -} + void audio_play(const AudioData&, bool = false, MIX_Mixer* = nullptr); + void audio_stop(const AudioData&, MIX_Mixer* = nullptr); + void audio_track_detach(const AudioData&, MIX_Mixer* = nullptr); + bool is_audio_playing(const AudioData&); + glm::vec2 audio_levels_get(const AudioData&); diff --git a/src/audio_data.cpp b/src/audio_data.cpp index c9ff41f..551390b 100644 --- a/src/audio_data.cpp +++ b/src/audio_data.cpp @@ -5,13 +5,11 @@ #include "uid.h" -namespace anm2ed::resource -{ AudioData::AudioData(const unsigned char* memory, size_t size) { if (!memory || size == 0) return; bytes.assign(memory, memory + size); - uid = util::uid_next(); + uid = uid_next(); } AudioData::AudioData(const std::filesystem::path& path) @@ -22,4 +20,3 @@ namespace anm2ed::resource } bool AudioData::is_valid() const { return !bytes.empty(); } -} diff --git a/src/audio_data.h b/src/audio_data.h index 1865d89..266b8c1 100644 --- a/src/audio_data.h +++ b/src/audio_data.h @@ -5,8 +5,6 @@ #include #include -namespace anm2ed::resource -{ // Encoded audio file bytes. uid identifies the bytes so playback state can be cached by it. struct AudioData { @@ -19,4 +17,3 @@ namespace anm2ed::resource bool is_valid() const; }; -} diff --git a/src/audio_stream.cpp b/src/audio_stream.cpp index db3eb36..8058c1f 100644 --- a/src/audio_stream.cpp +++ b/src/audio_stream.cpp @@ -7,8 +7,6 @@ #pragma GCC diagnostic ignored "-Wunused-parameter" #endif -namespace anm2ed -{ void AudioStream::callback(void* userData, MIX_Mixer* mixer, const SDL_AudioSpec* spec, float* pcm, int samples) { auto self = (AudioStream*)userData; @@ -23,4 +21,3 @@ namespace anm2ed AudioStream::AudioStream(MIX_Mixer* mixer) { MIX_GetMixerFormat(mixer, &spec); } -} diff --git a/src/audio_stream.h b/src/audio_stream.h index ee2f189..a589712 100644 --- a/src/audio_stream.h +++ b/src/audio_stream.h @@ -3,8 +3,6 @@ #include #include -namespace anm2ed -{ class AudioStream { static void callback(void*, MIX_Mixer*, const SDL_AudioSpec*, float*, int); @@ -19,4 +17,3 @@ namespace anm2ed AudioStream(MIX_Mixer*); }; -} diff --git a/src/canvas.cpp b/src/canvas.cpp index 7f03e20..60b6ed8 100644 --- a/src/canvas.cpp +++ b/src/canvas.cpp @@ -9,24 +9,20 @@ #include "texture.h" using namespace glm; -using namespace anm2ed::resource; -using namespace anm2ed::util; -namespace anm2ed -{ - void canvas_blend_premultiplied_set() + static void canvas_blend_premultiplied_set() { glEnable(GL_BLEND); glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); } - void canvas_blend_straight_set() + static void canvas_blend_straight_set() { glBlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); glEnable(GL_BLEND); } - void vertex_array_make(GLuint& vao, GLuint& vbo, const void* data, GLsizeiptr size, GLenum usage, + static void vertex_array_make(GLuint& vao, GLuint& vbo, const void* data, GLsizeiptr size, GLenum usage, std::initializer_list attributeSizes) { glGenVertexArrays(1, &vao); @@ -75,7 +71,7 @@ namespace anm2ed mat4 Canvas::transform_get(float zoom, vec2 pan) const { - auto zoomFactor = math::percent_to_unit(zoom); + auto zoomFactor = percent_to_unit(zoom); auto projection = glm::ortho(0.0f, (float)size.x, 0.0f, (float)size.y, -1.0f, 1.0f); auto view = mat4{1.0f}; @@ -85,7 +81,7 @@ namespace anm2ed return projection * view; } - void Canvas::axes_render(Shader& shader, float zoom, vec2 pan, vec4 color) const + void Canvas::axes_render(ShaderProgram& shader, float zoom, vec2 pan, vec4 color) const { canvas_blend_premultiplied_set(); @@ -94,15 +90,15 @@ namespace anm2ed glUseProgram(shader.id); - glUniform4fv(glGetUniformLocation(shader.id, shader::UNIFORM_COLOR), 1, value_ptr(color)); - glUniform2f(glGetUniformLocation(shader.id, shader::UNIFORM_ORIGIN_NDC), originNDC.x, originNDC.y); + glUniform4fv(glGetUniformLocation(shader.id, UNIFORM_COLOR), 1, value_ptr(color)); + glUniform2f(glGetUniformLocation(shader.id, UNIFORM_ORIGIN_NDC), originNDC.x, originNDC.y); glBindVertexArray(axisVAO); - glUniform1i(glGetUniformLocation(shader.id, shader::UNIFORM_AXIS), 0); + glUniform1i(glGetUniformLocation(shader.id, UNIFORM_AXIS), 0); glDrawArrays(GL_LINES, 0, 2); - glUniform1i(glGetUniformLocation(shader.id, shader::UNIFORM_AXIS), 1); + glUniform1i(glGetUniformLocation(shader.id, UNIFORM_AXIS), 1); glDrawArrays(GL_LINES, 0, 2); glBindVertexArray(0); @@ -110,7 +106,7 @@ namespace anm2ed canvas_blend_straight_set(); } - void Canvas::grid_render(Shader& shader, float zoom, vec2 pan, ivec2 size, ivec2 offset, vec4 color) const + void Canvas::grid_render(ShaderProgram& shader, float zoom, vec2 pan, ivec2 size, ivec2 offset, vec4 color) const { canvas_blend_premultiplied_set(); @@ -118,10 +114,10 @@ namespace anm2ed glUseProgram(shader.id); - glUniformMatrix4fv(glGetUniformLocation(shader.id, shader::UNIFORM_TRANSFORM), 1, GL_FALSE, value_ptr(transform)); - glUniform2f(glGetUniformLocation(shader.id, shader::UNIFORM_SIZE), (float)size.x, (float)size.y); - glUniform2f(glGetUniformLocation(shader.id, shader::UNIFORM_OFFSET), (float)offset.x, (float)offset.y); - glUniform4f(glGetUniformLocation(shader.id, shader::UNIFORM_COLOR), color.r, color.g, color.b, color.a); + glUniformMatrix4fv(glGetUniformLocation(shader.id, UNIFORM_TRANSFORM), 1, GL_FALSE, value_ptr(transform)); + glUniform2f(glGetUniformLocation(shader.id, UNIFORM_SIZE), (float)size.x, (float)size.y); + glUniform2f(glGetUniformLocation(shader.id, UNIFORM_OFFSET), (float)offset.x, (float)offset.y); + glUniform4f(glGetUniformLocation(shader.id, UNIFORM_COLOR), color.r, color.g, color.b, color.a); glBindVertexArray(gridVAO); glDrawArrays(GL_TRIANGLES, 0, 3); @@ -131,11 +127,11 @@ namespace anm2ed canvas_blend_straight_set(); } - void texture_uniform_set(const shader::Uniform& uniform, vec4 value) + static void texture_uniform_set(const ShaderUniform& uniform, vec4 value) { - if (uniform.valueType == shader::UNIFORM_VALUE_INT || uniform.valueType == shader::UNIFORM_VALUE_SAMPLER2D) + if (uniform.valueType == UNIFORM_VALUE_INT || uniform.valueType == UNIFORM_VALUE_SAMPLER2D) return glUniform1i(uniform.location, uniform.intValue); - switch (shader::UNIFORM_VALUE_TYPE_INFOS[uniform.valueType].componentCount) + switch (UNIFORM_VALUE_TYPE_INFOS[uniform.valueType].componentCount) { case 2: return glUniform2fv(uniform.location, 1, value_ptr(value)); @@ -144,28 +140,28 @@ namespace anm2ed case 4: return glUniform4fv(uniform.location, 1, value_ptr(value)); default: - if (uniform.valueType == shader::UNIFORM_VALUE_FLOAT) glUniform1f(uniform.location, value.x); + if (uniform.valueType == UNIFORM_VALUE_FLOAT) glUniform1f(uniform.location, value.x); } } - vec4 texture_uniform_components_get(const shader::Uniform& uniform, float playbackTime) + static vec4 texture_uniform_components_get(const ShaderUniform& uniform, float playbackTime) { vec4 result{}; for (int i = 0; i < (int)uniform.components.size(); ++i) - result[i] = uniform.components[i].binding == shader::UNIFORM_BINDING_PLAYBACK_TIME ? playbackTime + result[i] = uniform.components[i].binding == UNIFORM_BINDING_PLAYBACK_TIME ? playbackTime : uniform.components[i].value; return result; } - void texture_uniforms_set(Shader& shader, mat4 transform, vec4 tint, vec4 colorOffset, vec2 textureSize, + static void texture_uniforms_set(ShaderProgram& shader, mat4 transform, vec4 tint, vec4 colorOffset, vec2 textureSize, float playbackTime) { if (shader.uniforms.empty()) { - glUniform1i(glGetUniformLocation(shader.id, shader::UNIFORM_TEXTURE), 0); - glUniform4fv(glGetUniformLocation(shader.id, shader::UNIFORM_COLOR_OFFSET), 1, value_ptr(colorOffset)); - glUniform4fv(glGetUniformLocation(shader.id, shader::UNIFORM_TINT), 1, value_ptr(tint)); - glUniformMatrix4fv(glGetUniformLocation(shader.id, shader::UNIFORM_TRANSFORM), 1, GL_FALSE, value_ptr(transform)); + glUniform1i(glGetUniformLocation(shader.id, UNIFORM_TEXTURE), 0); + glUniform4fv(glGetUniformLocation(shader.id, UNIFORM_COLOR_OFFSET), 1, value_ptr(colorOffset)); + glUniform4fv(glGetUniformLocation(shader.id, UNIFORM_TINT), 1, value_ptr(tint)); + glUniformMatrix4fv(glGetUniformLocation(shader.id, UNIFORM_TRANSFORM), 1, GL_FALSE, value_ptr(transform)); return; } @@ -175,29 +171,29 @@ namespace anm2ed switch (uniform.binding) { - case shader::UNIFORM_BINDING_MAIN_TEXTURE: + case UNIFORM_BINDING_MAIN_TEXTURE: glUniform1i(uniform.location, 0); break; - case shader::UNIFORM_BINDING_TRANSFORM: - if (uniform.valueType == shader::UNIFORM_VALUE_MAT4) + case UNIFORM_BINDING_TRANSFORM: + if (uniform.valueType == UNIFORM_VALUE_MAT4) glUniformMatrix4fv(uniform.location, 1, GL_FALSE, value_ptr(transform)); break; - case shader::UNIFORM_BINDING_FRAME_TINT: + case UNIFORM_BINDING_FRAME_TINT: texture_uniform_set(uniform, tint); break; - case shader::UNIFORM_BINDING_COLOR_OFFSET: + case UNIFORM_BINDING_COLOR_OFFSET: texture_uniform_set(uniform, colorOffset); break; - case shader::UNIFORM_BINDING_TEXTURE_SIZE: + case UNIFORM_BINDING_TEXTURE_SIZE: texture_uniform_set(uniform, vec4(textureSize, 0.0f, 0.0f)); break; - case shader::UNIFORM_BINDING_PLAYBACK_TIME: + case UNIFORM_BINDING_PLAYBACK_TIME: texture_uniform_set(uniform, vec4(playbackTime)); break; - case shader::UNIFORM_BINDING_COMPONENTS: + case UNIFORM_BINDING_COMPONENTS: texture_uniform_set(uniform, texture_uniform_components_get(uniform, playbackTime)); break; - case shader::UNIFORM_BINDING_MANUAL: + case UNIFORM_BINDING_MANUAL: texture_uniform_set(uniform, uniform.value); break; default: @@ -206,7 +202,7 @@ namespace anm2ed } } - void Canvas::texture_render(Shader& shader, GLuint texture, mat4 transform, vec4 tint, vec4 colorOffset, + void Canvas::texture_render(ShaderProgram& shader, GLuint texture, mat4 transform, vec4 tint, vec4 colorOffset, float* vertices, vec2 textureSize, float playbackTime, TextureBlur blur) const { canvas_blend_premultiplied_set(); @@ -215,9 +211,9 @@ namespace anm2ed texture_uniforms_set(shader, transform, tint, colorOffset, textureSize, playbackTime); // The editor's own texture shader blurs; a custom shader without these uniforms ignores them. - glUniform1f(glGetUniformLocation(shader.id, shader::UNIFORM_BLUR), blur.radius); - glUniform4fv(glGetUniformLocation(shader.id, shader::UNIFORM_REGION), 1, value_ptr(blur.region)); - glUniform2fv(glGetUniformLocation(shader.id, shader::UNIFORM_TEXEL), 1, + glUniform1f(glGetUniformLocation(shader.id, UNIFORM_BLUR), blur.radius); + glUniform4fv(glGetUniformLocation(shader.id, UNIFORM_REGION), 1, value_ptr(blur.region)); + glUniform2fv(glGetUniformLocation(shader.id, UNIFORM_TEXEL), 1, value_ptr(textureSize.x > 0 && textureSize.y > 0 ? 1.0f / textureSize : vec2())); glVertexAttrib4fv(2, value_ptr(tint)); @@ -239,17 +235,17 @@ namespace anm2ed canvas_blend_straight_set(); } - void rect_begin(Shader& shader, const mat4& transform, const mat4& model, vec4 color) + static void rect_begin(ShaderProgram& shader, const mat4& transform, const mat4& model, vec4 color) { canvas_blend_premultiplied_set(); glUseProgram(shader.id); - glUniformMatrix4fv(glGetUniformLocation(shader.id, shader::UNIFORM_TRANSFORM), 1, GL_FALSE, value_ptr(transform)); - if (auto location = glGetUniformLocation(shader.id, shader::UNIFORM_MODEL); location != -1) + glUniformMatrix4fv(glGetUniformLocation(shader.id, UNIFORM_TRANSFORM), 1, GL_FALSE, value_ptr(transform)); + if (auto location = glGetUniformLocation(shader.id, UNIFORM_MODEL); location != -1) glUniformMatrix4fv(location, 1, GL_FALSE, value_ptr(model)); - glUniform4fv(glGetUniformLocation(shader.id, shader::UNIFORM_COLOR), 1, value_ptr(color)); + glUniform4fv(glGetUniformLocation(shader.id, UNIFORM_COLOR), 1, value_ptr(color)); } - void rect_end(GLuint vao, GLenum mode, int count = 4) + static void rect_end(GLuint vao, GLenum mode, int count = 4) { glBindVertexArray(vao); glDrawArrays(mode, 0, count); @@ -258,19 +254,19 @@ namespace anm2ed canvas_blend_straight_set(); } - void Canvas::dashed_render(Shader& shader, const mat4& transform, const mat4& model, vec4 color, float dashLength, + void Canvas::dashed_render(ShaderProgram& shader, const mat4& transform, const mat4& model, vec4 color, float dashLength, float dashGap, float dashOffset, GLenum mode, int count) const { rect_begin(shader, transform, model, color); auto origin = model * vec4(0.0f, 0.0f, 0.0f, 1.0f); - for (auto [name, axis] : {std::pair{shader::UNIFORM_AXIS_X, vec4(1.0f, 0.0f, 0.0f, 1.0f)}, - std::pair{shader::UNIFORM_AXIS_Y, vec4(0.0f, 1.0f, 0.0f, 1.0f)}}) + for (auto [name, axis] : {std::pair{UNIFORM_AXIS_X, vec4(1.0f, 0.0f, 0.0f, 1.0f)}, + std::pair{UNIFORM_AXIS_Y, vec4(0.0f, 1.0f, 0.0f, 1.0f)}}) if (auto location = glGetUniformLocation(shader.id, name); location != -1) glUniform2fv(location, 1, value_ptr(vec2(model * axis - origin))); for (auto [name, value] : - {std::pair{shader::UNIFORM_DASH_LENGTH, dashLength}, std::pair{shader::UNIFORM_DASH_GAP, dashGap}, - std::pair{shader::UNIFORM_DASH_OFFSET, dashOffset}}) + {std::pair{UNIFORM_DASH_LENGTH, dashLength}, std::pair{UNIFORM_DASH_GAP, dashGap}, + std::pair{UNIFORM_DASH_OFFSET, dashOffset}}) if (auto location = glGetUniformLocation(shader.id, name); location != -1) glUniform1f(location, value); rect_end(rectVAO, mode, count); @@ -278,52 +274,52 @@ namespace anm2ed // A layer draw's crop of its spritesheet. A blurred one (Flash's BlurFilter: a box `blur` canvas pixels wide) grows by // the box's reach, in texels at the draw's scale, and averages its crop over it. - void Canvas::layer_render(Shader& shader, GLuint texture, vec2 textureSize, const mat4& transform, - const model::Draw& draw, vec4 tint, vec4 colorOffset) const + void Canvas::layer_render(ShaderProgram& shader, GLuint texture, vec2 textureSize, const mat4& transform, + const Draw& draw, vec4 tint, vec4 colorOffset) const { auto blurred = draw; auto& frame = blurred.frame; TextureBlur blur{.region = vec4(frame.crop, frame.crop + frame.size) / vec4(textureSize, textureSize)}; if (frame.blur > 0.0f && frame.size.x > 0.0f && frame.size.y > 0.0f) { - auto canvasArea = std::abs(glm::determinant(glm::mat2(draw.parent * model::draw_quad_model_get(draw)))); + auto canvasArea = std::abs(glm::determinant(glm::mat2(draw.parent * draw_quad_model_get(draw)))); auto canvasPerTexel = std::sqrt(canvasArea / (frame.size.x * frame.size.y)); blur.radius = canvasPerTexel > 0.0f ? std::round(frame.blur * 0.5f / canvasPerTexel) : 0.0f; frame.crop -= blur.radius; frame.size += blur.radius * 2.0f; frame.pivot += blur.radius; } - auto vertices = math::uv_vertices_get(frame.crop / textureSize, (frame.crop + frame.size) / textureSize); - texture_render(shader, texture, transform * blurred.parent * model::draw_quad_model_get(blurred), tint, colorOffset, + auto vertices = uv_vertices_get(frame.crop / textureSize, (frame.crop + frame.size) / textureSize); + texture_render(shader, texture, transform * blurred.parent * draw_quad_model_get(blurred), tint, colorOffset, vertices.data(), textureSize, draw.time, blur); } // An animation's layers alone (no markers or helpers); spritesheet images are looked up by draw, custom shaders by id. - void Canvas::layers_render(Shader& shader, const model::Model& model, const model::Animation& animation, - const model::DrawOptions& options, const mat4& transform, - const std::function& image_get, - const std::function& shader_get) const + void Canvas::layers_render(ShaderProgram& shader, const Model& model, const Animation& animation, + const DrawOptions& options, const mat4& transform, + const std::function& image_get, + const std::function& shader_get) const { - for (const auto& draw : model::animation_draws_get(model, animation, options)) + for (const auto& draw : animation_draws_get(model, animation, options)) { - if (draw.type != model::DrawType::LAYER) continue; + if (draw.type != DrawType::LAYER) continue; auto& frame = draw.frame; auto image = image_get(draw); if (!image || !image->is_valid() || frame.size == vec2()) continue; auto customShader = shader_get ? shader_get(frame.shaderId) : nullptr; - layer_render(customShader ? *customShader : shader, texture::id_get(*image), image->unit_size_get(), transform, + layer_render(customShader ? *customShader : shader, texture_id_get(*image), image->unit_size_get(), transform, draw, frame.tint, frame.colorOffset); } } - void Canvas::rect_render(Shader& shader, const mat4& transform, const mat4& model, vec4 color, float dashLength, + void Canvas::rect_render(ShaderProgram& shader, const mat4& transform, const mat4& model, vec4 color, float dashLength, float dashGap, float dashOffset) const { dashed_render(shader, transform, model, color, dashLength, dashGap, dashOffset, GL_LINE_LOOP, RECT_VERTEX_COUNT); } // A line from start to end: the bottom edge of a rectangle laid along it. - void Canvas::line_render(Shader& shader, const mat4& transform, vec2 start, vec2 end, vec4 color, float dashLength, + void Canvas::line_render(ShaderProgram& shader, const mat4& transform, vec2 start, vec2 end, vec4 color, float dashLength, float dashGap, float dashOffset) const { auto direction = end - start; @@ -333,7 +329,7 @@ namespace anm2ed dashed_render(shader, transform, model, color, dashLength, dashGap, dashOffset, GL_LINES, LINE_VERTEX_COUNT); } - void Canvas::rect_fill_render(Shader& shader, const mat4& transform, const mat4& model, vec4 color) const + void Canvas::rect_fill_render(ShaderProgram& shader, const mat4& transform, const mat4& model, vec4 color) const { rect_begin(shader, transform, model, color); rect_end(rectVAO, GL_TRIANGLE_FAN); @@ -363,11 +359,11 @@ namespace anm2ed void Canvas::zoom_level_adjust(float& zoom, vec2& pan, vec2 focus, int levelDelta) const { - auto zoomFactor = math::percent_to_unit(zoom); + auto zoomFactor = percent_to_unit(zoom); float newZoom = zoom_level_get(zoom, levelDelta); if (newZoom != zoom) { - float newZoomFactor = math::percent_to_unit(newZoom); + float newZoomFactor = percent_to_unit(newZoom); pan += focus * (zoomFactor - newZoomFactor); zoom = newZoom; } @@ -375,7 +371,7 @@ namespace anm2ed vec2 Canvas::position_translate(float& zoom, vec2& pan, vec2 position) const { - auto zoomFactor = math::percent_to_unit(zoom); + auto zoomFactor = percent_to_unit(zoom); return (position - pan - (size * 0.5f)) / zoomFactor; } @@ -387,10 +383,9 @@ namespace anm2ed f32 scaleY = size.y / rect.w; f32 fitScale = std::min(scaleX, scaleY); - zoom = math::unit_to_percent(fitScale); + zoom = unit_to_percent(fitScale); vec2 rectCenter = {rect.x + rect.z * 0.5f, rect.y + rect.w * 0.5f}; pan = -rectCenter * fitScale; } } -} diff --git a/src/canvas.h b/src/canvas.h index 12bcf46..63c3dad 100644 --- a/src/canvas.h +++ b/src/canvas.h @@ -13,8 +13,6 @@ #include "types.h" -namespace anm2ed -{ // A box blur `radius` texels wide each way over the texture's `region` (UV min, max); outside it is clear. struct TextureBlur { @@ -53,7 +51,7 @@ namespace anm2ed static constexpr auto BORDER_DASH_LENGTH = 1.0f; static constexpr auto BORDER_DASH_GAP = 0.5f; static constexpr auto BORDER_DASH_OFFSET = 0.0f; - static constexpr auto PIVOT_COLOR = types::color::PINK; + static constexpr auto PIVOT_COLOR = COLOR_PINK; GLuint axisVAO{}; GLuint axisVBO{}; @@ -69,26 +67,25 @@ namespace anm2ed Canvas(glm::vec2); ~Canvas(); glm::mat4 transform_get(float = 100.0f, glm::vec2 = {}) const; - void axes_render(resource::Shader&, float, glm::vec2, glm::vec4 = glm::vec4(1.0f)) const; - void grid_render(resource::Shader&, float, glm::vec2, glm::ivec2 = glm::ivec2(32, 32), glm::ivec2 = {}, + void axes_render(ShaderProgram&, float, glm::vec2, glm::vec4 = glm::vec4(1.0f)) const; + void grid_render(ShaderProgram&, float, glm::vec2, glm::ivec2 = glm::ivec2(32, 32), glm::ivec2 = {}, glm::vec4 = glm::vec4(1.0f)) const; - void texture_render(resource::Shader&, GLuint, glm::mat4 = {1.0f}, glm::vec4 = glm::vec4(1.0f), glm::vec4 = {}, + void texture_render(ShaderProgram&, GLuint, glm::mat4 = {1.0f}, glm::vec4 = glm::vec4(1.0f), glm::vec4 = {}, float* = (float*)TEXTURE_VERTICES, glm::vec2 = {}, float = 0.0f, TextureBlur = {}) const; - void layer_render(resource::Shader&, GLuint, glm::vec2, const glm::mat4&, const model::Draw&, glm::vec4, + void layer_render(ShaderProgram&, GLuint, glm::vec2, const glm::mat4&, const Draw&, glm::vec4, glm::vec4) const; - void rect_fill_render(resource::Shader&, const glm::mat4&, const glm::mat4&, glm::vec4 = glm::vec4(1.0f)) const; - void layers_render(resource::Shader&, const model::Model&, const model::Animation&, const model::DrawOptions&, - const glm::mat4&, const std::function&, - const std::function& = {}) const; - void dashed_render(resource::Shader&, const glm::mat4&, const glm::mat4&, glm::vec4, float, float, float, GLenum, + void rect_fill_render(ShaderProgram&, const glm::mat4&, const glm::mat4&, glm::vec4 = glm::vec4(1.0f)) const; + void layers_render(ShaderProgram&, const Model&, const Animation&, const DrawOptions&, + const glm::mat4&, const std::function&, + const std::function& = {}) const; + void dashed_render(ShaderProgram&, const glm::mat4&, const glm::mat4&, glm::vec4, float, float, float, GLenum, int) const; - void rect_render(resource::Shader&, const glm::mat4&, const glm::mat4&, glm::vec4 = glm::vec4(1.0f), + void rect_render(ShaderProgram&, const glm::mat4&, const glm::mat4&, glm::vec4 = glm::vec4(1.0f), float dashLength = DASH_LENGTH, float dashGap = DASH_GAP, float dashOffset = DASH_OFFSET) const; - void line_render(resource::Shader&, const glm::mat4&, glm::vec2, glm::vec2, glm::vec4 = glm::vec4(1.0f), + void line_render(ShaderProgram&, const glm::mat4&, glm::vec2, glm::vec2, glm::vec4 = glm::vec4(1.0f), float dashLength = DASH_LENGTH, float dashGap = DASH_GAP, float dashOffset = DASH_OFFSET) const; float zoom_level_get(float, int) const; void zoom_level_adjust(float&, glm::vec2&, glm::vec2, int) const; glm::vec2 position_translate(float&, glm::vec2&, glm::vec2) const; void set_to_rect(float& zoom, glm::vec2& pan, glm::vec4 rect) const; }; -} diff --git a/src/cli.cpp b/src/cli.cpp index e7295e7..ea81321 100644 --- a/src/cli.cpp +++ b/src/cli.cpp @@ -19,10 +19,6 @@ #include "settings.h" #include "working_directory.h" -using namespace anm2ed::util; - -namespace anm2ed::cli -{ constexpr const char* USAGE = R"(usage: anm2ed [options] commands: @@ -73,16 +69,16 @@ options: }; // PNG sequences go into a folder; everything else is a file. - bool type_is_folder(const Arguments& arguments) + static bool type_is_folder(const Arguments& arguments) { return arguments.command == "render" && arguments.get("type").value_or("") == "pngs"; } - std::optional arguments_get(int argc, const char** argv) + static std::optional arguments_get(int argc, const char** argv) { if (argc < 3) return {}; // Absolute, so a bare file name still has a folder for the paths in it. - Arguments arguments{.command = argv[1], .file = std::filesystem::absolute(path::from_utf8(argv[2]))}; + Arguments arguments{.command = argv[1], .file = std::filesystem::absolute(path_from_utf8(argv[2]))}; for (int i = 3; i < argc; ++i) { std::string name = argv[i]; @@ -95,7 +91,7 @@ options: } // RRGGBB (opaque) or "transparent". - glm::vec4 background_get(const Arguments& arguments) + static glm::vec4 background_get(const Arguments& arguments) { auto text = arguments.get("background").value_or("transparent"); if (text.starts_with('#')) text.erase(0, 1); @@ -108,17 +104,17 @@ options: } // --ffmpeg, or else the FFmpeg the editor's Render Animation uses (or "ffmpeg" on the PATH). - std::filesystem::path ffmpeg_path_get(const Arguments& arguments) + static std::filesystem::path ffmpeg_path_get(const Arguments& arguments) { - if (auto ffmpeg = arguments.get("ffmpeg")) return path::from_utf8(*ffmpeg); - auto settingsPath = sdl::preferences_directory_get() / "settings.ini"; + if (auto ffmpeg = arguments.get("ffmpeg")) return path_from_utf8(*ffmpeg); + auto settingsPath = preferences_directory_get() / "settings.ini"; auto settingsFfmpeg = - path::is_exist(settingsPath) ? Settings(settingsPath).renderFFmpegPath : std::filesystem::path{}; + is_path_exist(settingsPath) ? Settings(settingsPath).renderFFmpegPath : std::filesystem::path{}; return settingsFfmpeg.empty() ? std::filesystem::path("ffmpeg") : settingsFfmpeg; } // By index or name; the default animation otherwise. - std::pair animation_get(const model::Model& model, const Arguments& arguments) + static std::pair animation_get(const Model& model, const Arguments& arguments) { auto animations = model.animations_get(); auto name = arguments.get("animation").value_or(model.animations.defaultAnimation); @@ -132,25 +128,25 @@ options: return {-1, nullptr}; } - int info_print(const Arguments& arguments) + static int info_print(const Arguments& arguments) { - model::Model model{}; + Model model{}; std::string error{}; - if (!model::model_load(model, arguments.file, &error)) + if (!model_load(model, arguments.file, &error)) { - std::println(stderr, "could not load {}: {}", path::to_utf8(arguments.file), error); + std::println(stderr, "could not load {}: {}", path_to_utf8(arguments.file), error); return 1; } auto& content = model.content; - std::println("file: {}", path::to_utf8(arguments.file)); + std::println("file: {}", path_to_utf8(arguments.file)); std::println("fps: {}, created by: {}", model.info.fps, model.info.createdBy); std::println("animations (default: {}):", model.animations.defaultAnimation); for (auto [index, animation] : model.animations_get()) { int layers{}, nulls{}; - model::tracks_each(animation->layers, [&](const model::Track&, auto*) { ++layers; }); - model::tracks_each(animation->nulls, [&](const model::Track&, auto*) { ++nulls; }); + tracks_each(animation->layers, [&](const Track&, auto*) { ++layers; }); + tracks_each(animation->nulls, [&](const Track&, auto*) { ++nulls; }); std::println(" [{}] {}: {} frames{}, {} layer tracks, {} null tracks, {} triggers", index, animation->name, animation->frameNum, animation->isLoop ? ", loops" : "", layers, nulls, animation->triggers.frames.size()); @@ -160,13 +156,13 @@ options: std::println("spritesheets:"); for (const auto& spritesheet : content.spritesheets) { - auto image = resource::Image(path::case_insensitive_find(spritesheet.path)); + auto image = Image(path_case_insensitive_find(spritesheet.path)); auto status = image.is_valid() ? std::format("{}x{}", image.size.x, image.size.y) : std::string("missing"); - std::println(" #{} {} ({}), {} regions", spritesheet.id, path::to_utf8(spritesheet.path), status, + std::println(" #{} {} ({}), {} regions", spritesheet.id, path_to_utf8(spritesheet.path), status, spritesheet.regions.size()); } for (const auto& library : content.libraries) - std::println("library #{} {}", library.id, path::to_utf8(library.path)); + std::println("library #{} {}", library.id, path_to_utf8(library.path)); for (const auto& layer : content.layers) if (layer.is_animation()) std::println("layer #{} {} (animation {}, library #{})", layer.id, layer.name, layer.animation, @@ -178,9 +174,9 @@ options: for (const auto& event : content.events) std::println("event #{} {}", event.id, event.name); for (const auto& sound : content.sounds) - std::println("sound #{} {}", sound.id, path::to_utf8(sound.path)); + std::println("sound #{} {}", sound.id, path_to_utf8(sound.path)); - auto issues = model::isaac_issues_get(model); + auto issues = isaac_issues_get(model); std::println("isaac issues: {} eased frames, {} group transforms, {} skewed frames, {} shader frames, {} depth " "frames, {} alpha offset frames, {} blurred frames, {} extra trigger events, {} trigger sounds, " "{} animation layers, {} vector spritesheets", @@ -190,7 +186,7 @@ options: return 0; } - int draw_run(const Arguments& arguments) + static int draw_run(const Arguments& arguments) { auto out = arguments.get("out"); if (!out) @@ -199,7 +195,7 @@ options: return 2; } - render::HeadlessGL gl{}; + HeadlessGL gl{}; if (!gl.is_valid()) { std::println(stderr, "could not create an OpenGL 3.3 context"); @@ -210,7 +206,7 @@ options: Document document(arguments.file, false, &error); if (!document.is_valid()) { - std::println(stderr, "could not load {}: {}", path::to_utf8(arguments.file), error); + std::println(stderr, "could not load {}: {}", path_to_utf8(arguments.file), error); return 1; } auto [index, animation] = animation_get(document.model, arguments); @@ -220,27 +216,27 @@ options: return 1; } - auto& textureInfo = resource::shader::SHADERS[resource::shader::TEXTURE]; - resource::Shader shader(textureInfo.vertex, textureInfo.fragment); + auto& textureInfo = SHADERS[SHADER_TEXTURE]; + ShaderProgram shader(textureInfo.vertex, textureInfo.fragment); Canvas canvas(glm::vec2(1.0f)); auto isRootTransform = !arguments.is("no-root-transform"); - auto bounds = render::animation_bounds_get(document, *animation, isRootTransform); + auto bounds = animation_bounds_get(document, *animation, isRootTransform); auto scale = arguments.number_get("scale", SCALE_DEFAULT); auto background = background_get(arguments); auto frame_render = [&](float time) { - return render::animation_frame_render(canvas, shader, document, *animation, time, bounds, scale, background, + return animation_frame_render(canvas, shader, document, *animation, time, bounds, scale, background, isRootTransform); }; - auto outPath = path::from_utf8(*out); + auto outPath = path_from_utf8(*out); std::error_code ec{}; std::filesystem::create_directories(type_is_folder(arguments) ? outPath : outPath.parent_path(), ec); if (arguments.command == "frame") { auto pixels = frame_render(arguments.number_get("time", 0.0f)); - render::pixels_unpremultiply(pixels); - if (!resource::Image::write_pixels_png(outPath, glm::ivec2(canvas.size), pixels.data())) + pixels_unpremultiply(pixels); + if (!Image::write_pixels_png(outPath, glm::ivec2(canvas.size), pixels.data())) { std::println(stderr, "could not write {}", *out); return 1; @@ -251,19 +247,19 @@ options: } auto typeName = arguments.get("type").value_or("sheet"); - auto type = typeName == "sheet" ? render::SPRITESHEET : render::PNGS; - for (int i = 0; i < render::COUNT; ++i) - if (render::EXTENSIONS[i] == "." + typeName) type = (render::Type)i; - if (typeName != "sheet" && typeName != "pngs" && type == render::PNGS) + auto type = typeName == "sheet" ? RENDER_SPRITESHEET : RENDER_PNGS; + for (int i = 0; i < RENDER_COUNT; ++i) + if (RENDER_EXTENSIONS[i] == "." + typeName) type = (RenderType)i; + if (typeName != "sheet" && typeName != "pngs" && type == RENDER_PNGS) { std::println(stderr, "unknown --type: {}", typeName); return 2; } auto fps = std::max(document.model.info.fps, 1); - render::RecorderOptions options{.type = type, + RecorderOptions options{.type = type, .path = outPath, - .format = path::from_utf8(arguments.get("format").value_or("{}.png")), + .format = path_from_utf8(arguments.get("format").value_or("{}.png")), .ffmpegPath = ffmpeg_path_get(arguments), .start = arguments.number_get("start", 0), .end = arguments.number_get("end", animation->frameNum - 1), @@ -271,19 +267,19 @@ options: .fps = arguments.number_get("fps", fps), .rows = arguments.number_get("rows", 0), .columns = arguments.number_get("columns", 0)}; - auto count = render::frame_count_get(options.start, options.end, options.animationFps, options.fps); - if (!render::animation_record(options, canvas, shader, document, *animation, bounds, scale, background, + auto count = frame_count_get(options.start, options.end, options.animationFps, options.fps); + if (!animation_record(options, canvas, shader, document, *animation, bounds, scale, background, isRootTransform)) { - std::println(stderr, "could not write {} (FFmpeg: {})", *out, path::to_utf8(options.ffmpegPath)); + std::println(stderr, "could not write {} (FFmpeg: {})", *out, path_to_utf8(options.ffmpegPath)); return 1; } std::print("{}: \"{}\", {} frames ({} to {} at {} fps), each {}x{}", *out, animation->name, count, options.start, options.end, options.fps, (int)canvas.size.x, (int)canvas.size.y); - if (type == render::SPRITESHEET) + if (type == RENDER_SPRITESHEET) { - auto layout = render::spritesheet_layout_get(options.rows, options.columns, count); + auto layout = spritesheet_layout_get(options.rows, options.columns, count); std::print(", {} rows x {} columns, left to right", layout.rows, layout.columns); } std::println(""); @@ -291,7 +287,7 @@ options: } // Saved as the editor saves it: XML (the game's copy, with the editor's embedded) or the editor's JSON. - int convert_run(const Arguments& arguments) + static int convert_run(const Arguments& arguments) { auto format = arguments.get("format").value_or("xml"); if (format != "xml" && format != "json") @@ -300,22 +296,22 @@ options: return 2; } // The game's copy bakes what it can't draw with OpenGL (and the document's shaders compile only with it). - std::optional gl{}; + std::optional gl{}; if (format == "xml") gl.emplace(); std::string error{}; Document document(arguments.file, false, &error); - auto fileUtf8 = path::to_utf8(arguments.file); + auto fileUtf8 = path_to_utf8(arguments.file); if (!document.is_valid()) { std::println(stderr, "could not load {}: {}", fileUtf8, error); return 1; } if (!error.empty()) std::println(stderr, "{}:\n{}", fileUtf8, error); - auto out = std::filesystem::absolute(arguments.get("out").transform(path::from_utf8).value_or(arguments.file)); + auto out = std::filesystem::absolute(arguments.get("out").transform(path_from_utf8).value_or(arguments.file)); Options options{}; options.isJson = format == "json"; if (document.save(out, &error, options)) return 0; - std::println(stderr, "could not write {}: {}", path::to_utf8(out), error); + std::println(stderr, "could not write {}: {}", path_to_utf8(out), error); return 1; } @@ -323,10 +319,10 @@ options: bool is_cli(int argc, const char** argv) { - return argc >= 2 && std::ranges::contains(COMMANDS, std::string_view(argv[1])) && !path::is_exist(argv[1]); + return argc >= 2 && std::ranges::contains(COMMANDS, std::string_view(argv[1])) && !is_path_exist(argv[1]); } - int run(int argc, const char** argv) + int cli_run(int argc, const char** argv) { auto arguments = arguments_get(argc, argv); if (!arguments) @@ -338,4 +334,3 @@ options: if (arguments->command == "convert") return convert_run(*arguments); return draw_run(*arguments); } -} diff --git a/src/cli.h b/src/cli.h index 1d5d07f..df47a6f 100644 --- a/src/cli.h +++ b/src/cli.h @@ -3,8 +3,5 @@ // The command-line mode: "anm2ed [options]" looks at a file without the editor, as // text or drawn (by the editor's OpenGL renderer, in a hidden window) to a PNG frame, a contact sheet, PNGs, a GIF or // a video. -namespace anm2ed::cli -{ bool is_cli(int, const char**); - int run(int, const char**); -} + int cli_run(int, const char**); diff --git a/src/clipboard.cpp b/src/clipboard.cpp index 61e0ee3..394024f 100644 --- a/src/clipboard.cpp +++ b/src/clipboard.cpp @@ -3,8 +3,6 @@ #include #include -namespace anm2ed -{ Clipboard::Clipboard() { set(""); } std::string Clipboard::get() @@ -19,4 +17,3 @@ namespace anm2ed bool Clipboard::is_empty() { return !SDL_HasClipboardText(); } void Clipboard::set(const std::string& string) { SDL_SetClipboardText(string.c_str()); } -} diff --git a/src/clipboard.h b/src/clipboard.h index 12a7065..6a946fc 100644 --- a/src/clipboard.h +++ b/src/clipboard.h @@ -2,8 +2,6 @@ #include -namespace anm2ed -{ class Clipboard { public: @@ -12,4 +10,3 @@ namespace anm2ed std::string get(); void set(const std::string&); }; -} diff --git a/src/dialog.cpp b/src/dialog.cpp index da9e188..ca7e9d2 100644 --- a/src/dialog.cpp +++ b/src/dialog.cpp @@ -16,10 +16,6 @@ #include "path.h" -using namespace anm2ed::util; - -namespace anm2ed -{ static void callback(void* userData, const char* const* filelist, int filter) { auto self = (Dialog*)(userData); @@ -28,7 +24,7 @@ namespace anm2ed { self->paths.clear(); for (int i = 0; filelist[i] && strlen(filelist[i]) > 0; ++i) - self->paths.push_back(path::from_utf8(filelist[i])); + self->paths.push_back(path_from_utf8(filelist[i])); self->path = self->paths.empty() ? std::filesystem::path{} : self->paths.front(); self->selectedFilter = filter; } @@ -61,7 +57,7 @@ namespace anm2ed if (type == Dialog::NONE) return; path.clear(); paths.clear(); - auto defaultPathString = path::to_utf8(defaultPath); + auto defaultPathString = path_to_utf8(defaultPath); auto defaultPathCStr = defaultPathString.empty() ? nullptr : defaultPathString.c_str(); SDL_ShowSaveFileDialog(callback, this, window, FILTERS[TYPE_FILTERS[type]], std::size(FILTERS[TYPE_FILTERS[type]]), defaultPathCStr); @@ -79,7 +75,7 @@ namespace anm2ed #ifdef __unix__ // A string as one single-quoted shell word. - std::string shell_quote(std::string_view text) + static std::string shell_quote(std::string_view text) { std::string quoted = "'"; for (auto character : text) @@ -89,10 +85,10 @@ namespace anm2ed // A file:// URI; everything but unreserved characters and slashes is percent-encoded (commas too, which dbus-send // would otherwise take as array separators). - std::string file_uri_get(const std::filesystem::path& path) + static std::string file_uri_get(const std::filesystem::path& path) { std::string uri = "file://"; - for (unsigned char character : path::to_utf8(path)) + for (unsigned char character : path_to_utf8(path)) if (std::isalnum(character) || std::string_view("-._~/").contains((char)character)) uri += (char)character; else @@ -117,7 +113,7 @@ namespace anm2ed #elif __unix__ // File managers that implement org.freedesktop.FileManager1 (Nautilus, Dolphin, Nemo, Caja, Thunar...) select the // file; anything else opens its folder. - auto folder = shell_quote(path::to_utf8(isFile ? absolutePath.parent_path() : absolutePath)); + auto folder = shell_quote(path_to_utf8(isFile ? absolutePath.parent_path() : absolutePath)); auto command = isFile ? std::format("(dbus-send --session --print-reply --dest=org.freedesktop.FileManager1 " "--type=method_call /org/freedesktop/FileManager1 " "org.freedesktop.FileManager1.ShowItems array:string:{} string:'' " @@ -134,4 +130,3 @@ namespace anm2ed bool Dialog::is_selected(Type type) const { return this->type == type && !paths.empty(); } -}; diff --git a/src/dialog.h b/src/dialog.h index 4c624ca..c45449f 100644 --- a/src/dialog.h +++ b/src/dialog.h @@ -5,8 +5,6 @@ #include -namespace anm2ed -{ class Dialog { public: @@ -96,4 +94,3 @@ namespace anm2ed void reset(); void file_explorer_open(const std::filesystem::path&); }; -} diff --git a/src/document.cpp b/src/document.cpp index 92c6452..b78e919 100644 --- a/src/document.cpp +++ b/src/document.cpp @@ -28,13 +28,8 @@ #include "ui/toast.h" #include "working_directory.h" -using namespace anm2ed::imgui; -using namespace anm2ed::types; -using namespace anm2ed::util; using namespace glm; -namespace anm2ed::document -{ constexpr std::string_view BAKED_EXTENSION = ".baked.png"; constexpr std::string_view AUTOSAVE_EXTENSION = ".autosave"; constexpr int VECTOR_LEVEL_MAX = 3; @@ -42,44 +37,44 @@ namespace anm2ed::document constexpr std::uint64_t HASH_COMBINE_CONSTANT = 0x9e3779b97f4a7c15ULL; // A path written in a document in `directory`, as an absolute path. - std::filesystem::path absolute_path_get(const std::filesystem::path& directory, const std::filesystem::path& path) + static std::filesystem::path absolute_path_get(const std::filesystem::path& directory, const std::filesystem::path& path) { - util::WorkingDirectory workingDirectory(directory); + WorkingDirectory workingDirectory(directory); std::error_code ec{}; - auto absolutePath = std::filesystem::weakly_canonical(directory / path::case_insensitive_find(path), ec); + auto absolutePath = std::filesystem::weakly_canonical(directory / path_case_insensitive_find(path), ec); return ec ? directory / path : absolutePath; } - void library_load(const std::filesystem::path& path, LibraryData& library) + static void library_load(const std::filesystem::path& path, LibraryData& library) { library = {}; std::string errorString{}; - model::model_load(library.model, path, &errorString); + model_load(library.model, path, &errorString); // Why it couldn't load, or what a JSON library couldn't read. - if (!errorString.empty()) toast_log(Level::WARNING, TOAST_LIBRARY_ISSUES, path::to_utf8(path), errorString); + if (!errorString.empty()) toast_log(Level::WARNING, TOAST_LIBRARY_ISSUES, path_to_utf8(path), errorString); std::error_code ec{}; library.writeTime = std::filesystem::last_write_time(path, ec); - util::WorkingDirectory workingDirectory(path.parent_path()); + WorkingDirectory workingDirectory(path.parent_path()); for (const auto& spritesheet : library.model.content.spritesheets) - library.images.emplace(spritesheet.id, resource::Image(path::case_insensitive_find(spritesheet.path))); + library.images.emplace(spritesheet.id, Image(path_case_insensitive_find(spritesheet.path))); for (const auto& sound : library.model.content.sounds) - library.sounds.emplace(sound.id, resource::AudioData(path::case_insensitive_find(sound.path))); + library.sounds.emplace(sound.id, AudioData(path_case_insensitive_find(sound.path))); } - uint64_t document_tab_id_next() + static uint64_t document_tab_id_next() { static uint64_t next{1}; return next++; } - std::filesystem::path shader_absolute_path_get(Document& document, const std::filesystem::path& path) + static std::filesystem::path shader_absolute_path_get(Document& document, const std::filesystem::path& path) { - auto loadPath = path::backslash_handle(path); + auto loadPath = path_backslash_handle(path); if (loadPath.empty() || loadPath.is_absolute()) return loadPath; return document.directory_get() / loadPath; } - void shader_status_append(const resource::ShaderCompileResult& result, std::string* status) + static void shader_status_append(const ShaderCompileResult& result, std::string* status) { if (!status) return; @@ -93,7 +88,7 @@ namespace anm2ed::document if (!result.output.empty()) *status += result.output; } - std::string shader_source_lines_get(std::string_view label, std::string_view source) + static std::string shader_source_lines_get(std::string_view label, std::string_view source) { std::string output = std::format("\n{}:\n", label); int lineNumber{1}; @@ -110,14 +105,14 @@ namespace anm2ed::document return output; } - void shader_status_format_append(std::string* status, StringType format, StringType argument) + static void shader_status_format_append(std::string* status, StringType format, StringType argument) { if (!status) return; auto argumentString = std::string(localize.get(argument)); *status += std::vformat(localize.get(format), std::make_format_args(argumentString)) + "\n"; } - bool shader_source_load(Document& document, const std::filesystem::path& shaderPath, std::string& source, + static bool shader_source_load(Document& document, const std::filesystem::path& shaderPath, std::string& source, StringType label, std::string* status, const char* fallback = nullptr) { if (shaderPath.empty() && !fallback) @@ -131,12 +126,12 @@ namespace anm2ed::document return true; } - auto absolute = path::case_insensitive_find(shader_absolute_path_get(document, shaderPath)); - if (file::read_to_string(absolute, &source)) return true; + auto absolute = path_case_insensitive_find(shader_absolute_path_get(document, shaderPath)); + if (file_text_load(absolute, &source)) return true; if (status) { - auto pathString = path::to_utf8(shaderPath); + auto pathString = path_to_utf8(shaderPath); *status += std::vformat(localize.get(LABEL_SHADER_READ_FAILED), std::make_format_args(pathString)) + "\n"; } return false; @@ -148,14 +143,14 @@ namespace anm2ed::document std::unordered_map& paths, Load&& load) { std::set validIds{}; - util::WorkingDirectory workingDirectory(document.directory_get()); + WorkingDirectory workingDirectory(document.directory_get()); for (auto& element : items) { validIds.insert(element.id); auto path = paths.find(element.id); if (!keys.contains(element.id) || path == paths.end() || path->second != element.path) { - load(element.id, path::case_insensitive_find(element.path)); + load(element.id, path_case_insensitive_find(element.path)); paths[element.id] = element.path; } } @@ -165,34 +160,31 @@ namespace anm2ed::document } // A spritesheet is dirty when its path or image asset differs from what was last saved. - uint64_t spritesheet_hash_get(const model::Spritesheet& spritesheet, std::uint64_t imageKey) + static uint64_t spritesheet_hash_get(const Spritesheet& spritesheet, std::uint64_t imageKey) { - auto seed = std::hash{}(path::to_utf8(spritesheet.path)); + auto seed = std::hash{}(path_to_utf8(spritesheet.path)); return seed ^ (imageKey + HASH_COMBINE_CONSTANT + (seed << 6) + (seed >> 2)); } - Reference item_reference_get(Reference reference) + static Reference item_reference_get(Reference reference) { reference.frameIndex = -1; return reference; } - void frame_time_sync(Document& document) + static void frame_time_sync(Document& document) { auto reference = document.reference_get(); auto item = document.model.track_get(reference); auto frameIndex = reference.frameIndex; document.frameTime = item && frameIndex >= 0 ? frame_time_from_index_get(*item, frameIndex) : 0.0f; } -} -namespace anm2ed -{ Document::Document(const std::filesystem::path& path, bool isNew, std::string* errorString) { - tabId = document::document_tab_id_next(); - model = model::model_make(); - if (!isNew) model::model_load(model, path, errorString); + tabId = document_tab_id_next(); + model = model_make(); + if (!isNew) model_load(model, path, errorString); if (isNew ? !save(path, errorString) : !model.isValid) { isValid = false; @@ -219,7 +211,7 @@ namespace anm2ed bool Document::save(const std::filesystem::path& path, std::string* errorString, Options options) { auto absolutePath = !path.empty() ? path : this->path; - auto absolutePathUtf8 = path::to_utf8(absolutePath); + auto absolutePathUtf8 = path_to_utf8(absolutePath); if (file_write(absolutePath, errorString, options)) { this->path = absolutePath; @@ -232,14 +224,14 @@ namespace anm2ed } // A library's spritesheet path, made relative to this document (for flattening its animation layers). - edit::SpritesheetPathGet Document::spritesheet_path_resolver_get() const + SpritesheetPathGet Document::spritesheet_path_resolver_get() const { - return [this](const model::Model& source, const std::filesystem::path& spritesheetPath) + return [this](const Model& source, const std::filesystem::path& spritesheetPath) { for (const auto& [libraryPath, library] : libraries) if (&library.model == &source) - return path::backslash_replace( - path::make_relative(document::absolute_path_get(libraryPath.parent_path(), spritesheetPath), + return path_backslash_replace( + path_make_relative(absolute_path_get(libraryPath.parent_path(), spritesheetPath), std::filesystem::absolute(directory_get()))); return spritesheetPath; }; @@ -249,48 +241,48 @@ namespace anm2ed // can't show worked around. bool Document::file_write(const std::filesystem::path& path, std::string* errorString, Options options) { - std::optional game{}; + std::optional game{}; if (!options.isJson) { - game = edit::animation_layers_flatten(model, library_resolver_get(), spritesheet_path_resolver_get()); + game = animation_layers_flatten(model, library_resolver_get(), spritesheet_path_resolver_get()); if (!model.info.isIsaacIgnored) { auto bakedPath = path; if (options.isPixelBaked) - render::frames_bake(*this, *game, bakedPath.replace_extension(document::BAKED_EXTENSION)); - game = edit::isaac_bridge(std::move(*game)); + frames_bake(*this, *game, bakedPath.replace_extension(BAKED_EXTENSION)); + game = isaac_bridge(std::move(*game)); } } options.gameModel = game ? &*game : nullptr; - return model::model_save(model, path, errorString, options); + return model_save(model, path, errorString, options); } std::filesystem::path Document::autosave_path_get() { return directory_get() / - path::from_utf8("." + path::to_utf8(filename_get()) + std::string(document::AUTOSAVE_EXTENSION)); + path_from_utf8("." + path_to_utf8(filename_get()) + std::string(AUTOSAVE_EXTENSION)); } std::filesystem::path Document::path_from_autosave_get(const std::filesystem::path& path) { - auto fileName = path::to_utf8(path.filename()); + auto fileName = path_to_utf8(path.filename()); if (fileName.starts_with('.')) fileName.erase(fileName.begin()); - if (fileName.ends_with(document::AUTOSAVE_EXTENSION)) - fileName.erase(fileName.size() - document::AUTOSAVE_EXTENSION.size()); + if (fileName.ends_with(AUTOSAVE_EXTENSION)) + fileName.erase(fileName.size() - AUTOSAVE_EXTENSION.size()); return path.parent_path() / std::filesystem::path(std::u8string(fileName.begin(), fileName.end())); } bool Document::autosave(std::string* errorString, Options options) { auto autosavePath = autosave_path_get(); - auto autosavePathUtf8 = path::to_utf8(autosavePath); + auto autosavePathUtf8 = path_to_utf8(autosavePath); // An autosave is read back from the editor's copy, so the game's needs no baked spritesheet. options.isPixelBaked = false; if (file_write(autosavePath, errorString, options)) { for (auto id : spritesheets_autosave_dirty_get()) { - auto spritesheet = model::item_get(model.content.spritesheets, id); + auto spritesheet = item_get(model.content.spritesheets, id); auto texture = texture_get(id); if (texture && texture->write(spritesheet_autosave_path_get(*spritesheet))) spritesheetAutosaveHashes[id] = spritesheetHashes.at(id); @@ -307,25 +299,25 @@ namespace anm2ed void Document::texture_change(int id) { - if (texture_get(id) && model::item_get(model.content.spritesheets, id)) change(); + if (texture_get(id) && item_get(model.content.spritesheets, id)) change(); } bool Document::texture_reload(int id) { - auto spritesheet = model::item_get(model.content.spritesheets, id); + auto spritesheet = item_get(model.content.spritesheets, id); if (!spritesheet) return false; - util::WorkingDirectory workingDirectory(directory_get()); - texture_set(id, resource::Image(path::case_insensitive_find(spritesheet->path))); + WorkingDirectory workingDirectory(directory_get()); + texture_set(id, Image(path_case_insensitive_find(spritesheet->path))); texturePaths[id] = spritesheet->path; return true; } bool Document::sound_reload(int id) { - auto sound = model::item_get(model.content.sounds, id); + auto sound = item_get(model.content.sounds, id); if (!sound) return false; - util::WorkingDirectory workingDirectory(directory_get()); - sound_set(id, resource::AudioData(path::case_insensitive_find(sound->path))); + WorkingDirectory workingDirectory(directory_get()); + sound_set(id, AudioData(path_case_insensitive_find(sound->path))); soundPaths[id] = sound->path; return true; } @@ -341,37 +333,37 @@ namespace anm2ed }; // Without an OpenGL context (as the command line converts), there is nothing to compile it with. - auto shaderElement = SDL_GL_GetCurrentContext() ? model::item_get(model.content.shaders, shaderId) : nullptr; + auto shaderElement = SDL_GL_GetCurrentContext() ? item_get(model.content.shaders, shaderId) : nullptr; if (!shaderElement) { - document::shader_status_format_append(status, LABEL_SHADER_PATH_EMPTY, LABEL_FRAGMENT); + shader_status_format_append(status, LABEL_SHADER_PATH_EMPTY, LABEL_FRAGMENT); return shader_erase(); } std::string vertexSource{}; std::string fragmentSource{}; - auto isVertexLoaded = document::shader_source_load(*this, shaderElement->vertex, vertexSource, LABEL_VERTEX, status, - resource::shader::TEXTURE_COMPATIBILITY_VERTEX); + auto isVertexLoaded = shader_source_load(*this, shaderElement->vertex, vertexSource, LABEL_VERTEX, status, + TEXTURE_COMPATIBILITY_VERTEX); auto isFragmentLoaded = - document::shader_source_load(*this, shaderElement->fragment, fragmentSource, LABEL_FRAGMENT, status); + shader_source_load(*this, shaderElement->fragment, fragmentSource, LABEL_FRAGMENT, status); if (!isVertexLoaded || !isFragmentLoaded) return shader_erase(); - auto vertex = resource::shader::gles_vertex_convert(vertexSource); - auto fragment = resource::shader::gles_fragment_convert(fragmentSource); - auto result = resource::shader_compile(vertex.c_str(), fragment.c_str()); - document::shader_status_append(result, status); + auto vertex = gles_vertex_convert(vertexSource); + auto fragment = gles_fragment_convert(fragmentSource); + auto result = shader_compile(vertex.c_str(), fragment.c_str()); + shader_status_append(result, status); if (status && (!result.isCompiled || !result.isLinked)) { - *status += document::shader_source_lines_get("Converted vertex shader", vertex); - *status += document::shader_source_lines_get("Converted fragment shader", fragment); + *status += shader_source_lines_get("Converted vertex shader", vertex); + *status += shader_source_lines_get("Converted fragment shader", fragment); } if (!result.isLinked || !result.id) return shader_erase(); - resource::Shader runtime{}; + ShaderProgram runtime{}; runtime.id = result.id; runtime.uniforms = std::move(result.uniforms); - if (resource::shader::uniform_configs_trim(*shaderElement, runtime.uniforms)) hash_set(); - resource::shader::uniform_configs_apply(*shaderElement, runtime.uniforms); + if (uniform_configs_trim(*shaderElement, runtime.uniforms)) hash_set(); + uniform_configs_apply(*shaderElement, runtime.uniforms); shaders[shaderId] = std::move(runtime); shaderVertexPaths[shaderId] = shaderElement->vertex; shaderFragmentPaths[shaderId] = shaderElement->fragment; @@ -381,15 +373,15 @@ namespace anm2ed void Document::assets_sync() { libraries_sync(); - document::resources_sync(*this, model.content.spritesheets, textures, texturePaths, + resources_sync(*this, model.content.spritesheets, textures, texturePaths, [&](int id, const std::filesystem::path& path) - { texture_set(id, resource::Image(path)); }); - document::resources_sync(*this, model.content.sounds, sounds, soundPaths, + { texture_set(id, Image(path)); }); + resources_sync(*this, model.content.sounds, sounds, soundPaths, [&](int id, const std::filesystem::path& path) - { sound_set(id, resource::AudioData(path)); }); + { sound_set(id, AudioData(path)); }); std::set validShaderIds{}; - util::WorkingDirectory workingDirectory(directory_get()); + WorkingDirectory workingDirectory(directory_get()); for (auto& shaderElement : model.content.shaders) { auto id = shaderElement.id; @@ -406,7 +398,7 @@ namespace anm2ed else if (isReload) shader_reload(id); else if (auto shader = shader_get(id)) - resource::shader::uniform_configs_apply(shaderElement, shader->uniforms); + uniform_configs_apply(shaderElement, shader->uniforms); } auto is_invalid = [&](const auto& pair) { return !validShaderIds.contains(pair.first); }; @@ -426,22 +418,22 @@ namespace anm2ed std::filesystem::path Document::library_path_get(int id) const { - auto library = model::item_get(model.content.libraries, id); - return library ? document::absolute_path_get(std::filesystem::absolute(directory_get()), library->path) + auto library = item_get(model.content.libraries, id); + return library ? absolute_path_get(std::filesystem::absolute(directory_get()), library->path) : std::filesystem::path{}; } // A library of this document (or of a copy of it) or of one of its libraries. - const LibraryData* Document::library_get(const model::Model& from, int id) const + const LibraryData* Document::library_get(const Model& from, int id) const { auto isLibrary = std::ranges::any_of(libraries, [&](const auto& pair) { return &pair.second.model == &from; }); auto link = libraryLinks.find({isLibrary ? &from : nullptr, id}); return link == libraryLinks.end() ? nullptr : link->second; } - model::LibraryGet Document::library_resolver_get() const + LibraryGet Document::library_resolver_get() const { - return [this](const model::Model& from, int id) + return [this](const Model& from, int id) { auto library = library_get(from, id); return library ? &library->model : nullptr; @@ -449,7 +441,7 @@ namespace anm2ed } // An animation layer whose animation isn't there; a library that didn't load leaves the question open (false). - bool Document::is_layer_animation_missing(const model::Layer& layer) const + bool Document::is_layer_animation_missing(const Layer& layer) const { if (!layer.is_animation()) return false; auto library = layer.libraryId == -1 ? nullptr : library_get(model, layer.libraryId); @@ -470,9 +462,9 @@ namespace anm2ed } // A layer draw's spritesheet image, at `scale` (see vector_image_get). - const resource::Image* Document::draw_image_get(const model::Draw& draw, float scale) const + const Image* Document::draw_image_get(const Draw& draw, float scale) const { - const resource::Image* image{}; + const Image* image{}; if (!draw.source || draw.source == &model) image = texture_get(draw.spritesheetId); for (const auto& [path, library] : libraries) if (&library.model == draw.source) @@ -481,12 +473,12 @@ namespace anm2ed } // A vector image drawn again (cached) for when `scale` screen pixels show each of its pixels; others as they are. - const resource::Image* Document::vector_image_get(const resource::Image* image, float scale) const + const Image* Document::vector_image_get(const Image* image, float scale) const { if (!image || !image->is_vector() || scale <= 1.0f) return image; - auto level = std::min((int)std::ceil(std::log2(scale)), document::VECTOR_LEVEL_MAX); - while (level > 0 && std::max(image->size.x, image->size.y) << level > document::VECTOR_SIZE_MAX) + auto level = std::min((int)std::ceil(std::log2(scale)), VECTOR_LEVEL_MAX); + while (level > 0 && std::max(image->size.x, image->size.y) << level > VECTOR_SIZE_MAX) --level; if (level == 0) return image; auto [it, isNew] = vectorImages.try_emplace({image->uid, level}); @@ -499,7 +491,7 @@ namespace anm2ed { libraryLinks.clear(); std::set reached{}; - std::vector> pending{ + std::vector> pending{ {&model, std::filesystem::absolute(directory_get())}}; while (!pending.empty()) { @@ -507,11 +499,11 @@ namespace anm2ed pending.pop_back(); for (const auto& library : from->content.libraries) { - auto path = document::absolute_path_get(directory, library.path); + auto path = absolute_path_get(directory, library.path); auto [it, isNew] = libraries.try_emplace(path); if (isNew) { - document::library_load(path, it->second); + library_load(path, it->second); ++librariesRevision; } libraryLinks[{from == &model ? nullptr : from, library.id}] = &it->second; @@ -530,7 +522,7 @@ namespace anm2ed std::error_code ec{}; auto time = std::filesystem::last_write_time(path, ec); if (ec || time == library.writeTime) continue; - document::library_load(path, library); + library_load(path, library); ++librariesRevision; isReloaded = true; } @@ -544,7 +536,7 @@ namespace anm2ed libraries_sync(); } - const resource::Image* Document::texture_get(int id) const + const Image* Document::texture_get(int id) const { if (auto draft = textureDrafts.find(id); draft != textureDrafts.end()) return &draft->second; auto key = textures.find(id); @@ -552,29 +544,29 @@ namespace anm2ed } // A private copy of the spritesheet's image to draw on; it becomes a new asset on the next change(). - resource::Image* Document::texture_edit(int id) + Image* Document::texture_edit(int id) { auto texture = texture_get(id); if (!texture || texture->is_vector()) return nullptr; return &textureDrafts.try_emplace(id, *texture).first->second; } - void Document::texture_set(int id, resource::Image image) + void Document::texture_set(int id, Image image) { textureDrafts.erase(id); textures[id] = assets.image_add(std::move(image)); } - const resource::AudioData* Document::sound_get(int id) const + const AudioData* Document::sound_get(int id) const { auto key = sounds.find(id); return key == sounds.end() ? nullptr : assets.audio_get(key->second); } // Every sound that may be playing: this document's and its libraries'. - std::vector Document::sounds_get() const + std::vector Document::sounds_get() const { - std::vector result{}; + std::vector result{}; for (const auto& [id, key] : sounds) if (auto sound = sound_get(id)) result.push_back(sound); for (const auto& [path, library] : libraries) @@ -585,19 +577,19 @@ namespace anm2ed // The sounds triggers play on an animation's frame, its children's included: one of each trigger's sounds, at random // (or picked by `index` for repeatable renders). - std::vector Document::trigger_sounds_get(const model::Animation& animation, int time, + std::vector Document::trigger_sounds_get(const Animation& animation, int time, int index) const { - std::vector result{}; + std::vector result{}; for (const auto& [source, trigger, layerId] : - model::animation_triggers_get(model, animation, time, library_resolver_get())) + animation_triggers_get(model, animation, time, library_resolver_get())) { if (trigger.soundIds.empty()) continue; auto count = trigger.soundIds.size(); auto soundIndex = std::min( - index >= 0 ? (std::size_t)index % count : (std::size_t)math::random_in_range(0.0f, (float)count), count - 1); + index >= 0 ? (std::size_t)index % count : (std::size_t)random_in_range(0.0f, (float)count), count - 1); auto soundId = trigger.soundIds[soundIndex]; - const resource::AudioData* sound{}; + const AudioData* sound{}; if (source == &model) sound = sound_get(soundId); for (const auto& [path, library] : libraries) if (&library.model == source) @@ -607,9 +599,9 @@ namespace anm2ed return result; } - void Document::sound_set(int id, resource::AudioData data) { sounds[id] = assets.audio_add(std::move(data)); } + void Document::sound_set(int id, AudioData data) { sounds[id] = assets.audio_add(std::move(data)); } - resource::Shader* Document::shader_get(int shaderId) + ShaderProgram* Document::shader_get(int shaderId) { auto it = shaders.find(shaderId); return it == shaders.end() || !it->second.is_valid() ? nullptr : &it->second; @@ -618,13 +610,13 @@ namespace anm2ed bool Document::regions_trim(int spritesheetId, const std::set& ids) { auto texture = texture_get(spritesheetId); - return texture && edit::regions_trim(model, spritesheetId, ids, *texture); + return texture && ::regions_trim(model, spritesheetId, ids, *texture); } bool Document::spritesheet_pack(int id, int padding) { auto texture = texture_get(id); - auto packed = texture ? edit::spritesheet_pack(model, id, *texture, padding) : std::nullopt; + auto packed = texture ? ::spritesheet_pack(model, id, *texture, padding) : std::nullopt; if (!packed) return false; texture_set(id, std::move(*packed)); assets_sync(); @@ -634,25 +626,25 @@ namespace anm2ed bool Document::spritesheets_merge(const std::set& ids, bool isAppendRight, bool isMakeRegions, bool isMakePrimaryRegion, Origin origin) { - auto merged = edit::spritesheets_merge( + auto merged = ::spritesheets_merge( model, ids, [this](int id) { return texture_get(id); }, isAppendRight, isMakeRegions, isMakePrimaryRegion, origin); if (!merged) return false; texture_set(*ids.begin(), std::move(*merged)); // The merged sheet may now be an SVG (or a PNG) under a new name; it is written when saved. - texturePaths[*ids.begin()] = model::item_get(model.content.spritesheets, *ids.begin())->path; + texturePaths[*ids.begin()] = item_get(model.content.spritesheets, *ids.begin())->path; for (auto id : ids) if (id != *ids.begin()) textures.erase(id); assets_sync(); return true; } - void Document::hash_set() { hash = model::model_hash(model); } + void Document::hash_set() { hash = model_hash(model); } void Document::clean() { assets_sync(); - saveHash = model::model_hash(model); + saveHash = model_hash(model); hash = saveHash; lastAutosaveTime = 0.0f; isForceDirty = false; @@ -664,7 +656,7 @@ namespace anm2ed for (auto& spritesheet : model.content.spritesheets) { validIds.insert(spritesheet.id); - auto currentHash = document::spritesheet_hash_get( + auto currentHash = spritesheet_hash_get( spritesheet, textures.contains(spritesheet.id) ? textures.at(spritesheet.id) : 0); spritesheetHashes[spritesheet.id] = currentHash; spritesheetSaveHashes.try_emplace(spritesheet.id, currentHash); @@ -685,12 +677,12 @@ namespace anm2ed spritesheet_hashes_sync(); snapshots.commit(); - index = model::UidIndex(model); + index = UidIndex(model); } void Document::edit_begin(StringType label) { snapshots.push(localize.get(label)); } - edit::Uids Document::edit_run(StringType label, const std::function& operation) + Uids Document::edit_run(StringType label, const std::function& operation) { edit_begin(label); auto uids = operation(model); @@ -698,9 +690,9 @@ namespace anm2ed return uids; } - std::vector Document::references_get(const edit::Uids& uids) const + std::vector Document::references_get(const Uids& uids) const { - model::UidIndex index(model); + UidIndex index(model); std::vector references{}; for (auto uid : uids) if (auto reference = index.reference_get(uid)) references.push_back(*reference); @@ -711,11 +703,11 @@ namespace anm2ed bool Document::is_autosave_dirty() { return hash != autosaveHash || !spritesheets_autosave_dirty_get().empty(); } // Edited spritesheets are autosaved as a hidden copy beside their file: ..png.autosave. - std::filesystem::path Document::spritesheet_autosave_path_get(const model::Spritesheet& spritesheet) + std::filesystem::path Document::spritesheet_autosave_path_get(const Spritesheet& spritesheet) { auto path = directory_get() / spritesheet.path; return path.parent_path() / - path::from_utf8("." + path::to_utf8(path.filename()) + std::string(document::AUTOSAVE_EXTENSION)); + path_from_utf8("." + path_to_utf8(path.filename()) + std::string(AUTOSAVE_EXTENSION)); } // Spritesheets with unsaved pixel edits that their autosave copy doesn't have yet. @@ -739,8 +731,8 @@ namespace anm2ed for (const auto& spritesheet : model.content.spritesheets) { auto path = spritesheet_autosave_path_get(spritesheet); - if (!path::is_exist(path)) continue; - if (auto image = resource::Image(path); image.is_valid()) texture_set(spritesheet.id, std::move(image)); + if (!is_path_exist(path)) continue; + if (auto image = Image(path); image.is_valid()) texture_set(spritesheet.id, std::move(image)); } } @@ -754,10 +746,10 @@ namespace anm2ed void Document::spritesheet_hash_update(int id) { - auto spritesheet = model::item_get(model.content.spritesheets, id); + auto spritesheet = item_get(model.content.spritesheets, id); if (!spritesheet) return; assets_sync(); - spritesheetHashes[id] = document::spritesheet_hash_get(*spritesheet, textures.contains(id) ? textures.at(id) : 0); + spritesheetHashes[id] = spritesheet_hash_get(*spritesheet, textures.contains(id) ? textures.at(id) : 0); } // The spritesheet matches its file (just saved or reloaded); its file's time is remembered to notice later changes. @@ -767,7 +759,7 @@ namespace anm2ed if (spritesheetHashes.contains(id)) spritesheetSaveHashes[id] = spritesheetHashes[id]; textureWriteTimes.erase(id); spritesheets_changed_get(); - if (auto spritesheet = model::item_get(model.content.spritesheets, id)) + if (auto spritesheet = item_get(model.content.spritesheets, id)) { std::error_code ec{}; std::filesystem::remove(spritesheet_autosave_path_get(*spritesheet), ec); @@ -779,11 +771,11 @@ namespace anm2ed std::set Document::spritesheets_changed_get() { std::set ids{}; - util::WorkingDirectory workingDirectory(directory_get()); + WorkingDirectory workingDirectory(directory_get()); for (const auto& spritesheet : model.content.spritesheets) { std::error_code ec{}; - auto time = std::filesystem::last_write_time(path::case_insensitive_find(spritesheet.path), ec); + auto time = std::filesystem::last_write_time(path_case_insensitive_find(spritesheet.path), ec); if (ec) continue; auto [it, isNew] = textureWriteTimes.try_emplace(spritesheet.id, time); if (!isNew && it->second != time && !spritesheet_is_dirty(spritesheet.id)) ids.insert(spritesheet.id); @@ -795,16 +787,16 @@ namespace anm2ed void Document::spritesheets_reload(const std::set& ids) { edit_apply(EDIT_RELOAD_SPRITESHEETS, - [&](model::Model&) + [&](Model&) { for (auto id : ids) texture_reload(id); }); for (auto id : ids) - if (auto spritesheet = model::item_get(model.content.spritesheets, id)) + if (auto spritesheet = item_get(model.content.spritesheets, id)) { spritesheet_hash_set_saved(id); - toast_log(Level::INFO, TOAST_RELOAD_SPRITESHEET, id, path::to_utf8(spritesheet->path)); + toast_log(Level::INFO, TOAST_RELOAD_SPRITESHEET, id, path_to_utf8(spritesheet->path)); } } @@ -813,16 +805,16 @@ namespace anm2ed { std::set converted{}; edit_apply(EDIT_CONVERT_SVG_SPRITESHEETS, - [&](model::Model& model) + [&](Model& model) { for (auto id : ids) { - auto spritesheet = model::item_get(model.content.spritesheets, id); + auto spritesheet = item_get(model.content.spritesheets, id); auto texture = texture_get(id); if (!spritesheet || !texture || !texture->is_vector()) continue; auto pngPath = - std::filesystem::path(spritesheet->path).replace_extension(resource::image::PNG_EXTENSION); - auto pathString = path::to_utf8(pngPath); + std::filesystem::path(spritesheet->path).replace_extension(PNG_EXTENSION); + auto pathString = path_to_utf8(pngPath); if (!texture->write_png(std::filesystem::absolute(directory_get()) / pngPath)) { toast_log(Level::ERROR, TOAST_SAVE_SPRITESHEET_FAILED, id, pathString); @@ -840,7 +832,7 @@ namespace anm2ed bool Document::spritesheet_is_dirty(int id) { - if (!model::item_get(model.content.spritesheets, id)) return false; + if (!item_get(model.content.spritesheets, id)) return false; if (!spritesheetHashes.contains(id)) spritesheet_hash_update(id); auto saveIt = spritesheetSaveHashes.find(id); return saveIt != spritesheetSaveHashes.end() && spritesheetHashes.at(id) != saveIt->second; @@ -848,7 +840,7 @@ namespace anm2ed bool Document::spritesheet_any_dirty() { - return std::ranges::any_of(model.content.spritesheets, [&](const model::Spritesheet& spritesheet) + return std::ranges::any_of(model.content.spritesheets, [&](const Spritesheet& spritesheet) { return spritesheet_is_dirty(spritesheet.id); }); } @@ -917,7 +909,7 @@ namespace anm2ed { return [format](const auto& item) { - auto pathString = path::to_utf8(item.path); + auto pathString = path_to_utf8(item.path); return std::vformat(localize.get(format), std::make_format_args(item.id, pathString)); }; }; @@ -933,7 +925,7 @@ namespace anm2ed } // Selects the frames an edit returned and moves the playhead to the first. - void Document::frames_select(const edit::Uids& uids) + void Document::frames_select(const Uids& uids) { auto references = references_get(uids); if (references.empty()) return; @@ -942,7 +934,7 @@ namespace anm2ed frame_references_set({references.begin(), references.end()}); reference_set(focus); if (auto item = model.track_get(focus); item && focus.itemType != TRIGGER) - frameTime = model::frame_time_from_index_get(*item, focus.frameIndex); + frameTime = frame_time_from_index_get(*item, focus.frameIndex); } void Document::frame_select(Reference frameReference) @@ -971,12 +963,12 @@ namespace anm2ed { selection.uids[SelectionKind::GROUPS].clear(); editTarget = EditTarget::FRAME; - if (document::item_reference_get(firstReference) != document::item_reference_get(lastReference) || + if (item_reference_get(firstReference) != item_reference_get(lastReference) || firstReference.frameIndex < 0 || lastReference.frameIndex < 0) return false; auto item = model.track_get(lastReference); - if (!item || std::max(firstReference.frameIndex, lastReference.frameIndex) >= model::track_frames_count_get(*item)) + if (!item || std::max(firstReference.frameIndex, lastReference.frameIndex) >= track_frames_count_get(*item)) return false; auto [firstIndex, lastIndex] = std::minmax(firstReference.frameIndex, lastReference.frameIndex); @@ -1013,7 +1005,7 @@ namespace anm2ed { itemReference.frameIndex = -1; if (itemReference.itemType == LAYER) - if (auto layer = model::item_get(model.content.layers, itemReference.itemID)) + if (auto layer = item_get(model.content.layers, itemReference.itemID)) focused_id_set(SelectionKind::SPRITESHEETS, layer->spritesheetId); reference_set(itemReference); frame_references_clear(); @@ -1053,7 +1045,7 @@ namespace anm2ed { auto selectedItems = selected_get(SelectionKind::TRACKS); if (auto reference = reference_get(); selectedItems.empty() && reference.itemType != NONE) - selectedItems.insert(document::item_reference_get(reference)); + selectedItems.insert(item_reference_get(reference)); std::set result{}; for (auto itemReference : selectedItems) @@ -1076,7 +1068,7 @@ namespace anm2ed std::erase_if(frameReferences, [&](const Reference& frame) { return !model.frame_get(frame); }); std::set tracks{}; for (auto frame : frameReferences) - tracks.insert(document::item_reference_get(frame)); + tracks.insert(item_reference_get(frame)); selected_set(SelectionKind::FRAMES, frameReferences); selected_set(SelectionKind::TRACKS, tracks); if (!frameReferences.empty() && !frameReferences.contains(reference_get())) reference_set(*frameReferences.begin()); @@ -1094,7 +1086,7 @@ namespace anm2ed auto reference = reference_get(); std::set selectedReferences = selected_get(SelectionKind::TRACKS); if (selectedReferences.empty() && reference.itemType != NONE) - selectedReferences.insert(document::item_reference_get(reference)); + selectedReferences.insert(item_reference_get(reference)); std::vector result{}; for (auto itemReference : selectedReferences) @@ -1110,19 +1102,19 @@ namespace anm2ed auto& items = model.content.spritesheets; auto directory = directory_get(); - std::vector> loaded{}; + std::vector> loaded{}; for (auto& path : paths) { - auto storagePath = path::backslash_handle(path); + auto storagePath = path_backslash_handle(path); std::optional workingDirectory{}; if (!storagePath.is_absolute()) workingDirectory.emplace(directory); - auto texture = resource::Image(path::case_insensitive_find(storagePath)); + auto texture = Image(path_case_insensitive_find(storagePath)); if (!texture.is_valid()) { - toast_log(Level::ERROR, TOAST_SPRITESHEET_INIT_FAILED, path::to_utf8(path)); + toast_log(Level::ERROR, TOAST_SPRITESHEET_INIT_FAILED, path_to_utf8(path)); continue; } - loaded.emplace_back(path::backslash_replace(path::make_relative(storagePath, directory)), std::move(texture)); + loaded.emplace_back(path_backslash_replace(path_make_relative(storagePath, directory)), std::move(texture)); } if (loaded.empty()) return; @@ -1132,12 +1124,12 @@ namespace anm2ed for (auto& [relativePath, texture] : loaded) { auto& element = - items.emplace_back(model::Spritesheet{.id = model::item_next_id_get(items), .path = relativePath}); + items.emplace_back(Spritesheet{.id = item_next_id_get(items), .path = relativePath}); texture_set(element.id, std::move(texture)); texturePaths[element.id] = element.path; added.insert(element.id); spritesheet_hash_set_saved(element.id); - toast_log(Level::INFO, TOAST_SPRITESHEET_INITIALIZED, element.id, path::to_utf8(element.path)); + toast_log(Level::INFO, TOAST_SPRITESHEET_INITIALIZED, element.id, path_to_utf8(element.path)); } selected_ids_set(SelectionKind::SPRITESHEETS, added); focused_id_set(SelectionKind::SPRITESHEETS, *added.rbegin()); @@ -1155,14 +1147,14 @@ namespace anm2ed for (auto& path : paths) { if (path.empty()) continue; - auto& element = items.emplace_back(model::Sound{ - .id = model::item_next_id_get(items), - .path = path::backslash_replace(path::make_relative(path::backslash_handle(path), directory_get()))}); + auto& element = items.emplace_back(Sound{ + .id = item_next_id_get(items), + .path = path_backslash_replace(path_make_relative(path_backslash_handle(path), directory_get()))}); WorkingDirectory workingDirectory(directory_get()); - sound_set(element.id, resource::AudioData(path::case_insensitive_find(element.path))); + sound_set(element.id, AudioData(path_case_insensitive_find(element.path))); soundPaths[element.id] = element.path; added.insert(element.id); - toast_log(Level::INFO, TOAST_SOUND_INITIALIZED, element.id, path::to_utf8(element.path)); + toast_log(Level::INFO, TOAST_SOUND_INITIALIZED, element.id, path_to_utf8(element.path)); } selected_ids_set(SelectionKind::SOUNDS, added); focused_id_set(SelectionKind::SOUNDS, *added.rbegin()); @@ -1174,22 +1166,22 @@ namespace anm2ed std::set added{}; edit_apply( EDIT_ADD_LIBRARY, - [&](model::Model& model) + [&](Model& model) { auto& libraries = model.content.libraries; for (auto& path : paths) if (!path.empty()) { - auto& library = libraries.emplace_back(model::Library{ - .id = model::item_next_id_get(libraries), - .path = path::backslash_replace(path::make_relative(path::backslash_handle(path), directory_get()))}); + auto& library = libraries.emplace_back(Library{ + .id = item_next_id_get(libraries), + .path = path_backslash_replace(path_make_relative(path_backslash_handle(path), directory_get()))}); added.insert(library.id); } }); if (added.empty()) return; for (auto id : added) toast_log(Level::INFO, TOAST_LIBRARY_INITIALIZED, id, - path::to_utf8(model::item_get(model.content.libraries, id)->path)); + path_to_utf8(item_get(model.content.libraries, id)->path)); selected_ids_set(SelectionKind::LIBRARIES, added); focused_id_set(SelectionKind::LIBRARIES, *added.rbegin()); } @@ -1197,7 +1189,7 @@ namespace anm2ed void Document::undo() { if (!snapshots.undo()) return; - document::frame_time_sync(*this); + frame_time_sync(*this); toast_log(Level::INFO, TOAST_UNDO, message); change(); } @@ -1205,11 +1197,10 @@ namespace anm2ed void Document::redo() { if (!snapshots.redo()) return; - document::frame_time_sync(*this); + frame_time_sync(*this); toast_log(Level::INFO, TOAST_REDO, message); change(); } bool Document::is_able_to_undo() { return !snapshots.undoStack.is_empty(); } bool Document::is_able_to_redo() { return !snapshots.redoStack.is_empty(); } -} diff --git a/src/document.h b/src/document.h index 8491598..70ff7ee 100644 --- a/src/document.h +++ b/src/document.h @@ -20,8 +20,6 @@ #include "shader.h" -namespace anm2ed -{ class Manager; struct Command; @@ -35,9 +33,9 @@ namespace anm2ed // A linked .anm2, loaded read-only: its document, its spritesheets' images and its sounds. struct LibraryData { - model::Model model{}; - std::map images{}; - std::map sounds{}; + Model model{}; + std::map images{}; + std::map sounds{}; std::filesystem::file_time_type writeTime{}; }; @@ -59,8 +57,8 @@ namespace anm2ed std::filesystem::path path{}; uint64_t tabId{}; Snapshots snapshots{}; - resource::AssetStore assets{}; - std::map textureDrafts{}; + AssetStore assets{}; + std::map textureDrafts{}; int changeAllFramePropertiesRegionId{-1}; int changeAllFramePropertiesShaderId{-1}; @@ -89,13 +87,13 @@ namespace anm2ed std::unordered_map soundPaths{}; std::map shaderVertexPaths{}; std::map shaderFragmentPaths{}; - std::map shaders{}; + std::map shaders{}; // Libraries by absolute path, and what each (document, library id) points at (nullptr is this document). std::map libraries{}; - std::map, const LibraryData*> libraryLinks{}; + std::map, const LibraryData*> libraryLinks{}; std::uint64_t librariesRevision{}; // counts library loads, for anything drawn from them // Vector spritesheets drawn again for zooms past 100%, by (image uid, power-of-two level). - mutable std::map, resource::Image> vectorImages{}; + mutable std::map, Image> vectorImages{}; bool isAnimationPreviewSet{false}; bool isSpritesheetEditorSet{false}; }; @@ -123,7 +121,7 @@ namespace anm2ed #undef X std::string& message = current.message; EditTarget editTarget{EditTarget::NONE}; - model::UidIndex index{}; + UidIndex index{}; Document(const std::filesystem::path&, bool = false, std::string* = nullptr); Document(const Document&) = delete; @@ -137,21 +135,21 @@ namespace anm2ed bool texture_reload(int); bool sound_reload(int); bool shader_reload(int, std::string* = nullptr); - const resource::Image* texture_get(int) const; - resource::Image* texture_edit(int); - void texture_set(int, resource::Image); - const resource::AudioData* sound_get(int) const; - std::vector sounds_get() const; - std::vector trigger_sounds_get(const model::Animation&, int, int = -1) const; - void sound_set(int, resource::AudioData); - resource::Shader* shader_get(int); + const Image* texture_get(int) const; + Image* texture_edit(int); + void texture_set(int, Image); + const AudioData* sound_get(int) const; + std::vector sounds_get() const; + std::vector trigger_sounds_get(const Animation&, int, int = -1) const; + void sound_set(int, AudioData); + ShaderProgram* shader_get(int); std::filesystem::path library_path_get(int) const; - const LibraryData* library_get(const model::Model&, int) const; - model::LibraryGet library_resolver_get() const; - edit::SpritesheetPathGet spritesheet_path_resolver_get() const; + const LibraryData* library_get(const Model&, int) const; + LibraryGet library_resolver_get() const; + SpritesheetPathGet spritesheet_path_resolver_get() const; std::vector animation_names_get(int) const; - const resource::Image* draw_image_get(const model::Draw&, float = 1.0f) const; - const resource::Image* vector_image_get(const resource::Image*, float) const; + const Image* draw_image_get(const Draw&, float = 1.0f) const; + const Image* vector_image_get(const Image*, float) const; void libraries_sync(); bool libraries_reload(); void library_reload(int); @@ -162,15 +160,15 @@ namespace anm2ed void clean(); void change(); void edit_begin(StringType); - edit::Uids edit_run(StringType, const std::function&); + Uids edit_run(StringType, const std::function&); // Snapshots for undo, runs the operation on the model, then commits; void operations select nothing. - template edit::Uids edit_apply(StringType label, Operation&& operation) + template Uids edit_apply(StringType label, Operation&& operation) { return edit_run(label, - [&](model::Model& model) -> edit::Uids + [&](Model& model) -> Uids { - if constexpr (std::is_void_v>) + if constexpr (std::is_void_v>) { operation(model); return {}; @@ -179,9 +177,9 @@ namespace anm2ed return operation(model); }); } - std::vector references_get(const edit::Uids&) const; + std::vector references_get(const Uids&) const; bool is_dirty() const; - bool is_layer_animation_missing(const model::Layer&) const; + bool is_layer_animation_missing(const Layer&) const; bool is_autosave_dirty(); std::filesystem::path directory_get() const; std::filesystem::path filename_get() const; @@ -195,7 +193,7 @@ namespace anm2ed std::set spritesheets_changed_get(); void spritesheets_reload(const std::set&); void spritesheets_vector_convert(const std::set&); - std::filesystem::path spritesheet_autosave_path_get(const model::Spritesheet&); + std::filesystem::path spritesheet_autosave_path_get(const Spritesheet&); std::set spritesheets_autosave_dirty_get(); void spritesheets_autosave_restore(); void spritesheets_autosave_clear(); @@ -209,7 +207,7 @@ namespace anm2ed void focused_id_set(SelectionKind, int); void selected_clear(SelectionKind); Choices choices_get(SelectionKind, int = -1) const; - void frames_select(const edit::Uids&); + void frames_select(const Uids&); void frame_select(Reference); void frame_toggle(Reference); bool frames_range_select(Reference, Reference, bool); @@ -238,4 +236,3 @@ namespace anm2ed bool is_able_to_undo(); bool is_able_to_redo(); }; -} diff --git a/src/edit/animations.cpp b/src/edit/animations.cpp index c076bbc..41da0f0 100644 --- a/src/edit/animations.cpp +++ b/src/edit/animations.cpp @@ -2,10 +2,6 @@ #include "model/xml.h" -using namespace anm2ed::model; - -namespace anm2ed::edit -{ constexpr std::string_view ANIMATION_MERGED_SUFFIX = " (Merged)"; using AnimationPointer = std::shared_ptr; @@ -33,7 +29,7 @@ namespace anm2ed::edit std::vector groups{}; }; - AnimationsTaken animations_take(Model& model, const std::set& indices, const std::set& groupIds) + static AnimationsTaken animations_take(Model& model, const std::set& indices, const std::set& groupIds) { AnimationsTaken taken{}; int index{}; @@ -73,7 +69,7 @@ namespace anm2ed::edit int position{-1}; }; - AnimationPlace animation_place_get(Model& model, std::uint64_t uid) + static AnimationPlace animation_place_get(Model& model, std::uint64_t uid) { auto& entries = model.animations.entries; for (int i = 0; i < (int)entries.size(); ++i) @@ -90,7 +86,7 @@ namespace anm2ed::edit return {}; } - int animation_group_entry_get(const Model& model, int groupId) + static int animation_group_entry_get(const Model& model, int groupId) { auto& entries = model.animations.entries; for (int i = 0; i < (int)entries.size(); ++i) @@ -98,14 +94,14 @@ namespace anm2ed::edit return -1; } - AnimationGroup* animation_group_find(Model& model, int groupId) + static AnimationGroup* animation_group_find(Model& model, int groupId) { auto entry = animation_group_entry_get(model, groupId); return entry == -1 ? nullptr : &std::get(model.animations.entries[entry]); } // Inserts animations before the animation at a flat index (or at the end), inside `groupId` when given. - void animations_insert(Model& model, int index, int groupId, std::vector animations) + static void animations_insert(Model& model, int index, int groupId, std::vector animations) { auto before = model.animation_get(index); auto place = before ? animation_place_get(model, before->uid) : AnimationPlace{}; @@ -135,7 +131,7 @@ namespace anm2ed::edit } // An empty copy of a track list: same tracks and groups, no frames. - std::vector track_entries_shell_get(const std::vector& entries) + static std::vector track_entries_shell_get(const std::vector& entries) { std::vector shell{}; auto track_shell_get = [](const Track& track) @@ -287,20 +283,20 @@ namespace anm2ed::edit return uids; } - void track_merge(Track& destination, const Track& source, types::merge::Type type) + static void track_merge(Track& destination, const Track& source, Merge type) { std::vector frames{}; for (const auto& frame : source.frames) frames.push_back(frame_clone(frame)); switch (type) { - case types::merge::APPEND: + case MERGE_APPEND: destination.frames.insert(destination.frames.end(), frames.begin(), frames.end()); break; - case types::merge::PREPEND: + case MERGE_PREPEND: destination.frames.insert(destination.frames.begin(), frames.begin(), frames.end()); break; - case types::merge::REPLACE: + case MERGE_REPLACE: if (destination.frames.size() < frames.size()) destination.frames.resize(frames.size()); std::ranges::copy(frames, destination.frames.begin()); break; @@ -311,8 +307,8 @@ namespace anm2ed::edit // Merges a source animation's layer or null tracks: groups match by name (else are added), tracks match by id // within their group (else are added). - void track_entries_merge(std::vector& destination, const std::vector& source, - types::merge::Type type) + static void track_entries_merge(std::vector& destination, const std::vector& source, + Merge type) { std::map groupRemap{}; std::set matchedGroupIds{}; @@ -378,7 +374,7 @@ namespace anm2ed::edit // Merges source animations into the target (frames appended, prepended, replacing or ignored), optionally deleting // the sources; `ungroupIds` dissolves groups afterwards. Returns the merged animation's uid. - Uids animations_merge(Model& model, int target, std::set sources, types::merge::Type type, bool isDeleteAfter, + Uids animations_merge(Model& model, int target, std::set sources, Merge type, bool isDeleteAfter, const std::set& ungroupIds) { if (!model.animation_get(target)) return {}; @@ -396,13 +392,13 @@ namespace anm2ed::edit if (!source) continue; auto sourceCopy = *source; auto& destination = *model.animation_edit(target); - if (type == types::merge::APPEND) + if (type == MERGE_APPEND) for (auto& trigger : sourceCopy.triggers.frames) trigger.atFrame += length; - if (type == types::merge::PREPEND) + if (type == MERGE_PREPEND) for (auto& trigger : destination.triggers.frames) trigger.atFrame += sourceCopy.frameNum; - if (type == types::merge::APPEND || type == types::merge::PREPEND) length += sourceCopy.frameNum; + if (type == MERGE_APPEND || type == MERGE_PREPEND) length += sourceCopy.frameNum; track_merge(destination.root, sourceCopy.root, type); track_entries_merge(destination.layers, sourceCopy.layers, type); track_entries_merge(destination.nulls, sourceCopy.nulls, type); @@ -428,4 +424,3 @@ namespace anm2ed::edit animation_groups_remove(model, ungroupIds); return {uid}; } -} diff --git a/src/edit/content.cpp b/src/edit/content.cpp index 4c68a0d..093c686 100644 --- a/src/edit/content.cpp +++ b/src/edit/content.cpp @@ -6,10 +6,6 @@ #include "model/frames.h" #include "model/xml.h" -using namespace anm2ed::model; - -namespace anm2ed::edit -{ std::string region_name_get(const std::string& format, int number) { try @@ -22,14 +18,14 @@ namespace anm2ed::edit } } - bool is_region_matched(const Region& region, const Frame& frame) + static bool is_region_matched(const Region& region, const Frame& frame) { return glm::ivec2(region.crop) == glm::ivec2(frame.crop) && glm::ivec2(region.size) == glm::ivec2(frame.size) && glm::ivec2(region.pivot) == glm::ivec2(frame.pivot); } // Every frame of every layer track whose layer has a spritesheet, with that spritesheet's id. - template void layer_frames_each(Model& model, int animationIndex, Callback&& callback) + template static void layer_frames_each(Model& model, int animationIndex, Callback&& callback) { auto animation = model.animation_get(animationIndex); if (!animation) return; @@ -545,4 +541,3 @@ namespace anm2ed::edit defaultAnimationName.empty() ? source.animations.defaultAnimation : defaultAnimationName; return true; } -} diff --git a/src/edit/edit.h b/src/edit/edit.h index 91aa932..382248e 100644 --- a/src/edit/edit.h +++ b/src/edit/edit.h @@ -14,10 +14,8 @@ // Document edits as plain functions of the model. Each returns the uids of the elements it created or changed that // the caller may want to select (the first one is the focus); selection itself stays with the UI. -namespace anm2ed::edit -{ using Uids = std::vector; - using ImageGet = std::function; + using ImageGet = std::function; struct RowTarget { @@ -90,59 +88,58 @@ namespace anm2ed::edit }; bool is_frame_property_valid(FrameProperty, ItemType); - void frame_property_copy(model::Frame&, const model::Frame&, FrameProperty); - Uids frames_property_set(model::Model&, const std::set&, FrameProperty, const model::Frame&); + void frame_property_copy(Frame&, const Frame&, FrameProperty); + Uids frames_property_set(Model&, const std::set&, FrameProperty, const Frame&); std::map> frames_by_track_get(const std::set&); - Uids frame_insert(model::Model&, Reference, int); - Uids frames_delete(model::Model&, const std::set&); - Uids frames_duplicate(model::Model&, const std::set&, Reference); - Uids frames_reverse(model::Model&, const std::set&); - Uids frames_bake(model::Model&, const std::set&, int, bool, bool); - Uids frame_split(model::Model&, Reference, int); - Uids frames_split(model::Model&, const std::set&, int); - Uids frames_move(model::Model&, const std::set&, Reference, int); - Uids frame_durations_set(model::Model&, const std::map&); - Uids trigger_at_frame_set(model::Model&, Reference, int); - Uids frames_paste(model::Model&, Reference, const std::set&, const std::string&, int, std::string*); - Uids root_bake_into(model::Model&, const std::set&, const std::set&, RootBakeOptions); + Uids frame_insert(Model&, Reference, int); + Uids frames_delete(Model&, const std::set&); + Uids frames_duplicate(Model&, const std::set&, Reference); + Uids frames_reverse(Model&, const std::set&); + Uids frames_bake(Model&, const std::set&, int, bool, bool); + Uids frame_split(Model&, Reference, int); + Uids frames_split(Model&, const std::set&, int); + Uids frames_move(Model&, const std::set&, Reference, int); + Uids frame_durations_set(Model&, const std::map&); + Uids trigger_at_frame_set(Model&, Reference, int); + Uids frames_paste(Model&, Reference, const std::set&, const std::string&, int, std::string*); + Uids root_bake_into(Model&, const std::set&, const std::set&, RootBakeOptions); - Uids items_remove(model::Model&, int, const std::map>&, const std::map>&); - Uids items_group(model::Model&, int, int, const std::set&, const std::string&); - Uids items_move(model::Model&, int, int, const std::set&, const std::set&, RowTarget, bool, bool); - Uids animation_length_fit(model::Model&, int); - int item_add(model::Model&, ItemType, int, int, model::Layer, model::Null, int, types::destination::Type); + Uids items_remove(Model&, int, const std::map>&, const std::map>&); + Uids items_group(Model&, int, int, const std::set&, const std::string&); + Uids items_move(Model&, int, int, const std::set&, const std::set&, RowTarget, bool, bool); + Uids animation_length_fit(Model&, int); + int item_add(Model&, ItemType, int, int, Layer, Null, int, Destination); - std::set animation_group_ids_get(const model::Model&); - std::set animation_group_indices_get(const model::Model&, int); - void animation_groups_remove(model::Model&, const std::set&); - Uids animation_add(model::Model&, int, int, int, const std::string&); - Uids animations_remove(model::Model&, const std::set&, const std::set&); - Uids animations_move(model::Model&, const std::set&, const std::set&, AnimationTarget); - Uids animations_group(model::Model&, const std::set&, const std::string&); - Uids animations_paste(model::Model&, const std::string&, int, int, std::set&, std::string*); - Uids animations_merge(model::Model&, int, std::set, types::merge::Type, bool, const std::set&); + std::set animation_group_ids_get(const Model&); + std::set animation_group_indices_get(const Model&, int); + void animation_groups_remove(Model&, const std::set&); + Uids animation_add(Model&, int, int, int, const std::string&); + Uids animations_remove(Model&, const std::set&, const std::set&); + Uids animations_move(Model&, const std::set&, const std::set&, AnimationTarget); + Uids animations_group(Model&, const std::set&, const std::string&); + Uids animations_paste(Model&, const std::string&, int, int, std::set&, std::string*); + Uids animations_merge(Model&, int, std::set, Merge, bool, const std::set&); std::string region_name_get(const std::string&, int); - Uids regions_generate(model::Model&, const std::set&, const std::set&, const std::string&, + Uids regions_generate(Model&, const std::set&, const std::set&, const std::string&, RegionFrameMapping); - Uids regions_scan(model::Model&); - Uids region_frames_sync(model::Model&); - Uids regions_paste(model::Model&, int, const std::string&, int, std::string*); - Uids animation_grid_generate(model::Model&, const std::vector&, const GridOptions&); - Uids frames_change_apply(model::Model&, const ChangeTargets&, FrameChange, ChangeType); - bool regions_trim(model::Model&, int, const std::set&, const resource::Image&); - std::optional spritesheet_pack(model::Model&, int, const resource::Image&, int); - std::optional spritesheets_merge(model::Model&, const std::set&, const ImageGet&, bool, bool, + Uids regions_scan(Model&); + Uids region_frames_sync(Model&); + Uids regions_paste(Model&, int, const std::string&, int, std::string*); + Uids animation_grid_generate(Model&, const std::vector&, const GridOptions&); + Uids frames_change_apply(Model&, const ChangeTargets&, FrameChange, ChangeType); + bool regions_trim(Model&, int, const std::set&, const Image&); + std::optional spritesheet_pack(Model&, int, const Image&, int); + std::optional spritesheets_merge(Model&, const std::set&, const ImageGet&, bool, bool, bool, Origin); // Where a spritesheet path of a document (this one, or a library) points, from this document. - using SpritesheetPathGet = std::function; - model::Model animation_layers_flatten(model::Model, const model::LibraryGet&, const SpritesheetPathGet&, + using SpritesheetPathGet = std::function; + Model animation_layers_flatten(Model, const LibraryGet&, const SpritesheetPathGet&, const std::set& = {}); - Uids content_remove(model::Model&, ElementType, const std::set&, int, const model::LibraryGet&, + Uids content_remove(Model&, ElementType, const std::set&, int, const LibraryGet&, const SpritesheetPathGet&); - model::Model isaac_bridge(model::Model); - bool file_merge(model::Model&, const std::filesystem::path&, const std::filesystem::path&, FileMergePreset); -} + Model isaac_bridge(Model); + bool file_merge(Model&, const std::filesystem::path&, const std::filesystem::path&, FileMergePreset); diff --git a/src/edit/flatten.cpp b/src/edit/flatten.cpp index 8431466..96dd67b 100644 --- a/src/edit/flatten.cpp +++ b/src/edit/flatten.cpp @@ -7,14 +7,9 @@ #include "math_util.h" #include "model/frames.h" -using namespace anm2ed::model; -using namespace anm2ed::util; - -namespace anm2ed::edit -{ // A draw as a plain layer frame of one frame: its transform (parents included) taken apart into position, scale and // rotation. Skew has no place in a plain frame, and is dropped. - Frame draw_frame_bake(const Draw& draw) + static Frame draw_frame_bake(const Draw& draw) { auto frame = draw.frame; auto size = glm::max(frame.size, glm::vec2(1.0f)); @@ -24,7 +19,7 @@ namespace anm2ed::edit auto scaleX = glm::length(column0); auto determinant = column0.x * column1.y - column0.y * column1.x; frame.position = glm::vec2(model * glm::vec4(frame.pivot / size, 0.0f, 1.0f)); - frame.scale = math::unit_to_percent(glm::vec2(scaleX, scaleX > 0.0f ? determinant / scaleX : 0.0f)); + frame.scale = unit_to_percent(glm::vec2(scaleX, scaleX > 0.0f ? determinant / scaleX : 0.0f)); frame.rotation = glm::degrees(std::atan2(column0.y, column0.x)); frame.skew = {}; frame.depth = 0; @@ -35,7 +30,7 @@ namespace anm2ed::edit return frame; } - bool is_frame_baked_equal(Frame a, const Frame& b) + static bool is_frame_baked_equal(Frame a, const Frame& b) { a.uid = b.uid; a.duration = b.duration; @@ -163,4 +158,3 @@ namespace anm2ed::edit std::erase_if(content.layers, is_flattened); return model; } -} diff --git a/src/edit/frames.cpp b/src/edit/frames.cpp index 3f8362f..e68158b 100644 --- a/src/edit/frames.cpp +++ b/src/edit/frames.cpp @@ -7,11 +7,6 @@ #include "model/frames.h" #include "model/xml.h" -using namespace anm2ed::util; -using namespace anm2ed::model; - -namespace anm2ed::edit -{ std::map> frames_by_track_get(const std::set& frames) { std::map> result{}; @@ -23,7 +18,7 @@ namespace anm2ed::edit return result; } - Uids frames_uids_get(const Track& track, int start, int count) + static Uids frames_uids_get(const Track& track, int start, int count) { Uids uids{}; for (int i = std::max(start, 0); i < std::min(start + count, (int)track.frames.size()); ++i) @@ -446,4 +441,3 @@ namespace anm2ed::edit model.track_edit(rootReference)->frames = std::move(rewritten); return uids; } -} diff --git a/src/edit/isaac.cpp b/src/edit/isaac.cpp index 2915c45..2910f80 100644 --- a/src/edit/isaac.cpp +++ b/src/edit/isaac.cpp @@ -7,15 +7,10 @@ #include "math_util.h" #include "model/frames.h" -using namespace anm2ed::model; -using namespace anm2ed::util; - -namespace anm2ed::edit -{ // An alpha offset joins the alpha tint: exact on opaque pixels, which the offset can only fade. - void alpha_offsets_bridge(Model& model) + static void alpha_offsets_bridge(Model& model) { - auto is_offset = [](const Frame& frame) { return math::float_to_uint8(frame.colorOffset.a) != 0; }; + auto is_offset = [](const Frame& frame) { return float_to_uint8(frame.colorOffset.a) != 0; }; for (int i = 0; i < model.animations_count_get(); ++i) { auto isUsed = false; @@ -38,7 +33,7 @@ namespace anm2ed::edit // A layer frame's depth becomes a copy of its layer, named for the depth, standing where the editor draws it (the // layer at the copy's place + depth, past the layer already there), and showing only the frames at that depth; the // layer itself shows the rest. Groups can't stand apart in the game, so their roots go into their tracks first. - void depths_bridge(Model& model) + static void depths_bridge(Model& model) { auto& content = model.content; std::map, int> copyIds{}; @@ -117,4 +112,3 @@ namespace anm2ed::edit depths_bridge(model); return model; } -} diff --git a/src/edit/spritesheets.cpp b/src/edit/spritesheets.cpp index 4466d7a..ee0e34a 100644 --- a/src/edit/spritesheets.cpp +++ b/src/edit/spritesheets.cpp @@ -9,13 +9,7 @@ #include "pack.h" #include "path.h" -using namespace anm2ed::model; -using namespace anm2ed::resource; -using namespace anm2ed::util; - // Spritesheet pixel edits: the model changes in place, and a new image is returned for the document to store. -namespace anm2ed::edit -{ bool regions_trim(Model& model, int spritesheetId, const std::set& ids, const Image& source) { auto spritesheet = item_get(model.content.spritesheets, spritesheetId); @@ -35,9 +29,9 @@ namespace anm2ed::edit for (int y = minPoint.y; y < maxPoint.y; ++y) for (int x = minPoint.x; x < maxPoint.x; ++x) { - auto index = ((std::size_t)y * source.size.x + x) * image::CHANNELS; - if (index + image::CHANNELS > source.pixels.size()) continue; - if (std::all_of(source.pixels.begin() + index, source.pixels.begin() + index + image::CHANNELS, + auto index = ((std::size_t)y * source.size.x + x) * IMAGE_CHANNELS; + if (index + IMAGE_CHANNELS > source.pixels.size()) continue; + if (std::all_of(source.pixels.begin() + index, source.pixels.begin() + index + IMAGE_CHANNELS, [](auto channel) { return channel == 0; })) continue; contentMin = glm::min(contentMin, glm::ivec2(x, y)); @@ -100,7 +94,7 @@ namespace anm2ed::edit glm::ivec2 packedSize{}; std::vector positions{}; - if (!util::pack::rects_pack(sizes, packedSize, positions) || packedSize.x <= 0 || packedSize.y <= 0) return {}; + if (!rects_pack(sizes, packedSize, positions) || packedSize.x <= 0 || packedSize.y <= 0) return {}; std::vector parts{}; for (int i = 0; i < (int)items.size(); ++i) @@ -132,7 +126,7 @@ namespace anm2ed::edit auto source = item_get(model.content.spritesheets, sourceId); Region region{}; region.id = item_next_id_get(base->regions); - auto stem = path::to_utf8(source->path.stem()); + auto stem = path_to_utf8(source->path.stem()); region.name = stem.empty() ? std::format("#{}", sourceId) : stem; region.crop = crop; region.size = size; @@ -157,7 +151,7 @@ namespace anm2ed::edit { auto sourceRegionId = sourceRegion.id; sourceRegion.id = item_next_id_get(base->regions); - sourceRegion.uid = util::uid_next(); + sourceRegion.uid = uid_next(); sourceRegion.crop += offset; base->regions.push_back(sourceRegion); regionIdMap[id][sourceRegionId] = sourceRegion.id; @@ -185,10 +179,9 @@ namespace anm2ed::edit }); auto isVector = std::ranges::any_of(parts, [](const ImagePart& part) { return part.image->is_vector(); }); - if (isVector != path::is_extension(base->path, image::SVG_EXTENSION)) - base->path.replace_extension(isVector ? image::SVG_EXTENSION : image::PNG_EXTENSION); + if (isVector != is_path_extension(base->path, SVG_EXTENSION)) + base->path.replace_extension(isVector ? SVG_EXTENSION : PNG_EXTENSION); std::erase_if(model.content.spritesheets, [&](const Spritesheet& spritesheet) { return spritesheet.id != baseId && ids.contains(spritesheet.id); }); return Image::compose(parts, mergedSize, isVector); } -} diff --git a/src/edit/tracks.cpp b/src/edit/tracks.cpp index 13cb425..6176911 100644 --- a/src/edit/tracks.cpp +++ b/src/edit/tracks.cpp @@ -1,10 +1,6 @@ #include "edit/edit.h" -using namespace anm2ed::model; - -namespace anm2ed::edit -{ - std::vector* track_entries_edit(Model& model, int animationIndex, int type) + static std::vector* track_entries_edit(Model& model, int animationIndex, int type) { if (type != LAYER && type != NULL_) return nullptr; auto animation = model.animation_edit(animationIndex); @@ -161,7 +157,7 @@ namespace anm2ed::edit // Adds a layer or null (or updates the one with the item's id) and gives it a track in one or every animation. // Adds track `id` (a new item, from `layer` or `null`, at -1) to an animation or all of them. int item_add(Model& model, ItemType type, int animationIndex, int id, Layer layer, Null null, int insertBeforeId, - types::destination::Type destination) + Destination destination) { auto& content = model.content; auto item_insert = [&](auto& items, auto item) @@ -192,11 +188,10 @@ namespace anm2ed::edit entries.insert(insertBeforeId == -1 ? entries.end() : before, Track{.type = type, .id = id}); }; - if (destination == types::destination::ALL) + if (destination == DESTINATION_ALL) for (int i = 0; i < model.animations_count_get(); ++i) add(i); else if (model.animation_get(animationIndex)) add(animationIndex); return id; } -} diff --git a/src/file.cpp b/src/file.cpp index 7eb35e2..f65bf41 100644 --- a/src/file.cpp +++ b/src/file.cpp @@ -2,8 +2,6 @@ #include -namespace anm2ed::util -{ File::File(const std::filesystem::path& path, const char* mode) { open(path, mode); } File::~File() { close(); } @@ -42,9 +40,7 @@ namespace anm2ed::util File::operator bool() const { return handle != nullptr; } - namespace file - { - bool read_to_string(const std::filesystem::path& path, std::string* output, const char* mode) + bool file_text_load(const std::filesystem::path& path, std::string* output, const char* mode) { if (!output) return false; @@ -61,12 +57,10 @@ namespace anm2ed::util } } - bool write_string(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, const char* mode) { File file(path, mode); if (!file) return false; return std::fwrite(data.data(), 1, data.size(), file.get()) == data.size(); } - } -} diff --git a/src/file.h b/src/file.h index abb485c..e1ddd5e 100644 --- a/src/file.h +++ b/src/file.h @@ -4,8 +4,6 @@ #include #include -namespace anm2ed::util -{ class File { public: @@ -22,9 +20,5 @@ namespace anm2ed::util FILE* handle{}; }; - namespace file - { - bool read_to_string(const std::filesystem::path&, std::string*, const char* mode = "rb"); - bool write_string(const std::filesystem::path&, std::string_view, const char* mode = "wb"); - } -} + 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"); diff --git a/src/font.cpp b/src/font.cpp index 371ee6b..12d5f32 100644 --- a/src/font.cpp +++ b/src/font.cpp @@ -1,7 +1,5 @@ #include "font.h" -namespace anm2ed::resource -{ Font::Font() = default; Font::Font(void* data, size_t length, int size) @@ -52,4 +50,3 @@ namespace anm2ed::resource } return *this; } -} \ No newline at end of file diff --git a/src/font.h b/src/font.h index 477a6f2..3e15cfc 100644 --- a/src/font.h +++ b/src/font.h @@ -3,25 +3,20 @@ #include #include "embed.h" -namespace anm2ed::resource::font -{ - constexpr auto SIZE = 16; - constexpr auto SIZE_LARGE = 32; + constexpr auto FONT_SIZE = 16; + constexpr auto FONT_SIZE_LARGE = 32; - enum Type + enum FontStyle { - REGULAR, - ITALICS, - BOLD, - BOLD_ITALICS, - COUNT + FONT_REGULAR, + FONT_ITALICS, + FONT_BOLD, + FONT_BOLD_ITALICS, + FONT_COUNT }; - constexpr const Embed* FONTS[COUNT] = {&FONT_REGULAR_TTF, &FONT_ITALICS_TTF, &FONT_BOLD_TTF, &FONT_BOLD_ITALICS_TTF}; -} + constexpr const Embed* FONTS[FONT_COUNT] = {&FONT_REGULAR_TTF, &FONT_ITALICS_TTF, &FONT_BOLD_TTF, &FONT_BOLD_ITALICS_TTF}; -namespace anm2ed::resource -{ class Font { ImFont* pointer{}; @@ -36,4 +31,3 @@ namespace anm2ed::resource ImFont* get(); Font& operator=(Font&&) noexcept; }; -} diff --git a/src/framebuffer.cpp b/src/framebuffer.cpp index 54aa08b..43dde62 100644 --- a/src/framebuffer.cpp +++ b/src/framebuffer.cpp @@ -2,11 +2,8 @@ #include "texture.h" -using namespace anm2ed::resource; using namespace glm; -namespace anm2ed -{ Framebuffer::Framebuffer() { glGenFramebuffers(1, &fbo); @@ -60,7 +57,7 @@ namespace anm2ed std::vector Framebuffer::pixels_get() const { - auto count = size.x * size.y * image::CHANNELS; + auto count = size.x * size.y * IMAGE_CHANNELS; std::vector pixels(count); glReadBuffer(GL_COLOR_ATTACHMENT0); @@ -85,4 +82,3 @@ namespace anm2ed void Framebuffer::viewport_set() const { glViewport(0, 0, size.x, size.y); } void Framebuffer::bind() const { glBindFramebuffer(GL_FRAMEBUFFER, fbo); } void Framebuffer::unbind() const { glBindFramebuffer(GL_FRAMEBUFFER, 0); } -} diff --git a/src/framebuffer.h b/src/framebuffer.h index 6d72043..22c7110 100644 --- a/src/framebuffer.h +++ b/src/framebuffer.h @@ -3,8 +3,6 @@ #include #include -namespace anm2ed -{ class Framebuffer { public: @@ -35,4 +33,3 @@ namespace anm2ed void bind() const; void unbind() const; }; -}; diff --git a/src/friends.h b/src/friends.h index a4c9982..16dbdce 100644 --- a/src/friends.h +++ b/src/friends.h @@ -2,9 +2,7 @@ #include "embed.h" -namespace anm2ed::resource::friends -{ - struct Info + struct FriendInfo { const char* name{}; const Embed* png{}; @@ -12,22 +10,21 @@ namespace anm2ed::resource::friends }; #define FRIENDS_LIST \ - X(MEAT_BOY, "Meat Boy", FRIENDS_MEAT_BOY) \ - X(ISAAC, "Isaac", FRIENDS_ISAAC) \ - X(STACY, "Stacy", FRIENDS_STACY) \ - X(ASH, "Ash", FRIENDS_ASH) + X(FRIEND_MEAT_BOY, "Meat Boy", FRIENDS_MEAT_BOY) \ + X(FRIEND_ISAAC, "Isaac", FRIENDS_ISAAC) \ + X(FRIEND_STACY, "Stacy", FRIENDS_STACY) \ + X(FRIEND_ASH, "Ash", FRIENDS_ASH) - enum Type + enum Friend { #define X(symbol, name, embed) symbol, FRIENDS_LIST #undef X - COUNT + FRIEND_COUNT }; - constexpr Info FRIENDS[COUNT] = { + constexpr FriendInfo FRIENDS[FRIEND_COUNT] = { #define X(symbol, name, embed) {name, &embed##_PNG, &embed##_ANM2}, FRIENDS_LIST #undef X }; -} diff --git a/src/icon.h b/src/icon.h index ee88c73..ca1919c 100644 --- a/src/icon.h +++ b/src/icon.h @@ -2,78 +2,75 @@ #include "embed.h" #include -namespace anm2ed::resource::icon -{ - constexpr auto SIZE_SMALL = glm::ivec2(64, 64); - constexpr auto SIZE_NORMAL = glm::ivec2(128, 128); - constexpr auto SIZE_LARGE = glm::ivec2(256, 256); - constexpr auto SIZE_HUGE = glm::ivec2(512, 512); + constexpr auto ICON_SIZE_SMALL = glm::ivec2(64, 64); + constexpr auto ICON_SIZE_NORMAL = glm::ivec2(128, 128); + constexpr auto ICON_SIZE_LARGE = glm::ivec2(256, 256); + constexpr auto ICON_SIZE_HUGE = glm::ivec2(512, 512); #define SVG_LIST \ - X(NONE, &ICON_NONE_SVG, SIZE_SMALL) \ - X(FILE, &ICON_FILE_SVG, SIZE_NORMAL) \ - X(FOLDER, &ICON_FOLDER_SVG, SIZE_NORMAL) \ - X(FOLDER_OPEN, &ICON_FOLDER_OPEN_SVG, SIZE_NORMAL) \ - X(CLOSE, &ICON_CLOSE_SVG, SIZE_NORMAL) \ - X(ROOT, &ICON_ROOT_SVG, SIZE_NORMAL) \ - X(LAYER, &ICON_LAYER_SVG, SIZE_NORMAL) \ - X(NULL_, &ICON_NULL_SVG, SIZE_NORMAL) \ - X(SOUND, &ICON_SOUND_SVG, SIZE_NORMAL) \ - X(SHADER, &ICON_SHADER_SVG, SIZE_NORMAL) \ - X(TRIGGERS, &ICON_TRIGGERS_SVG, SIZE_NORMAL) \ - X(VISIBLE, &ICON_VISIBLE_SVG, SIZE_NORMAL) \ - X(INVISIBLE, &ICON_INVISIBLE_SVG, SIZE_NORMAL) \ - X(SHOW_RECT, &ICON_SHOW_RECT_SVG, SIZE_NORMAL) \ - X(HIDE_RECT, &ICON_HIDE_RECT_SVG, SIZE_NORMAL) \ - X(SHOW_UNUSED, &ICON_SHOW_UNUSED_SVG, SIZE_NORMAL) \ - X(HIDE_UNUSED, &ICON_HIDE_UNUSED_SVG, SIZE_NORMAL) \ - X(SHOW_LAYERS, &ICON_SHOW_LAYERS_SVG, SIZE_NORMAL) \ - X(HIDE_LAYERS, &ICON_HIDE_LAYERS_SVG, SIZE_NORMAL) \ - X(OVER, &ICON_OVER_SVG, SIZE_NORMAL) \ - X(UNDER, &ICON_UNDER_SVG, SIZE_NORMAL) \ - X(PAN, &ICON_PAN_SVG, SIZE_NORMAL) \ - X(MOVE, &ICON_MOVE_SVG, SIZE_NORMAL) \ - X(ROTATE, &ICON_ROTATE_SVG, SIZE_NORMAL) \ - X(SCALE, &ICON_SCALE_SVG, SIZE_NORMAL) \ - X(SKEW, &ICON_SKEW_SVG, SIZE_NORMAL) \ - X(CROP, &ICON_CROP_SVG, SIZE_NORMAL) \ - X(DRAW, &ICON_DRAW_SVG, SIZE_NORMAL) \ - X(ERASE, &ICON_ERASE_SVG, SIZE_NORMAL) \ - X(COLOR_PICKER, &ICON_COLOR_PICKER_SVG, SIZE_NORMAL) \ - X(UNDO, &ICON_UNDO_SVG, SIZE_NORMAL) \ - X(REDO, &ICON_REDO_SVG, SIZE_NORMAL) \ - X(ANIMATION, &ICON_ANIMATION_SVG, SIZE_NORMAL) \ - X(SPRITESHEET, &ICON_SPRITESHEET_SVG, SIZE_NORMAL) \ - X(EVENT, &ICON_EVENT_SVG, SIZE_NORMAL) \ - X(INTERPOLATED, &ICON_INTERPOLATED_SVG, SIZE_NORMAL) \ - X(UNINTERPOLATED, &ICON_UNINTERPOLATED_SVG, SIZE_NORMAL) \ - X(EASE_IN, &ICON_EASE_IN_SVG, SIZE_NORMAL) \ - X(EASE_OUT, &ICON_EASE_OUT_SVG, SIZE_NORMAL) \ - X(EASE_IN_OUT, &ICON_EASE_IN_OUT_SVG, SIZE_NORMAL) \ - X(TRIGGER, &ICON_TRIGGER_SVG, SIZE_NORMAL) \ - X(PLAYHEAD, &ICON_PLAYHEAD_SVG, SIZE_NORMAL) \ - X(PIVOT, &ICON_PIVOT_SVG, SIZE_NORMAL) \ - X(POINT, &ICON_UNINTERPOLATED_SVG, SIZE_NORMAL) \ - X(TARGET, &ICON_TARGET_SVG, SIZE_HUGE) \ - X(TARGET_ALT, &ICON_TARGET_ALT_SVG, SIZE_HUGE) + X(ICON_NONE, &ICON_NONE_SVG, ICON_SIZE_SMALL) \ + X(ICON_FILE, &ICON_FILE_SVG, ICON_SIZE_NORMAL) \ + X(ICON_FOLDER, &ICON_FOLDER_SVG, ICON_SIZE_NORMAL) \ + X(ICON_FOLDER_OPEN, &ICON_FOLDER_OPEN_SVG, ICON_SIZE_NORMAL) \ + X(ICON_CLOSE, &ICON_CLOSE_SVG, ICON_SIZE_NORMAL) \ + X(ICON_ROOT, &ICON_ROOT_SVG, ICON_SIZE_NORMAL) \ + X(ICON_LAYER, &ICON_LAYER_SVG, ICON_SIZE_NORMAL) \ + X(ICON_NULL, &ICON_NULL_SVG, ICON_SIZE_NORMAL) \ + X(ICON_SOUND, &ICON_SOUND_SVG, ICON_SIZE_NORMAL) \ + X(ICON_SHADER, &ICON_SHADER_SVG, ICON_SIZE_NORMAL) \ + X(ICON_TRIGGERS, &ICON_TRIGGERS_SVG, ICON_SIZE_NORMAL) \ + X(ICON_VISIBLE, &ICON_VISIBLE_SVG, ICON_SIZE_NORMAL) \ + X(ICON_INVISIBLE, &ICON_INVISIBLE_SVG, ICON_SIZE_NORMAL) \ + X(ICON_SHOW_RECT, &ICON_SHOW_RECT_SVG, ICON_SIZE_NORMAL) \ + X(ICON_HIDE_RECT, &ICON_HIDE_RECT_SVG, ICON_SIZE_NORMAL) \ + X(ICON_SHOW_UNUSED, &ICON_SHOW_UNUSED_SVG, ICON_SIZE_NORMAL) \ + X(ICON_HIDE_UNUSED, &ICON_HIDE_UNUSED_SVG, ICON_SIZE_NORMAL) \ + X(ICON_SHOW_LAYERS, &ICON_SHOW_LAYERS_SVG, ICON_SIZE_NORMAL) \ + X(ICON_HIDE_LAYERS, &ICON_HIDE_LAYERS_SVG, ICON_SIZE_NORMAL) \ + X(ICON_OVER, &ICON_OVER_SVG, ICON_SIZE_NORMAL) \ + X(ICON_UNDER, &ICON_UNDER_SVG, ICON_SIZE_NORMAL) \ + X(ICON_PAN, &ICON_PAN_SVG, ICON_SIZE_NORMAL) \ + X(ICON_MOVE, &ICON_MOVE_SVG, ICON_SIZE_NORMAL) \ + X(ICON_ROTATE, &ICON_ROTATE_SVG, ICON_SIZE_NORMAL) \ + X(ICON_SCALE, &ICON_SCALE_SVG, ICON_SIZE_NORMAL) \ + X(ICON_SKEW, &ICON_SKEW_SVG, ICON_SIZE_NORMAL) \ + X(ICON_CROP, &ICON_CROP_SVG, ICON_SIZE_NORMAL) \ + X(ICON_DRAW, &ICON_DRAW_SVG, ICON_SIZE_NORMAL) \ + X(ICON_ERASE, &ICON_ERASE_SVG, ICON_SIZE_NORMAL) \ + X(ICON_COLOR_PICKER, &ICON_COLOR_PICKER_SVG, ICON_SIZE_NORMAL) \ + X(ICON_UNDO, &ICON_UNDO_SVG, ICON_SIZE_NORMAL) \ + X(ICON_REDO, &ICON_REDO_SVG, ICON_SIZE_NORMAL) \ + X(ICON_ANIMATION, &ICON_ANIMATION_SVG, ICON_SIZE_NORMAL) \ + X(ICON_SPRITESHEET, &ICON_SPRITESHEET_SVG, ICON_SIZE_NORMAL) \ + X(ICON_EVENT, &ICON_EVENT_SVG, ICON_SIZE_NORMAL) \ + X(ICON_INTERPOLATED, &ICON_INTERPOLATED_SVG, ICON_SIZE_NORMAL) \ + X(ICON_UNINTERPOLATED, &ICON_UNINTERPOLATED_SVG, ICON_SIZE_NORMAL) \ + X(ICON_EASE_IN, &ICON_EASE_IN_SVG, ICON_SIZE_NORMAL) \ + X(ICON_EASE_OUT, &ICON_EASE_OUT_SVG, ICON_SIZE_NORMAL) \ + X(ICON_EASE_IN_OUT, &ICON_EASE_IN_OUT_SVG, ICON_SIZE_NORMAL) \ + X(ICON_TRIGGER, &ICON_TRIGGER_SVG, ICON_SIZE_NORMAL) \ + X(ICON_PLAYHEAD, &ICON_PLAYHEAD_SVG, ICON_SIZE_NORMAL) \ + X(ICON_PIVOT, &ICON_PIVOT_SVG, ICON_SIZE_NORMAL) \ + X(ICON_POINT, &ICON_UNINTERPOLATED_SVG, ICON_SIZE_NORMAL) \ + X(ICON_TARGET, &ICON_TARGET_SVG, ICON_SIZE_HUGE) \ + X(ICON_TARGET_ALT, &ICON_TARGET_ALT_SVG, ICON_SIZE_HUGE) - enum Type + enum Icon { #define X(name, data, size) name, SVG_LIST #undef X - COUNT + ICON_COUNT }; - struct Info + struct IconInfo { const Embed* svg{}; glm::ivec2 size{}; }; - constexpr Info ICONS[COUNT] = { + constexpr IconInfo ICONS[ICON_COUNT] = { #define X(name, data, size) {data, size}, SVG_LIST #undef X }; -} diff --git a/src/image.cpp b/src/image.cpp index 9c5bf48..0f8ae94 100644 --- a/src/image.cpp +++ b/src/image.cpp @@ -36,13 +36,8 @@ #include "path.h" #include "uid.h" -using namespace anm2ed::resource::image; -using namespace anm2ed::util::math; -using namespace anm2ed::util; using namespace glm; -namespace anm2ed::resource -{ constexpr std::size_t BASE64_GROUP_BYTES = 3; constexpr int BASE64_DIGIT_BITS = 6; constexpr std::uint32_t BASE64_DIGIT_MASK = 0x3F; @@ -70,13 +65,13 @@ namespace anm2ed::resource // Closes the hairline seams an SVG's anti-aliasing leaves where two shapes meet: a partly covered pixel with opaque // pixels on both sides of it (along any axis, within SEAM_REACH) takes their color over its own and becomes opaque. // Outer edges, with transparency on one side, keep their anti-aliasing. - void seams_fill(Image& image) + static void seams_fill(Image& image) { constexpr glm::ivec2 AXES[] = {{1, 0}, {0, 1}, {1, 1}, {1, -1}}; // Coverage as drawn (filling only ever raises it, and only on partly covered pixels, whose colors no check reads). std::vector alphas((std::size_t)image.size.x * image.size.y); for (std::size_t i = 0; i < alphas.size(); ++i) - alphas[i] = image.pixels[i * CHANNELS + ALPHA]; + alphas[i] = image.pixels[i * IMAGE_CHANNELS + ALPHA]; auto index_get = [&](glm::ivec2 point) { return (std::size_t)point.y * image.size.x + point.x; }; auto opaque_get = [&](glm::ivec2 point, glm::ivec2 step) -> const uint8_t* { @@ -86,7 +81,7 @@ namespace anm2ed::resource if (glm::any(glm::lessThan(neighbor, glm::ivec2(0))) || glm::any(glm::greaterThanEqual(neighbor, image.size))) return nullptr; if (alphas[index_get(neighbor)] >= SEAM_OPAQUE_ALPHA) - return image.pixels.data() + index_get(neighbor) * CHANNELS; + return image.pixels.data() + index_get(neighbor) * IMAGE_CHANNELS; } return nullptr; }; @@ -101,7 +96,7 @@ namespace anm2ed::resource auto before = opaque_get({x, y}, -axis); auto after = before ? opaque_get({x, y}, axis) : nullptr; if (!after) continue; - auto pixel = image.pixels.data() + index_get({x, y}) * CHANNELS; + auto pixel = image.pixels.data() + index_get({x, y}) * IMAGE_CHANNELS; auto coverage = alpha / (float)UINT8_MAX; for (int channel = 0; channel < ALPHA; ++channel) pixel[channel] = (uint8_t)std::round(pixel[channel] * coverage + @@ -113,7 +108,7 @@ namespace anm2ed::resource } // An SVG drawn at about `scale` pixels per unit (exactly, after rounding to whole pixels); nothing if it won't parse. - Image svg_render(std::shared_ptr svg, float scale) + static Image svg_render(std::shared_ptr svg, float scale) { auto document = svg ? lunasvg::Document::loadFromData(*svg) : nullptr; if (!document || document->width() <= 0.0f) return {}; @@ -130,7 +125,7 @@ namespace anm2ed::resource Image Image::vector_render(float scale) const { return svg_render(svg, scale); } - size_t Image::pixel_size_get() const { return size.x * size.y * CHANNELS; } + size_t Image::pixel_size_get() const { return size.x * size.y * IMAGE_CHANNELS; } Image::Image(const uint8_t* data, ivec2 size, bool isLinear) : isLinear(isLinear) { @@ -147,7 +142,7 @@ namespace anm2ed::resource auto sizeInt = static_cast(pngSize); if (sizeInt <= 0) return; - if (auto data = stbi_load_from_memory(pngData, sizeInt, &size.x, &size.y, nullptr, CHANNELS); data) + if (auto data = stbi_load_from_memory(pngData, sizeInt, &size.x, &size.y, nullptr, IMAGE_CHANNELS); data) { *this = Image(data, size); stbi_image_free((void*)data); @@ -158,7 +153,7 @@ namespace anm2ed::resource Image::Image(const std::filesystem::path& path) { auto text = std::make_shared(); - if (!file::read_to_string(path, text.get())) return; + if (!file_text_load(path, text.get())) return; *this = Image((const unsigned char*)text->data(), text->size()); if (!is_valid()) *this = svg_render(std::move(text), 1.0f); } @@ -177,13 +172,13 @@ namespace anm2ed::resource { auto write_func = [](void* context, void* bytes, int count) { fwrite(bytes, 1, count, static_cast(context)); }; - return stbi_write_png_to_func(write_func, handle, size.x, size.y, CHANNELS, data, size.x * CHANNELS) != 0; + return stbi_write_png_to_func(write_func, handle, size.x, size.y, IMAGE_CHANNELS, data, size.x * IMAGE_CHANNELS) != 0; } return false; } // Copies a size-sized block between images; pixels outside either image are skipped. - void pixels_copy(const Image& from, glm::ivec2 fromMin, Image& to, glm::ivec2 toMin, glm::ivec2 size) + static void pixels_copy(const Image& from, glm::ivec2 fromMin, Image& to, glm::ivec2 toMin, glm::ivec2 size) { for (int y = 0; y < size.y; ++y) for (int x = 0; x < size.x; ++x) @@ -193,9 +188,9 @@ namespace anm2ed::resource if (glm::any(glm::lessThan(source, glm::ivec2(0))) || glm::any(glm::greaterThanEqual(source, from.size)) || glm::any(glm::lessThan(target, glm::ivec2(0))) || glm::any(glm::greaterThanEqual(target, to.size))) continue; - std::copy_n(from.pixels.data() + ((std::size_t)source.y * from.size.x + source.x) * image::CHANNELS, - image::CHANNELS, - to.pixels.data() + ((std::size_t)target.y * to.size.x + target.x) * image::CHANNELS); + std::copy_n(from.pixels.data() + ((std::size_t)source.y * from.size.x + source.x) * IMAGE_CHANNELS, + IMAGE_CHANNELS, + to.pixels.data() + ((std::size_t)target.y * to.size.x + target.x) * IMAGE_CHANNELS); } } @@ -206,13 +201,13 @@ namespace anm2ed::resource { Image region{}; region.size = regionSize; - region.pixels.assign((std::size_t)regionSize.x * regionSize.y * image::CHANNELS, 0); + region.pixels.assign((std::size_t)regionSize.x * regionSize.y * IMAGE_CHANNELS, 0); pixels_copy(*this, min, region, {}, regionSize); return region; } // Base64 of bytes, for an image embedded in an SVG. - std::string base64_get(const std::vector& bytes) + static std::string base64_get(const std::vector& bytes) { std::string text{}; for (std::size_t i = 0; i < bytes.size(); i += BASE64_GROUP_BYTES) @@ -230,7 +225,7 @@ namespace anm2ed::resource } // Sets an attribute, adding it when the element doesn't have it yet. - template void attribute_set(pugi::xml_node element, const char* name, const T& value) + template static void attribute_set(pugi::xml_node element, const char* name, const T& value) { auto attribute = element.attribute(name); (attribute ? attribute : element.append_attribute(name)).set_value(value); @@ -239,7 +234,7 @@ namespace anm2ed::resource // An image as one SVG definition: a vector one as a symbol of its drawing (its ids prefixed with `id`, so // several drawings can share a document), a raster one as an embedded PNG. Either draws at the image's size in // SVG units. - void svg_definition_add(pugi::xml_node root, pugi::xml_node defs, const Image& image, const std::string& id) + static void svg_definition_add(pugi::xml_node root, pugi::xml_node defs, const Image& image, const std::string& id) { if (!image.is_vector()) { @@ -250,7 +245,7 @@ namespace anm2ed::resource static_cast*>(context)->insert(static_cast*>(context)->end(), (uint8_t*)data, (uint8_t*)data + count); }, - &png, image.size.x, image.size.y, CHANNELS, image.pixels.data(), image.size.x * CHANNELS); + &png, image.size.x, image.size.y, IMAGE_CHANNELS, image.pixels.data(), image.size.x * IMAGE_CHANNELS); auto element = defs.append_child("image"); element.append_attribute("id") = id.c_str(); element.append_attribute("width") = image.size.x; @@ -335,7 +330,7 @@ namespace anm2ed::resource { if (!isVector) { - std::vector pixels((std::size_t)size.x * size.y * CHANNELS, 0); + std::vector pixels((std::size_t)size.x * size.y * IMAGE_CHANNELS, 0); Image composed(pixels.data(), size); for (const auto& part : parts) composed.paste(part.image->region_get(part.source, part.size), part.destination); @@ -382,19 +377,19 @@ namespace anm2ed::resource // Writes a vector image as its SVG (unless the path asks for a PNG), and any other as a PNG. bool Image::write(const std::filesystem::path& path) const { - if (is_vector() && !path::is_extension(path, PNG_EXTENSION)) return file::write_string(path, *svg); + if (is_vector() && !is_path_extension(path, PNG_EXTENSION)) return file_text_save(path, *svg); return write_png(path); } vec4 Image::pixel_read(vec2 position) const { - if (pixels.size() < CHANNELS || size.x <= 0 || size.y <= 0) return vec4(0.0f); + if (pixels.size() < IMAGE_CHANNELS || size.x <= 0 || size.y <= 0) return vec4(0.0f); int x = glm::clamp((int)(position.x), 0, size.x - 1); int y = glm::clamp((int)(position.y), 0, size.y - 1); - auto index = ((size_t)(y) * (size_t)(size.x) + (size_t)(x)) * CHANNELS; - if (index + CHANNELS > pixels.size()) return vec4(0.0f); + auto index = ((size_t)(y) * (size_t)(size.x) + (size_t)(x)) * IMAGE_CHANNELS; + if (index + IMAGE_CHANNELS > pixels.size()) return vec4(0.0f); vec4 color{uint8_to_float(pixels[index + 0]), uint8_to_float(pixels[index + 1]), uint8_to_float(pixels[index + 2]), uint8_to_float(pixels[index + 3])}; @@ -411,7 +406,7 @@ namespace anm2ed::resource (uint8)float_to_uint8(color.a)}; if (pixels.size() != pixel_size_get()) return; - size_t idx = (position.y * size.x + position.x) * CHANNELS; + size_t idx = (position.y * size.x + position.x) * IMAGE_CHANNELS; memcpy(&pixels[idx], rgba8, 4); uid = uid_next(); } @@ -448,4 +443,3 @@ namespace anm2ed::resource } } } -} diff --git a/src/image.h b/src/image.h index 1c04578..d93fc8f 100644 --- a/src/image.h +++ b/src/image.h @@ -9,15 +9,10 @@ #include -namespace anm2ed::resource::image -{ - constexpr auto CHANNELS = 4; + constexpr auto IMAGE_CHANNELS = 4; constexpr auto SVG_EXTENSION = "svg"; constexpr auto PNG_EXTENSION = "png"; -} -namespace anm2ed::resource -{ class Image; // A block of an image placed at `destination`, for composing images. @@ -61,4 +56,3 @@ namespace anm2ed::resource void pixel_set(glm::ivec2, glm::vec4); void pixel_line(glm::ivec2, glm::ivec2, glm::vec4); }; -} diff --git a/src/loader.cpp b/src/loader.cpp index ee963d4..33414f8 100644 --- a/src/loader.cpp +++ b/src/loader.cpp @@ -24,11 +24,6 @@ #include #endif -using namespace anm2ed::types; -using namespace anm2ed::util; - -namespace anm2ed -{ constexpr auto WINDOW_4K_SIZE = glm::ivec2(3840, 2160); constexpr auto UI_SCALE_4K_DEFAULT = 150.0f; constexpr auto WINDOW_DEFAULT_SIZE_MULTIPLIER = 0.90f; @@ -44,7 +39,7 @@ namespace anm2ed constexpr int SOCKET_ERROR_ADDRESS_IN_USE = EADDRINUSE; #endif - bool socket_paths_send(Socket& socket, const std::vector& paths) + static bool socket_paths_send(Socket& socket, const std::vector& paths) { uint32_t count = htonl(static_cast(paths.size())); if (!socket.send(&count, sizeof(count))) return false; @@ -59,7 +54,7 @@ namespace anm2ed return true; } - std::vector socket_paths_receive(Socket& socket) + static std::vector socket_paths_receive(Socket& socket) { uint32_t count{}; if (!socket.receive(&count, sizeof(count))) return {}; @@ -84,7 +79,7 @@ namespace anm2ed return paths; } - std::filesystem::path Loader::settings_path() { return sdl::preferences_directory_get() / "settings.ini"; } + std::filesystem::path Loader::settings_path() { return preferences_directory_get() / "settings.ini"; } Loader::Loader(int argc, const char** argv) { @@ -226,7 +221,7 @@ namespace anm2ed glDisable(GL_DEPTH_TEST); glDisable(GL_LINE_SMOOTH); - math::random_seed_set(); + random_seed_set(); IMGUI_CHECKVERSION(); if (!ImGui::CreateContext()) @@ -238,7 +233,7 @@ namespace anm2ed logger.info("Initialized Dear ImGui"); - imgui::theme_set((imgui::theme::Type)settings.theme); + theme_set((Theme)settings.theme); ImGui_ImplSDL3_InitForOpenGL(window, glContext); ImGui_ImplOpenGL3_Init("#version 330"); @@ -250,7 +245,7 @@ namespace anm2ed io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; io.KeyRepeatDelay = settings.keyboardRepeatDelay; io.KeyRepeatRate = settings.keyboardRepeatRate; - ImGui::GetStyle().FontScaleMain = math::percent_to_unit(settings.uiScale); + ImGui::GetStyle().FontScaleMain = percent_to_unit(settings.uiScale); io.ConfigWindowsMoveFromTitleBarOnly = true; if (auto imguiData = Settings::imgui_data_load(settings_path()); !imguiData.empty()) @@ -319,7 +314,7 @@ namespace anm2ed if (ImGui::GetCurrentContext()) { settings.save(settings_path(), ImGui::SaveIniSettingsToMemory(nullptr)); - resource::texture::garbage_collect(); + texture_garbage_collect(); ImGui_ImplSDL3_Shutdown(); ImGui_ImplOpenGL3_Shutdown(); @@ -335,4 +330,3 @@ namespace anm2ed SDL_Quit(); } } -} diff --git a/src/loader.h b/src/loader.h index 5caeaeb..9dc5564 100644 --- a/src/loader.h +++ b/src/loader.h @@ -10,8 +10,6 @@ #include "settings.h" #include "socket.h" -namespace anm2ed -{ class Loader { std::filesystem::path settings_path(); @@ -30,4 +28,3 @@ namespace anm2ed Loader(int, const char**); ~Loader(); }; -} diff --git a/src/localization.h b/src/localization.h index 6125914..ef53b92 100644 --- a/src/localization.h +++ b/src/localization.h @@ -3,8 +3,6 @@ #include #include -namespace anm2ed -{ #define SELECT_ENGLISH(symbol, english, spanish, russian, chinese, korean) english, #define SELECT_SPANISH(symbol, english, spanish, russian, chinese, korean) spanish, #define SELECT_RUSSIAN(symbol, english, spanish, russian, chinese, korean) russian, @@ -914,15 +912,11 @@ namespace anm2ed return LANGUAGE_STRING_COLLECTIONS[useLanguage][type]; } }; -} -inline anm2ed::Localizer localize; +inline Localizer localize; -namespace anm2ed -{ // A localized format string filled with arguments. template std::string localize_format(StringType format, Args... args) { return std::vformat(localize.get(format), std::make_format_args(args...)); } -} diff --git a/src/log.cpp b/src/log.cpp index 87aa2dc..3ec120d 100644 --- a/src/log.cpp +++ b/src/log.cpp @@ -21,12 +21,6 @@ #include #endif -using namespace anm2ed::util; - -namespace anm2ed -{ - namespace log - { constexpr auto SESSION_LIMIT = 10; constexpr std::uintmax_t DIRECTORY_SIZE_LIMIT = 100ull * 1024ull * 1024ull; constexpr std::uintmax_t SESSION_SIZE_LIMIT = 25ull * 1024ull * 1024ull; @@ -38,7 +32,7 @@ namespace anm2ed std::uintmax_t size{}; }; - std::uint32_t process_id_get() + static std::uint32_t process_id_get() { #if _WIN32 return (std::uint32_t)_getpid(); @@ -47,13 +41,13 @@ namespace anm2ed #endif } - std::filesystem::path session_path_get(const std::filesystem::path& directory) + static std::filesystem::path session_path_get(const std::filesystem::path& directory) { - auto name = std::format("anm2ed_{}_{}.log", time::get("%Y-%m-%d_%H-%M-%S"), process_id_get()); - return directory / "logs" / path::from_utf8(name); + auto name = std::format("anm2ed_{}_{}.log", timestamp_get("%Y-%m-%d_%H-%M-%S"), process_id_get()); + return directory / "logs" / path_from_utf8(name); } - std::vector session_files_get(const std::filesystem::path& directory, + static std::vector session_files_get(const std::filesystem::path& directory, const std::filesystem::path& currentPath) { std::vector files{}; @@ -82,14 +76,14 @@ namespace anm2ed return files; } - void session_file_remove(const SessionFile& file, std::uintmax_t& totalSize) + static void session_file_remove(const SessionFile& file, std::uintmax_t& totalSize) { std::error_code ec{}; std::filesystem::remove(file.path, ec); if (!ec && totalSize >= file.size) totalSize -= file.size; } - void sessions_prune(const std::filesystem::path& directory, const std::filesystem::path& currentPath) + static void sessions_prune(const std::filesystem::path& directory, const std::filesystem::path& currentPath) { auto files = session_files_get(directory, currentPath); std::sort(files.begin(), files.end(), @@ -112,7 +106,7 @@ namespace anm2ed } } - void legacy_log_remove(const std::filesystem::path& currentPath) + static void legacy_log_remove(const std::filesystem::path& currentPath) { auto directory = currentPath.parent_path().parent_path(); if (directory.empty()) return; @@ -123,7 +117,6 @@ namespace anm2ed std::error_code ec{}; std::filesystem::remove(legacyPath, ec); } - } void Logger::write_raw(const std::string& message) { @@ -140,18 +133,18 @@ namespace anm2ed try { auto lineSize = (std::uintmax_t)message.size() + 1; - auto isLineWithinLimit = logSize <= log::SESSION_SIZE_LIMIT && lineSize <= log::SESSION_SIZE_LIMIT - logSize; + auto isLineWithinLimit = logSize <= SESSION_SIZE_LIMIT && lineSize <= SESSION_SIZE_LIMIT - logSize; if (isLineWithinLimit) { auto line = message + '\n'; - if (file::write_string(logPath, line, "ab")) logSize += line.size(); + if (file_text_save(logPath, line, "ab")) logSize += line.size(); } else if (!isLogLimitReached) { std::string line = "[WARNING] Session log size limit reached; suppressing further file logs for this session.\n"; - if (logSize + line.size() <= log::SESSION_SIZE_LIMIT) - if (file::write_string(logPath, line, "ab")) logSize += line.size(); + if (logSize + line.size() <= SESSION_SIZE_LIMIT) + if (file_text_save(logPath, line, "ab")) logSize += line.size(); isLogLimitReached = true; } } @@ -163,7 +156,7 @@ namespace anm2ed void Logger::write(const Level level, const std::string& message) { - std::string formatted = std::format("{} {} {}", LEVEL_STRINGS[level], time::get("(%d-%B-%Y %I:%M:%S)"), message); + std::string formatted = std::format("{} {} {}", LEVEL_STRINGS[level], timestamp_get("(%d-%B-%Y %I:%M:%S)"), message); write_raw(formatted); } @@ -276,11 +269,11 @@ namespace anm2ed std::error_code ec{}; auto directory = logPath.parent_path(); if (!directory.empty()) std::filesystem::create_directories(directory, ec); - log::legacy_log_remove(logPath); - log::sessions_prune(directory, logPath); + legacy_log_remove(logPath); + sessions_prune(directory, logPath); logSize = std::filesystem::file_size(logPath, ec); if (ec) logSize = 0; - isLogLimitReached = logSize >= log::SESSION_SIZE_LIMIT; + isLogLimitReached = logSize >= SESSION_SIZE_LIMIT; } stderr_redirect_start(); } @@ -289,7 +282,7 @@ namespace anm2ed void Logger::session_open(const std::filesystem::path& directory) { - open(log::session_path_get(directory)); + open(session_path_get(directory)); info(std::format("Initializing {}", localize.get(LABEL_APPLICATION_NAME, ENGLISH))); } @@ -319,6 +312,5 @@ namespace anm2ed return EXIT_FAILURE; } -} -anm2ed::Logger logger; +Logger logger; diff --git a/src/log.h b/src/log.h index 29851f1..3b745f1 100644 --- a/src/log.h +++ b/src/log.h @@ -8,8 +8,6 @@ #include #include -namespace anm2ed -{ #if defined(INFO) #undef INFO #endif @@ -77,6 +75,4 @@ namespace anm2ed int log_exceptions(const std::function&); -} - -extern anm2ed::Logger logger; +extern Logger logger; diff --git a/src/main.cpp b/src/main.cpp index a6b407c..2aa5720 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -15,8 +15,6 @@ #endif #ifdef _WIN32 -namespace anm2ed::main -{ struct CommandLineArguments { std::vector strings{}; @@ -57,14 +55,11 @@ namespace anm2ed::main return arguments; } -} #endif -namespace anm2ed -{ - int application_run(int argc, const char** argv) + static int application_run(int argc, const char** argv) { - if (cli::is_cli(argc, argv)) + if (is_cli(argc, argv)) { #ifdef _WIN32 // A GUI-subsystem build has no console of its own; print to the one it was started from. @@ -74,10 +69,10 @@ namespace anm2ed freopen("CONOUT$", "w", stderr); } #endif - return cli::run(argc, argv); + return cli_run(argc, argv); } - logger.session_open(util::sdl::preferences_directory_get()); + logger.session_open(preferences_directory_get()); return log_exceptions( [&]() { @@ -93,22 +88,21 @@ namespace anm2ed return EXIT_SUCCESS; }); } -} int main(int argc, const char** argv) { #ifdef _WIN32 - auto arguments = anm2ed::main::command_line_arguments_get(); + auto arguments = command_line_arguments_get(); if (!arguments.pointers.empty()) - return anm2ed::application_run((int)arguments.pointers.size(), arguments.pointers.data()); + return application_run((int)arguments.pointers.size(), arguments.pointers.data()); #endif - return anm2ed::application_run(argc, argv); + return application_run(argc, argv); } #ifdef _WIN32 int APIENTRY WinMain(HINSTANCE, HINSTANCE, LPSTR, int) { - auto arguments = anm2ed::main::command_line_arguments_get(); - return anm2ed::application_run((int)arguments.pointers.size(), arguments.pointers.data()); + auto arguments = command_line_arguments_get(); + return application_run((int)arguments.pointers.size(), arguments.pointers.data()); } #endif diff --git a/src/manager.cpp b/src/manager.cpp index e287051..2079ef0 100644 --- a/src/manager.cpp +++ b/src/manager.cpp @@ -16,61 +16,56 @@ #include "ui/shortcut.h" #include "vector.h" -using namespace anm2ed::types; -using namespace anm2ed::util; - -namespace anm2ed -{ constexpr std::size_t RECENT_LIMIT = 10; - void ensure_parent_directory_exists(const std::filesystem::path& path) + static void ensure_parent_directory_exists(const std::filesystem::path& path) { auto parent = path.parent_path(); if (parent.empty()) return; std::error_code ec{}; std::filesystem::create_directories(parent, ec); - if (ec) logger.warning(std::format("Could not create directory for {}: {}", path::to_utf8(path), ec.message())); + if (ec) logger.warning(std::format("Could not create directory for {}: {}", path_to_utf8(path), ec.message())); } - void autosave_file_remove(const std::filesystem::path& path) + static void autosave_file_remove(const std::filesystem::path& path) { if (path.empty()) return; std::error_code ec{}; std::filesystem::remove(path, ec); - if (ec) logger.warning(std::format("Could not remove autosave file {}: {}", path::to_utf8(path), ec.message())); + if (ec) logger.warning(std::format("Could not remove autosave file {}: {}", path_to_utf8(path), ec.message())); } - std::vector path_list_load(const std::filesystem::path& path, std::string_view name) + static std::vector path_list_load(const std::filesystem::path& path, std::string_view name) { std::string fileData{}; - if (!file::read_to_string(path, &fileData, "rb")) + if (!file_text_load(path, &fileData, "rb")) { - logger.warning(std::format("Could not load {} from: {}. Skipping...", name, path::to_utf8(path))); + logger.warning(std::format("Could not load {} from: {}. Skipping...", name, path_to_utf8(path))); return {}; } - logger.info(std::format("Loading {} from: {}", name, path::to_utf8(path))); + logger.info(std::format("Loading {} from: {}", name, path_to_utf8(path))); std::vector result{}; std::istringstream file(fileData); for (std::string line{}; std::getline(file, line);) { if (!line.empty() && line.back() == '\r') line.pop_back(); - auto entry = path::from_utf8(line); + auto entry = path_from_utf8(line); if (!line.empty() && std::ranges::find(result, entry) == result.end()) result.push_back(entry); } return result; } - void path_list_save(const std::filesystem::path& path, const std::vector& entries, + static void path_list_save(const std::filesystem::path& path, const std::vector& entries, std::string_view name) { ensure_parent_directory_exists(path); std::ostringstream file{}; for (auto& entry : entries) - file << path::to_utf8(entry) << '\n'; - if (!file::write_string(path, file.str(), "wb")) - logger.warning(std::format("Could not write {} to: {}. Skipping...", name, path::to_utf8(path))); + file << path_to_utf8(entry) << '\n'; + if (!file_text_save(path, file.str(), "wb")) + logger.warning(std::format("Could not write {} to: {}. Skipping...", name, path_to_utf8(path))); } void Manager::selection_history_push(int index) @@ -100,8 +95,8 @@ namespace anm2ed if (documents.empty()) selectionHistory.clear(); } - std::filesystem::path Manager::recent_files_path_get() { return sdl::preferences_directory_get() / "recent.txt"; } - std::filesystem::path Manager::autosave_path_get() { return sdl::preferences_directory_get() / "autosave.txt"; } + std::filesystem::path Manager::recent_files_path_get() { return preferences_directory_get() / "recent.txt"; } + std::filesystem::path Manager::autosave_path_get() { return preferences_directory_get() / "autosave.txt"; } Manager::Manager() { @@ -109,7 +104,7 @@ namespace anm2ed autosave_files_load(); } - Document* Manager::get(int index) { return vector::find(documents, index > -1 ? index : selected); } + Document* Manager::get(int index) { return vector_find(documents, index > -1 ? index : selected); } void Manager::command_push(Command command) { @@ -137,7 +132,7 @@ namespace anm2ed { std::string errorString{}; documents.emplace_back(path, isNew, &errorString); - auto pathString = path::to_utf8(path); + auto pathString = path_to_utf8(path); auto& document = documents.back(); if (!document.is_valid()) @@ -216,7 +211,7 @@ namespace anm2ed void Manager::close(int index) { - if (!vector::in_bounds(documents, index)) return; + if (!is_vector_in_bounds(documents, index)) return; documents.erase(documents.begin() + index); selection_history_cleanup(index); @@ -290,11 +285,11 @@ namespace anm2ed auto parent = get(index); auto animation = parent ? parent->model.animation_get(layerTrack.animationIndex) : nullptr; auto track = parent ? parent->model.track_get(layerTrack) : nullptr; - auto layer = parent ? model::item_get(parent->model.content.layers, layerTrack.itemID) : nullptr; + auto layer = parent ? item_get(parent->model.content.layers, layerTrack.itemID) : nullptr; if (!animation || !track || !layer || !layer->is_animation()) return; auto time = parent->frameTime > -1 && !parent->playback.isPlaying ? parent->frameTime : parent->playback.time; auto [childModel, childAnimation] = - model::child_get(parent->model, *layer, model::frame_generate(*track, time), parent->library_resolver_get()); + child_get(parent->model, *layer, frame_generate(*track, time), parent->library_resolver_get()); if (!childAnimation) return; auto steps = parent->childSteps; @@ -304,7 +299,7 @@ namespace anm2ed .layer = layerTrack, .animationName = animation->name, .layerName = layer->name}); - auto childTime = model::child_time_get(*track, time, childAnimation->frameNum, layer->id); + auto childTime = child_time_get(*track, time, childAnimation->frameNum, layer->id); auto childName = childAnimation->name; parent->playback.isPlaying = false; auto targetIndex = index; @@ -354,8 +349,8 @@ namespace anm2ed if (!document || (type != ElementType::LAYER_ELEMENT && type != ElementType::NULL_ELEMENT)) return; auto isLayer = type == ElementType::LAYER_ELEMENT; auto& content = document->model.content; - auto layer = isLayer ? model::item_get(content.layers, id) : nullptr; - auto null = isLayer ? nullptr : model::item_get(content.nulls, id); + auto layer = isLayer ? item_get(content.layers, id) : nullptr; + auto null = isLayer ? nullptr : item_get(content.nulls, id); if (id != -1 && !layer && !null) return; itemEdit = layer ? ItemEdit{.id = id, .name = layer->name, @@ -388,7 +383,7 @@ namespace anm2ed std::vector ordered; ordered.reserve(orderedEntries.size()); for (const auto& [pathString, _] : orderedEntries) - ordered.emplace_back(path::from_utf8(pathString)); + ordered.emplace_back(path_from_utf8(pathString)); return ordered; } @@ -398,11 +393,11 @@ namespace anm2ed std::error_code ec{}; if (!std::filesystem::exists(path, ec)) { - logger.warning(std::format("Skipping missing recent file: {}", path::to_utf8(path))); + logger.warning(std::format("Skipping missing recent file: {}", path_to_utf8(path))); return; } - recentFiles[path::to_utf8(path)] = ++recentFilesCounter; + recentFiles[path_to_utf8(path)] = ++recentFilesCounter; recent_files_trim(); recent_files_write(); } @@ -416,9 +411,9 @@ namespace anm2ed { std::error_code ec{}; if (std::filesystem::exists(*it, ec)) - recentFiles[path::to_utf8(*it)] = ++recentFilesCounter; + recentFiles[path_to_utf8(*it)] = ++recentFilesCounter; else - logger.warning(std::format("Skipping missing recent file: {}", path::to_utf8(*it))); + logger.warning(std::format("Skipping missing recent file: {}", path_to_utf8(*it))); } recent_files_trim(); } @@ -472,8 +467,7 @@ namespace anm2ed { saveOptions = {.isJson = settings.fileIsJson}; for (int i = 0; i < SHORTCUT_COUNT; i++) - chords[i] = imgui::string_to_chord(settings.*SHORTCUT_MEMBERS[i]); + chords[i] = string_to_chord(settings.*SHORTCUT_MEMBERS[i]); } Manager::~Manager() = default; -} diff --git a/src/manager.h b/src/manager.h index 507ae9c..07a9f34 100644 --- a/src/manager.h +++ b/src/manager.h @@ -13,8 +13,6 @@ #include "localization.h" #include "ui/popup.h" -namespace anm2ed -{ constexpr auto FILE_LABEL_FORMAT = "{} [{}]"; class Manager; @@ -57,10 +55,10 @@ namespace anm2ed std::vector anm2DragDropPaths{}; bool isAnm2DragDrop{}; int anm2DragDropMergePreset{FILE_MERGE_PRESET_MERGE_BY_NAME}; - imgui::PopupHelper anm2DragDropPopup{ - imgui::PopupHelper(LABEL_MANAGER_ANM2_DRAG_DROP, imgui::POPUP_NORMAL, imgui::POPUP_BY_CURSOR)}; - imgui::PopupHelper anm2DragDropMergePopup{ - imgui::PopupHelper(LABEL_DOCUMENTS_MERGE_INTO_CURRENT, imgui::POPUP_SMALL_NO_HEIGHT)}; + PopupHelper anm2DragDropPopup{ + PopupHelper(LABEL_MANAGER_ANM2_DRAG_DROP, POPUP_NORMAL, POPUP_BY_CURSOR)}; + PopupHelper anm2DragDropMergePopup{ + PopupHelper(LABEL_DOCUMENTS_MERGE_INTO_CURRENT, POPUP_SMALL_NO_HEIGHT)}; std::filesystem::path spritesheetDragDropPath{}; bool isSpritesheetDragDrop{}; @@ -75,16 +73,16 @@ namespace anm2ed int libraryId{-1}; std::string animation{}; } itemEdit{}; - imgui::PopupHelper itemPropertiesPopups[2]{ - imgui::PopupHelper(LABEL_MANAGER_LAYER_PROPERTIES, imgui::POPUP_SMALL_NO_HEIGHT), - imgui::PopupHelper(LABEL_MANAGER_NULL_PROPERTIES, imgui::POPUP_SMALL_NO_HEIGHT)}; + PopupHelper itemPropertiesPopups[2]{ + PopupHelper(LABEL_MANAGER_LAYER_PROPERTIES, POPUP_SMALL_NO_HEIGHT), + PopupHelper(LABEL_MANAGER_NULL_PROPERTIES, POPUP_SMALL_NO_HEIGHT)}; - model::Region makeRegion{}; + Region makeRegion{}; int makeRegionSpritesheetId{-1}; bool isMakeRegionRequested{}; - imgui::PopupHelper progressPopup{ - imgui::PopupHelper(LABEL_MANAGER_RENDERING_PROGRESS, imgui::POPUP_SMALL_NO_HEIGHT)}; + PopupHelper progressPopup{ + PopupHelper(LABEL_MANAGER_RENDERING_PROGRESS, POPUP_SMALL_NO_HEIGHT)}; std::vector selectionHistory{}; @@ -122,4 +120,3 @@ namespace anm2ed void settings_apply(Settings&); }; -} diff --git a/src/math_util.cpp b/src/math_util.cpp index 8a3cf9d..7c0ae86 100644 --- a/src/math_util.cpp +++ b/src/math_util.cpp @@ -6,8 +6,6 @@ using namespace glm; -namespace anm2ed::util::math -{ constexpr auto FLOAT_FORMAT_MAX_DECIMALS = 7; constexpr auto FLOAT_FORMAT_EPSILON = 1e-7f; constexpr float FLOAT_FORMAT_POW10[] = {1.f, 10.f, 100.f, 1000.f, 10000.f, 100000.f, 1000000.f, 10000000.f}; @@ -41,7 +39,7 @@ namespace anm2ed::util::math return formatString.c_str(); } - mat4 skew_get(vec2 skew) + static mat4 skew_get(vec2 skew) { mat4 result(1.0f); result[1][0] = skew.x; @@ -85,7 +83,6 @@ namespace anm2ed::util::math return glm::translate(mat4(1.0f), vec3(position, 0.0f)) * local; } - float random() { return (float)rand() / RAND_MAX; } - float random_in_range(float min, float max) { return min + random() * (max - min); } + float random_unit_get() { return (float)rand() / RAND_MAX; } + float random_in_range(float min, float max) { return min + random_unit_get() * (max - min); } void random_seed_set() { srand(std::time(nullptr)); } -} diff --git a/src/math_util.h b/src/math_util.h index 3de3d66..5d33dca 100644 --- a/src/math_util.h +++ b/src/math_util.h @@ -3,8 +3,6 @@ #include #include -namespace anm2ed::util::math -{ template constexpr T percent_to_unit(T value) { return value / 100.0f; } template constexpr T unit_to_percent(T value) { return value * 100.0f; } @@ -30,7 +28,6 @@ namespace anm2ed::util::math glm::mat4 quad_model_parent_get(glm::vec2 = {}, glm::vec2 = {}, glm::vec2 = glm::vec2(1.0f), float = {}, glm::vec2 = {}); - float random(); + float random_unit_get(); float random_in_range(float min, float max); void random_seed_set(); -} diff --git a/src/model/common.h b/src/model/common.h index ecbc3d5..23a4741 100644 --- a/src/model/common.h +++ b/src/model/common.h @@ -44,8 +44,6 @@ X(FRAME, "Frame") \ X(TRIGGER, "Trigger") -namespace anm2ed -{ enum class ElementType { #define X(symbol, tag) symbol, @@ -165,10 +163,7 @@ namespace anm2ed constexpr Flags SERIALIZE_ANM2ED_DEFAULT = SERIALIZE_GROUPS | SERIALIZE_REGIONS | SERIALIZE_SOUNDS | SERIALIZE_NESTED_GROUPS | SERIALIZE_EXTENSIONS; - namespace model - { class Model; - } // How a document saves: the game's copy with the editor's embedded, or the editor's own JSON; `gameModel` is the // game's copy when it differs from the document (animation layers flattened). @@ -176,7 +171,7 @@ namespace anm2ed { bool isJson{}; // the editor's own JSON document instead bool isPixelBaked{true}; // what the game can't draw is baked into a spritesheet beside the file - const model::Model* gameModel{}; + const Model* gameModel{}; }; #define FRAME_CHANGE_SCALARS \ @@ -256,4 +251,3 @@ namespace anm2ed return value < 0.5f ? (2.0f * value * value) : (1.0f - std::pow(-2.0f * value + 2.0f, 2.0f) * 0.5f); return 0.0f; } -} diff --git a/src/model/draw.cpp b/src/model/draw.cpp index 53546c4..e62f3aa 100644 --- a/src/model/draw.cpp +++ b/src/model/draw.cpp @@ -6,25 +6,21 @@ #include "model/frames.h" #include "math_util.h" -using namespace anm2ed::util; - -namespace anm2ed::model -{ constexpr unsigned RANDOM_MULTIPLIER_A = 73856093u; constexpr unsigned RANDOM_MULTIPLIER_B = 19349663u; glm::mat4 draw_quad_model_get(const Draw& draw) { auto& frame = draw.frame; - return math::quad_model_get(frame.size, frame.position, frame.pivot, math::percent_to_unit(frame.scale), - frame.rotation, math::percent_to_unit(frame.skew)); + return quad_model_get(frame.size, frame.position, frame.pivot, percent_to_unit(frame.scale), + frame.rotation, percent_to_unit(frame.skew)); } // Where an animation layer's frame puts its child: the frame's transform, with its pivot as the child's origin. glm::mat4 frame_child_model_get(const Frame& frame) { - return math::quad_model_get(glm::vec2(1.0f), frame.position, frame.pivot, math::percent_to_unit(frame.scale), - frame.rotation, math::percent_to_unit(frame.skew)); + return quad_model_get(glm::vec2(1.0f), frame.position, frame.pivot, percent_to_unit(frame.scale), + frame.rotation, percent_to_unit(frame.skew)); } // How many canvas pixels one spritesheet pixel of a layer draw covers (along its longer axis). @@ -36,7 +32,7 @@ namespace anm2ed::model } // When an item is drawn: now, and for each sample its time if the track has a frame there. - std::vector> draw_times_get(const Animation& animation, const Track& track, + static std::vector> draw_times_get(const Animation& animation, const Track& track, const DrawOptions& options) { std::vector> times{}; @@ -59,7 +55,7 @@ namespace anm2ed::model } // A keyframe's start frame in its child animation; a random start is fixed per layer and keyframe. - float child_start_get(const Frame& frame, int length, int seed, int index) + static float child_start_get(const Frame& frame, int length, int seed, int index) { if (!frame.isChildStartRandom) return (float)frame.childStart; return (float)((((unsigned)seed * RANDOM_MULTIPLIER_A) ^ ((unsigned)index * RANDOM_MULTIPLIER_B)) % @@ -105,7 +101,7 @@ namespace anm2ed::model return {childModel, childAnimation}; } - void animation_triggers_add(std::vector& fires, const Model& model, const Animation& animation, int time, + static void animation_triggers_add(std::vector& fires, const Model& model, const Animation& animation, int time, const LibraryGet& library_get, std::vector& playing, int layerId = -1) { if (animation.triggers.isVisible) @@ -169,7 +165,7 @@ namespace anm2ed::model } // `playing` holds the animations being drawn into one another, so an animation never draws itself. - std::vector animation_draws_get(const Model& model, const Animation& animation, const DrawOptions& options, + static std::vector animation_draws_get(const Model& model, const Animation& animation, const DrawOptions& options, std::vector& playing) { std::vector draws{}; @@ -287,4 +283,3 @@ namespace anm2ed::model std::vector playing{&animation}; return animation_draws_get(model, animation, options, playing); } -} diff --git a/src/model/draw.h b/src/model/draw.h index fe145dc..a34028f 100644 --- a/src/model/draw.h +++ b/src/model/draw.h @@ -7,8 +7,6 @@ #include "model/model.h" // What an animation draws at a time, as plain data: every canvas (preview, render, about) draws from this list. -namespace anm2ed::model -{ enum class DrawType { ROOT, @@ -70,4 +68,3 @@ namespace anm2ed::model 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/frames.cpp b/src/model/frames.cpp index 84bcd4c..41e6f76 100644 --- a/src/model/frames.cpp +++ b/src/model/frames.cpp @@ -6,10 +6,6 @@ #include "model/draw.h" #include "math_util.h" -using namespace anm2ed::util; - -namespace anm2ed::model -{ void frame_mix(Frame& frame, const Frame& next, float amount) { frame.rotation = glm::mix(frame.rotation, next.rotation, amount); @@ -42,14 +38,14 @@ namespace anm2ed::model glm::mat4 frame_parent_model_get(const Frame& frame) { - return math::quad_model_parent_get(frame.position, {}, math::percent_to_unit(frame.scale), frame.rotation, - math::percent_to_unit(frame.skew)); + return quad_model_parent_get(frame.position, {}, percent_to_unit(frame.scale), frame.rotation, + percent_to_unit(frame.skew)); } void frame_root_transform_apply(Frame& frame, const Frame& rootFrame, bool isRoundScale, bool isRoundRotation, bool isUseRootPivot) { - auto rootScale = math::percent_to_unit(rootFrame.scale); + auto rootScale = percent_to_unit(rootFrame.scale); auto pivot = isUseRootPivot ? rootFrame.position : glm::vec2(); auto offset = (frame.position - pivot) * rootScale; auto radians = glm::radians(rootFrame.rotation); @@ -261,4 +257,3 @@ namespace anm2ed::model if (!isAny) return glm::vec4(-1.0f); return {min.x, min.y, max.x - min.x, max.y - min.y}; } -} diff --git a/src/model/frames.h b/src/model/frames.h index 69145fb..efa81f2 100644 --- a/src/model/frames.h +++ b/src/model/frames.h @@ -5,8 +5,6 @@ #include "model/draw.h" -namespace anm2ed::model -{ void frame_mix(Frame&, const Frame&, float); std::vector frame_bake_split(const Frame&, const Frame&, int, bool, bool); glm::mat4 frame_parent_model_get(const Frame&); @@ -21,4 +19,3 @@ namespace anm2ed::model void frames_sort_by_at_frame(Track&); void frames_change(Track&, FrameChange, ItemType, ChangeType, const std::set&, bool isAnimationLayer = false); glm::vec4 animation_rect(const Model&, const Animation&, bool, const LibraryGet& = {}); -} diff --git a/src/model/json.cpp b/src/model/json.cpp index d8dea96..fde811a 100644 --- a/src/model/json.cpp +++ b/src/model/json.cpp @@ -13,10 +13,7 @@ #include "model/xml.h" using namespace simdjson; -using namespace anm2ed::util; -namespace anm2ed::model -{ constexpr std::string_view INDENT = " "; constexpr std::size_t LINE_WIDTH_MAX = 100; constexpr std::string_view WHITESPACE = " \t\r\n"; @@ -38,26 +35,26 @@ namespace anm2ed::model return start != std::string_view::npos && text[start] == '{'; } - template int index_get(const Items& items, int id) + template static int index_get(const Items& items, int id) { auto it = std::ranges::find(items, id, &std::ranges::range_value_t::id); return it == items.end() ? -1 : (int)(it - items.begin()); } - glm::ivec4 color_to_bytes(const glm::vec4& color) + static glm::ivec4 color_to_bytes(const glm::vec4& color) { - return {math::float_to_uint8(color.r), math::float_to_uint8(color.g), math::float_to_uint8(color.b), - math::float_to_uint8(color.a)}; + return {float_to_uint8(color.r), float_to_uint8(color.g), float_to_uint8(color.b), + float_to_uint8(color.a)}; } - glm::vec4 color_from_bytes(const glm::ivec4& bytes) + static glm::vec4 color_from_bytes(const glm::ivec4& bytes) { - return {math::uint8_to_float(bytes.r), math::uint8_to_float(bytes.g), math::uint8_to_float(bytes.b), - math::uint8_to_float(bytes.a)}; + return {uint8_to_float(bytes.r), uint8_to_float(bytes.g), uint8_to_float(bytes.b), + uint8_to_float(bytes.a)}; } // The editor keeps dates as "MM/DD/YYYY hh:mm:ss AM"; JSON has them as ISO 8601. Anything else is kept as it is. - std::string date_to_iso(const std::string& date) + static std::string date_to_iso(const std::string& date) { int month{}, day{}, year{}, hour{}, minute{}, second{}; char meridiem[DATE_MERIDIEM_SIZE]{}; @@ -68,7 +65,7 @@ namespace anm2ed::model return std::format("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}", year, month, day, hour, minute, second); } - std::string date_from_iso(const std::string& date) + static std::string date_from_iso(const std::string& date) { int year{}, month{}, day{}, hour{}, minute{}, second{}; if (std::sscanf(date.c_str(), "%d-%d-%dT%d:%d:%d", &year, &month, &day, &hour, &minute, &second) != DATE_FIELDS) @@ -78,7 +75,7 @@ namespace anm2ed::model hour < HOURS_HALF_DAY ? "AM" : "PM"); } - void line_break(std::string& text, int depth) + static void line_break(std::string& text, int depth) { text += '\n'; for (int i = 0; i < depth; ++i) @@ -161,7 +158,7 @@ namespace anm2ed::model void value(int value) { number(value); } void value(float value) { number(value); } void value(const std::string& value) { this->value(std::string_view(value)); } - void value(const std::filesystem::path& value) { this->value(path::to_utf8(value)); } + void value(const std::filesystem::path& value) { this->value(path_to_utf8(value)); } void value(std::string_view value) { @@ -277,7 +274,7 @@ namespace anm2ed::model }; // Each returns what it expected when the value is the wrong kind (and leaves the value as it was). - std::string_view value_read(dom::element element, bool& value) + static std::string_view value_read(dom::element element, bool& value) { bool read{}; if (element.get(read)) return "true or false"; @@ -295,7 +292,7 @@ namespace anm2ed::model return {}; } - std::string_view value_read(dom::element element, std::string& value) + static std::string_view value_read(dom::element element, std::string& value) { std::string_view read{}; if (element.get(read)) return "a string"; @@ -303,11 +300,11 @@ namespace anm2ed::model return {}; } - std::string_view value_read(dom::element element, std::filesystem::path& value) + static std::string_view value_read(dom::element element, std::filesystem::path& value) { std::string read{}; auto expected = value_read(element, read); - if (expected.empty()) value = path::from_utf8(read); + if (expected.empty()) value = path_from_utf8(read); return expected; } @@ -325,7 +322,7 @@ namespace anm2ed::model return {}; } - template std::string_view value_read(dom::element element, std::vector& value) + template static std::string_view value_read(dom::element element, std::vector& value) { dom::array array{}; if (element.get(array)) return "an array"; @@ -478,7 +475,7 @@ namespace anm2ed::model // Each part of the document is described once; with a JsonWriter it is written, with a JsonReader read. - template void frame_io(Io& io, F& frame, ItemType type, const std::vector& regions) + template static void frame_io(Io& io, F& frame, ItemType type, const std::vector& regions) { static const Frame FRAME_DEFAULT{}; auto& content = io.model.content; @@ -530,7 +527,7 @@ namespace anm2ed::model io.list(name, frames, [&](auto& frameIo, auto& frame) { frame_io(frameIo, frame, type, regions); }, true, false); } - template void track_io(Io& io, T& track, ItemType type) + template static void track_io(Io& io, T& track, ItemType type) { auto isLayer = type == ItemType::LAYER; if constexpr (Io::IS_READING) track.type = type; @@ -548,7 +545,7 @@ namespace anm2ed::model } // A group is an entry with a "group" name, its root and its own tracks. - template void entries_io(Io& io, std::string_view name, Entries& entries, ItemType type) + template static void entries_io(Io& io, std::string_view name, Entries& entries, ItemType type) { io.list( name, entries, @@ -581,7 +578,7 @@ namespace anm2ed::model } } - template void animation_io(Io& io, A& animation) + template static void animation_io(Io& io, A& animation) { io.field("length", animation.frameNum, 1); io.field("loop", animation.isLoop, true); @@ -596,7 +593,7 @@ namespace anm2ed::model // Animations (and groups, which hold an "animations" object) are keyed by name; a repeated name is renumbered. // Animation names are unique document-wide (default names one); a group's only among the top-level keys. - void animations_write(JsonWriter& io, const Model& model) + static void animations_write(JsonWriter& io, const Model& model) { std::set animationNames{}; std::set keys{}; @@ -649,7 +646,7 @@ namespace anm2ed::model false); } - void animations_read(JsonReader& io, Model& model) + static void animations_read(JsonReader& io, Model& model) { auto animation_read = [&](std::string_view name, JsonReader& animationIo) { @@ -694,7 +691,7 @@ namespace anm2ed::model } // Content comes before animations, which read it (and anything named comes before what names it). - template void model_io(Io& io, M& model) + template static void model_io(Io& io, M& model) { auto& content = model.content; io.object( @@ -818,4 +815,3 @@ namespace anm2ed::model if (issues.size() > ISSUES_SHOWN_MAX) *errorString += std::format("\n({} more)", issues.size() - ISSUES_SHOWN_MAX); return true; } -} diff --git a/src/model/json.h b/src/model/json.h index 4b1ecc0..b9dd423 100644 --- a/src/model/json.h +++ b/src/model/json.h @@ -7,9 +7,6 @@ // The editor's own JSON document: content items in arrays (an item's index is its id), animations keyed by their // unique name, and every value left out when it is the default. Unknown XML (extras) is not kept. -namespace anm2ed::model -{ bool is_json(std::string_view); std::string model_to_json(const Model&); bool model_from_json(Model&, std::string_view, std::string* = nullptr); -} diff --git a/src/model/model.cpp b/src/model/model.cpp index 475790b..d012779 100644 --- a/src/model/model.cpp +++ b/src/model/model.cpp @@ -6,12 +6,8 @@ #include "image.h" #include "path.h" -using namespace anm2ed::util; - -namespace anm2ed::model -{ // The slot holding the animation at a flat index (animations inside groups count in order), or nullptr. - template auto animation_slot_get(Entries& entries, int index) -> decltype(&std::get<0>(entries[0])) + template static auto animation_slot_get(Entries& entries, int index) -> decltype(&std::get<0>(entries[0])) { if (index < 0) return nullptr; for (auto& entry : entries) @@ -67,7 +63,7 @@ namespace anm2ed::model return result; } - template auto animation_group_find(Self& self, int index) + template static auto animation_group_find(Self& self, int index) { using Group = std::conditional_t, const AnimationGroup, AnimationGroup>; Group* result{}; @@ -95,7 +91,7 @@ namespace anm2ed::model return group ? group->id : -1; } - template auto animation_track_group_find(A& animation, int groupType, int groupId) + template static auto animation_track_group_find(A& animation, int groupType, int groupId) { using Group = std::conditional_t, const TrackGroup, TrackGroup>; Group* result{}; @@ -120,7 +116,7 @@ namespace anm2ed::model // A track by item type and id; a group root when the item is ROOT with a group, and grouped tracks only match their // own group when one is given. - template auto animation_track_find(A& animation, int itemType, int id, int groupType, int groupId) + template static auto animation_track_find(A& animation, int itemType, int id, int groupType, int groupId) { using T = std::conditional_t, const Track, Track>; T* result{}; @@ -214,7 +210,7 @@ namespace anm2ed::model return resolved; } - template std::set unused_ids_get(const Items& items, const std::set& used) + template static std::set unused_ids_get(const Items& items, const std::set& used) { std::set unused{}; for (const auto& item : items) @@ -334,7 +330,7 @@ namespace anm2ed::model return handle.frame ? handle.frame : handle.item ? handle.item : handle.animation; } - template void animation_uids_each(Animation& animation, Callback&& callback) + template static void animation_uids_each(Animation& animation, Callback&& callback) { callback(animation.uid); for (auto* entries : {&animation.layers, &animation.nulls}) @@ -354,7 +350,7 @@ namespace anm2ed::model std::unordered_set seen{}; auto repair = [&](std::uint64_t& uid) { - if (!uid || !seen.insert(uid).second) uid = util::uid_next(); + if (!uid || !seen.insert(uid).second) uid = uid_next(); }; for (int i = 0; i < animations_count_get(); ++i) @@ -395,7 +391,7 @@ namespace anm2ed::model std::set ids{}; for (const auto& layer : model.content.layers) if (auto spritesheet = item_get(model.content.spritesheets, layer.spritesheetId); - spritesheet && !layer.is_animation() && path::is_extension(spritesheet->path, resource::image::SVG_EXTENSION)) + spritesheet && !layer.is_animation() && is_path_extension(spritesheet->path, SVG_EXTENSION)) ids.insert(spritesheet->id); return ids; } @@ -428,25 +424,25 @@ namespace anm2ed::model Frame frame_clone(Frame frame) { - frame.uid = util::uid_next(); + frame.uid = uid_next(); return frame; } Track track_clone(Track track) { - track.uid = util::uid_next(); + track.uid = uid_next(); for (auto& frame : track.frames) - frame.uid = util::uid_next(); + frame.uid = uid_next(); return track; } Animation animation_clone(Animation animation) { - animation_uids_each(animation, [](std::uint64_t& uid) { uid = util::uid_next(); }); + animation_uids_each(animation, [](std::uint64_t& uid) { uid = uid_next(); }); return animation; } - void track_locations_add(std::unordered_map& locations, const Track& track, + static void track_locations_add(std::unordered_map& locations, const Track& track, Reference reference) { constexpr ElementType TRACK_TYPES[] = {ElementType::UNKNOWN, ElementType::ROOT_ANIMATION, @@ -529,4 +525,3 @@ namespace anm2ed::model } return true; } -} diff --git a/src/model/model.h b/src/model/model.h index 81bfbdd..41c2034 100644 --- a/src/model/model.h +++ b/src/model/model.h @@ -15,8 +15,6 @@ #include "uid.h" // The typed document model. XML exists only in model/xml.cpp; everything else edits and reads these structs. -namespace anm2ed::model -{ // An XML element the editor does not understand, kept verbatim so it survives a save. struct XmlNode { @@ -41,7 +39,7 @@ namespace anm2ed::model // A keyframe; on a triggers track the same struct is a trigger (atFrame, eventIds, soundIds). struct Frame { - std::uint64_t uid{util::uid_next()}; + std::uint64_t uid{uid_next()}; glm::vec2 crop{}; glm::vec2 size{}; glm::vec2 pivot{}; @@ -49,7 +47,7 @@ namespace anm2ed::model glm::vec2 scale{100.0f, 100.0f}; glm::vec2 skew{}; float rotation{}; - glm::vec4 tint{types::color::WHITE}; + glm::vec4 tint{COLOR_WHITE}; glm::vec4 colorOffset{}; int duration{1}; bool isVisible{true}; @@ -74,7 +72,7 @@ namespace anm2ed::model struct Track { - std::uint64_t uid{util::uid_next()}; + std::uint64_t uid{uid_next()}; ItemType type{ItemType::LAYER}; int id{-1}; bool isVisible{true}; @@ -86,7 +84,7 @@ namespace anm2ed::model struct TrackGroup { - std::uint64_t uid{util::uid_next()}; + std::uint64_t uid{uid_next()}; int id{-1}; std::string name{}; bool isExpanded{true}; @@ -102,7 +100,7 @@ namespace anm2ed::model struct Animation { - std::uint64_t uid{util::uid_next()}; + std::uint64_t uid{uid_next()}; std::string name{}; int frameNum{1}; bool isLoop{true}; @@ -124,7 +122,7 @@ namespace anm2ed::model struct AnimationGroup { - std::uint64_t uid{util::uid_next()}; + std::uint64_t uid{uid_next()}; int id{-1}; std::string name{}; bool isExpanded{true}; @@ -139,7 +137,7 @@ namespace anm2ed::model struct Region { - std::uint64_t uid{util::uid_next()}; + std::uint64_t uid{uid_next()}; int id{-1}; std::string name{}; glm::vec2 crop{}; @@ -153,7 +151,7 @@ namespace anm2ed::model struct Spritesheet { - std::uint64_t uid{util::uid_next()}; + std::uint64_t uid{uid_next()}; int id{-1}; std::filesystem::path path{}; std::vector regions{}; @@ -185,7 +183,7 @@ namespace anm2ed::model struct Shader { - std::uint64_t uid{util::uid_next()}; + std::uint64_t uid{uid_next()}; int id{-1}; std::string name{}; std::filesystem::path vertex{}; @@ -198,7 +196,7 @@ namespace anm2ed::model struct Layer { - std::uint64_t uid{util::uid_next()}; + std::uint64_t uid{uid_next()}; int id{-1}; std::string name{}; int spritesheetId{}; @@ -215,7 +213,7 @@ namespace anm2ed::model // Another .anm2 whose animations this one's layers can play. struct Library { - std::uint64_t uid{util::uid_next()}; + std::uint64_t uid{uid_next()}; int id{-1}; std::filesystem::path path{}; Extras extras{}; @@ -225,7 +223,7 @@ namespace anm2ed::model struct Null { - std::uint64_t uid{util::uid_next()}; + std::uint64_t uid{uid_next()}; int id{-1}; std::string name{}; bool isShowRect{}; @@ -236,7 +234,7 @@ namespace anm2ed::model struct Event { - std::uint64_t uid{util::uid_next()}; + std::uint64_t uid{uid_next()}; int id{-1}; std::string name{}; Extras extras{}; @@ -246,7 +244,7 @@ namespace anm2ed::model struct Sound { - std::uint64_t uid{util::uid_next()}; + std::uint64_t uid{uid_next()}; int id{-1}; std::filesystem::path path{}; Extras extras{}; @@ -420,4 +418,3 @@ namespace anm2ed::model Animation animation_clone(Animation); Frame frame_clone(Frame); Track track_clone(Track); -} diff --git a/src/model/xml.cpp b/src/model/xml.cpp index 6514e13..bcb9337 100644 --- a/src/model/xml.cpp +++ b/src/model/xml.cpp @@ -19,10 +19,6 @@ #include "path.h" #include "timestamp.h" -using namespace anm2ed::util; - -namespace anm2ed::model -{ constexpr std::string_view ELEMENT_TAGS[] = { #define X(symbol, tag) tag, ANM2_ELEMENT_TYPES @@ -68,15 +64,15 @@ namespace anm2ed::model constexpr std::uint64_t HASH_PRIME = 1099511628211ull; constexpr Flags CLIPBOARD_FLAGS = SERIALIZE_EDITOR_DEFAULT; - const char* tag_get(ElementType type) { return ELEMENT_TAGS[(int)type].data(); } + static const char* tag_get(ElementType type) { return ELEMENT_TAGS[(int)type].data(); } - ElementType type_get(pugi::xml_node element) + static ElementType type_get(pugi::xml_node element) { auto it = std::ranges::find(ELEMENT_TAGS, std::string_view(element.name())); return it == std::end(ELEMENT_TAGS) ? ElementType::UNKNOWN : (ElementType)(it - std::begin(ELEMENT_TAGS)); } - ElementType track_element_type_get(ItemType type) + static ElementType track_element_type_get(ItemType type) { switch (type) { @@ -95,27 +91,27 @@ namespace anm2ed::model // Numbers and booleans read as tinyxml2 (which older builds used) reads them: "%d" and "%f" on the leading text, // and booleans as a number or true/false. - const char* attribute_get(pugi::xml_node element, const char* name) + static const char* attribute_get(pugi::xml_node element, const char* name) { auto attribute = element.attribute(name); return attribute ? attribute.value() : nullptr; } - bool is_int_read(const char* text, int& value) { return text && std::sscanf(text, "%d", &value) == 1; } + static bool is_int_read(const char* text, int& value) { return text && std::sscanf(text, "%d", &value) == 1; } - int int_get(pugi::xml_node element, const char* name, int value = -1) + static int int_get(pugi::xml_node element, const char* name, int value = -1) { is_int_read(attribute_get(element, name), value); return value; } - float float_get(pugi::xml_node element, const char* name, float value = 0.0f) + static float float_get(pugi::xml_node element, const char* name, float value = 0.0f) { if (auto text = attribute_get(element, name)) std::sscanf(text, "%f", &value); return value; } - bool bool_get(pugi::xml_node element, const char* name, bool value) + static bool bool_get(pugi::xml_node element, const char* name, bool value) { auto text = attribute_get(element, name); if (int number{}; is_int_read(text, number)) return number != 0; @@ -125,32 +121,32 @@ namespace anm2ed::model return value; } - std::string string_get(pugi::xml_node element, const char* name, std::string value = {}) + static std::string string_get(pugi::xml_node element, const char* name, std::string value = {}) { if (auto attribute = attribute_get(element, name)) value = attribute; return value; } - std::filesystem::path path_get(pugi::xml_node element, const char* name) + static std::filesystem::path path_get(pugi::xml_node element, const char* name) { auto attribute = attribute_get(element, name); - return attribute ? path::from_utf8(attribute) : std::filesystem::path{}; + return attribute ? path_from_utf8(attribute) : std::filesystem::path{}; } - float color_get(pugi::xml_node element, const char* name, float value) + static float color_get(pugi::xml_node element, const char* name, float value) { - if (int color{}; is_int_read(attribute_get(element, name), color)) value = math::uint8_to_float(color); + if (int color{}; is_int_read(attribute_get(element, name), color)) value = uint8_to_float(color); return value; } // An element's text: its first child, when that is text. - const char* text_get(pugi::xml_node element) + static const char* text_get(pugi::xml_node element) { auto first = element.first_child(); return first.type() == pugi::node_pcdata || first.type() == pugi::node_cdata ? first.value() : nullptr; } - Interpolation interpolation_read(pugi::xml_node element, const char* name) + static Interpolation interpolation_read(pugi::xml_node element, const char* name) { auto value = attribute_get(element, name); if (!value) return Interpolation::NONE; @@ -159,7 +155,7 @@ namespace anm2ed::model return bool_get(element, name, false) ? Interpolation::LINEAR : Interpolation::NONE; } - pugi::xml_node element_next(pugi::xml_node node) + static pugi::xml_node element_next(pugi::xml_node node) { do node = node.next_sibling(); @@ -167,14 +163,14 @@ namespace anm2ed::model return node; } - pugi::xml_node element_first(pugi::xml_node parent) + static pugi::xml_node element_first(pugi::xml_node parent) { auto child = parent.first_child(); return !child || child.type() == pugi::node_element ? child : element_next(child); } // Shader elements are only read where they belong; one anywhere else is dropped. - bool is_child_kept(pugi::xml_node parent, pugi::xml_node child) + static bool is_child_kept(pugi::xml_node parent, pugi::xml_node child) { std::string_view tag = child.name(); if (tag == LEGACY_OVERLAY_TAG || tag == SOURCE_DOCUMENT_TAG) return false; @@ -195,7 +191,7 @@ namespace anm2ed::model } // Child elements with their position, skipping legacy Overlay, nested SourceDocument copies and misplaced shaders. - template void children_each(pugi::xml_node parent, Callback&& callback) + template static void children_each(pugi::xml_node parent, Callback&& callback) { int position{}; for (auto child : parent.children()) @@ -204,7 +200,7 @@ namespace anm2ed::model } // A repeated attribute keeps its first position and last value. - void attribute_read(std::vector>& attributes, pugi::xml_attribute attribute) + static void attribute_read(std::vector>& attributes, pugi::xml_attribute attribute) { auto existing = std::ranges::find(attributes, std::string_view(attribute.name()), [](const auto& pair) { return std::string_view(pair.first); }); @@ -214,7 +210,7 @@ namespace anm2ed::model attributes.emplace_back(attribute.name(), attribute.value()); } - XmlNode node_read(pugi::xml_node element) + static XmlNode node_read(pugi::xml_node element) { XmlNode node{.tag = element.name()}; for (auto attribute : element.attributes()) @@ -224,7 +220,7 @@ namespace anm2ed::model return node; } - Extras extras_read(pugi::xml_node element) + static Extras extras_read(pugi::xml_node element) { Extras extras{}; for (auto attribute : element.attributes()) @@ -234,12 +230,12 @@ namespace anm2ed::model return extras; } - void extras_child_add(Extras& extras, pugi::xml_node child, int position) + static void extras_child_add(Extras& extras, pugi::xml_node child, int position) { extras.children.emplace_back(position, node_read(child)); } - Frame frame_read(pugi::xml_node element) + static Frame frame_read(pugi::xml_node element) { Frame frame{}; frame.crop = {float_get(element, "XCrop"), float_get(element, "YCrop")}; @@ -292,7 +288,7 @@ namespace anm2ed::model return frame; } - Track track_read(pugi::xml_node element, ItemType type) + static Track track_read(pugi::xml_node element, ItemType type) { Track track{.type = type, .isVisible = bool_get(element, "Visible", true), .extras = extras_read(element)}; if (type == ItemType::LAYER) track.id = int_get(element, "LayerId"); @@ -340,12 +336,12 @@ namespace anm2ed::model using TrackItem = ContainerItem; using AnimationItem = ContainerItem, AnimationGroup>; - auto& group_children_get(TrackGroup& group) { return group.tracks; } - auto& group_children_get(AnimationGroup& group) { return group.animations; } + static auto& group_children_get(TrackGroup& group) { return group.tracks; } + static auto& group_children_get(AnimationGroup& group) { return group.animations; } // Groups become entries followed by their children: nested children move out after their group, and a child joins a // group seen before it. Unknown XML becomes extras at its position. - template std::vector entries_build(std::vector items, Extras& extras) + template static std::vector entries_build(std::vector items, Extras& extras) { int nextGroupId{}; for (const auto& item : items) @@ -387,7 +383,7 @@ namespace anm2ed::model return entries; } - TrackItem track_group_item_read(pugi::xml_node element, ItemType type) + static TrackItem track_group_item_read(pugi::xml_node element, ItemType type) { TrackItem item{.group = TrackGroup{.id = int_get(element, "Id"), .name = string_get(element, "Name"), @@ -419,7 +415,7 @@ namespace anm2ed::model return item; } - std::vector track_items_read(pugi::xml_node container, ItemType type) + static std::vector track_items_read(pugi::xml_node container, ItemType type) { std::vector items{}; children_each(container, @@ -437,7 +433,7 @@ namespace anm2ed::model // Track groups as any version wrote them: legacy *AnimationGroups metadata is placed back at its Index, and a group // whose tracks were written baked (FrameRestore) gets its original root and tracks back. - std::vector track_entries_build(std::vector items, std::vector legacyGroups, + static std::vector track_entries_build(std::vector items, std::vector legacyGroups, Extras& extras) { if (!legacyGroups.empty()) @@ -476,7 +472,7 @@ namespace anm2ed::model return entries_build(std::move(items), extras); } - Animation animation_read(pugi::xml_node element) + static Animation animation_read(pugi::xml_node element) { Animation animation{.name = string_get(element, "Name"), .frameNum = int_get(element, "FrameNum", 1), @@ -541,7 +537,7 @@ namespace anm2ed::model return animation; } - std::vector animation_entries_read(pugi::xml_node parent, Extras& extras) + static std::vector animation_entries_read(pugi::xml_node parent, Extras& extras) { std::vector items{}; children_each(parent, @@ -572,7 +568,7 @@ namespace anm2ed::model return entries_build(std::move(items), extras); } - Region region_read(pugi::xml_node element) + static Region region_read(pugi::xml_node element) { Region region{.id = int_get(element, "Id"), .name = string_get(element, "Name"), @@ -588,7 +584,7 @@ namespace anm2ed::model return region; } - Spritesheet spritesheet_read(pugi::xml_node element) + static Spritesheet spritesheet_read(pugi::xml_node element) { Spritesheet spritesheet{ .id = int_get(element, "Id"), .path = path_get(element, "Path"), .extras = extras_read(element)}; @@ -603,7 +599,7 @@ namespace anm2ed::model return spritesheet; } - Shader shader_read(pugi::xml_node element) + static Shader shader_read(pugi::xml_node element) { Shader shader{.id = int_get(element, "Id"), .name = string_get(element, "Name"), @@ -633,7 +629,7 @@ namespace anm2ed::model return shader; } - template Item item_read(pugi::xml_node); + template static Item item_read(pugi::xml_node); template <> Spritesheet item_read(pugi::xml_node element) { return spritesheet_read(element); } template <> Region item_read(pugi::xml_node element) { return region_read(element); } template <> Shader item_read(pugi::xml_node element) { return shader_read(element); } @@ -676,7 +672,7 @@ namespace anm2ed::model template <> constexpr ElementType ITEM_TYPE{ElementType::SOUND_ELEMENT}; template <> constexpr ElementType ITEM_TYPE{ElementType::LIBRARY}; - template std::vector items_read(pugi::xml_node container, Content& content, ElementType type) + template static std::vector items_read(pugi::xml_node container, Content& content, ElementType type) { std::vector items{}; auto extras = extras_read(container); @@ -692,7 +688,7 @@ namespace anm2ed::model return items; } - Content content_read(pugi::xml_node element) + static Content content_read(pugi::xml_node element) { Content content{.layout = {}, .extras = extras_read(element)}; children_each(element, @@ -719,7 +715,7 @@ namespace anm2ed::model } // Gives every item a unique, non-negative id; the first holder of a duplicated id keeps it. - template void ids_repair(Items& items) + template static void ids_repair(Items& items) { std::set usedIds{}; for (const auto& item : items) @@ -737,7 +733,7 @@ namespace anm2ed::model } } - bool is_region_matched(const Region& region, const Frame& frame) + static bool is_region_matched(const Region& region, const Frame& frame) { return glm::ivec2(region.crop) == glm::ivec2(frame.crop) && glm::ivec2(region.size) == glm::ivec2(frame.size) && glm::ivec2(region.pivot) == glm::ivec2(frame.pivot); @@ -799,7 +795,7 @@ namespace anm2ed::model } } - Model model_read(pugi::xml_node element) + static Model model_read(pugi::xml_node element) { Model model{.layout = {}, .extras = extras_read(element)}; children_each(element, @@ -862,13 +858,13 @@ namespace anm2ed::model bool is(Flag flag) const { return has_flag(flags, flag); } }; - int id_map_get(const std::map& ids, int id) + static int id_map_get(const std::map& ids, int id) { auto it = ids.find(id); return it == ids.end() ? -1 : it->second; } - bool is_float_whole(double value) + static bool is_float_whole(double value) { return std::abs(value) < FLOAT_WHOLE_MAX && value == std::trunc(value) && !(value == 0 && std::signbit(value)); } @@ -1061,13 +1057,13 @@ namespace anm2ed::model // Unknown XML goes back where it was read: attributes after the known ones, then text, and (through Children) // children at their recorded positions among the known ones. - void extras_attributes_write(Sink& sink, const Extras& extras) + static void extras_attributes_write(Sink& sink, const Extras& extras) { for (const auto& [name, value] : extras.attributes) sink.attribute_text(name, value); } - void extras_write(Sink& sink, const Extras& extras) + static void extras_write(Sink& sink, const Extras& extras) { extras_attributes_write(sink, extras); sink.text_add(extras.text); @@ -1104,14 +1100,14 @@ namespace anm2ed::model } }; - void element_close(Sink& sink, const Extras& extras) { Children{sink, extras}.close(); } + static void element_close(Sink& sink, const Extras& extras) { Children{sink, extras}.close(); } - void path_add(Sink& sink, const char* name, const std::filesystem::path& value) + static void path_add(Sink& sink, const char* name, const std::filesystem::path& value) { - if (!value.empty()) sink.attribute(name, path::to_utf8(value)); + if (!value.empty()) sink.attribute(name, path_to_utf8(value)); } - void interpolation_add(Sink& sink, const char* name, Interpolation interpolation) + static void interpolation_add(Sink& sink, const char* name, Interpolation interpolation) { if (interpolation == Interpolation::NONE || interpolation == Interpolation::LINEAR) sink.attribute(name, interpolation == Interpolation::LINEAR); @@ -1119,18 +1115,18 @@ namespace anm2ed::model sink.attribute(name, INTERPOLATION_VALUES[(int)interpolation]); } - bool is_group_id_written(const Writer& writer) + static bool is_group_id_written(const Writer& writer) { return writer.is(SERIALIZE_GROUPS) && !writer.is(SERIALIZE_NESTED_GROUPS); } - bool is_special_interpolation(Interpolation interpolation) + static bool is_special_interpolation(Interpolation interpolation) { return interpolation != Interpolation::NONE && interpolation != Interpolation::LINEAR; } // A whole document's frames use renumbered shader and region ids; a layer frame on a region takes its rectangle. - Frame frame_normalize(const Writer& writer, Frame frame, const Track* layerTrack) + static Frame frame_normalize(const Writer& writer, Frame frame, const Track* layerTrack) { if (!writer.model) return frame; if (frame.shaderId != -1) frame.shaderId = id_map_get(writer.shaderIds, frame.shaderId); @@ -1157,7 +1153,7 @@ namespace anm2ed::model int delay{}; }; - void frame_write(Sink& sink, const Writer& writer, const Frame& frame, ItemType type, FrameBake bake = {}) + static void frame_write(Sink& sink, const Writer& writer, const Frame& frame, ItemType type, FrameBake bake = {}) { if (type == ItemType::TRIGGER) { @@ -1214,13 +1210,13 @@ namespace anm2ed::model } auto isPurged = writer.is(SERIALIZE_PURGE_DEFAULT_COLORS); for (int i = 0; i < (int)std::size(TINT_ATTRIBUTES); ++i) - if (auto tint = math::float_to_uint8(frame.tint[i]); !isPurged || tint != math::float_to_uint8(1.0f)) + if (auto tint = float_to_uint8(frame.tint[i]); !isPurged || tint != float_to_uint8(1.0f)) sink.attribute(TINT_ATTRIBUTES[i], tint); for (int i = 0; i < (int)std::size(OFFSET_ATTRIBUTES); ++i) - if (auto offset = math::float_to_uint8(frame.colorOffset[i]); !isPurged || offset != 0) + if (auto offset = 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)); + if (writer.is(SERIALIZE_EXTENSIONS) && float_to_uint8(frame.colorOffset.a) != 0) + sink.attribute("AlphaOffset", float_to_uint8(frame.colorOffset.a)); sink.attribute("Rotation", frame.rotation); interpolation_add(sink, "Interpolated", frame.interpolation); if (writer.is(SERIALIZE_EXTENSIONS) && frame.shaderId != -1) sink.attribute("ShaderId", frame.shaderId); @@ -1247,7 +1243,7 @@ namespace anm2ed::model } // A backup (FrameRestore) track keeps its frames' region ids as they are. - void track_write(Sink& sink, const Writer& writer, const Track& track, int groupId = -1, bool isBackup = false) + static void track_write(Sink& sink, const Writer& writer, const Track& track, int groupId = -1, bool isBackup = false) { sink.open(tag_get(track_element_type_get(track.type))); if (track.type == ItemType::LAYER || track.type == ItemType::NULL_) @@ -1317,7 +1313,7 @@ namespace anm2ed::model std::optional ownGroupId{}; }; - template ContainerChild group_child_make(Sink& sink, const Writer& writer, const Group& group) + template static ContainerChild group_child_make(Sink& sink, const Writer& writer, const Group& group) { return {.write = [&](std::optional index, const std::function& members) { group_write(sink, writer, group, index, members); }, @@ -1326,7 +1322,7 @@ namespace anm2ed::model // Children are laid out flat (a group, then its children) and reshaped for the flags: nested into their groups, or, // in a track container, moved to a *AnimationGroups sibling (`groupsType`) that records each group's position. - void container_write(Sink& sink, const Writer& writer, std::vector flat, const Extras& extras, + static void container_write(Sink& sink, const Writer& writer, std::vector flat, const Extras& extras, ElementType groupsType = ElementType::UNKNOWN) { extras_write(sink, extras); @@ -1377,7 +1373,7 @@ namespace anm2ed::model sink.close(); } - void track_entries_write(Sink& sink, const Writer& writer, const std::vector& entries, ElementType type, + static void track_entries_write(Sink& sink, const Writer& writer, const std::vector& entries, ElementType type, const Extras& extras) { std::vector flat{}; @@ -1403,7 +1399,7 @@ namespace anm2ed::model : ElementType::NULL_ANIMATION_GROUPS); } - bool is_frame_transform_default(const Frame& frame) + static bool is_frame_transform_default(const Frame& frame) { Frame base{}; return frame.position == base.position && frame.scale == base.scale && frame.rotation == base.rotation && @@ -1430,7 +1426,7 @@ namespace anm2ed::model issues.skewFrames += frame.skew != glm::vec2(); issues.shaderFrames += frame.shaderId != -1; issues.depthFrames += track.type == ItemType::LAYER && frame.depth != 0; - issues.alphaOffsetFrames += math::float_to_uint8(frame.colorOffset.a) != 0; + issues.alphaOffsetFrames += float_to_uint8(frame.colorOffset.a) != 0; issues.blurFrames += track.type == ItemType::LAYER && frame.blur != 0.0f; issues.extraEvents += track.type == ItemType::TRIGGER ? std::max((int)frame.eventIds.size() - 1, 0) : 0; issues.triggerSounds += track.type == ItemType::TRIGGER && @@ -1443,7 +1439,7 @@ namespace anm2ed::model // The game's copy: group roots baked into their tracks (originals kept in a FrameRestore node the editor reads // back), and interpolation flattened into single-step frames. - Animation animation_bake(const Writer& writer, Animation animation) + static Animation animation_bake(const Writer& writer, Animation animation) { if (writer.is(SERIALIZE_BAKE_GROUP_FRAMES)) for (auto* entries : {&animation.layers, &animation.nulls}) @@ -1480,7 +1476,7 @@ namespace anm2ed::model } // Known children in their recorded order; a part with content that was never in the file is appended. - std::vector layout_get(std::vector layout, + static std::vector layout_get(std::vector layout, std::initializer_list> parts) { for (auto [type, isContent] : parts) @@ -1488,7 +1484,7 @@ namespace anm2ed::model return layout; } - void animation_write(Sink& sink, const Writer& writer, const Animation& source, int groupId = -1) + static void animation_write(Sink& sink, const Writer& writer, const Animation& source, int groupId = -1) { auto isBaked = writer.model && (writer.is(SERIALIZE_BAKE_GROUP_FRAMES) || writer.is(SERIALIZE_FLATTEN_SPECIAL_INTERPOLATED_FRAMES)); @@ -1522,7 +1518,7 @@ namespace anm2ed::model children.close(); } - void animations_write(Sink& sink, const Writer& writer, const Animations& animations) + static void animations_write(Sink& sink, const Writer& writer, const Animations& animations) { std::vector flat{}; auto animation_child_make = [&](const Animation& animation, int groupId) @@ -1546,7 +1542,7 @@ namespace anm2ed::model container_write(sink, writer, std::move(flat), animations.extras); } - void item_write(Sink& sink, const Writer&, const Region& region, int id) + static void item_write(Sink& sink, const Writer&, const Region& region, int id) { sink.open(tag_get(ElementType::REGION)); sink.attribute("Id", id); @@ -1566,7 +1562,7 @@ namespace anm2ed::model element_close(sink, region.extras); } - void item_write(Sink& sink, const Writer& writer, const Spritesheet& spritesheet, int id) + static void item_write(Sink& sink, const Writer& writer, const Spritesheet& spritesheet, int id) { sink.open(tag_get(ElementType::SPRITESHEET)); sink.attribute("Id", id); @@ -1582,13 +1578,13 @@ namespace anm2ed::model children.close(); } - void binding_value_add(Sink& sink, const std::string& binding, const std::string& value) + static void binding_value_add(Sink& sink, const std::string& binding, const std::string& value) { if (!binding.empty()) sink.attribute("Binding", binding); if (!value.empty()) sink.attribute("Value", value); } - void item_write(Sink& sink, const Writer&, const Shader& shader, int id) + static void item_write(Sink& sink, const Writer&, const Shader& shader, int id) { sink.open(tag_get(ElementType::SHADER)); sink.attribute("Id", id); @@ -1619,7 +1615,7 @@ namespace anm2ed::model children.close(); } - void item_write(Sink& sink, const Writer& writer, const Layer& layer, int id) + static void item_write(Sink& sink, const Writer& writer, const Layer& layer, int id) { sink.open(tag_get(ElementType::LAYER_ELEMENT)); sink.attribute("Id", id); @@ -1634,7 +1630,7 @@ namespace anm2ed::model element_close(sink, layer.extras); } - void item_write(Sink& sink, const Writer&, const Null& null, int id) + static void item_write(Sink& sink, const Writer&, const Null& null, int id) { sink.open(tag_get(ElementType::NULL_ELEMENT)); sink.attribute("Id", id); @@ -1644,7 +1640,7 @@ namespace anm2ed::model element_close(sink, null.extras); } - void item_write(Sink& sink, const Writer&, const Event& event, int id) + static void item_write(Sink& sink, const Writer&, const Event& event, int id) { sink.open(tag_get(ElementType::EVENT_ELEMENT)); sink.attribute("Id", id); @@ -1654,7 +1650,7 @@ namespace anm2ed::model } // Sounds and libraries are a path. - template void item_path_write(Sink& sink, const Item& item, ElementType type, int id) + template static void item_path_write(Sink& sink, const Item& item, ElementType type, int id) { sink.open(tag_get(type)); sink.attribute("Id", id); @@ -1663,18 +1659,18 @@ namespace anm2ed::model element_close(sink, item.extras); } - void item_write(Sink& sink, const Writer&, const Sound& sound, int id) + static void item_write(Sink& sink, const Writer&, const Sound& sound, int id) { item_path_write(sink, sound, ElementType::SOUND_ELEMENT, id); } - void item_write(Sink& sink, const Writer&, const Library& library, int id) + static void item_write(Sink& sink, const Writer&, const Library& library, int id) { item_path_write(sink, library, ElementType::LIBRARY, id); } // A content container's unknown XML (a file may repeat a container; its parts are merged in order). - Extras container_extras_get(const Content& content, ElementType type) + static Extras container_extras_get(const Content& content, ElementType type) { Extras merged{}; for (const auto& [extrasType, extras] : content.containerExtras) @@ -1703,7 +1699,7 @@ namespace anm2ed::model children.close(); } - void content_write(Sink& sink, const Writer& writer, const Content& content) + static void content_write(Sink& sink, const Writer& writer, const Content& content) { sink.open(tag_get(ElementType::CONTENT)); extras_write(sink, content.extras); @@ -1738,7 +1734,7 @@ namespace anm2ed::model } // A whole document; `inner` writes anything after its children (the SourceDocument copy) and `tag` renames it. - void model_write(Sink& sink, const Model& model, Flags flags, const std::function& inner = {}, + static void model_write(Sink& sink, const Model& model, Flags flags, const std::function& inner = {}, std::string_view tag = {}) { Writer writer(flags, &model); @@ -1771,7 +1767,7 @@ namespace anm2ed::model // A save is the game's document with the editor's own copy embedded as SourceDocument; neither writes tints of 255 // or color offsets of 0, which readers assume. - void document_write(Sink& sink, const Model& model, Options options) + static void document_write(Sink& sink, const Model& model, Options options) { model_write( sink, options.gameModel ? *options.gameModel : model, SERIALIZE_ISAAC_DEFAULT | SERIALIZE_PURGE_DEFAULT_COLORS, @@ -1782,14 +1778,14 @@ namespace anm2ed::model } // The text of whatever `write` sends to a sink. - template std::string text_get(Write&& write) + template static std::string text_get(Write&& write) { Sink sink{}; write(sink); return std::move(sink.text); } - bool model_invalid_set(Model& model) + static bool model_invalid_set(Model& model) { model = model_make(); model.isValid = false; @@ -1797,7 +1793,7 @@ namespace anm2ed::model } // A parse error says where it is: "Error parsing element name (line 12)". - bool document_parse(pugi::xml_document& document, std::string_view text, std::string* errorString) + static bool document_parse(pugi::xml_document& document, std::string_view text, std::string* errorString) { auto result = document.load_buffer(text.data(), text.size()); if (result) return true; @@ -1807,7 +1803,7 @@ namespace anm2ed::model return false; } - bool document_load(Model& model, std::string_view text, std::string* errorString) + static bool document_load(Model& model, std::string_view text, std::string* errorString) { pugi::xml_document document{}; if (!document_parse(document, text, errorString)) return model_invalid_set(model); @@ -1826,14 +1822,14 @@ namespace anm2ed::model Model model_make() { Model model{}; - model.info.createdOn = time::get(CREATED_ON_FORMAT); + model.info.createdOn = timestamp_get(CREATED_ON_FORMAT); return model; } bool model_load(Model& model, const std::filesystem::path& path, std::string* errorString) { std::string text{}; - if (file::read_to_string(path, &text)) return model_load_string(model, text, errorString); + if (file_text_load(path, &text)) return model_load_string(model, text, errorString); if (errorString) *errorString = "File not found."; return model_invalid_set(model); } @@ -1914,12 +1910,12 @@ namespace anm2ed::model return entries; } - template std::string item_to_string(const Item& item) + template static std::string item_to_string(const Item& item) { return text_get([&](Sink& sink) { item_write(sink, Writer(CLIPBOARD_FLAGS), item, item.id); }); } - template std::vector items_from_string(const std::string& text, std::string* errorString) + template static std::vector items_from_string(const std::string& text, std::string* errorString) { pugi::xml_document document{}; if (!document_parse(document, text, errorString)) return {}; @@ -1928,7 +1924,7 @@ namespace anm2ed::model for (auto element : document.children(tag)) { auto item = item_read(element); - if constexpr (requires { item.path; }) item.path = path::backslash_handle(item.path); + if constexpr (requires { item.path; }) item.path = path_backslash_handle(item.path); items.push_back(std::move(item)); } if (items.empty() && errorString) *errorString = std::format("No valid {}(s).", tag); @@ -1947,4 +1943,3 @@ namespace anm2ed::model X(Sound) X(Library) #undef X -} diff --git a/src/model/xml.h b/src/model/xml.h index 5fe9c19..c9408ab 100644 --- a/src/model/xml.h +++ b/src/model/xml.h @@ -6,8 +6,6 @@ #include "model/model.h" // The only place the model meets XML: reading and writing documents (with the SourceDocument copy) and clipboard text. -namespace anm2ed::model -{ // What the game's copy of a save can't keep as it is: how many of each. struct IsaacIssues { @@ -44,4 +42,3 @@ namespace anm2ed::model template std::string item_to_string(const Item&); template std::vector items_from_string(const std::string&, std::string* = nullptr); -} diff --git a/src/pack.cpp b/src/pack.cpp index 8f9a157..cf3f9be 100644 --- a/src/pack.cpp +++ b/src/pack.cpp @@ -5,8 +5,6 @@ #include #include -namespace anm2ed::util::pack -{ constexpr int WIDTH_CANDIDATES_MAX = 512; struct Rect @@ -17,17 +15,17 @@ namespace anm2ed::util::pack int h{}; }; - bool is_rect_intersecting(const Rect& a, const Rect& b) + static bool is_rect_intersecting(const Rect& a, const Rect& b) { return !(b.x >= a.x + a.w || b.x + b.w <= a.x || b.y >= a.y + a.h || b.y + b.h <= a.y); } - bool is_rect_contained(const Rect& a, const Rect& b) + static bool is_rect_contained(const Rect& a, const Rect& b) { return b.x >= a.x && b.y >= a.y && b.x + b.w <= a.x + a.w && b.y + b.h <= a.y + a.h; } - void free_rects_split(std::vector& freeRects, const Rect& used) + static void free_rects_split(std::vector& freeRects, const Rect& used) { std::vector next{}; next.reserve(freeRects.size() * 2); @@ -48,7 +46,7 @@ namespace anm2ed::util::pack freeRects = std::move(next); } - void free_rects_prune(std::vector& freeRects) + static void free_rects_prune(std::vector& freeRects) { for (int i = 0; i < (int)freeRects.size(); ++i) { @@ -72,7 +70,7 @@ namespace anm2ed::util::pack } } - bool rect_insert(std::vector& freeRects, glm::ivec2 size, Rect& result) + static bool rect_insert(std::vector& freeRects, glm::ivec2 size, Rect& result) { int bestShort = std::numeric_limits::max(); int bestLong = std::numeric_limits::max(); @@ -147,4 +145,3 @@ namespace anm2ed::util::pack return bestArea != std::numeric_limits::max(); } -} diff --git a/src/pack.h b/src/pack.h index 1e7f012..7e7a212 100644 --- a/src/pack.h +++ b/src/pack.h @@ -4,7 +4,4 @@ #include -namespace anm2ed::util::pack -{ bool rects_pack(const std::vector&, glm::ivec2&, std::vector&); -} diff --git a/src/path.cpp b/src/path.cpp index 837f6b1..93f2d52 100644 --- a/src/path.cpp +++ b/src/path.cpp @@ -6,9 +6,7 @@ #include #include -namespace anm2ed::util::path -{ - template CharT to_lower_char(CharT character) + template static CharT to_lower_char(CharT character) { if constexpr (std::is_same_v) return static_cast(std::towlower(static_cast(character))); @@ -16,7 +14,7 @@ namespace anm2ed::util::path return static_cast(std::tolower(static_cast(character))); } - std::filesystem::path to_lower(const std::filesystem::path& path) + std::filesystem::path path_to_lower(const std::filesystem::path& path) { auto native = path.native(); for (auto& character : native) @@ -24,7 +22,7 @@ namespace anm2ed::util::path return std::filesystem::path(native); } - std::filesystem::path backslash_replace(const std::filesystem::path& path) + std::filesystem::path path_backslash_replace(const std::filesystem::path& path) { auto native = path.native(); constexpr auto backslash = static_cast('\\'); @@ -34,33 +32,33 @@ namespace anm2ed::util::path return std::filesystem::path(native); } - std::string to_utf8(const std::filesystem::path& path) + std::string path_to_utf8(const std::filesystem::path& path) { auto u8 = path.u8string(); return std::string(u8.begin(), u8.end()); } - std::filesystem::path from_utf8(const std::string& utf8) + std::filesystem::path path_from_utf8(const std::string& utf8) { return std::filesystem::path(std::u8string(utf8.begin(), utf8.end())); } - bool is_exist(const std::filesystem::path& path) + bool is_path_exist(const std::filesystem::path& path) { if (path.empty()) return false; std::error_code errorCode; return std::filesystem::exists(path, errorCode) && ((void)std::filesystem::status(path, errorCode), !errorCode); } - bool is_extension(const std::filesystem::path& path, const std::string& extension) + bool is_path_extension(const std::filesystem::path& path, const std::string& extension) { if (path.empty()) return false; - auto extensionUtf8 = to_utf8(std::filesystem::path(path).extension()); + auto extensionUtf8 = path_to_utf8(std::filesystem::path(path).extension()); std::transform(extensionUtf8.begin(), extensionUtf8.end(), extensionUtf8.begin(), ::tolower); return extensionUtf8 == ("." + extension); } - bool is_executable(const std::filesystem::path& path) + bool is_path_executable(const std::filesystem::path& path) { if (path.empty()) return false; @@ -71,7 +69,7 @@ namespace anm2ed::util::path if (!std::filesystem::is_regular_file(status)) return false; #ifdef WIN32 - auto extension = to_lower(path.extension()); + auto extension = path_to_lower(path.extension()); if (extension != ".exe" && extension != ".bat" && extension != ".cmd") return false; #else auto permissions = status.permissions(); @@ -83,17 +81,17 @@ namespace anm2ed::util::path return true; } - bool ensure_directory(const std::filesystem::path& path) + bool path_ensure_directory(const std::filesystem::path& path) { if (path.empty()) return false; std::error_code ec; if (std::filesystem::create_directories(path, ec)) return true; - return is_exist(path.parent_path()); + return is_path_exist(path.parent_path()); } - std::filesystem::path make_relative(const std::filesystem::path& path) + std::filesystem::path path_make_relative(const std::filesystem::path& path) { if (path.empty()) return path; if (!path.is_absolute()) return path; @@ -104,7 +102,7 @@ namespace anm2ed::util::path return path; } - std::filesystem::path make_relative(const std::filesystem::path& path, const std::filesystem::path& base) + std::filesystem::path path_make_relative(const std::filesystem::path& path, const std::filesystem::path& base) { if (path.empty()) return path; if (base.empty() || !path.is_absolute()) return path; @@ -115,25 +113,25 @@ namespace anm2ed::util::path return path; } - std::filesystem::path backslash_handle(const std::filesystem::path& path) + std::filesystem::path path_backslash_handle(const std::filesystem::path& path) { auto newPath = path; - if (is_exist(newPath)) return newPath; + if (is_path_exist(newPath)) return newPath; - newPath = backslash_replace(newPath); + newPath = path_backslash_replace(newPath); return newPath; } - std::filesystem::path case_insensitive_find(const std::filesystem::path& path) + std::filesystem::path path_case_insensitive_find(const std::filesystem::path& path) { - auto handledPath = backslash_handle(path); - if (is_exist(handledPath)) return handledPath; + auto handledPath = path_backslash_handle(path); + if (is_path_exist(handledPath)) return handledPath; auto resolvedPath = handledPath.root_path(); for (const auto& part : handledPath.relative_path()) { auto candidate = resolvedPath / part; - if (is_exist(candidate)) + if (is_path_exist(candidate)) { resolvedPath = candidate; continue; @@ -144,11 +142,11 @@ namespace anm2ed::util::path bool isFound{}; if (std::filesystem::is_directory(parent, ec)) { - auto partLower = to_lower(part); + auto partLower = path_to_lower(part); std::filesystem::directory_iterator it(parent, ec); std::filesystem::directory_iterator end{}; for (; !ec && it != end; it.increment(ec)) - if (to_lower(it->path().filename()) == partLower) + if (path_to_lower(it->path().filename()) == partLower) { resolvedPath /= it->path().filename(); isFound = true; @@ -159,11 +157,10 @@ namespace anm2ed::util::path if (!isFound) resolvedPath = candidate; } - if (is_exist(resolvedPath)) return resolvedPath; + if (is_path_exist(resolvedPath)) return resolvedPath; - auto lowerPath = to_lower(handledPath); - if (is_exist(lowerPath)) return lowerPath; + auto lowerPath = path_to_lower(handledPath); + if (is_path_exist(lowerPath)) return lowerPath; return handledPath; } -} diff --git a/src/path.h b/src/path.h index bcaba0a..6923d97 100644 --- a/src/path.h +++ b/src/path.h @@ -3,21 +3,18 @@ #include #include -namespace anm2ed::util::path -{ - std::filesystem::path to_lower(const std::filesystem::path&); - std::filesystem::path backslash_replace(const std::filesystem::path&); - std::string to_utf8(const std::filesystem::path&); - std::filesystem::path from_utf8(const std::string&); - std::filesystem::path make_relative(const std::filesystem::path&); - std::filesystem::path make_relative(const std::filesystem::path&, const std::filesystem::path&); + std::filesystem::path path_to_lower(const std::filesystem::path&); + std::filesystem::path path_backslash_replace(const std::filesystem::path&); + std::string path_to_utf8(const std::filesystem::path&); + std::filesystem::path path_from_utf8(const std::string&); + std::filesystem::path path_make_relative(const std::filesystem::path&); + std::filesystem::path path_make_relative(const std::filesystem::path&, const std::filesystem::path&); - bool is_exist(const std::filesystem::path&); - bool is_executable(const std::filesystem::path&); - bool is_extension(const std::filesystem::path&, const std::string&); + bool is_path_exist(const std::filesystem::path&); + bool is_path_executable(const std::filesystem::path&); + bool is_path_extension(const std::filesystem::path&, const std::string&); - bool ensure_directory(const std::filesystem::path&); + bool path_ensure_directory(const std::filesystem::path&); - std::filesystem::path backslash_handle(const std::filesystem::path&); - std::filesystem::path case_insensitive_find(const std::filesystem::path&); -} + std::filesystem::path path_backslash_handle(const std::filesystem::path&); + std::filesystem::path path_case_insensitive_find(const std::filesystem::path&); diff --git a/src/playback.cpp b/src/playback.cpp index 88580b1..062b37b 100644 --- a/src/playback.cpp +++ b/src/playback.cpp @@ -4,8 +4,6 @@ #include -namespace anm2ed -{ void Playback::toggle() { if (isFinished) time = 0.0f; @@ -56,4 +54,3 @@ namespace anm2ed clamp(length); timing_reset(); } -} diff --git a/src/playback.h b/src/playback.h index 1239abc..8b309a0 100644 --- a/src/playback.h +++ b/src/playback.h @@ -1,7 +1,5 @@ #pragma once -namespace anm2ed -{ class Playback { public: @@ -19,4 +17,3 @@ namespace anm2ed private: float tickAccumulator{}; }; -} diff --git a/src/render.cpp b/src/render.cpp index 2e50cfe..82d0462 100644 --- a/src/render.cpp +++ b/src/render.cpp @@ -28,26 +28,20 @@ #include "texture.h" #include "ui/toast.h" -using namespace anm2ed::imgui; -using namespace anm2ed::resource; -using namespace anm2ed::util; - -namespace anm2ed -{ bool animation_render(const std::filesystem::path& ffmpegPath, const std::filesystem::path& path, const std::vector& framePaths, AudioStream& audioStream, - render::Type type, int fps) + RenderType type, int fps) { if (framePaths.empty() || ffmpegPath.empty() || path.empty()) return false; fps = std::max(fps, 1); - auto pathString = path::to_utf8(path); - auto ffmpegPathString = path::to_utf8(ffmpegPath); + auto pathString = path_to_utf8(path); + auto ffmpegPathString = path_to_utf8(ffmpegPath); auto loggerPath = logger.path(); - auto loggerPathString = path::to_utf8(loggerPath); + auto loggerPathString = path_to_utf8(loggerPath); #if _WIN32 auto ffmpegTempPath = loggerPath.parent_path() / "ffmpeg_log.temp.txt"; - auto ffmpegTempPathString = path::to_utf8(ffmpegTempPath); + auto ffmpegTempPathString = path_to_utf8(ffmpegTempPath); std::error_code ffmpegTempError; std::filesystem::remove(ffmpegTempPath, ffmpegTempError); #endif @@ -68,16 +62,16 @@ namespace anm2ed } }; - if (type != render::GIF && !audioStream.stream.empty() && audioStream.spec.freq > 0 && + if (type != RENDER_GIF && !audioStream.stream.empty() && audioStream.spec.freq > 0 && audioStream.spec.channels > 0) { auto tempFilenameUtf8 = std::format("anm2ed_audio_{}_{}.f32", std::hash{}(pathString), SDL_GetTicks()); - audioPath = temporaryDirectory / path::from_utf8(tempFilenameUtf8); + audioPath = temporaryDirectory / path_from_utf8(tempFilenameUtf8); auto data = (const char*)audioStream.stream.data(); auto byteCount = audioStream.stream.size() * sizeof(float); - if (file::write_string(audioPath, std::string_view(data, byteCount), "wb")) + if (file_text_save(audioPath, std::string_view(data, byteCount), "wb")) { auto sampleRate = std::max(audioStream.spec.freq, 1); auto channels = std::max(audioStream.spec.channels, 1); @@ -88,17 +82,17 @@ namespace anm2ed audioDurationFilter += std::format("apad,atrim=duration={:.9f}", expectedDurationSeconds); audioInputArguments = - std::format("-f f32le -ar {0} -ac {1} -i \"{2}\"", sampleRate, channels, path::to_utf8(audioPath)); + std::format("-f f32le -ar {0} -ac {1} -i \"{2}\"", sampleRate, channels, path_to_utf8(audioPath)); switch (type) { - case render::WEBM: + case RENDER_WEBM: audioOutputArguments = "-c:a libopus -b:a 160k -shortest"; break; - case render::OGV: + case RENDER_OGV: audioOutputArguments = "-c:a libvorbis -q:a 4 -shortest"; break; - case render::MP4: + case RENDER_MP4: audioOutputArguments = "-c:a aac -b:a 192k -shortest"; break; default: @@ -115,8 +109,8 @@ namespace anm2ed } } - auto framePattern = temporaryDirectory / path::from_utf8("frame_%06d.png"); - auto framePatternString = path::to_utf8(framePattern); + auto framePattern = temporaryDirectory / path_from_utf8("frame_%06d.png"); + auto framePatternString = path_to_utf8(framePattern); command = std::format("\"{0}\" -y -framerate {1} -start_number 0 -i \"{2}\"", ffmpegPathString, fps, framePatternString); @@ -125,23 +119,23 @@ namespace anm2ed switch (type) { - case render::GIF: + case RENDER_GIF: command += " -lavfi \"split[s0][s1];[s0]palettegen=stats_mode=full:reserve_transparent=1[p];" "[s1][p]paletteuse=dither=floyd_steinberg:alpha_threshold=128\"" " -loop 0"; command += std::format(" \"{}\"", pathString); break; - case render::WEBM: + case RENDER_WEBM: command += " -c:v libvpx-vp9 -crf 30 -b:v 0 -pix_fmt yuva420p -row-mt 1 -threads 0 -speed 2 -auto-alt-ref 0"; if (!audioOutputArguments.empty()) command += " " + audioOutputArguments; command += std::format(" \"{}\"", pathString); break; - case render::OGV: + 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: + 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"; if (!audioOutputArguments.empty()) command += " " + audioOutputArguments; @@ -182,24 +176,21 @@ namespace anm2ed audio_remove(); return true; } -} -namespace anm2ed::render -{ constexpr int TEMP_DIRECTORY_ATTEMPTS = 1000; constexpr glm::vec4 BOUNDS_DEFAULT = {-32.0f, -32.0f, 64.0f, 64.0f}; constexpr int ALPHA_OPAQUE = 255; constexpr float CHANNEL_MAX = 255.0f; - std::filesystem::path frame_filename_get(const std::filesystem::path& format, int index, Type type) + static std::filesystem::path frame_filename_get(const std::filesystem::path& format, int index, RenderType type) { - auto fallback = path::from_utf8(std::format("frame_{:06}.png", index)); - if (type != PNGS) return fallback; + auto fallback = path_from_utf8(std::format("frame_{:06}.png", index)); + if (type != RENDER_PNGS) return fallback; 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(path_to_utf8(format), std::make_format_args(index))).filename(); if (filename.empty()) return fallback; - if (filename.extension().empty()) filename.replace_extension(EXTENSIONS[SPRITESHEET]); + if (filename.extension().empty()) filename.replace_extension(RENDER_EXTENSIONS[RENDER_SPRITESHEET]); return filename; } catch (...) @@ -209,10 +200,10 @@ namespace anm2ed::render } // PNG sequences go straight to their folder; other outputs collect frames in a temporary folder beside the output. - std::filesystem::path frames_directory_create(const RecorderOptions& options) + static std::filesystem::path frames_directory_create(const RecorderOptions& options) { std::error_code ec{}; - if (options.type == PNGS) + if (options.type == RENDER_PNGS) { std::filesystem::create_directories(options.path, ec); return options.path; @@ -225,7 +216,7 @@ namespace anm2ed::render .count(); for (int suffix = 0; suffix < TEMP_DIRECTORY_ATTEMPTS; ++suffix) { - auto temporary = directory / path::from_utf8(std::format(".anm2ed_render_tmp_{}_{}", timestamp, suffix)); + auto temporary = directory / path_from_utf8(std::format(".anm2ed_render_tmp_{}_{}", timestamp, suffix)); if (std::filesystem::create_directories(temporary, ec)) return temporary; } return {}; @@ -234,7 +225,7 @@ namespace anm2ed::render // Rendered pixels are premultiplied; outputs on a transparent background want straight alpha. void pixels_unpremultiply(std::vector& pixels) { - for (std::size_t index = 0; index + 3 < pixels.size(); index += image::CHANNELS) + for (std::size_t index = 0; index + 3 < pixels.size(); index += IMAGE_CHANNELS) { auto alpha = pixels[index + 3]; if (alpha == ALPHA_OPAQUE) continue; @@ -246,15 +237,15 @@ namespace anm2ed::render } } - void sounds_detach(const Document& document, MIX_Mixer* mixer) + static void sounds_detach(const Document& document, MIX_Mixer* mixer) { for (auto sound : document.sounds_get()) - audio::track_detach(*sound, mixer); + audio_track_detach(*sound, mixer); } // Mixes each frame's trigger sounds into one stream at the render frame rate. - bool audio_stream_generate(AudioStream& audioStream, const Document& document, - const std::vector>& frameSounds, int fps) + static bool audio_stream_generate(AudioStream& audioStream, const Document& document, + const std::vector>& frameSounds, int fps) { audioStream.stream.clear(); if (frameSounds.empty() || fps <= 0) return true; @@ -272,7 +263,7 @@ namespace anm2ed::render for (const auto& sounds : frameSounds) { for (auto sound : sounds) - audio::play(*sound, false, mixer); + audio_play(*sound, false, mixer); accumulator += framesPerStep; auto sampleFrames = std::max((int)std::floor(accumulator), 1); accumulator -= (double)sampleFrames; @@ -313,14 +304,14 @@ namespace anm2ed::render bool HeadlessGL::is_valid() const { return context != nullptr; } - glm::vec4 animation_bounds_get(const Document& document, const model::Animation& animation, bool isRootTransform) + glm::vec4 animation_bounds_get(const Document& document, const Animation& animation, bool isRootTransform) { - auto bounds = model::animation_rect(document.model, animation, isRootTransform, document.library_resolver_get()); + auto bounds = animation_rect(document.model, animation, isRootTransform, document.library_resolver_get()); return bounds != glm::vec4(-1.0f) ? bounds : BOUNDS_DEFAULT; } - std::vector animation_frame_render(Canvas& canvas, Shader& shader, Document& document, - const model::Animation& animation, float time, glm::vec4 bounds, + std::vector animation_frame_render(Canvas& canvas, ShaderProgram& shader, Document& document, + const Animation& animation, float time, glm::vec4 bounds, float scale, glm::vec4 background, bool isRootTransform) { canvas.size_set(glm::vec2(glm::max(glm::ivec2(glm::ceil(glm::vec2(bounds.z, bounds.w) * scale)), glm::ivec2(1)))); @@ -334,7 +325,7 @@ namespace anm2ed::render shader, document.model, animation, {.time = time, .isRootTransform = isRootTransform, .library_get = document.library_resolver_get()}, canvas.transform_get(zoom, pan), - [&](const model::Draw& draw) { return document.draw_image_get(draw, scale * model::draw_scale_get(draw)); }, + [&](const Draw& draw) { return document.draw_image_get(draw, scale * draw_scale_get(draw)); }, [&](int id) { return document.shader_get(id); }); auto pixels = canvas.pixels_get(); canvas.unbind(); @@ -361,7 +352,7 @@ namespace anm2ed::render bool Recorder::is_sound_frame() const { return (int)std::floor(time_get()) != soundTime; } bool Recorder::frame_capture(std::vector pixels, glm::ivec2 size, - std::vector frameSounds) + std::vector frameSounds) { soundTime = (int)std::floor(time_get()); sounds.push_back(std::move(frameSounds)); @@ -375,11 +366,11 @@ namespace anm2ed::render void Recorder::finish(const Document& document, AudioStream& audioStream) { - auto pathString = path::to_utf8(options.path); - if (options.type == PNGS) + auto pathString = path_to_utf8(options.path); + if (options.type == RENDER_PNGS) toast_log(frames.empty() ? Level::ERROR : Level::INFO, frames.empty() ? TOAST_EXPORT_RENDERED_FRAMES_FAILED : TOAST_EXPORT_RENDERED_FRAMES, pathString); - else if (options.type == SPRITESHEET) + else if (options.type == RENDER_SPRITESHEET) { auto layout = spritesheet_layout_get(options.rows, options.columns, (int)frames.size()); auto first = frames.empty() ? Image{} : Image(frames.front()); @@ -391,7 +382,7 @@ namespace anm2ed::render { Image sheet{}; sheet.size = first.size * glm::ivec2(layout.columns, layout.rows); - sheet.pixels.resize((std::size_t)sheet.size.x * sheet.size.y * image::CHANNELS); + sheet.pixels.resize((std::size_t)sheet.size.x * sheet.size.y * IMAGE_CHANNELS); for (int i = 0; i < (int)frames.size() && i < layout.rows * layout.columns; ++i) if (auto frame = Image(frames[i]); frame.size == first.size) sheet.paste(frame, first.size * glm::ivec2(i % layout.columns, i / layout.columns)); @@ -403,7 +394,7 @@ namespace anm2ed::render else { audioStream.stream.clear(); - if (options.isSound && options.type != GIF && !audio_stream_generate(audioStream, document, sounds, options.fps)) + if (options.isSound && options.type != RENDER_GIF && !audio_stream_generate(audioStream, document, sounds, options.fps)) { toasts.push(localize.get(TOAST_EXPORT_RENDERED_ANIMATION_FAILED)); logger.error("Failed to generate deterministic render audio stream; exporting without audio."); @@ -420,15 +411,15 @@ namespace anm2ed::render void Recorder::cancel() { std::error_code ec{}; - if (options.type != PNGS && !directory.empty()) std::filesystem::remove_all(directory, ec); + if (options.type != RENDER_PNGS && !directory.empty()) std::filesystem::remove_all(directory, ec); directory.clear(); frames.clear(); sounds.clear(); index = count = 0; } - bool animation_record(const RecorderOptions& recorderOptions, Canvas& canvas, Shader& shader, Document& document, - const model::Animation& animation, glm::vec4 bounds, float scale, glm::vec4 background, + bool animation_record(const RecorderOptions& recorderOptions, Canvas& canvas, ShaderProgram& shader, Document& document, + const Animation& animation, glm::vec4 bounds, float scale, glm::vec4 background, bool isRootTransform) { auto options = recorderOptions; @@ -445,7 +436,7 @@ namespace anm2ed::render } AudioStream audioStream(nullptr); recorder.finish(document, audioStream); - return path::is_exist(options.path); + return is_path_exist(options.path); } constexpr float BAKE_MARGIN = 1.0f; @@ -453,12 +444,12 @@ namespace anm2ed::render // A layer draw alone at canvas pixels, cut to what it can cover (its blur's reach too): its image (straight alpha) and // the canvas position of the image's top-left. Its tint and color offset go into the pixels only when `isColored`. - std::optional> draw_bake(Canvas& canvas, Shader& shader, Document& document, - const model::Draw& draw, bool isColored) + static std::optional> draw_bake(Canvas& canvas, ShaderProgram& shader, Document& document, + const Draw& draw, bool isColored) { - auto image = document.draw_image_get(draw, model::draw_scale_get(draw)); + auto image = document.draw_image_get(draw, draw_scale_get(draw)); if (!image || !image->is_valid() || draw.frame.size == glm::vec2()) return {}; - auto quad = draw.parent * model::draw_quad_model_get(draw); + auto quad = draw.parent * draw_quad_model_get(draw); glm::vec2 low{std::numeric_limits::max()}; glm::vec2 high{std::numeric_limits::lowest()}; for (auto corner : {glm::vec2(0.0f), glm::vec2(1.0f, 0.0f), glm::vec2(0.0f, 1.0f), glm::vec2(1.0f)}) @@ -480,7 +471,7 @@ namespace anm2ed::render canvas.viewport_set(); canvas.clear(glm::vec4(0.0f)); auto custom = document.shader_get(draw.frame.shaderId); - canvas.layer_render(custom ? *custom : shader, texture::id_get(*image), image->unit_size_get(), + canvas.layer_render(custom ? *custom : shader, texture_id_get(*image), image->unit_size_get(), canvas.transform_get(zoom, pan), draw, isColored ? draw.frame.tint : glm::vec4(1.0f), isColored ? draw.frame.colorOffset : glm::vec4(0.0f)); auto pixels = canvas.pixels_get(); @@ -493,33 +484,33 @@ namespace anm2ed::render // layer frame under a skewed root or group root, which then goes into the images (the root becomes plain). A layer has one spritesheet in the game, so baked frames stand on a copy of their layer // ("name (baked)") right after it, one frame per step, while the layer hides them. The images (each once) are packed // into one spritesheet written to `path`, beside the document; when it can't be, `result` keeps its frames. - void frames_bake(Document& document, model::Model& result, const std::filesystem::path& path) + void frames_bake(Document& document, Model& result, const std::filesystem::path& path) { auto game = result; - auto is_baked = [](const model::Frame& frame) + auto is_baked = [](const Frame& frame) { return frame.skew != glm::vec2() || frame.blur > 0.0f || frame.shaderId != -1; }; - auto is_skewed = [](const model::Track& root) - { return std::ranges::any_of(root.frames, [](const model::Frame& frame) { return frame.skew != glm::vec2(); }); }; + auto is_skewed = [](const Track& root) + { return std::ranges::any_of(root.frames, [](const Frame& frame) { return frame.skew != glm::vec2(); }); }; std::vector indices{}; for (int i = 0; i < game.animations_count_get(); ++i) { auto& animation = *game.animation_get(i); auto isNeeded = is_skewed(animation.root); - model::tracks_each( - animation.layers, [&](const model::Track& track, const model::TrackGroup* group) + tracks_each( + animation.layers, [&](const Track& track, const TrackGroup* group) { isNeeded |= (group && is_skewed(group->root)) || std::ranges::any_of(track.frames, is_baked); }); if (isNeeded) indices.push_back(i); } - auto pathUtf8 = path::to_utf8(path); + auto pathUtf8 = path_to_utf8(path); if (indices.empty()) return; if (!SDL_GL_GetCurrentContext()) return toast_log(Level::WARNING, TOAST_BAKE_NO_OPENGL, pathUtf8); - auto& textureInfo = shader::SHADERS[shader::TEXTURE]; - Shader shader(textureInfo.vertex, textureInfo.fragment); + auto& textureInfo = SHADERS[SHADER_TEXTURE]; + ShaderProgram shader(textureInfo.vertex, textureInfo.fragment); Canvas canvas(glm::vec2(1.0f)); auto& content = game.content; - auto spritesheetId = model::item_next_id_get(content.spritesheets); + auto spritesheetId = item_next_id_get(content.spritesheets); std::vector images{}; std::map> imageHashes{}; @@ -538,15 +529,15 @@ namespace anm2ed::render { auto [it, isNew] = bakedLayerIds.try_emplace(layerId); if (!isNew) return it->second; - auto layer = model::item_get(content.layers, layerId); - it->second = model::item_next_id_get(content.layers); + auto layer = item_get(content.layers, layerId); + it->second = item_next_id_get(content.layers); content.layers.push_back({.id = it->second, .name = (layer ? layer->name : std::string{}) + " (baked)", .spritesheetId = spritesheetId}); return it->second; }; // Steps alike join into one frame. - auto step_add = [](model::Track& track, model::Frame frame) + auto step_add = [](Track& track, Frame frame) { frame.duration = FRAME_DURATION_MIN; frame.interpolation = Interpolation::NONE; @@ -565,21 +556,21 @@ namespace anm2ed::render auto& animation = *game.animation_edit(index); auto isRootFolded = is_skewed(animation.root); // A layer track's baked copy, the track left with the rest; nothing when no frame of it bakes. - auto track_bake = [&](model::Track& track, const model::Track* groupRoot) -> std::optional + auto track_bake = [&](Track& track, const Track* groupRoot) -> std::optional { auto isForced = isRootFolded || groupRoot; - auto layer = model::item_get(content.layers, track.id); + auto layer = item_get(content.layers, track.id); if (!layer || (!isForced && std::ranges::none_of(track.frames, is_baked))) return {}; - model::Track plain{track}; + Track plain{track}; plain.frames.clear(); - model::Track baked{.type = ItemType::LAYER, .id = -1, .isVisible = track.isVisible}; + Track baked{.type = ItemType::LAYER, .id = -1, .isVisible = track.isVisible}; auto isBaked = false; - auto length = std::max(model::track_length_get(track), animation.frameNum); + auto length = std::max(track_length_get(track), animation.frameNum); for (int time = 0; time < length; ++time) { - auto frame = model::frame_generate(track, (float)time); + auto frame = frame_generate(track, (float)time); std::optional> bakedImage{}; - model::Draw draw{.type = model::DrawType::LAYER, + Draw draw{.type = DrawType::LAYER, .id = track.id, .time = (float)time, .frame = frame, @@ -588,11 +579,11 @@ namespace anm2ed::render if (frame.isVisible && (isForced || is_baked(frame))) { for (auto* root : - std::initializer_list{isRootFolded ? &animation.root : nullptr, groupRoot}) + std::initializer_list{isRootFolded ? &animation.root : nullptr, groupRoot}) if (root) { - auto rootFrame = model::frame_generate(*root, (float)time); - draw.parent *= model::frame_parent_model_get(rootFrame); + auto rootFrame = frame_generate(*root, (float)time); + draw.parent *= frame_parent_model_get(rootFrame); draw.frame.tint *= rootFrame.tint; draw.frame.colorOffset += rootFrame.colorOffset; } @@ -601,7 +592,7 @@ namespace anm2ed::render if (!bakedImage) { step_add(plain, frame); - step_add(baked, model::Frame{.isVisible = false}); + step_add(baked, Frame{.isVisible = false}); continue; } // The image stands where it was drawn, its region found once the images are packed (kept in regionId). @@ -615,14 +606,14 @@ namespace anm2ed::render step.size = glm::vec2(bakedImage->first.size); step.pivot = {}; step.position = bakedImage->second; - step.scale = model::Frame{}.scale; + step.scale = Frame{}.scale; step.skew = {}; step.rotation = 0.0f; step.blur = 0.0f; step.shaderId = -1; step.regionId = image_index_get(std::move(bakedImage->first)); step_add(baked, step); - step_add(plain, model::Frame{.isVisible = false}); + step_add(plain, Frame{.isVisible = false}); isBaked = true; } if (!isBaked) return {}; @@ -631,9 +622,9 @@ namespace anm2ed::render return baked; }; - std::vector entries{}; + std::vector entries{}; for (auto& entry : animation.layers) - if (auto track = std::get_if(&entry)) + if (auto track = std::get_if(&entry)) { auto baked = track_bake(*track, nullptr); entries.emplace_back(std::move(*track)); @@ -641,9 +632,9 @@ namespace anm2ed::render } else { - auto group = std::get(entry); + auto group = std::get(entry); auto isGroupFolded = is_skewed(group.root); - std::vector tracks{}; + std::vector tracks{}; for (auto& groupTrack : group.tracks) { auto baked = track_bake(groupTrack, isGroupFolded ? &group.root : nullptr); @@ -651,7 +642,7 @@ namespace anm2ed::render if (baked) tracks.push_back(std::move(*baked)); } group.tracks = std::move(tracks); - if (isGroupFolded) group.root = model::TrackGroup{}.root; + if (isGroupFolded) group.root = TrackGroup{}.root; entries.emplace_back(std::move(group)); } animation.layers = std::move(entries); @@ -659,19 +650,19 @@ namespace anm2ed::render // A folded root's transform goes into the nulls too (their group roots first), and the root becomes plain. if (!isRootFolded) continue; for (auto& entry : animation.nulls) - if (auto track = std::get_if(&entry)) - model::track_group_root_bake(*track, animation.root, animation.frameNum); + if (auto track = std::get_if(&entry)) + track_group_root_bake(*track, animation.root, animation.frameNum); else { - auto& group = std::get(entry); + auto& group = std::get(entry); for (auto& groupTrack : group.tracks) { - model::track_group_root_bake(groupTrack, group.root, animation.frameNum); - model::track_group_root_bake(groupTrack, animation.root, animation.frameNum); + track_group_root_bake(groupTrack, group.root, animation.frameNum); + track_group_root_bake(groupTrack, animation.root, animation.frameNum); } - group.root = model::TrackGroup{}.root; + group.root = TrackGroup{}.root; } - animation.root = model::Animation{}.root; + animation.root = Animation{}.root; } if (images.empty()) return; @@ -680,7 +671,7 @@ namespace anm2ed::render sizes.push_back(image.size); glm::ivec2 packedSize{}; std::vector positions{}; - pack::rects_pack(sizes, packedSize, positions); + rects_pack(sizes, packedSize, positions); std::vector parts{}; for (int i = 0; i < (int)images.size(); ++i) parts.push_back({.image = &images[i], .size = images[i].size, .destination = positions[i]}); @@ -694,8 +685,8 @@ namespace anm2ed::render for (auto [layerId, bakedId] : bakedLayerIds) bakedIds.insert(bakedId); for (auto index : indices) - model::tracks_each(game.animation_edit(index)->layers, - [&](model::Track& track, auto*) + tracks_each(game.animation_edit(index)->layers, + [&](Track& track, auto*) { if (!bakedIds.contains(track.id)) return; for (auto& frame : track.frames) @@ -707,4 +698,3 @@ namespace anm2ed::render }); result = std::move(game); } -} diff --git a/src/render.h b/src/render.h index 7af633c..2613ae0 100644 --- a/src/render.h +++ b/src/render.h @@ -12,39 +12,28 @@ struct SDL_Window; struct SDL_GLContextState; -namespace anm2ed -{ class Canvas; class Document; -} -namespace anm2ed::model -{ struct Animation; class Model; -} -namespace anm2ed::resource -{ - class Shader; -} + class ShaderProgram; -namespace anm2ed::render -{ #define RENDER_LIST \ - X(PNGS, "PNGs", "") \ - X(SPRITESHEET, "Spritesheet (PNG)", ".png") \ - X(GIF, "GIF", ".gif") \ - X(WEBM, "WebM", ".webm") \ - X(OGV, "OGV", ".ogv") \ - X(MP4, "MP4", ".mp4") + X(RENDER_PNGS, "PNGs", "") \ + X(RENDER_SPRITESHEET, "Spritesheet (PNG)", ".png") \ + X(RENDER_GIF, "GIF", ".gif") \ + X(RENDER_WEBM, "WebM", ".webm") \ + X(RENDER_OGV, "OGV", ".ogv") \ + X(RENDER_MP4, "MP4", ".mp4") - enum Type + enum RenderType { #define X(symbol, string, extension) symbol, RENDER_LIST #undef X - COUNT + RENDER_COUNT }; enum FpsMode @@ -54,13 +43,13 @@ namespace anm2ed::render FPS_COUNT }; - constexpr const char* STRINGS[] = { + constexpr const char* RENDER_STRINGS[] = { #define X(symbol, string, extension) string, RENDER_LIST #undef X }; - constexpr const char* EXTENSIONS[] = { + constexpr const char* RENDER_EXTENSIONS[] = { #define X(symbol, string, extension) extension, RENDER_LIST #undef X @@ -140,16 +129,16 @@ namespace anm2ed::render }; // The area an animation covers over all its frames (or a default one when it draws nothing). - glm::vec4 animation_bounds_get(const Document&, const model::Animation&, bool); + glm::vec4 animation_bounds_get(const Document&, const Animation&, bool); // One frame drawn over `bounds` at `scale`, as premultiplied RGBA rows from the top. - std::vector animation_frame_render(Canvas&, resource::Shader&, Document&, const model::Animation&, float, + std::vector animation_frame_render(Canvas&, ShaderProgram&, Document&, const Animation&, float, glm::vec4, float, glm::vec4, bool); void pixels_unpremultiply(std::vector&); - void frames_bake(Document&, model::Model&, const std::filesystem::path&); + void frames_bake(Document&, Model&, const std::filesystem::path&); struct RecorderOptions { - Type type{}; + RenderType type{}; std::filesystem::path path{}; std::filesystem::path format{}; std::filesystem::path ffmpegPath{}; @@ -177,26 +166,22 @@ namespace anm2ed::render bool is_done() const; float time_get() const; bool is_sound_frame() const; - bool frame_capture(std::vector, glm::ivec2, std::vector = {}); + bool frame_capture(std::vector, glm::ivec2, std::vector = {}); void finish(const Document&, AudioStream&); void cancel(); private: std::filesystem::path directory{}; std::vector frames{}; - std::vector> sounds{}; + std::vector> sounds{}; int soundTime{-1}; }; // Records a whole animation with these options (bounded and isolated), each frame drawn as animation_frame_render // draws it; false when a frame or the output can't be written. - bool animation_record(const RecorderOptions&, Canvas&, resource::Shader&, Document&, const model::Animation&, + bool animation_record(const RecorderOptions&, Canvas&, ShaderProgram&, Document&, const Animation&, glm::vec4, float, glm::vec4, bool); -} -namespace anm2ed -{ std::filesystem::path ffmpeg_log_path(); bool animation_render(const std::filesystem::path&, const std::filesystem::path&, - const std::vector&, AudioStream&, render::Type, int); -} + const std::vector&, AudioStream&, RenderType, int); diff --git a/src/resources.cpp b/src/resources.cpp index 8783920..77cffb7 100644 --- a/src/resources.cpp +++ b/src/resources.cpp @@ -4,8 +4,6 @@ #include "log.h" -using namespace anm2ed::resource; - #ifdef _WIN32 static constexpr const char* CHINESE_FALLBACK = "C:\\Windows\\Fonts\\msyh.ttc"; static constexpr const char* KOREAN_FALLBACK = "C:\\Windows\\Fonts\\malgun.ttf"; @@ -18,8 +16,6 @@ static constexpr int CHINESE_FALLBACK_NUMBER = 2; static constexpr int KOREAN_FALLBACK_NUMBER = 1; #endif -namespace anm2ed -{ Resources::Resources() { auto isKoreanFallback = std::filesystem::exists(KOREAN_FALLBACK); @@ -28,29 +24,29 @@ namespace anm2ed if (!isKoreanFallback) logger.error(std::format("Failed to load Korean fallback font: {}", KOREAN_FALLBACK)); if (!isChineseFallback) logger.error(std::format("Failed to load Chinese fallback font: {}", CHINESE_FALLBACK)); - for (auto [i, fontInfo] : std::views::enumerate(font::FONTS)) + for (auto [i, fontInfo] : std::views::enumerate(FONTS)) { - fonts[i] = Font((void*)fontInfo->data, fontInfo->size, font::SIZE); + fonts[i] = Font((void*)fontInfo->data, fontInfo->size, FONT_SIZE); if (isKoreanFallback) - fonts[i].append(KOREAN_FALLBACK, font::SIZE, KOREAN_FALLBACK_NUMBER); + fonts[i].append(KOREAN_FALLBACK, FONT_SIZE, KOREAN_FALLBACK_NUMBER); else - fonts[i].append((void*)FONT_KOREAN_TTF.data, FONT_KOREAN_TTF.size, font::SIZE); + fonts[i].append((void*)FONT_KOREAN_TTF.data, FONT_KOREAN_TTF.size, FONT_SIZE); if (isChineseFallback) - fonts[i].append(CHINESE_FALLBACK, font::SIZE, CHINESE_FALLBACK_NUMBER); + fonts[i].append(CHINESE_FALLBACK, FONT_SIZE, CHINESE_FALLBACK_NUMBER); else - fonts[i].append((void*)FONT_CHINESE_TTF.data, FONT_CHINESE_TTF.size, font::SIZE); + fonts[i].append((void*)FONT_CHINESE_TTF.data, FONT_CHINESE_TTF.size, FONT_SIZE); } - for (auto [i, iconInfo] : std::views::enumerate(icon::ICONS)) - icons[i] = texture::svg_load((const char*)iconInfo.svg->data, iconInfo.svg->size, iconInfo.size); + for (auto [i, iconInfo] : std::views::enumerate(ICONS)) + icons[i] = texture_svg_load((const char*)iconInfo.svg->data, iconInfo.svg->size, iconInfo.size); - for (auto [i, shaderInfo] : std::views::enumerate(shader::SHADERS)) - shaders[i] = Shader(shaderInfo.vertex, shaderInfo.fragment); + for (auto [i, shaderInfo] : std::views::enumerate(SHADERS)) + shaders[i] = ShaderProgram(shaderInfo.vertex, shaderInfo.fragment); }; - GLuint Resources::icon_id_get(int icon) { return texture::id_get(icons[icon]); } + GLuint Resources::icon_id_get(int icon) { return texture_id_get(icons[icon]); } - resource::AudioData& Resources::music_track() + AudioData& Resources::music_track() { if (!isMusicLoaded) { @@ -60,5 +56,4 @@ namespace anm2ed return music; } - resource::AudioData* Resources::music_track_if_loaded() { return isMusicLoaded ? &music : nullptr; } -} + AudioData* Resources::music_track_if_loaded() { return isMusicLoaded ? &music : nullptr; } diff --git a/src/resources.h b/src/resources.h index 363acb5..ec73d7a 100644 --- a/src/resources.h +++ b/src/resources.h @@ -8,22 +8,19 @@ #include "shader.h" #include "texture.h" -namespace anm2ed -{ class Resources { public: - resource::Font fonts[resource::font::COUNT]{}; - resource::Image icons[resource::icon::COUNT]{}; - resource::Shader shaders[resource::shader::COUNT]{}; - resource::AudioData music{}; + Font fonts[FONT_COUNT]{}; + Image icons[ICON_COUNT]{}; + ShaderProgram shaders[SHADER_COUNT]{}; + AudioData music{}; Resources(); GLuint icon_id_get(int); - resource::AudioData& music_track(); - resource::AudioData* music_track_if_loaded(); + AudioData& music_track(); + AudioData* music_track_if_loaded(); private: bool isMusicLoaded{false}; }; -} diff --git a/src/sdl.cpp b/src/sdl.cpp index 23a349f..741881b 100644 --- a/src/sdl.cpp +++ b/src/sdl.cpp @@ -5,14 +5,11 @@ #include "path.h" -namespace anm2ed::util::sdl -{ std::filesystem::path preferences_directory_get() { auto sdlPath = SDL_GetPrefPath(nullptr, "anm2ed"); if (!sdlPath) return {}; - auto filePath = path::from_utf8(sdlPath); + auto filePath = path_from_utf8(sdlPath); SDL_free(sdlPath); return filePath; } -} diff --git a/src/sdl.h b/src/sdl.h index 64d40a7..e7d87d6 100644 --- a/src/sdl.h +++ b/src/sdl.h @@ -2,7 +2,4 @@ #include -namespace anm2ed::util::sdl -{ std::filesystem::path preferences_directory_get(); -} \ No newline at end of file diff --git a/src/selection.cpp b/src/selection.cpp index c1dead4..be16804 100644 --- a/src/selection.cpp +++ b/src/selection.cpp @@ -1,8 +1,6 @@ #include "selection.h" -namespace anm2ed -{ - std::set selection_references_get(const Selection& selection, const model::UidIndex& index, + std::set selection_references_get(const Selection& selection, const UidIndex& index, SelectionKind kind) { std::set references{}; @@ -12,12 +10,12 @@ namespace anm2ed return references; } - std::uint64_t handle_uid_get(Handle handle) + static std::uint64_t handle_uid_get(Handle handle) { return handle.frame ? handle.frame : handle.item ? handle.item : handle.animation; } - void selection_references_set(Selection& selection, const model::Model& model, SelectionKind kind, + void selection_references_set(Selection& selection, const Model& model, SelectionKind kind, const std::set& references) { auto& uids = selection.uids[kind]; @@ -27,20 +25,20 @@ namespace anm2ed } // The most specific part of the focus that still exists. - Reference selection_focus_get(const Selection& selection, const model::UidIndex& index) + Reference selection_focus_get(const Selection& selection, const UidIndex& index) { for (auto uid : {selection.focus.frame, selection.focus.item, selection.focus.animation}) if (auto reference = index.reference_get(uid)) return *reference; return {}; } - void selection_focus_set(Selection& selection, const model::Model& model, Reference reference) + void selection_focus_set(Selection& selection, const Model& model, Reference reference) { selection.focus = model.handle_get(reference); } // (id, uid) of every content item a kind selects from. - std::vector> content_keys_get(const Selection& selection, const model::Model& model, + static std::vector> content_keys_get(const Selection& selection, const Model& model, SelectionKind kind) { std::vector> keys{}; @@ -58,13 +56,13 @@ namespace anm2ed if (kind == SelectionKind::SOUNDS) add(content.sounds); if (kind == SelectionKind::LIBRARIES) add(content.libraries); if (kind == SelectionKind::REGIONS) - if (auto spritesheet = model::item_get(content.spritesheets, + if (auto spritesheet = item_get(content.spritesheets, selection_focus_id_get(selection, model, SelectionKind::SPRITESHEETS))) add(spritesheet->regions); return keys; } - std::set selection_ids_get(const Selection& selection, const model::Model& model, SelectionKind kind) + std::set selection_ids_get(const Selection& selection, const Model& model, SelectionKind kind) { std::set ids{}; auto uids = selection.uids.find(kind); @@ -74,7 +72,7 @@ namespace anm2ed return ids; } - void selection_ids_set(Selection& selection, const model::Model& model, SelectionKind kind, const std::set& ids) + void selection_ids_set(Selection& selection, const Model& model, SelectionKind kind, const std::set& ids) { auto& uids = selection.uids[kind]; uids.clear(); @@ -82,7 +80,7 @@ namespace anm2ed if (ids.contains(id)) uids.insert(uid); } - int selection_focus_id_get(const Selection& selection, const model::Model& model, SelectionKind kind) + int selection_focus_id_get(const Selection& selection, const Model& model, SelectionKind kind) { auto focus = selection.focuses.find(kind); if (focus == selection.focuses.end()) return -1; @@ -91,7 +89,7 @@ namespace anm2ed return -1; } - void selection_focus_id_set(Selection& selection, const model::Model& model, SelectionKind kind, int id) + void selection_focus_id_set(Selection& selection, const Model& model, SelectionKind kind, int id) { selection.focuses.erase(kind); for (auto [itemId, uid] : content_keys_get(selection, model, kind)) @@ -104,7 +102,7 @@ namespace anm2ed // After an edit: drops uids that no longer exist, and moves a focus whose element was removed to its nearest // survivor (a frame at the same index of its track, the animation's root track, or the nearest animation). - void selection_follow(Selection& selection, const model::Model& model, const model::UidIndex& index, Reference before) + void selection_follow(Selection& selection, const Model& model, const UidIndex& index, Reference before) { for (auto& [kind, uids] : selection.uids) if (kind < SelectionKind::SPRITESHEETS) @@ -133,4 +131,3 @@ namespace anm2ed selection_focus_set(selection, model, reference); } -} diff --git a/src/selection.h b/src/selection.h index 445b4d1..06df020 100644 --- a/src/selection.h +++ b/src/selection.h @@ -5,8 +5,6 @@ #include "model/model.h" -namespace anm2ed -{ enum class SelectionKind { ANIMATIONS, @@ -35,15 +33,14 @@ namespace anm2ed bool operator==(const Selection&) const = default; }; - std::set selection_references_get(const Selection&, const model::UidIndex&, SelectionKind); - void selection_references_set(Selection&, const model::Model&, SelectionKind, const std::set&); - Reference selection_focus_get(const Selection&, const model::UidIndex&); - void selection_focus_set(Selection&, const model::Model&, Reference); + std::set selection_references_get(const Selection&, const UidIndex&, SelectionKind); + void selection_references_set(Selection&, const Model&, SelectionKind, const std::set&); + Reference selection_focus_get(const Selection&, const UidIndex&); + void selection_focus_set(Selection&, const Model&, Reference); // Content items (spritesheets, regions of the focused spritesheet, shaders, layers, ...) are selected by uid and // read back as ids. - std::set selection_ids_get(const Selection&, const model::Model&, SelectionKind); - void selection_ids_set(Selection&, const model::Model&, SelectionKind, const std::set&); - int selection_focus_id_get(const Selection&, const model::Model&, SelectionKind); - void selection_focus_id_set(Selection&, const model::Model&, SelectionKind, int); - void selection_follow(Selection&, const model::Model&, const model::UidIndex&, Reference); -} + std::set selection_ids_get(const Selection&, const Model&, SelectionKind); + void selection_ids_set(Selection&, const Model&, SelectionKind, const std::set&); + int selection_focus_id_get(const Selection&, const Model&, SelectionKind); + void selection_focus_id_set(Selection&, const Model&, SelectionKind, int); + void selection_follow(Selection&, const Model&, const UidIndex&, Reference); diff --git a/src/settings.cpp b/src/settings.cpp index b8532fe..9d2d4bd 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -9,11 +9,8 @@ #include "math_util.h" #include "path.h" -using namespace anm2ed::util; using namespace glm; -namespace anm2ed -{ constexpr std::string_view SETTINGS_SHEAR = "Shear"; constexpr const char* COMPONENT_SUFFIXES_XY[] = {"X", "Y"}; @@ -26,7 +23,7 @@ namespace anm2ed value[0]; }; - const char* const* component_suffixes_get(std::string_view type) + static const char* const* component_suffixes_get(std::string_view type) { if (type.ends_with("_WH")) return COMPONENT_SUFFIXES_WH; if (type.starts_with("VEC3") || type.starts_with("VEC4")) return COMPONENT_SUFFIXES_RGBA; @@ -181,15 +178,13 @@ DockSpace ID=0x123F8F08 Window=0x6D581B32 Pos=8,62 Size=1902,991 DockNode ID=0x0000000C Parent=0x0000000A SizeRef=459,250 Selected=0xC1986EE2 DockNode ID=0x00000016 Parent=0x123F8F08 SizeRef=1902,329 Selected=0x597925B7 - - )"; Settings::Settings(const std::filesystem::path& path) { - auto pathUtf8 = path::to_utf8(path); - if (path::is_exist(path)) + auto pathUtf8 = path_to_utf8(path); + if (is_path_exist(path)) logger.info(std::format("Using settings from: {}", pathUtf8)); else { @@ -199,7 +194,7 @@ DockSpace ID=0x123F8F08 Window=0x6D581B32 Pos=8,62 Size=1902,991 } std::string fileData{}; - if (!file::read_to_string(path, &fileData, "rb")) + if (!file_text_load(path, &fileData, "rb")) { logger.error(std::format("Failed to open settings file: {}", pathUtf8)); return; @@ -228,7 +223,7 @@ DockSpace ID=0x123F8F08 Window=0x6D581B32 Pos=8,62 Size=1902,991 { std::string value; std::getline(ss, value); - dest = path::from_utf8(value); + dest = path_from_utf8(value); } else { @@ -282,14 +277,14 @@ DockSpace ID=0x123F8F08 Window=0x6D581B32 Pos=8,62 Size=1902,991 // Scales were once saved as multipliers; a value below the minimum percent is one, and is converted. for (auto [scale, min, max] : {std::tuple{&uiScale, UI_SCALE_MIN, UI_SCALE_MAX}, std::tuple{&renderScale, RENDER_SCALE_MIN, RENDER_SCALE_MAX}}) - *scale = std::clamp(*scale < min ? math::unit_to_percent(*scale) : *scale, min, max); + *scale = std::clamp(*scale < min ? unit_to_percent(*scale) : *scale, min, max); } std::string Settings::imgui_data_load(const std::filesystem::path& path) { - auto pathUtf8 = path::to_utf8(path); + auto pathUtf8 = path_to_utf8(path); std::string fileData{}; - if (!file::read_to_string(path, &fileData, "rb")) + if (!file_text_load(path, &fileData, "rb")) { logger.error( std::format("Failed to open settings file for Dear ImGui data: {}; using Dear ImGui defaults", pathUtf8)); @@ -333,7 +328,7 @@ DockSpace ID=0x123F8F08 Window=0x6D581B32 Pos=8,62 Size=1902,991 void Settings::save(const std::filesystem::path& path, const std::string& imguiData) { - auto pathUtf8 = path::to_utf8(path); + auto pathUtf8 = path_to_utf8(path); logger.info(std::format("Saving settings to: {}", pathUtf8)); std::ostringstream file{}; @@ -346,7 +341,7 @@ DockSpace ID=0x123F8F08 Window=0x6D581B32 Pos=8,62 Size=1902,991 if constexpr (std::is_same_v) file << key << "=" << (value ? "true" : "false") << "\n"; else if constexpr (std::is_same_v) - file << key << "=" << path::to_utf8(value) << "\n"; + file << key << "=" << path_to_utf8(value) << "\n"; else file << key << "=" << value << "\n"; }; @@ -377,11 +372,10 @@ DockSpace ID=0x123F8F08 Window=0x6D581B32 Pos=8,62 Size=1902,991 logger.error(std::format("Failed while writing settings file: {}", pathUtf8)); return; } - if (!file::write_string(path, file.str(), "wb")) + if (!file_text_save(path, file.str(), "wb")) { logger.error(std::format("Failed to save settings file: {}", pathUtf8)); return; } logger.info(std::format("Saved settings to: {}", pathUtf8)); } -} diff --git a/src/settings.h b/src/settings.h index 8e452c8..fc394c2 100644 --- a/src/settings.h +++ b/src/settings.h @@ -11,8 +11,6 @@ #include "types.h" #include "ui/theme.h" -namespace anm2ed -{ #ifdef _WIN32 constexpr auto FFMPEG_PATH_DEFAULT = "C:\\ffmpeg\\bin\\ffmpeg.exe"; #else @@ -58,7 +56,7 @@ namespace anm2ed X(IS_VSYNC, isVsync, STRING_UNDEFINED, BOOL, true) \ X(IS_DETACHABLE_WINDOWS, isDetachableWindows, STRING_UNDEFINED, BOOL, true) \ X(UI_SCALE, uiScale, STRING_UNDEFINED, FLOAT, 100.0f) \ - X(THEME, theme, STRING_UNDEFINED, INT, imgui::theme::DARK) \ + X(THEME, theme, STRING_UNDEFINED, INT, THEME_DARK) \ X(LANGUAGE, language, STRING_UNDEFINED, INT, ENGLISH) \ \ X(FILE_IS_AUTOSAVE, fileIsAutosave, STRING_UNDEFINED, BOOL, true) \ @@ -149,7 +147,7 @@ namespace anm2ed X(PREVIEW_IS_ALT_ICONS, previewIsAltIcons, STRING_UNDEFINED, BOOL, false) \ X(PREVIEW_IS_TRANSPARENT, animationPreviewTransparent, STRING_UNDEFINED, BOOL, false) \ X(PREVIEW_OVERLAY_TRANSPARENCY, previewOverlayTransparency, STRING_UNDEFINED, FLOAT, 100.0f) \ - X(PREVIEW_OVERLAY_DRAW_ORDER, previewOverlayDrawOrder, STRING_UNDEFINED, INT, types::overlay_draw_order::OVER) \ + X(PREVIEW_OVERLAY_DRAW_ORDER, previewOverlayDrawOrder, STRING_UNDEFINED, INT, OVERLAY_OVER) \ X(PREVIEW_START_ZOOM, previewStartZoom, STRING_UNDEFINED, FLOAT, 200.0f) \ X(PREVIEW_GRID_SIZE, previewGridSize, STRING_UNDEFINED, IVEC2, {32, 32}) \ X(PREVIEW_GRID_OFFSET, previewGridOffset, STRING_UNDEFINED, IVEC2, {}) \ @@ -199,8 +197,8 @@ namespace anm2ed X(BAKE_IS_USE_ROOT_PIVOT, bakeIsUseRootPivot, STRING_UNDEFINED, BOOL, true) \ \ X(TIMELINE_ADD_ITEM_TYPE, timelineAddItemType, STRING_UNDEFINED, INT, LAYER) \ - X(TIMELINE_ADD_ITEM_DESTINATION, timelineAddItemDestination, STRING_UNDEFINED, INT, types::destination::ALL) \ - X(TIMELINE_ADD_ITEM_SOURCE, timelineAddItemSource, STRING_UNDEFINED, INT, types::source::NEW) \ + X(TIMELINE_ADD_ITEM_DESTINATION, timelineAddItemDestination, STRING_UNDEFINED, INT, DESTINATION_ALL) \ + X(TIMELINE_ADD_ITEM_SOURCE, timelineAddItemSource, STRING_UNDEFINED, INT, SOURCE_NEW) \ X(TIMELINE_IS_SHOW_UNUSED, timelineIsShowUnused, STRING_UNDEFINED, BOOL, true) \ X(TIMELINE_IS_ONLY_SHOW_LAYERS, timelineIsOnlyShowLayers, STRING_UNDEFINED, BOOL, false) \ X(TIMELINE_IS_SOUND, timelineIsSound, STRING_UNDEFINED, BOOL, true) \ @@ -208,16 +206,16 @@ namespace anm2ed X(ONIONSKIN_IS_ENABLED, onionskinIsEnabled, STRING_UNDEFINED, BOOL, false) \ X(ONIONSKIN_BEFORE_COUNT, onionskinBeforeCount, STRING_UNDEFINED, INT, 0) \ X(ONIONSKIN_AFTER_COUNT, onionskinAfterCount, STRING_UNDEFINED, INT, 0) \ - X(ONIONSKIN_BEFORE_COLOR, onionskinBeforeColor, STRING_UNDEFINED, VEC3, types::color::RED) \ - X(ONIONSKIN_AFTER_COLOR, onionskinAfterColor, STRING_UNDEFINED, VEC3, types::color::BLUE) \ - X(ONIONSKIN_MODE, onionskinMode, STRING_UNDEFINED, INT, (int)types::OnionskinMode::TIME) \ + X(ONIONSKIN_BEFORE_COLOR, onionskinBeforeColor, STRING_UNDEFINED, VEC3, COLOR_RED) \ + X(ONIONSKIN_AFTER_COLOR, onionskinAfterColor, STRING_UNDEFINED, VEC3, COLOR_BLUE) \ + X(ONIONSKIN_MODE, onionskinMode, STRING_UNDEFINED, INT, (int)OnionskinMode::TIME) \ X(ONIONSKIN_IS_PIVOT_PATH, onionskinIsPivotPath, STRING_UNDEFINED, BOOL, false) \ X(ONIONSKIN_IS_ONLY_SELECTED, onionskinIsOnlySelected, STRING_UNDEFINED, BOOL, false) \ \ X(TOOL, tool, STRING_UNDEFINED, INT, 0) \ X(TOOL_COLOR, toolColor, STRING_UNDEFINED, VEC4, {1.0, 1.0, 1.0, 1.0}) \ \ - X(RENDER_TYPE, renderType, STRING_UNDEFINED, INT, render::GIF) \ + X(RENDER_TYPE, renderType, STRING_UNDEFINED, INT, RENDER_GIF) \ X(RENDER_PATH, renderPath, STRING_UNDEFINED, PATH, OUTPUT_PATH_DEFAULT) \ X(RENDER_ROWS, renderRows, STRING_UNDEFINED, INT, 0) \ X(RENDER_COLUMNS, renderColumns, STRING_UNDEFINED, INT, 0) \ @@ -225,7 +223,7 @@ namespace anm2ed 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, 100.0f) \ - X(RENDER_FPS_MODE, renderFpsMode, STRING_UNDEFINED, INT, render::FPS_ANIMATION) \ + X(RENDER_FPS_MODE, renderFpsMode, STRING_UNDEFINED, INT, FPS_ANIMATION) \ X(RENDER_FFMPEG_PATH, renderFFmpegPath, STRING_UNDEFINED, PATH, FFMPEG_PATH_DEFAULT) #define SETTINGS_SHORTCUTS \ @@ -365,4 +363,3 @@ namespace anm2ed SETTINGS_WINDOWS #undef X }; -} diff --git a/src/shader.cpp b/src/shader.cpp index 3ea0e0c..7208807 100644 --- a/src/shader.cpp +++ b/src/shader.cpp @@ -9,8 +9,6 @@ #include "log.h" #include "model/model.h" -namespace anm2ed::resource::shader -{ #define SHADER_GLES_WORD_REPLACEMENTS \ X("texture2D", "texture") \ X("gl_FragColor", "fragColor") @@ -49,9 +47,9 @@ namespace anm2ed::resource::shader #undef X }; - bool is_shader_identifier(char character) { return std::isalnum((unsigned char)character) || character == '_'; } + static bool is_shader_identifier(char character) { return std::isalnum((unsigned char)character) || character == '_'; } - std::string shader_text_replace(std::string string, std::string_view from, std::string_view to) + static std::string shader_text_replace(std::string string, std::string_view from, std::string_view to) { if (from.empty()) return string; std::size_t position{}; @@ -63,7 +61,7 @@ namespace anm2ed::resource::shader return string; } - std::string shader_word_replace(std::string string, std::string_view from, std::string_view to) + static std::string shader_word_replace(std::string string, std::string_view from, std::string_view to) { if (from.empty()) return string; @@ -84,7 +82,7 @@ namespace anm2ed::resource::shader return string; } - std::string shader_space_collapse(std::string_view string) + static std::string shader_space_collapse(std::string_view string) { std::string out{}; bool isSpace{}; @@ -103,7 +101,7 @@ namespace anm2ed::resource::shader return out; } - std::string shader_trim_get(std::string_view line) + static std::string shader_trim_get(std::string_view line) { std::size_t begin{}; while (begin < line.size() && std::isspace((unsigned char)line[begin])) @@ -116,7 +114,7 @@ namespace anm2ed::resource::shader return std::string(line.substr(begin, end - begin)); } - bool is_shader_word_present(std::string_view string, std::string_view word) + static bool is_shader_word_present(std::string_view string, std::string_view word) { std::size_t position{}; while ((position = string.find(word, position)) != std::string_view::npos) @@ -130,7 +128,7 @@ namespace anm2ed::resource::shader return false; } - bool is_shader_line_skipped(std::string_view line) + static bool is_shader_line_skipped(std::string_view line) { auto normalized = shader_space_collapse(shader_trim_get(line)); if (normalized.starts_with("#version")) return true; @@ -143,7 +141,7 @@ namespace anm2ed::resource::shader return false; } - std::string shader_precision_erase(std::string line) + static std::string shader_precision_erase(std::string line) { line = shader_word_replace(std::move(line), "lowp", ""); line = shader_word_replace(std::move(line), "mediump", ""); @@ -151,7 +149,7 @@ namespace anm2ed::resource::shader return line; } - std::string shader_line_convert(std::string line, ShaderStage stage) + static std::string shader_line_convert(std::string line, ShaderStage stage) { line = shader_precision_erase(std::move(line)); line = shader_word_replace(std::move(line), "attribute", "in"); @@ -162,20 +160,20 @@ namespace anm2ed::resource::shader return line; } - std::string shader_fragment_declarations_get(std::string_view body) + static std::string shader_fragment_declarations_get(std::string_view body) { if (!is_shader_word_present(body, "fragColor")) return {}; if (body.find("out vec4 fragColor") != std::string_view::npos) return {}; return "out vec4 fragColor;\n"; } - std::string uniform_name_clean_get(std::string name) + static std::string uniform_name_clean_get(std::string name) { if (name.ends_with("[0]")) name.erase(name.size() - 3); return name; } - std::string uniform_float_string_get(float value) { return std::format("{:.6g}", value); } + static std::string uniform_float_string_get(float value) { return std::format("{:.6g}", value); } UniformBinding uniform_binding_auto_get(std::string_view name, UniformValueType type) { @@ -244,16 +242,16 @@ namespace anm2ed::resource::shader bool is_uniform_value_vector(UniformValueType type) { return UNIFORM_VALUE_TYPE_INFOS[type].componentCount > 0; } - bool is_component_binding_valid(UniformBinding binding) + static bool is_component_binding_valid(UniformBinding binding) { return binding == UNIFORM_BINDING_MANUAL || binding == UNIFORM_BINDING_PLAYBACK_TIME; } - void uniform_configs_apply(const model::Shader& shader, std::vector& uniforms) + void uniform_configs_apply(const Shader& shader, std::vector& uniforms) { for (auto& uniform : uniforms) { - auto config = std::ranges::find(shader.uniforms, uniform.name, &model::Uniform::name); + auto config = std::ranges::find(shader.uniforms, uniform.name, &Uniform::name); if (config == shader.uniforms.end()) continue; if (auto binding = uniform_binding_get(config->binding); @@ -262,7 +260,7 @@ namespace anm2ed::resource::shader if (!config->value.empty()) uniform_value_parse(uniform, config->value); for (int index = 0; index < (int)uniform.components.size(); ++index) { - auto component = std::ranges::find(config->components, index, &model::Component::index); + auto component = std::ranges::find(config->components, index, &Component::index); if (component == config->components.end()) continue; if (auto binding = uniform_binding_get(component->binding); !component->binding.empty() && is_component_binding_valid(binding)) @@ -273,18 +271,18 @@ namespace anm2ed::resource::shader } // Drops saved uniform settings the compiled shader no longer has or cannot use. - bool uniform_configs_trim(model::Shader& shader, const std::vector& uniforms) + bool uniform_configs_trim(Shader& shader, const std::vector& uniforms) { bool isChanged = std::erase_if(shader.uniforms, - [&](const model::Uniform& config) + [&](const Uniform& config) { - return std::ranges::none_of(uniforms, [&](const Uniform& uniform) + return std::ranges::none_of(uniforms, [&](const ShaderUniform& uniform) { return uniform.name == config.name; }); }) > 0; for (auto& config : shader.uniforms) { - auto& uniform = *std::ranges::find(uniforms, config.name, &Uniform::name); + auto& uniform = *std::ranges::find(uniforms, config.name, &ShaderUniform::name); if (!config.binding.empty() && !is_uniform_binding_valid(uniform_binding_get(config.binding), uniform.valueType)) { config.binding.clear(); @@ -294,7 +292,7 @@ namespace anm2ed::resource::shader auto componentCount = UNIFORM_VALUE_TYPE_INFOS[uniform.valueType].componentCount; auto isComponents = uniform_binding_get(config.binding) == UNIFORM_BINDING_COMPONENTS; isChanged |= - std::erase_if(config.components, [&](const model::Component& component) + std::erase_if(config.components, [&](const Component& component) { return !isComponents || component.index < 0 || component.index >= componentCount; }) > 0; for (auto& component : config.components) @@ -308,9 +306,9 @@ namespace anm2ed::resource::shader return isChanged; } - void uniform_config_save(model::Shader& shader, const Uniform& uniform) + void uniform_config_save(Shader& shader, const ShaderUniform& uniform) { - auto config = std::ranges::find(shader.uniforms, uniform.name, &model::Uniform::name); + auto config = std::ranges::find(shader.uniforms, uniform.name, &Uniform::name); if (config == shader.uniforms.end()) config = shader.uniforms.insert(shader.uniforms.end(), {.name = uniform.name}); config->binding = std::string(uniform_binding_value_get(uniform.binding)); @@ -349,7 +347,7 @@ namespace anm2ed::resource::shader } } - void uniform_value_parse(Uniform& uniform, std::string_view value) + void uniform_value_parse(ShaderUniform& uniform, std::string_view value) { if (value.empty()) return; @@ -367,7 +365,7 @@ namespace anm2ed::resource::shader uniform.components[3].value = uniform.value.w; } - std::string uniform_value_string_get(const Uniform& uniform) + std::string uniform_value_string_get(const ShaderUniform& uniform) { switch (uniform.valueType) { @@ -391,14 +389,14 @@ namespace anm2ed::resource::shader } } - std::vector uniforms_get(GLuint id) + static std::vector uniforms_get(GLuint id) { GLint count{}; GLint maxLength{}; glGetProgramiv(id, GL_ACTIVE_UNIFORMS, &count); glGetProgramiv(id, GL_ACTIVE_UNIFORM_MAX_LENGTH, &maxLength); - std::vector uniforms{}; + std::vector uniforms{}; if (count <= 0 || maxLength <= 0) return uniforms; std::string name((std::size_t)maxLength, '\0'); @@ -412,7 +410,7 @@ namespace anm2ed::resource::shader auto uniformName = uniform_name_clean_get(std::string(name.data(), (std::size_t)length)); auto valueType = uniform_value_type_get(type); - Uniform uniform{}; + ShaderUniform uniform{}; uniform.name = uniformName; uniform.location = glGetUniformLocation(id, uniformName.c_str()); uniform.glType = type; @@ -453,10 +451,7 @@ namespace anm2ed::resource::shader std::string gles_fragment_convert(std::string_view source) { return gles_convert(source, SHADER_STAGE_FRAGMENT); } std::string gles_vertex_convert(std::string_view source) { return gles_convert(source, SHADER_STAGE_VERTEX); } -} -namespace anm2ed::resource -{ ShaderCompileResult shader_compile(const char* vertex, const char* fragment) { ShaderCompileResult result{}; @@ -493,7 +488,7 @@ namespace anm2ed::resource glAttachShader(result.id, vertexHandle); glAttachShader(result.id, fragmentHandle); - for (const auto& alias : shader::ATTRIBUTE_ALIASES) + for (const auto& alias : ATTRIBUTE_ALIASES) glBindAttribLocation(result.id, alias.index, alias.name); glLinkProgram(result.id); @@ -511,7 +506,7 @@ namespace anm2ed::resource result.output += std::format("Shader link log:\n{}\n", linkLog.c_str()); } else - result.uniforms = shader::uniforms_get(result.id); + result.uniforms = uniforms_get(result.id); } glDeleteShader(vertexHandle); @@ -526,9 +521,9 @@ namespace anm2ed::resource return result; } - Shader::Shader() = default; + ShaderProgram::ShaderProgram() = default; - Shader::Shader(const char* vertex, const char* fragment) + ShaderProgram::ShaderProgram(const char* vertex, const char* fragment) { auto result = shader_compile(vertex, fragment); id = result.id; @@ -536,9 +531,9 @@ namespace anm2ed::resource if (!result.output.empty()) logger.error(result.output); } - Shader::Shader(Shader&& other) noexcept { *this = std::move(other); } + ShaderProgram::ShaderProgram(ShaderProgram&& other) noexcept { *this = std::move(other); } - Shader& Shader::operator=(Shader&& other) noexcept + ShaderProgram& ShaderProgram::operator=(ShaderProgram&& other) noexcept { if (this != &other) { @@ -550,10 +545,9 @@ namespace anm2ed::resource return *this; } - Shader::~Shader() + ShaderProgram::~ShaderProgram() { if (is_valid()) glDeleteProgram(id); } - bool Shader::is_valid() const { return id != 0; } -} + bool ShaderProgram::is_valid() const { return id != 0; } diff --git a/src/shader.h b/src/shader.h index 4e6e1d8..b1ac233 100644 --- a/src/shader.h +++ b/src/shader.h @@ -8,14 +8,9 @@ #include #include -namespace anm2ed::model -{ struct Shader; -} -namespace anm2ed::resource::shader -{ - struct Info + struct ShaderInfo { const char* vertex; const char* fragment; @@ -355,7 +350,7 @@ namespace anm2ed::resource::shader #undef X }; - struct Uniform + struct ShaderUniform { struct Component { @@ -382,24 +377,24 @@ namespace anm2ed::resource::shader enum ShaderType { - LINE, - DASHED, - TEXTURE, - AXIS, - GRID, - COUNT + SHADER_LINE, + SHADER_DASHED, + SHADER_TEXTURE, + SHADER_AXIS, + SHADER_GRID, + SHADER_COUNT }; - const Info SHADERS[COUNT] = {{VERTEX, FRAGMENT}, + const ShaderInfo SHADERS[SHADER_COUNT] = {{VERTEX, FRAGMENT}, {DASHED_VERTEX, DASHED_FRAGMENT}, {VERTEX, TEXTURE_FRAGMENT}, {AXIS_VERTEX, FRAGMENT}, {GRID_VERTEX, GRID_FRAGMENT}}; UniformBinding uniform_binding_auto_get(std::string_view, UniformValueType); - void uniform_configs_apply(const model::Shader&, std::vector&); - bool uniform_configs_trim(model::Shader&, const std::vector&); - void uniform_config_save(model::Shader&, const Uniform&); + void uniform_configs_apply(const Shader&, std::vector&); + bool uniform_configs_trim(Shader&, const std::vector&); + void uniform_config_save(Shader&, const ShaderUniform&); UniformBinding uniform_binding_get(std::string_view); std::string_view uniform_binding_value_get(UniformBinding); std::string_view uniform_binding_label_get(UniformBinding); @@ -408,37 +403,33 @@ namespace anm2ed::resource::shader bool is_uniform_value_editable(UniformValueType); bool is_uniform_value_vector(UniformValueType); bool is_uniform_binding_valid(UniformBinding, UniformValueType); - void uniform_value_parse(Uniform&, std::string_view); - std::string uniform_value_string_get(const Uniform&); + void uniform_value_parse(ShaderUniform&, std::string_view); + std::string uniform_value_string_get(const ShaderUniform&); std::string gles_convert(std::string_view, ShaderStage); std::string gles_fragment_convert(std::string_view); std::string gles_vertex_convert(std::string_view); -} -namespace anm2ed::resource -{ struct ShaderCompileResult { GLuint id{}; std::string output{}; - std::vector uniforms{}; + std::vector uniforms{}; bool isCompiled{}; bool isLinked{}; }; ShaderCompileResult shader_compile(const char*, const char*); - class Shader + class ShaderProgram { public: GLuint id{}; - std::vector uniforms{}; + std::vector uniforms{}; - Shader(); - Shader(const char*, const char*); - Shader(Shader&&) noexcept; - Shader& operator=(Shader&&) noexcept; - ~Shader(); + ShaderProgram(); + ShaderProgram(const char*, const char*); + ShaderProgram(ShaderProgram&&) noexcept; + ShaderProgram& operator=(ShaderProgram&&) noexcept; + ~ShaderProgram(); bool is_valid() const; }; -} diff --git a/src/snapshots.cpp b/src/snapshots.cpp index f4fdfbb..94e0e3c 100644 --- a/src/snapshots.cpp +++ b/src/snapshots.cpp @@ -2,21 +2,19 @@ #include -namespace anm2ed::snapshots -{ - template bool is_value_equal(const T& left, const T& right) { return left == right; } + template static bool is_value_equal(const T& left, const T& right) { return left == right; } - bool is_value_equal(const model::Model& left, const model::Model& right) + static bool is_value_equal(const Model& left, const Model& right) { - return model::is_model_equal(left, right); + return is_model_equal(left, right); } - bool is_value_equal(const Playback& left, const Playback& right) + static bool is_value_equal(const Playback& left, const Playback& right) { return left.time == right.time && left.isPlaying == right.isPlaying && left.isFinished == right.isFinished; } - bool is_step_empty(const SnapshotStep& step) + static bool is_step_empty(const SnapshotStep& step) { #define X(type, name) \ if (!is_value_equal(step.before.name, step.after.name)) return false; @@ -25,7 +23,7 @@ namespace anm2ed::snapshots return true; } - void step_apply(Snapshot& current, const SnapshotStep& step, bool isUndo) + static void step_apply(Snapshot& current, const SnapshotStep& step, bool isUndo) { const auto& target = isUndo ? step.before : step.after; #define X(type, name) \ @@ -35,21 +33,18 @@ namespace anm2ed::snapshots current.message = step.after.message; } - Reference focus_get(const Snapshot& snapshot) + static Reference focus_get(const Snapshot& snapshot) { - return selection_focus_get(snapshot.selection, model::UidIndex(snapshot.model)); + return selection_focus_get(snapshot.selection, UidIndex(snapshot.model)); } - void selection_follow(Snapshot& snapshot, Reference before) + static void selection_follow(Snapshot& snapshot, Reference before) { snapshot.model.uids_repair(); - ::anm2ed::selection_follow(snapshot.selection, snapshot.model, model::UidIndex(snapshot.model), before); + selection_follow(snapshot.selection, snapshot.model, UidIndex(snapshot.model), before); } -} -namespace anm2ed -{ - int SnapshotStack::maxSize = snapshots::MAX; + int SnapshotStack::maxSize = SNAPSHOT_MAX; bool SnapshotStack::is_empty() { return stack.empty(); } std::size_t SnapshotStack::size() const { return stack.size(); } @@ -82,17 +77,17 @@ namespace anm2ed void Snapshots::push(const std::string& message) { if (pending || pendingFocus) commit(); - pendingFocus = snapshots::focus_get(current); + pendingFocus = focus_get(current); current.message = message; pending = current; } void Snapshots::commit() { - if (pendingFocus) snapshots::selection_follow(current, *std::exchange(pendingFocus, std::nullopt)); + if (pendingFocus) selection_follow(current, *std::exchange(pendingFocus, std::nullopt)); if (!pending) return; SnapshotStep step{std::move(*std::exchange(pending, std::nullopt)), current}; - if (snapshots::is_step_empty(step)) return; + if (is_step_empty(step)) return; undoStack.push(std::move(step)); redoStack.clear(); } @@ -103,9 +98,9 @@ namespace anm2ed pendingFocus.reset(); auto step = undoStack.pop(); if (!step) return false; - auto focus = snapshots::focus_get(current); - snapshots::step_apply(current, *step, true); - snapshots::selection_follow(current, focus); + auto focus = focus_get(current); + step_apply(current, *step, true); + selection_follow(current, focus); redoStack.push(std::move(*step)); return true; } @@ -116,9 +111,9 @@ namespace anm2ed pendingFocus.reset(); auto step = redoStack.pop(); if (!step) return false; - auto focus = snapshots::focus_get(current); - snapshots::step_apply(current, *step, false); - snapshots::selection_follow(current, focus); + auto focus = focus_get(current); + step_apply(current, *step, false); + selection_follow(current, focus); undoStack.push(std::move(*step)); return true; } @@ -136,4 +131,3 @@ namespace anm2ed undoStack.trim_to_limit(); redoStack.trim_to_limit(); } -} diff --git a/src/snapshots.h b/src/snapshots.h index 095fcaa..5fb3c46 100644 --- a/src/snapshots.h +++ b/src/snapshots.h @@ -9,18 +9,13 @@ #include "playback.h" #include "selection.h" -namespace anm2ed::snapshots -{ - constexpr auto ACTION = "Action"; - constexpr auto MAX = 20; -}; + constexpr auto SNAPSHOT_ACTION = "Action"; + constexpr auto SNAPSHOT_MAX = 20; -namespace anm2ed -{ using AssetKeys = std::map; #define SNAPSHOT_STEP_STATE_FIELDS \ - X(model::Model, model) \ + X(Model, model) \ X(Playback, playback) \ X(Selection, selection) \ X(float, frameTime) \ @@ -33,7 +28,7 @@ namespace anm2ed #define X(type, name) type name{}; SNAPSHOT_STEP_STATE_FIELDS #undef X - std::string message = snapshots::ACTION; + std::string message = SNAPSHOT_ACTION; }; // One undoable edit: the state before and after it; undo/redo restore only the fields the edit changed. @@ -76,4 +71,3 @@ namespace anm2ed void reset(); void apply_limit(); }; -} diff --git a/src/socket.cpp b/src/socket.cpp index 1574673..bbe8b95 100644 --- a/src/socket.cpp +++ b/src/socket.cpp @@ -3,8 +3,6 @@ #include #include -namespace anm2ed -{ #ifdef _WIN32 struct WSAInitializer { @@ -19,7 +17,7 @@ namespace anm2ed WSAInitializer initializer{}; #endif - int socket_last_error() + static int socket_last_error() { #ifdef _WIN32 return WSAGetLastError(); @@ -262,4 +260,3 @@ namespace anm2ed bool Socket::is_valid() const { return handle != SOCKET_INVALID; } int Socket::last_error() const { return lastError; } -} diff --git a/src/socket.h b/src/socket.h index ee03180..43c788b 100644 --- a/src/socket.h +++ b/src/socket.h @@ -17,8 +17,6 @@ using socket_handle = int; constexpr socket_handle SOCKET_INVALID = -1; #endif -namespace anm2ed -{ enum SocketRole { SERVER, @@ -60,4 +58,3 @@ namespace anm2ed bool is_valid() const; int last_error() const; }; -} diff --git a/src/state.cpp b/src/state.cpp index 9e7c266..645258c 100644 --- a/src/state.cpp +++ b/src/state.cpp @@ -15,12 +15,6 @@ #include "ui/toast.h" #include "ui/shortcut.h" -using namespace anm2ed::imgui; -using namespace anm2ed::util; -using namespace anm2ed::types; - -namespace anm2ed -{ constexpr auto UPDATE_RATE = 120; constexpr auto UPDATE_INTERVAL = (1000 / UPDATE_RATE); @@ -29,7 +23,7 @@ namespace anm2ed dialog = Dialog(window); for (const auto& argument : arguments) - manager.open(path::from_utf8(argument)); + manager.open(path_from_utf8(argument)); manager.settings_apply(settings); } @@ -77,8 +71,8 @@ namespace anm2ed { std::string droppedFile = event.drop.data ? event.drop.data : ""; if (droppedFile.empty()) break; - auto droppedPath = path::from_utf8(droppedFile); - if (path::is_extension(droppedPath, "anm2")) + auto droppedPath = path_from_utf8(droppedFile); + if (is_path_extension(droppedPath, "anm2")) { if (manager.documents.empty()) manager.open(droppedPath); @@ -91,12 +85,12 @@ namespace anm2ed } SDL_FlashWindow(window, SDL_FLASH_UNTIL_FOCUSED); } - else if (path::is_extension(droppedPath, resource::image::PNG_EXTENSION) || - path::is_extension(droppedPath, resource::image::SVG_EXTENSION)) + else if (is_path_extension(droppedPath, PNG_EXTENSION) || + is_path_extension(droppedPath, SVG_EXTENSION)) { spritesheetDropPaths.push_back(droppedPath); } - else if (path::is_extension(droppedPath, "wav") || path::is_extension(droppedPath, "ogg")) + else if (is_path_extension(droppedPath, "wav") || is_path_extension(droppedPath, "ogg")) { soundDropPaths.push_back(droppedPath); } @@ -139,8 +133,8 @@ namespace anm2ed std::string droppedFile = event.user.data1 ? static_cast(event.user.data1) : ""; if (event.user.data1) SDL_free(event.user.data1); if (droppedFile.empty()) break; - auto droppedPath = path::from_utf8(droppedFile); - if (path::is_extension(droppedPath, "anm2")) + auto droppedPath = path_from_utf8(droppedFile); + if (is_path_extension(droppedPath, "anm2")) { manager.open(droppedPath); SDL_FlashWindow(window, SDL_FLASH_UNTIL_FOCUSED); @@ -188,12 +182,12 @@ namespace anm2ed if (!dockspace.is_canvas_focused_get()) { float uiScaleDelta{}; - if (imgui::shortcut(manager.chords[SHORTCUT_ZOOM_IN], shortcut::GLOBAL)) uiScaleDelta += UI_SCALE_STEP; - if (imgui::shortcut(manager.chords[SHORTCUT_ZOOM_OUT], shortcut::GLOBAL)) uiScaleDelta -= UI_SCALE_STEP; + if (shortcut(manager.chords[SHORTCUT_ZOOM_IN], SCOPE_GLOBAL)) uiScaleDelta += UI_SCALE_STEP; + if (shortcut(manager.chords[SHORTCUT_ZOOM_OUT], SCOPE_GLOBAL)) uiScaleDelta -= UI_SCALE_STEP; if (uiScaleDelta != 0.0f) { settings.uiScale = std::clamp(settings.uiScale + uiScaleDelta, UI_SCALE_MIN, UI_SCALE_MAX); - ImGui::GetStyle().FontScaleMain = math::percent_to_unit(settings.uiScale); + ImGui::GetStyle().FontScaleMain = percent_to_unit(settings.uiScale); } } @@ -224,7 +218,7 @@ namespace anm2ed } SDL_GL_SwapWindow(window); - resource::texture::garbage_collect(); + texture_garbage_collect(); SDL_GL_SetSwapInterval(settings.isVsync); } @@ -265,4 +259,3 @@ namespace anm2ed SDL_Delay(1); } -} diff --git a/src/state.h b/src/state.h index 66a1544..bcd4d19 100644 --- a/src/state.h +++ b/src/state.h @@ -7,8 +7,6 @@ #include "ui/dockspace.h" -namespace anm2ed -{ class State { void tick(Settings&, float); @@ -23,9 +21,9 @@ namespace anm2ed Dialog dialog; Clipboard clipboard; - imgui::Taskbar taskbar; - imgui::Documents documents; - imgui::Dockspace dockspace; + Taskbar taskbar; + Documents documents; + Dockspace dockspace; uint64_t previousTick{}; uint64_t previousUpdate{}; @@ -38,4 +36,3 @@ namespace anm2ed void loop(SDL_Window*&, Settings&); }; -}; diff --git a/src/subprocess.cpp b/src/subprocess.cpp index f7c4ee6..a3d33a6 100644 --- a/src/subprocess.cpp +++ b/src/subprocess.cpp @@ -5,8 +5,6 @@ #include #endif -namespace anm2ed::util -{ #ifdef WIN32 std::wstring utf8_to_wstring(const char* text) { @@ -71,4 +69,3 @@ namespace anm2ed::util FILE* Process::get() const { return pipe; } Process::operator bool() const { return pipe != nullptr; } -} diff --git a/src/subprocess.h b/src/subprocess.h index d3654ae..4461796 100644 --- a/src/subprocess.h +++ b/src/subprocess.h @@ -2,8 +2,6 @@ #include -namespace anm2ed::util -{ class Process { public: @@ -21,4 +19,3 @@ namespace anm2ed::util private: FILE* pipe{}; }; -} \ No newline at end of file diff --git a/src/texture.cpp b/src/texture.cpp index 97ea8cc..af5c070 100644 --- a/src/texture.cpp +++ b/src/texture.cpp @@ -5,17 +5,15 @@ #include #include -namespace anm2ed::resource::texture -{ - struct Entry + struct TextureEntry { GLuint id{}; bool isUsed{}; }; - std::unordered_map entries{}; + static std::unordered_map entries{}; - GLuint id_get(const Image& image) + GLuint texture_id_get(const Image& image) { if (!image.is_valid()) return 0; @@ -38,7 +36,7 @@ namespace anm2ed::resource::texture return entry.id; } - void garbage_collect() + void texture_garbage_collect() { std::erase_if(entries, [](auto& pair) @@ -49,7 +47,7 @@ namespace anm2ed::resource::texture }); } - Image svg_load(const char* data, size_t length, glm::ivec2 size) + Image texture_svg_load(const char* data, size_t length, glm::ivec2 size) { auto document = data ? lunasvg::Document::loadFromData(data, length) : nullptr; if (!document) return {}; @@ -57,4 +55,3 @@ namespace anm2ed::resource::texture if (bitmap.width() == 0 || bitmap.height() == 0) return {}; return Image(bitmap.data(), size, true); } -} diff --git a/src/texture.h b/src/texture.h index 7d6f94c..bf4e1da 100644 --- a/src/texture.h +++ b/src/texture.h @@ -5,9 +5,6 @@ #include "image.h" // GPU copies of Images, uploaded on first use and evicted when a frame passes without them being drawn. -namespace anm2ed::resource::texture -{ - GLuint id_get(const Image&); - void garbage_collect(); - Image svg_load(const char*, size_t, glm::ivec2); -} + GLuint texture_id_get(const Image&); + void texture_garbage_collect(); + Image texture_svg_load(const char*, size_t, glm::ivec2); diff --git a/src/timestamp.cpp b/src/timestamp.cpp index fb3c0bf..f4e0579 100644 --- a/src/timestamp.cpp +++ b/src/timestamp.cpp @@ -5,9 +5,7 @@ #include #include -namespace anm2ed::util::time -{ - std::string get(const char* format) + std::string timestamp_get(const char* format) { auto now = std::chrono::system_clock::now(); auto time = std::chrono::system_clock::to_time_t(now); @@ -16,4 +14,3 @@ namespace anm2ed::util::time timeString << std::put_time(&localTime, format); return timeString.str(); } -} diff --git a/src/timestamp.h b/src/timestamp.h index f2f716d..4d67c18 100644 --- a/src/timestamp.h +++ b/src/timestamp.h @@ -2,9 +2,6 @@ #include -namespace anm2ed::util::time -{ - constexpr auto SECOND_M = 60; + constexpr auto SECOND_MINUTES = 60; - std::string get(const char*); -} \ No newline at end of file + std::string timestamp_get(const char*); diff --git a/src/tool.h b/src/tool.h index 45f896d..77060d0 100644 --- a/src/tool.h +++ b/src/tool.h @@ -6,74 +6,71 @@ #include "settings.h" #include "localization.h" -namespace anm2ed::tool -{ - enum Type + enum Tool { - PAN, - MOVE, - ROTATE, - SCALE, - SKEW, - CROP, - DRAW, - ERASE, - COLOR_PICKER, - UNDO, - REDO, - COLOR, - COUNT + TOOL_PAN, + TOOL_MOVE, + TOOL_ROTATE, + TOOL_SCALE, + TOOL_SKEW, + TOOL_CROP, + TOOL_DRAW, + TOOL_ERASE, + TOOL_COLOR_PICKER, + TOOL_UNDO, + TOOL_REDO, + TOOL_COLOR, + TOOL_COUNT }; - enum AreaType + enum ToolArea { - ANIMATION_PREVIEW, - SPRITESHEET_EDITOR, - ALL + TOOL_AREA_ANIMATION_PREVIEW, + TOOL_AREA_SPRITESHEET_EDITOR, + TOOL_AREA_ALL }; - struct Info + struct ToolInfo { ImGuiMouseCursor cursor{ImGuiMouseCursor_None}; - resource::icon::Type icon{}; + Icon icon{}; ShortcutType shortcut{}; - AreaType areaType; + ToolArea areaType; const char* label{}; StringType tooltip{}; bool isFrameRequired{}; bool isSpritesheetRequired{}; }; - constexpr Info INFO[] = { - {ImGuiMouseCursor_Hand, resource::icon::PAN, SHORTCUT_PAN, ALL, "##Pan", TOOLTIP_TOOL_PAN}, + constexpr ToolInfo TOOLS[] = { + {ImGuiMouseCursor_Hand, ICON_PAN, SHORTCUT_PAN, TOOL_AREA_ALL, "##Pan", TOOLTIP_TOOL_PAN}, - {ImGuiMouseCursor_ResizeAll, resource::icon::MOVE, SHORTCUT_MOVE, ALL, "##Move", TOOLTIP_TOOL_MOVE, true}, + {ImGuiMouseCursor_ResizeAll, ICON_MOVE, SHORTCUT_MOVE, TOOL_AREA_ALL, "##Move", TOOLTIP_TOOL_MOVE, true}, - {ImGuiMouseCursor_Arrow, resource::icon::ROTATE, SHORTCUT_ROTATE, ANIMATION_PREVIEW, "##Rotate", + {ImGuiMouseCursor_Arrow, ICON_ROTATE, SHORTCUT_ROTATE, TOOL_AREA_ANIMATION_PREVIEW, "##Rotate", TOOLTIP_TOOL_ROTATE, true}, - {ImGuiMouseCursor_ResizeNESW, resource::icon::SCALE, SHORTCUT_SCALE, ANIMATION_PREVIEW, "##Scale", + {ImGuiMouseCursor_ResizeNESW, ICON_SCALE, SHORTCUT_SCALE, TOOL_AREA_ANIMATION_PREVIEW, "##Scale", TOOLTIP_TOOL_SCALE, true}, - {ImGuiMouseCursor_ResizeNESW, resource::icon::SKEW, SHORTCUT_SKEW, ANIMATION_PREVIEW, "##Skew", TOOLTIP_TOOL_SKEW, + {ImGuiMouseCursor_ResizeNESW, ICON_SKEW, SHORTCUT_SKEW, TOOL_AREA_ANIMATION_PREVIEW, "##Skew", TOOLTIP_TOOL_SKEW, true}, - {ImGuiMouseCursor_Arrow, resource::icon::CROP, SHORTCUT_CROP, SPRITESHEET_EDITOR, "##Crop", TOOLTIP_TOOL_CROP, + {ImGuiMouseCursor_Arrow, ICON_CROP, SHORTCUT_CROP, TOOL_AREA_SPRITESHEET_EDITOR, "##Crop", TOOLTIP_TOOL_CROP, true}, - {ImGuiMouseCursor_Arrow, resource::icon::DRAW, SHORTCUT_DRAW, SPRITESHEET_EDITOR, "##Draw", TOOLTIP_TOOL_DRAW, + {ImGuiMouseCursor_Arrow, ICON_DRAW, SHORTCUT_DRAW, TOOL_AREA_SPRITESHEET_EDITOR, "##Draw", TOOLTIP_TOOL_DRAW, false, true}, - {ImGuiMouseCursor_Arrow, resource::icon::ERASE, SHORTCUT_ERASE, SPRITESHEET_EDITOR, "##Erase", TOOLTIP_TOOL_ERASE, + {ImGuiMouseCursor_Arrow, ICON_ERASE, SHORTCUT_ERASE, TOOL_AREA_SPRITESHEET_EDITOR, "##Erase", TOOLTIP_TOOL_ERASE, false, true}, - {ImGuiMouseCursor_Arrow, resource::icon::COLOR_PICKER, SHORTCUT_COLOR_PICKER, SPRITESHEET_EDITOR, + {ImGuiMouseCursor_Arrow, ICON_COLOR_PICKER, SHORTCUT_COLOR_PICKER, TOOL_AREA_SPRITESHEET_EDITOR, "##Color Picker", TOOLTIP_TOOL_COLOR_PICKER, false, true}, - {ImGuiMouseCursor_None, resource::icon::UNDO, SHORTCUT_UNDO, ALL, "##Undo", TOOLTIP_TOOL_UNDO}, + {ImGuiMouseCursor_None, ICON_UNDO, SHORTCUT_UNDO, TOOL_AREA_ALL, "##Undo", TOOLTIP_TOOL_UNDO}, - {ImGuiMouseCursor_None, resource::icon::REDO, SHORTCUT_REDO, ALL, "##Redo", TOOLTIP_TOOL_REDO}, + {ImGuiMouseCursor_None, ICON_REDO, SHORTCUT_REDO, TOOL_AREA_ALL, "##Redo", TOOLTIP_TOOL_REDO}, - {ImGuiMouseCursor_None, resource::icon::NONE, SHORTCUT_COLOR, ALL, "##Color", TOOLTIP_TOOL_COLOR}, + {ImGuiMouseCursor_None, ICON_NONE, SHORTCUT_COLOR, TOOL_AREA_ALL, "##Color", TOOLTIP_TOOL_COLOR}, }; -} diff --git a/src/types.h b/src/types.h index 624582a..4a6fd35 100644 --- a/src/types.h +++ b/src/types.h @@ -2,81 +2,58 @@ #include -namespace anm2ed::types::shortcut -{ - enum Type + enum ShortcutScope { - FOCUSED, - GLOBAL, - FOCUSED_SET, - GLOBAL_SET + SCOPE_FOCUSED, + SCOPE_GLOBAL, + SCOPE_FOCUSED_SET, + SCOPE_GLOBAL_SET }; -} -namespace anm2ed::types::destination -{ - enum Type + enum Destination { - ALL, - THIS + DESTINATION_ALL, + DESTINATION_THIS }; -} -namespace anm2ed::types::source -{ - enum Type + enum Source { - NEW, - EXISTING + SOURCE_NEW, + SOURCE_EXISTING }; -} -namespace anm2ed::types::overlay_draw_order -{ - enum Type + enum OverlayDrawOrder { - OVER, - UNDER + OVERLAY_OVER, + OVERLAY_UNDER }; -} -namespace anm2ed::types::merge -{ - enum Type + enum Merge { - PREPEND, - APPEND, - REPLACE, - IGNORE + MERGE_PREPEND, + MERGE_APPEND, + MERGE_REPLACE, + MERGE_IGNORE }; -} -namespace anm2ed::types::edit_state -{ - enum Type + enum EditState { - NONE, - START, - DURING, - END, - COMPLETE + EDIT_STATE_NONE, + EDIT_STATE_START, + EDIT_STATE_DURING, + EDIT_STATE_END, + EDIT_STATE_COMPLETE }; -} -namespace anm2ed::types::color -{ using namespace glm; - constexpr auto WHITE = vec4(1.0); - constexpr auto BLACK = vec4(0.0, 0.0, 0.0, 1.0); - constexpr auto RED = vec4(1.0, 0.0, 0.0, 1.0); - constexpr auto GREEN = vec4(0.0, 1.0, 0.0, 1.0); - constexpr auto BLUE = vec4(0.0, 0.0, 1.0, 1.0); - constexpr auto PINK = vec4(1.0, 0.0, 1.0, 1.0); -} + constexpr auto COLOR_WHITE = vec4(1.0); + constexpr auto COLOR_BLACK = vec4(0.0, 0.0, 0.0, 1.0); + constexpr auto COLOR_RED = vec4(1.0, 0.0, 0.0, 1.0); + constexpr auto COLOR_GREEN = vec4(0.0, 1.0, 0.0, 1.0); + constexpr auto COLOR_BLUE = vec4(0.0, 0.0, 1.0, 1.0); + constexpr auto COLOR_PINK = vec4(1.0, 0.0, 1.0, 1.0); -namespace anm2ed::types -{ enum class OnionskinMode { TIME, @@ -84,4 +61,3 @@ namespace anm2ed::types }; constexpr auto ID_NONE = -1; -} diff --git a/src/ui/about.cpp b/src/ui/about.cpp index 35637ef..0a77ea1 100644 --- a/src/ui/about.cpp +++ b/src/ui/about.cpp @@ -19,12 +19,8 @@ #include "localization.h" #include "ui/draw.h" -using namespace anm2ed::resource; -using namespace anm2ed::util; using namespace glm; -namespace anm2ed::imgui::wizard -{ // The credits roll, after the original editor's About box: lengths are its pixels (for 14 px text), at its 30 Hz. enum RollEffect { @@ -65,42 +61,42 @@ namespace anm2ed::imgui::wizard static constexpr float FRIEND_HEIGHT_RATIO = 47.0f / 183.0f; static constexpr float FRIEND_PADDING_RATIO = 0.15f; static constexpr float TITLE_SCALE = 2.0f; - static constexpr int FRIEND_ORDER_LEFT[] = {resource::friends::MEAT_BOY, resource::friends::ISAAC}; - static constexpr int FRIEND_ORDER_RIGHT[] = {resource::friends::STACY, resource::friends::ASH}; + static constexpr int FRIEND_ORDER_LEFT[] = {FRIEND_MEAT_BOY, FRIEND_ISAAC}; + static constexpr int FRIEND_ORDER_RIGHT[] = {FRIEND_STACY, FRIEND_ASH}; static constexpr About::Credit CREDITS[] = { - {"Anm2Ed", font::BOLD}, + {"Anm2Ed", FONT_BOLD}, {"License: GPLv3"}, {""}, - {"Design/Programming", font::BOLD}, + {"Design/Programming", FONT_BOLD}, {"Shweet"}, {"OpenAI Codex"}, {"Claude Code"}, {""}, - {"Additional Help", font::BOLD}, + {"Additional Help", FONT_BOLD}, {"im-tem"}, {""}, - {"Localization", font::BOLD}, + {"Localization", FONT_BOLD}, {"Gabriel Asencio (Spanish (Latin America))"}, {"ExtremeThreat (Russian)"}, {"CxRedix (Chinese)"}, {"sawalk/사왈이 (Korean)"}, {""}, - {"Based on the work of", font::BOLD}, + {"Based on the work of", FONT_BOLD}, {"Adrian Gavrilita"}, {"Simon Parzer"}, {"Matt Kapuszczak"}, {""}, - {"Music", font::BOLD}, + {"Music", FONT_BOLD}, {"Soundbin"}, {"\"Digital Antidepressant\""}, {"https://www.newgrounds.com/audio/listen/1565433"}, {"License: CC0"}, {""}, - {"Dancing Characters", font::BOLD}, + {"Dancing Characters", FONT_BOLD}, {"Shweet"}, {""}, - {"Libraries", font::BOLD}, + {"Libraries", FONT_BOLD}, {"Dear ImGui"}, {"https://github.com/ocornut/imgui"}, {"License: MIT"}, @@ -129,17 +125,17 @@ namespace anm2ed::imgui::wizard {"https://github.com/sammycage/lunasvg"}, {"License: MIT"}, {""}, - {"Icons", font::BOLD}, + {"Icons", FONT_BOLD}, {"Remix Icons"}, {"remixicon.com"}, {"License: Apache"}, {""}, - {"Font", font::BOLD}, + {"Font", FONT_BOLD}, {"Noto Sans"}, {"https://fonts.google.com/noto/specimen/Noto+Sans"}, {"License: OFL"}, {""}, - {"Special Thanks", font::BOLD}, + {"Special Thanks", FONT_BOLD}, {"Edmund McMillen"}, {"Florian Himsl"}, {"Tyrone Rodriguez"}, @@ -161,7 +157,7 @@ namespace anm2ed::imgui::wizard }; static constexpr auto CREDIT_COUNT = (int)(sizeof(CREDITS) / sizeof(About::Credit)); - const model::Animation* friend_animation_get(const About::FriendState& state) + static const Animation* friend_animation_get(const About::FriendState& state) { auto animations = state.model.animations_get(); for (auto [index, animation] : animations) @@ -169,7 +165,7 @@ namespace anm2ed::imgui::wizard return animations.empty() ? nullptr : animations.front().second; } - void friend_state_load(About::FriendState& state, const resource::friends::Info& info) + static void friend_state_load(About::FriendState& state, const FriendInfo& info) { if (!state.canvas) { @@ -177,7 +173,7 @@ namespace anm2ed::imgui::wizard state.canvas->filter = GL_NEAREST; } - state.model = model::Model{}; + state.model = Model{}; state.textures.clear(); state.rect = vec4(-1.0f); state.time = 0.0f; @@ -185,7 +181,7 @@ namespace anm2ed::imgui::wizard state.isLoaded = false; std::string errorString{}; - if (!model::model_load_string(state.model, std::string_view((const char*)info.anm2->data, info.anm2->size), &errorString)) + if (!model_load_string(state.model, std::string_view((const char*)info.anm2->data, info.anm2->size), &errorString)) { logger.error(std::format("Unable to load friend animation {}: {}", info.name, errorString)); return; @@ -194,7 +190,7 @@ namespace anm2ed::imgui::wizard if (state.model.info.fps > 0) state.fps = (float)state.model.info.fps; for (auto& spritesheet : state.model.content.spritesheets) - state.textures[spritesheet.id] = resource::Image(info.png->data, info.png->size); + state.textures[spritesheet.id] = Image(info.png->data, info.png->size); auto animation = friend_animation_get(state); if (!animation) @@ -203,11 +199,11 @@ namespace anm2ed::imgui::wizard return; } - state.rect = model::animation_rect(state.model, *animation, true); + state.rect = animation_rect(state.model, *animation, true); state.isLoaded = state.rect != vec4(-1.0f) && !state.textures.empty(); } - void friend_state_tick(About::FriendState& state, float delta) + static void friend_state_tick(About::FriendState& state, float delta) { if (!state.isLoaded) return; @@ -218,7 +214,7 @@ namespace anm2ed::imgui::wizard if (state.time < 0.0f) state.time += (float)animation->frameNum; } - ImVec2 friend_size_get(const About::FriendState& state, float height) + static ImVec2 friend_size_get(const About::FriendState& state, float height) { auto width = height; if (state.rect.w > 0.0f && state.rect.z > 0.0f) width = height * (state.rect.z / state.rect.w); @@ -226,7 +222,7 @@ namespace anm2ed::imgui::wizard } // The animation's bounds with some room around them. - vec4 friend_rect_get(const About::FriendState& state) + static vec4 friend_rect_get(const About::FriendState& state) { auto rect = state.rect; auto padding = std::max(2.0f, std::max(rect.z, rect.w) * FRIEND_PADDING_RATIO); @@ -234,7 +230,7 @@ namespace anm2ed::imgui::wizard } // Rendered 1:1 into its canvas, which is drawn scaled up with nearest filtering so the pixels stay sharp. - void friend_canvas_draw(About::FriendState& state, Resources& resources) + static void friend_canvas_draw(About::FriendState& state, Resources& resources) { if (!state.isLoaded || !state.canvas) return; @@ -255,9 +251,9 @@ namespace anm2ed::imgui::wizard vec2 pan{}; state.canvas->set_to_rect(zoom, pan, rect); - state.canvas->layers_render(resources.shaders[shader::TEXTURE], state.model, *animation, + state.canvas->layers_render(resources.shaders[SHADER_TEXTURE], state.model, *animation, {.time = state.time, .isRootTransform = true}, state.canvas->transform_get(zoom, pan), - [&](const model::Draw& draw) + [&](const Draw& draw) { auto texture = state.textures.find(draw.spritesheetId); return texture == state.textures.end() ? nullptr : &texture->second; @@ -267,13 +263,13 @@ namespace anm2ed::imgui::wizard } // The application name, as large as fits its row. - void title_draw(About& about, Resources& resources, const char* title, float width) + static void title_draw(About& about, Resources& resources, const char* title, float width) { - auto font = resources.fonts[font::BOLD].get(); - auto fontSize = (float)font::SIZE_LARGE * TITLE_SCALE; + auto font = resources.fonts[FONT_BOLD].get(); + auto fontSize = (float)FONT_SIZE_LARGE * TITLE_SCALE; fontSize *= std::min(1.0f, width / font->CalcTextSizeA(fontSize, FLT_MAX, 0.0f, title).x); auto textSize = font->CalcTextSizeA(fontSize, FLT_MAX, 0.0f, title); - auto rowHeight = (float)font::SIZE_LARGE * TITLE_SCALE; + auto rowHeight = (float)FONT_SIZE_LARGE * TITLE_SCALE; auto min = ImGui::GetCursorScreenPos(); auto color = about.roll.titleColor ? about.roll.titleColor : ImGui::GetColorU32(ImGuiCol_Text); ImGui::GetWindowDrawList()->AddText( @@ -283,7 +279,7 @@ namespace anm2ed::imgui::wizard } // The dancing characters stand in the credits box's bottom corners, inside the volume bars. - void friends_draw(About& about, Resources& resources, ImDrawList* drawList, ImVec2 min, ImVec2 max, float inset) + static void friends_draw(About& about, Resources& resources, ImDrawList* drawList, ImVec2 min, ImVec2 max, float inset) { auto height = (max.y - min.y) * FRIEND_HEIGHT_RATIO; auto row_draw = [&](std::span indices, float left) @@ -307,9 +303,9 @@ namespace anm2ed::imgui::wizard } // One tick: the credits scroll up (a new pass, and effect, once they are gone) and the bars follow the music. - void roll_tick(About::RollState& roll, Resources& resources, float boxHeight, float textHeight) + static void roll_tick(About::RollState& roll, Resources& resources, float boxHeight, float textHeight) { - auto levels = audio::levels_get(resources.music_track()); + auto levels = audio_levels_get(resources.music_track()); roll.levelPeak = std::max({roll.levelPeak * BAR_LEVEL_DECAY, levels.x, levels.y, BAR_LEVEL_FLOOR}); levels *= boxHeight / roll.levelPeak; roll.scroll -= ROLL_SCROLL_STEP; @@ -344,7 +340,7 @@ namespace anm2ed::imgui::wizard if (roll.history.size() > ROLL_HISTORY_MAX) roll.history.pop_back(); } - ImU32 color_weighted_get(ImU32 color, float weight) + static ImU32 color_weighted_get(ImU32 color, float weight) { auto value = ImGui::ColorConvertU32ToFloat4(color); value.w *= weight; @@ -352,7 +348,7 @@ namespace anm2ed::imgui::wizard } // The credits as one tick drew them; `weight` fades the copies that linger as trails. - void roll_text_draw(ImDrawList* drawList, Resources& resources, const About::RollFrame& frame, ImVec2 min, ImVec2 max, + static void roll_text_draw(ImDrawList* drawList, Resources& resources, const About::RollFrame& frame, ImVec2 min, ImVec2 max, float scale, float lineHeight, float weight) { auto centerX = (min.x + max.x) * 0.5f; @@ -366,7 +362,7 @@ namespace anm2ed::imgui::wizard auto x = centerX - font->CalcTextSizeA(lineHeight, FLT_MAX, 0.0f, credit.string).x * 0.5f + frame.offsetX * scale; if (frame.effect == EFFECT_WAVE) x += std::round(std::sin((y - min.y) / scale * ROLL_WAVE_FREQUENCY) * ROLL_WAVE_AMPLITUDE) * scale; - auto color = credit.font == font::BOLD ? ROLL_HEADER_COLOR : ROLL_NAME_COLOR; + auto color = credit.font == FONT_BOLD ? ROLL_HEADER_COLOR : ROLL_NAME_COLOR; auto vertexStart = drawList->VtxBuffer.Size; drawList->AddText(font, lineHeight, ImVec2(x, y), color_weighted_get(color, weight), credit.string); @@ -377,7 +373,7 @@ namespace anm2ed::imgui::wizard } // A volume bar's color at a height: red at the bottom into the tick's color at its gradient height. - ImU32 bar_color_get(const About::RollFrame& frame, float height, float weight) + static ImU32 bar_color_get(const About::RollFrame& frame, float height, float weight) { auto color = ImLerp(ImGui::ColorConvertU32ToFloat4(BAR_BASE_COLOR), ImGui::ColorConvertU32ToFloat4(frame.gradientColor), height / frame.gradientHeight); @@ -386,7 +382,7 @@ namespace anm2ed::imgui::wizard } // The left and right volume bars; older, taller bars show above newer ones, fading as they age. - void roll_bars_draw(ImDrawList* drawList, const std::deque& history, ImVec2 min, ImVec2 max, + static void roll_bars_draw(ImDrawList* drawList, const std::deque& history, ImVec2 min, ImVec2 max, float scale) { auto width = BAR_WIDTH * scale; @@ -412,7 +408,7 @@ namespace anm2ed::imgui::wizard } } - void roll_draw(About& about, Resources& resources, ImVec2 min, ImVec2 size) + static void roll_draw(About& about, Resources& resources, ImVec2 min, ImVec2 size) { auto& roll = about.roll; auto max = ImVec2(min.x + size.x, min.y + size.y); @@ -458,11 +454,11 @@ namespace anm2ed::imgui::wizard void About::reset(Resources& resources) { - resource::audio::play(resources.music_track(), true); + audio_play(resources.music_track(), true); roll = {}; - for (int i = 0; i < resource::friends::COUNT; ++i) - friend_state_load(friendStates[i], resource::friends::FRIENDS[i]); + for (int i = 0; i < FRIEND_COUNT; ++i) + friend_state_load(friendStates[i], FRIENDS[i]); } void About::update(Resources& resources) @@ -479,4 +475,3 @@ namespace anm2ed::imgui::wizard auto rollSize = ImGui::GetContentRegionAvail(); if (rollSize.x > 0.0f && rollSize.y > 0.0f) roll_draw(*this, resources, ImGui::GetCursorScreenPos(), rollSize); } -} diff --git a/src/ui/about.h b/src/ui/about.h index fa7eaf9..cff88c7 100644 --- a/src/ui/about.h +++ b/src/ui/about.h @@ -13,15 +13,13 @@ #include "friends.h" #include "resources.h" -namespace anm2ed::imgui::wizard -{ class About { public: struct Credit { const char* string{}; - resource::font::Type font{resource::font::REGULAR}; + FontStyle font{FONT_REGULAR}; }; // One 30 Hz tick of the credits roll, after the original editor's About box. Lengths are in its pixels (for @@ -53,9 +51,9 @@ namespace anm2ed::imgui::wizard struct FriendState { - model::Model model{}; + Model model{}; std::unique_ptr canvas{}; - std::unordered_map textures{}; + std::unordered_map textures{}; glm::vec4 rect{-1.0f}; float time{}; float fps{30.0f}; @@ -63,10 +61,9 @@ namespace anm2ed::imgui::wizard }; RollState roll{}; - std::array friendStates{}; + std::array friendStates{}; void reset(Resources& resources); void update(Resources& resources); }; -} diff --git a/src/ui/actions.cpp b/src/ui/actions.cpp index a5ef444..e7ec3a1 100644 --- a/src/ui/actions.cpp +++ b/src/ui/actions.cpp @@ -5,17 +5,15 @@ #include "ui/layout.h" #include "ui/shortcut.h" -namespace anm2ed::imgui -{ - bool is_action_shortcut_valid(int shortcutType) { return shortcutType >= 0 && shortcutType < SHORTCUT_COUNT; } + static bool is_action_shortcut_valid(int shortcutType) { return shortcutType >= 0 && shortcutType < SHORTCUT_COUNT; } - std::string action_shortcut_text_get(const Action& action, Settings& settings) + static std::string action_shortcut_text_get(const Action& action, Settings& settings) { if (!is_action_shortcut_valid(action.shortcut)) return {}; return settings.*SHORTCUT_MEMBERS[action.shortcut]; } - ImGuiKeyChord action_chord_get(const Action& action, Manager& manager) + static ImGuiKeyChord action_chord_get(const Action& action, Manager& manager) { if (!is_action_shortcut_valid(action.shortcut)) return ImGuiKey_None; return manager.chords[action.shortcut]; @@ -55,7 +53,7 @@ namespace anm2ed::imgui { manager.command_push({manager.selected, [](Manager&, Document& document) { document.redo(); }}); }); } - void action_items_menu_draw(std::vector& items, Settings& settings) + static void action_items_menu_draw(std::vector& items, Settings& settings) { bool isPreviousSeparator{}; for (auto& action : items) @@ -111,7 +109,7 @@ namespace anm2ed::imgui return true; } - void actions_shortcuts_update(Actions& actions, Manager& manager, types::shortcut::Type shortcutType) + void actions_shortcuts_update(Actions& actions, Manager& manager, ShortcutScope shortcutType) { for (auto& action : actions.items) { @@ -140,4 +138,3 @@ namespace anm2ed::imgui } isSameLine = true; } -} diff --git a/src/ui/actions.h b/src/ui/actions.h index 832f858..63f2a4e 100644 --- a/src/ui/actions.h +++ b/src/ui/actions.h @@ -8,8 +8,6 @@ #include "manager.h" #include "settings.h" -namespace anm2ed::imgui -{ #define ACTIONS(X) \ X(ACTION_UNDO, SHORTCUT_STRING_UNDO, SHORTCUT_UNDO) \ X(ACTION_REDO, SHORTCUT_STRING_REDO, SHORTCUT_REDO) \ @@ -91,6 +89,5 @@ namespace anm2ed::imgui bool actions_context_window_draw(const char*, Actions&, Settings&, ImGuiPopupFlags = ImGuiPopupFlags_MouseButtonRight, ImGuiHoveredFlags = ImGuiHoveredFlags_None); bool actions_popup_draw(const char*, Actions&, Settings&); - void actions_shortcuts_update(Actions&, Manager&, types::shortcut::Type = types::shortcut::FOCUSED); + void actions_shortcuts_update(Actions&, Manager&, ShortcutScope = SCOPE_FOCUSED); void action_button_draw(Action&, Manager&, Settings&, ImVec2, bool&); -} diff --git a/src/ui/animation_preview.cpp b/src/ui/animation_preview.cpp index 01684ee..4db10d3 100644 --- a/src/ui/animation_preview.cpp +++ b/src/ui/animation_preview.cpp @@ -30,14 +30,8 @@ #include "ui/shortcut.h" #include "ui/timeline.h" -using namespace anm2ed::types; -using namespace anm2ed::util; -using namespace anm2ed::resource; -using namespace anm2ed::resource::image; using namespace glm; -namespace anm2ed::imgui -{ constexpr auto NULL_RECT_COLOR = vec4(0.0f, 0.0f, 1.0f, 0.90f); constexpr auto SELECTED_LAYER_BORDER_COLOR = vec4(1.0f, 0.1059f, 0.5882f, 1.0f); constexpr auto TARGET_SIZE = vec2(32, 32); @@ -52,13 +46,13 @@ namespace anm2ed::imgui std::string label{}; }; - std::vector overlay_animation_options_get(Manager& manager) + static std::vector overlay_animation_options_get(Manager& manager) { std::vector options{{.label = std::string(localize.get(BASIC_NONE))}}; for (auto& document : manager.documents) { - auto documentLabel = path::to_utf8(document.filename_get()); + auto documentLabel = path_to_utf8(document.filename_get()); for (auto [animationIndex, animation] : document.model.animations_get()) { auto label = std::format("{} ({})", animation->name, documentLabel); @@ -69,7 +63,7 @@ namespace anm2ed::imgui return options; } - std::vector overlay_animation_option_labels_get(std::vector& options) + static std::vector overlay_animation_option_labels_get(std::vector& options) { std::vector labels{}; labels.reserve(options.size()); @@ -78,7 +72,7 @@ namespace anm2ed::imgui return labels; } - int overlay_animation_option_index_get(const Document& document, const std::vector& options) + static int overlay_animation_option_index_get(const Document& document, const std::vector& options) { if (document.overlayIndex == -1) return 0; auto documentId = document.overlayDocumentId ? document.overlayDocumentId : document.tabId; @@ -87,7 +81,7 @@ namespace anm2ed::imgui return -1; } - Document* overlay_animation_document_get(Manager& manager, const Document& document) + static Document* overlay_animation_document_get(Manager& manager, const Document& document) { if (document.overlayIndex == -1) return nullptr; auto documentId = document.overlayDocumentId ? document.overlayDocumentId : document.tabId; @@ -96,7 +90,7 @@ namespace anm2ed::imgui return nullptr; } - std::optional animation_rects_merge(std::optional rect, vec4 next) + static std::optional animation_rects_merge(std::optional rect, vec4 next) { if (next == vec4(-1.0f)) return rect; if (!rect) return next; @@ -106,19 +100,19 @@ namespace anm2ed::imgui return vec4(minPoint, maxPoint - minPoint); } - std::optional animation_render_rect_get(Manager& manager, Document& document, const model::Animation* animation, + static std::optional animation_render_rect_get(Manager& manager, Document& document, const Animation* animation, bool isRootTransform) { std::optional rect{}; if (animation) rect = animation_rects_merge( - rect, model::animation_rect(document.model, *animation, isRootTransform, document.library_resolver_get())); + rect, animation_rect(document.model, *animation, isRootTransform, document.library_resolver_get())); if (auto overlayDocument = overlay_animation_document_get(manager, document)) if (auto overlayAnimation = overlayDocument->model.animation_get(document.overlayIndex)) rect = animation_rects_merge(rect, - model::animation_rect(overlayDocument->model, *overlayAnimation, isRootTransform, + animation_rect(overlayDocument->model, *overlayAnimation, isRootTransform, overlayDocument->library_resolver_get())); return rect; @@ -134,7 +128,7 @@ namespace anm2ed::imgui auto stop_all_sounds = [&]() { for (auto sound : document.sounds_get()) - audio::stop(*sound, mixer); + audio_stop(*sound, mixer); }; if (manager.isRecording) @@ -163,7 +157,7 @@ namespace anm2ed::imgui else { auto fps = std::max(model.info.fps, 1); - auto range = model::animation_play_range_get(*animation); + auto range = animation_play_range_get(*animation); if (!wasPlaybackPlaying) soundFrame = (int)std::floor(playback.time) - 1; playback.tick(fps, range.x, range.y, (animation->isLoop || settings.playbackIsLoop) && !manager.isRecording, deltaSeconds); @@ -175,7 +169,7 @@ namespace anm2ed::imgui soundFrame = soundFrame + 1 >= range.y || soundFrame + 1 < range.x ? range.x : soundFrame + 1; if (manager.isRecording || !isSound) continue; for (auto sound : document.trigger_sounds_get(*animation, soundFrame)) - audio::play(*sound, false, mixer); + audio_play(*sound, false, mixer); } frameTime = playback.time; @@ -197,18 +191,18 @@ namespace anm2ed::imgui // Starts a render from the render settings; a bounded render frames the animation (and overlay) at the render scale. void AnimationPreview::recording_start(Manager& manager, Settings& settings, Document& document, - const model::Animation* animation) + const Animation* animation) { auto animationFps = std::max(document.model.info.fps, 1); - render::RecorderOptions options{ - .type = (render::Type)settings.renderType, + RecorderOptions options{ + .type = (RenderType)settings.renderType, .path = settings.renderPath, .format = settings.renderFormat, .ffmpegPath = settings.renderFFmpegPath, .start = manager.recordingStart, .end = manager.recordingEnd, .animationFps = animationFps, - .fps = render::fps_get(settings.renderFpsMode, animationFps, settings.playbackTickRate), + .fps = fps_get(settings.renderFpsMode, animationFps, settings.playbackTickRate), .rows = settings.renderRows, .columns = settings.renderColumns, .isSound = settings.timelineIsSound, @@ -221,7 +215,7 @@ namespace anm2ed::imgui recordPan = document.previewPan; if (auto rect = animation_render_rect_get(manager, document, animation, settings.previewIsRootTransform)) { - recordSize = glm::vec2(rect->z, rect->w) * math::percent_to_unit(settings.renderScale); + recordSize = glm::vec2(rect->z, rect->w) * percent_to_unit(settings.renderScale); auto previousSize = size; size = recordSize; set_to_rect(recordZoom, recordPan, *rect); @@ -233,7 +227,7 @@ namespace anm2ed::imgui manager.isRecording = true; if (!recorder.start(options)) { - toast_log(Level::ERROR, TOAST_EXPORT_RENDERED_ANIMATION_FAILED, path::to_utf8(options.path)); + toast_log(Level::ERROR, TOAST_EXPORT_RENDERED_ANIMATION_FAILED, path_to_utf8(options.path)); return recording_stop(manager, document); } document.playback.isPlaying = true; @@ -271,19 +265,19 @@ namespace anm2ed::imgui auto& isBorder = settings.previewIsBorder; auto& tool = settings.tool; auto& isOnlyShowLayers = settings.timelineIsOnlyShowLayers; - auto& shaderLine = resources.shaders[shader::LINE]; - bool isLightTheme = settings.theme == theme::LIGHT; - auto& shaderAxes = resources.shaders[shader::AXIS]; - auto& shaderGrid = resources.shaders[shader::GRID]; - auto& shaderTexture = resources.shaders[shader::TEXTURE]; - auto& shaderDashed = resources.shaders[shader::DASHED]; + auto& shaderLine = resources.shaders[SHADER_LINE]; + bool isLightTheme = settings.theme == THEME_LIGHT; + auto& shaderAxes = resources.shaders[SHADER_AXIS]; + auto& shaderGrid = resources.shaders[SHADER_GRID]; + auto& shaderTexture = resources.shaders[SHADER_TEXTURE]; + auto& shaderDashed = resources.shaders[SHADER_DASHED]; auto center_view = [&]() { pan = vec2(); }; auto fit_view = [&]() { if (animation) set_to_rect(zoom, pan, - model::animation_rect(model, *animation, isRootTransform, document.library_resolver_get())); + animation_rect(model, *animation, isRootTransform, document.library_resolver_get())); }; manager.isAbleToRecord = false; @@ -367,7 +361,7 @@ namespace anm2ed::imgui } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_OVERLAY)); - overlayDrawOrder = glm::clamp(overlayDrawOrder, (int)overlay_draw_order::OVER, (int)overlay_draw_order::UNDER); + overlayDrawOrder = glm::clamp(overlayDrawOrder, (int)OVERLAY_OVER, (int)OVERLAY_UNDER); overlayTransparency = glm::clamp(overlayTransparency, 0.0f, 100.0f); auto orderIconSize = icon_size_get(); auto orderButtonWidth = orderIconSize.x + ImGui::GetStyle().FramePadding.x * 2.0f; @@ -382,13 +376,13 @@ namespace anm2ed::imgui overlayTransparency = glm::clamp(overlayTransparency, 0.0f, 100.0f); ImGui::SameLine(); - radio_button_icon("##Overlay Over", &overlayDrawOrder, overlay_draw_order::OVER, - resources.icon_id_get(icon::OVER), orderIconSize, overlayIconTint); + radio_button_icon("##Overlay Over", &overlayDrawOrder, OVERLAY_OVER, + resources.icon_id_get(ICON_OVER), orderIconSize, overlayIconTint); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_OVERLAY_OVER)); ImGui::SameLine(); - radio_button_icon("##Overlay Under", &overlayDrawOrder, overlay_draw_order::UNDER, - resources.icon_id_get(icon::UNDER), orderIconSize, overlayIconTint); + radio_button_icon("##Overlay Under", &overlayDrawOrder, OVERLAY_UNDER, + resources.icon_id_get(ICON_UNDER), orderIconSize, overlayIconTint); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_OVERLAY_UNDER)); } ImGui::EndChild(); @@ -476,17 +470,17 @@ namespace anm2ed::imgui auto frame = selectedFrameReferences.empty() ? nullptr : model.frame_get(editReference); auto selectedNull = - editReference.itemType == NULL_ ? model::item_get(model.content.nulls, editReference.itemID) : nullptr; + editReference.itemType == NULL_ ? item_get(model.content.nulls, editReference.itemID) : nullptr; bool isSelectedNullRect = selectedNull && selectedNull->isShowRect; - auto null_rect_top_left = [](const model::Frame& frame) { return frame.position - (frame.scale * 0.5f); }; + auto null_rect_top_left = [](const Frame& frame) { return frame.position - (frame.scale * 0.5f); }; - auto useTool = (tool::Type)tool; - if (input.isMiddleDown) useTool = tool::PAN; - if (tool == tool::MOVE && input.isRightDown) useTool = tool::SCALE; - if (tool == tool::SCALE && input.isRightDown) useTool = tool::MOVE; + auto useTool = (Tool)tool; + if (input.isMiddleDown) useTool = TOOL_PAN; + if (tool == TOOL_MOVE && input.isRightDown) useTool = TOOL_SCALE; + if (tool == TOOL_SCALE && input.isRightDown) useTool = TOOL_MOVE; // A tool swapped in by the right button is driven by the right button. - auto isSwapped = useTool != tool && useTool != tool::PAN; + auto isSwapped = useTool != tool && useTool != TOOL_PAN; auto isToolClicked = isSwapped ? input.isRightClicked : input.isLeftClicked; auto isToolDown = isSwapped ? input.isRightDown : input.isLeftDown; auto isToolReleased = isSwapped ? input.isRightReleased : input.isLeftReleased; @@ -508,14 +502,14 @@ namespace anm2ed::imgui .scaleY = rectSize.y - frame->scale.y}); }; - tool_cursor_update(useTool, tool::ANIMATION_PREVIEW, frame != nullptr, true, + tool_cursor_update(useTool, TOOL_AREA_ANIMATION_PREVIEW, frame != nullptr, true, input.isLeftDown || input.isRightDown || input.isMiddleDown || input.isArrowDown, TEXT_SELECT_FRAME); - if (useTool != tool::MOVE) isMoveDragging = false; - if (useTool == tool::PAN && (input.isLeftDown || input.isRightDown || input.isMiddleDown)) + if (useTool != TOOL_MOVE) isMoveDragging = false; + if (useTool == TOOL_PAN && (input.isLeftDown || input.isRightDown || input.isMiddleDown)) pan += input.mouseDelta; - if (frame && useTool == tool::MOVE) + if (frame && useTool == TOOL_MOVE) { if (isBegin) edit_begin_push(manager, EDIT_FRAME_POSITION); if (isToolClicked) @@ -535,7 +529,7 @@ namespace anm2ed::imgui if (isEnd) document_change_push(manager); } - if (frame && useTool == tool::SCALE) + if (frame && useTool == TOOL_SCALE) { if (isBegin) edit_begin_push(manager, EDIT_FRAME_SCALE); if (isToolClicked && isSelectedNullRect) nullRectScaleAnchor = null_rect_top_left(*frame); @@ -569,7 +563,7 @@ namespace anm2ed::imgui if (isEnd) document_change_push(manager); } - if (frame && useTool == tool::ROTATE) + if (frame && useTool == TOOL_ROTATE) { if (isBegin) edit_begin_push(manager, EDIT_FRAME_ROTATION); if (isToolDown) frames_change({.rotation = input.mouseDelta.x}); @@ -579,7 +573,7 @@ namespace anm2ed::imgui if (isEnd) document_change_push(manager); } - if (frame && useTool == tool::SKEW) + if (frame && useTool == TOOL_SKEW) { if (isBegin) edit_begin_push(manager, EDIT_FRAME_SKEW); if (isToolDown) @@ -608,7 +602,7 @@ namespace anm2ed::imgui auto baseTransform = transform_get(viewZoom, viewPan); auto frameTime = document.frameTime > -1 && !playback.isPlaying ? document.frameTime : playback.time; - model::DrawOptions drawOptions{.time = frameTime, + DrawOptions drawOptions{.time = frameTime, .isRootTransform = isRootTransform, .isIndexSampled = settings.onionskinMode == (int)OnionskinMode::INDEX}; std::vector sampleColors{}; @@ -641,16 +635,16 @@ namespace anm2ed::imgui }; // The item the reference points at: the root (or a group's root), a layer or a null. - auto is_draw_selected = [&](const model::Draw& draw) + auto is_draw_selected = [&](const Draw& draw) { switch (draw.type) { - case model::DrawType::ROOT: + case DrawType::ROOT: return referenceItemType == ItemType::ROOT && reference.groupId == -1; - case model::DrawType::GROUP_ROOT: + case DrawType::GROUP_ROOT: return referenceItemType == ItemType::ROOT && reference.groupType == draw.groupType && reference.groupId == draw.id; - case model::DrawType::LAYER: + case DrawType::LAYER: return referenceItemType == ItemType::LAYER && reference.itemID == draw.id; default: return referenceItemType == ItemType::NULL_ && reference.itemID == draw.id; @@ -661,18 +655,18 @@ namespace anm2ed::imgui // Draws an animation's draw list; onion-skin samples are tinted and faded, `alphaOffset` fades the overlay. A // parent around a stepped-into child is drawn in the child's space (`scene`), its layers only, without the // animation layer playing the child (`skipLayerId`). - auto render = [&](Document& sampleDocument, const model::Animation& sampleAnimation, float alphaOffset, - const model::DrawOptions& options, const mat4& scene = mat4(1.0f), int skipLayerId = -1) + auto render = [&](Document& sampleDocument, const Animation& sampleAnimation, float alphaOffset, + const DrawOptions& options, const mat4& scene = mat4(1.0f), int skipLayerId = -1) { auto isActiveDocument = &sampleDocument == &document && skipLayerId == -1; auto isParent = skipLayerId != -1; auto& sampleModel = sampleDocument.model; - auto targetIcon = resources.icon_id_get(isAltIcons && !isIsolated ? icon::TARGET_ALT : icon::TARGET); + auto targetIcon = resources.icon_id_get(isAltIcons && !isIsolated ? ICON_TARGET_ALT : ICON_TARGET); auto sampleOptions = options; sampleOptions.library_get = sampleDocument.library_resolver_get(); - for (const auto& draw : model::animation_draws_get(sampleModel, sampleAnimation, sampleOptions)) + for (const auto& draw : animation_draws_get(sampleModel, sampleAnimation, sampleOptions)) { - if (isParent && (draw.type != model::DrawType::LAYER || draw.id == skipLayerId)) continue; + if (isParent && (draw.type != DrawType::LAYER || draw.id == skipLayerId)) continue; auto isOnion = draw.sample != -1; if (isOnion && isOnlySelected && !(isActiveDocument && is_draw_selected(draw))) continue; auto sampleColor = isOnion ? sampleColors[draw.sample] : vec3(); @@ -682,60 +676,60 @@ namespace anm2ed::imgui auto transform = baseTransform * scene * draw.parent; auto marker_model_get = [&](vec2 markerSize) { - return math::quad_model_get(markerSize, frame.position, markerSize * 0.5f, - math::percent_to_unit(frame.scale), frame.rotation, - math::percent_to_unit(frame.skew)); + return quad_model_get(markerSize, frame.position, markerSize * 0.5f, + percent_to_unit(frame.scale), frame.rotation, + percent_to_unit(frame.skew)); }; - if (draw.type == model::DrawType::ROOT || draw.type == model::DrawType::GROUP_ROOT) + if (draw.type == DrawType::ROOT || draw.type == DrawType::GROUP_ROOT) { if (isViewOnlyLayers) continue; - auto isSelected = isActiveDocument && draw.type == model::DrawType::GROUP_ROOT && + auto isSelected = isActiveDocument && draw.type == DrawType::GROUP_ROOT && referenceItemType == ItemType::ROOT && reference.groupType == draw.groupType && reference.groupId == draw.id; auto color = isOnion ? vec4(sampleColor, sampleAlpha) - : draw.type == model::DrawType::ROOT ? color::GREEN - : isSelected ? color::RED + : draw.type == DrawType::ROOT ? COLOR_GREEN + : isSelected ? COLOR_RED : ROOT_COLOR; - auto markerModel = isRootTransform ? math::quad_model_get(TARGET_SIZE, {}, TARGET_SIZE * 0.5f) + auto markerModel = isRootTransform ? quad_model_get(TARGET_SIZE, {}, TARGET_SIZE * 0.5f) : marker_model_get(TARGET_SIZE); texture_render(shaderTexture, targetIcon, transform * markerModel, color); } - else if (draw.type == model::DrawType::LAYER) + else if (draw.type == DrawType::LAYER) { auto layerTexture = - sampleDocument.draw_image_get(draw, math::percent_to_unit(viewZoom) * model::draw_scale_get(draw)); + sampleDocument.draw_image_get(draw, percent_to_unit(viewZoom) * draw_scale_get(draw)); if (!layerTexture || !layerTexture->is_valid() || layerTexture->size.x <= 0 || layerTexture->size.y <= 0) continue; auto textureSize = layerTexture->unit_size_get(); - auto layerModel = model::draw_quad_model_get(draw); + auto layerModel = draw_quad_model_get(draw); auto layerTransform = transform * layerModel; auto tint = frame.tint; tint.a = std::max(0.0f, tint.a - (alphaOffset + sampleAlpha)); auto customShader = sampleDocument.shader_get(frame.shaderId); - layer_render(customShader ? *customShader : shaderTexture, resource::texture::id_get(*layerTexture), + layer_render(customShader ? *customShader : shaderTexture, texture_id_get(*layerTexture), textureSize, baseTransform * scene, draw, tint, frame.colorOffset + vec4(sampleColor, 0.0f)); if (isParent) continue; auto color = isOnion ? onionColor : isActiveDocument && is_layer_selected(draw.id) ? SELECTED_LAYER_BORDER_COLOR - : color::RED; + : COLOR_RED; if (isBorder && !isIsolated) rect_render(shaderLine, layerTransform, layerModel, color); if (isPivots && !isIsolated) - texture_render(shaderTexture, resources.icon_id_get(icon::PIVOT), + texture_render(shaderTexture, resources.icon_id_get(ICON_PIVOT), transform * marker_model_get(PIVOT_SIZE), color); } else if (!isViewOnlyLayers) { - auto isShowRect = model::item_get(sampleModel.content.nulls, draw.id)->isShowRect; + auto isShowRect = item_get(sampleModel.content.nulls, draw.id)->isShowRect; auto isSelected = isActiveDocument && draw.id == reference.itemID && referenceItemType == ItemType::NULL_; - auto color = isOnion ? onionColor : isSelected ? color::RED : NULL_RECT_COLOR; + auto color = isOnion ? onionColor : isSelected ? COLOR_RED : NULL_RECT_COLOR; auto markerSize = isShowRect ? POINT_SIZE : TARGET_SIZE; - texture_render(shaderTexture, isShowRect ? resources.icon_id_get(icon::POINT) : targetIcon, + texture_render(shaderTexture, isShowRect ? resources.icon_id_get(ICON_POINT) : targetIcon, transform * marker_model_get(markerSize), color); if (!isShowRect) continue; - auto rectModel = math::quad_model_get(frame.scale, frame.position, frame.scale * 0.5f, vec2(1.0f), - frame.rotation, math::percent_to_unit(frame.skew)); + auto rectModel = quad_model_get(frame.scale, frame.position, frame.scale * 0.5f, vec2(1.0f), + frame.rotation, percent_to_unit(frame.skew)); rect_render(shaderLine, transform * rectModel, rectModel, color); } } @@ -747,7 +741,7 @@ namespace anm2ed::imgui { if (auto overlayDocument = isIsolated ? nullptr : overlay_animation_document_get(manager, document)) if (auto overlayAnimation = overlayDocument->model.animation_get(overlayIndex)) - render(*overlayDocument, *overlayAnimation, 1.0f - math::percent_to_unit(overlayTransparency), + render(*overlayDocument, *overlayAnimation, 1.0f - percent_to_unit(overlayTransparency), drawOptions); }; @@ -759,7 +753,7 @@ 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(*parentAnimation, step.layer.itemID, + auto placement = parentAnimation ? layer_child_transform_get(*parentAnimation, step.layer.itemID, step.frameTime, isRootTransform) : std::nullopt; if (placement && glm::determinant(*placement) != 0.0f) @@ -768,9 +762,9 @@ namespace anm2ed::imgui step.layer.itemID); } - if (overlayDrawOrder == overlay_draw_order::UNDER) overlay_render(); + if (overlayDrawOrder == OVERLAY_UNDER) overlay_render(); render(document, *animation, 0.0f, drawOptions); - if (overlayDrawOrder == overlay_draw_order::OVER) overlay_render(); + if (overlayDrawOrder == OVERLAY_OVER) overlay_render(); if (settings.onionskinIsEnabled && settings.onionskinIsPivotPath && !isIsolated) { @@ -780,7 +774,7 @@ namespace anm2ed::imgui pivotPathsKey = key; pivotPaths.clear(); for (int time = 0; time < animation->frameNum; ++time) - for (const auto& draw : model::animation_draws_get(model, *animation, + for (const auto& draw : animation_draws_get(model, *animation, {.time = (float)time, .isRootTransform = isRootTransform, .library_get = document.library_resolver_get()})) @@ -796,16 +790,16 @@ namespace anm2ed::imgui } } - auto pointIcon = resources.icon_id_get(icon::POINT); + auto pointIcon = resources.icon_id_get(ICON_POINT); for (const auto& path : pivotPaths) { if (isOnlySelected && !is_draw_selected(path.item)) continue; for (std::size_t i = 0; i < path.points.size(); ++i) { - if (i > 0) line_render(shaderDashed, baseTransform, path.points[i - 1], path.points[i], color::RED); + if (i > 0) line_render(shaderDashed, baseTransform, path.points[i - 1], path.points[i], COLOR_RED); texture_render(shaderTexture, pointIcon, - baseTransform * math::quad_model_get(POINT_SIZE, path.points[i], POINT_SIZE * 0.5f), - color::RED); + baseTransform * quad_model_get(POINT_SIZE, path.points[i], POINT_SIZE * 0.5f), + COLOR_RED); } } } @@ -815,10 +809,10 @@ namespace anm2ed::imgui { auto sounds = settings.timelineIsSound && animation && recorder.is_sound_frame() ? document.trigger_sounds_get(*animation, (int)frameTime, recorder.index) - : std::vector{}; + : std::vector{}; if (!recorder.frame_capture(pixels_get(), size, sounds)) { - toast_log(Level::ERROR, TOAST_EXPORT_RENDERED_ANIMATION_FAILED, path::to_utf8(recorder.options.path)); + toast_log(Level::ERROR, TOAST_EXPORT_RENDERED_ANIMATION_FAILED, path_to_utf8(recorder.options.path)); recorder.cancel(); recording_stop(manager, document); } @@ -837,9 +831,9 @@ namespace anm2ed::imgui std::string names{}; if (animation && !isOnlyShowLayers && !manager.isRecording) for (const auto& [source, trigger, layerId] : - model::animation_triggers_get(model, *animation, (int)frameTime, document.library_resolver_get())) + animation_triggers_get(model, *animation, (int)frameTime, document.library_resolver_get())) for (auto eventId : trigger.eventIds) - if (auto event = model::item_get(source->content.events, eventId)) + if (auto event = item_get(source->content.events, eventId)) names += (names.empty() ? "" : ", ") + event->name; if (!names.empty()) { @@ -849,7 +843,7 @@ namespace anm2ed::imgui auto textPos = to_imvec2(to_vec2(cursorScreenPos) + to_vec2(ImGui::GetStyle().WindowPadding)); drawList->PushClipRect(clipMin, clipMax); - ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE_LARGE); + ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE_LARGE); auto triggerTextColor = isLightTheme ? TRIGGER_TEXT_COLOR_LIGHT : TRIGGER_TEXT_COLOR_DARK; drawList->AddText(textPos, ImGui::GetColorU32(triggerTextColor), names.c_str()); ImGui::PopFont(); @@ -857,7 +851,7 @@ namespace anm2ed::imgui } } - if (tool == tool::PAN) + if (tool == TOOL_PAN) view_context_menu_draw("##Animation Preview Context Menu", manager, settings, document, zoom, pan, center_view, fit_view, animation != nullptr); @@ -889,4 +883,3 @@ namespace anm2ed::imgui settings.previewStartZoom = zoom; ImGui::End(); } -} diff --git a/src/ui/animation_preview.h b/src/ui/animation_preview.h index e8e7ed0..ed7fe23 100644 --- a/src/ui/animation_preview.h +++ b/src/ui/animation_preview.h @@ -11,8 +11,6 @@ #include "resources.h" #include "settings.h" -namespace anm2ed::imgui -{ class AnimationPreview : public CanvasView { MIX_Mixer* mixer = MIX_CreateMixerDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, nullptr); @@ -22,7 +20,7 @@ namespace anm2ed::imgui bool isMoveDragging{}; glm::vec2 moveOffset{}; glm::vec2 nullRectScaleAnchor{}; - render::Recorder recorder{}; + Recorder recorder{}; glm::vec2 recordSize{}; glm::vec2 recordPan{}; float recordZoom{}; @@ -30,17 +28,16 @@ namespace anm2ed::imgui // Where each item's pivot is at every frame of the animation, kept until the document or view changes. struct PivotPath { - model::Draw item{}; + Draw item{}; std::vector points{}; }; std::vector pivotPaths{}; std::tuple pivotPathsKey{}; - void recording_start(Manager&, Settings&, Document&, const model::Animation*); + void recording_start(Manager&, Settings&, Document&, const Animation*); void recording_stop(Manager&, Document&); public: void tick(Manager&, Settings&, float); void update(Manager&, Settings&, Resources&); }; -} diff --git a/src/ui/animations.cpp b/src/ui/animations.cpp index 644ad61..4f0904a 100644 --- a/src/ui/animations.cpp +++ b/src/ui/animations.cpp @@ -9,11 +9,6 @@ #include "ui/shortcut.h" #include "ui/tree.h" -using namespace anm2ed::resource; -using namespace anm2ed::types; - -namespace anm2ed::imgui -{ constexpr const char* ANIMATION_DRAG_DROP = "Animation Drag Drop"; constexpr float DROP_ZONE_FRACTION = 1.0f / 3.0f; constexpr int MERGE_OPTIONS_ROWS = 2; @@ -45,68 +40,68 @@ namespace anm2ed::imgui { std::set selection{}; int reference{-1}; - merge::Type type{}; + Merge type{}; bool isDeleteAnimationsAfter{}; }; // Calls back for each top-level entry: (animation index, animation) for loose animations, (index, group) for groups. - template void animation_entries_each(const model::Model& model, Callback&& callback) + template static void animation_entries_each(const Model& model, Callback&& callback) { int index{}; for (const auto& entry : model.animations.entries) - if (auto animation = std::get_if>(&entry)) - callback(index++, animation->get(), (const model::AnimationGroup*)nullptr); + if (auto animation = std::get_if>(&entry)) + callback(index++, animation->get(), (const AnimationGroup*)nullptr); else { - auto& group = std::get(entry); - callback(index, (const model::Animation*)nullptr, &group); + auto& group = std::get(entry); + callback(index, (const Animation*)nullptr, &group); index += (int)group.animations.size(); } } // The flat index of a group's first animation. - int animation_group_first_index_get(const model::Model& model, int groupId) + static int animation_group_first_index_get(const Model& model, int groupId) { int first{-1}; animation_entries_each(model, - [&](int index, auto*, const model::AnimationGroup* group) + [&](int index, auto*, const AnimationGroup* group) { if (group && group->id == groupId) first = index; }); return first; } - std::set animation_groups_selected_get(const Document& document) + static std::set animation_groups_selected_get(const Document& document) { std::set groupIds{}; auto uids = document.selection.uids.find(SelectionKind::ANIMATION_GROUPS); if (uids == document.selection.uids.end()) return groupIds; for (const auto& entry : document.model.animations.entries) - if (auto group = std::get_if(&entry); group && uids->second.contains(group->uid)) + if (auto group = std::get_if(&entry); group && uids->second.contains(group->uid)) groupIds.insert(group->id); return groupIds; } - void animations_selection_set(Document& document, const std::set& indices, const std::set& groupIds) + static void animations_selection_set(Document& document, const std::set& indices, const std::set& groupIds) { document.animations_selected_set(indices); auto& groupUids = document.selection.uids[SelectionKind::ANIMATION_GROUPS]; groupUids.clear(); for (const auto& entry : document.model.animations.entries) - if (auto group = std::get_if(&entry); group && groupIds.contains(group->id)) + if (auto group = std::get_if(&entry); group && groupIds.contains(group->id)) groupUids.insert(group->uid); } // Selected animations plus every animation of a selected group. - std::set animation_selected_indices_get(const Document& document) + static std::set animation_selected_indices_get(const Document& document) { auto result = document.animations_selected_get(); for (auto groupId : animation_groups_selected_get(document)) - result.merge(edit::animation_group_indices_get(document.model, groupId)); + result.merge(animation_group_indices_get(document.model, groupId)); return result; } - std::vector animation_groupable_indices_get(const Document& document) + static std::vector animation_groupable_indices_get(const Document& document) { std::vector result{}; for (auto index : document.animations_selected_get()) @@ -117,19 +112,19 @@ namespace anm2ed::imgui return result; } - std::set animation_merge_indices_get(const Document& document, const std::set& keys, int reference) + static std::set animation_merge_indices_get(const Document& document, const std::set& keys, int reference) { std::set result{}; for (auto key : keys) if (!is_group_key(key)) result.insert(key); else - result.merge(edit::animation_group_indices_get(document.model, group_id_from_key_get(key))); + result.merge(animation_group_indices_get(document.model, group_id_from_key_get(key))); result.erase(reference); return result; } - void animation_overlay_reset(Document& document, const std::set& indices) + static void animation_overlay_reset(Document& document, const std::set& indices) { auto isOverlayDocument = document.overlayDocumentId == 0 || document.overlayDocumentId == document.tabId; if (!isOverlayDocument || !indices.contains(document.overlayIndex)) return; @@ -137,19 +132,19 @@ namespace anm2ed::imgui document.overlayDocumentId = 0; } - void animations_erase(Document& document, const std::set& indices, const std::set& groupIds, + static void animations_erase(Document& document, const std::set& indices, const std::set& groupIds, StringType label) { document.edit_apply(label, - [&](model::Model& model) + [&](Model& model) { animation_overlay_reset(document, indices); animations_selection_set(document, {}, {}); - return edit::animations_remove(model, indices, groupIds); + return animations_remove(model, indices, groupIds); }); } - std::set animation_indices_get(Document& document, const edit::Uids& uids) + static std::set animation_indices_get(Document& document, const Uids& uids) { std::set indices{}; for (auto reference : document.references_get(uids)) @@ -157,33 +152,33 @@ namespace anm2ed::imgui return indices; } - std::string animation_clipboard_text_get(const Document& document) + static std::string animation_clipboard_text_get(const Document& document) { std::string clipboardText{}; auto& model = document.model; auto groupIds = animation_groups_selected_get(document); auto selection = document.animations_selected_get(); for (const auto& entry : model.animations.entries) - if (auto group = std::get_if(&entry); group && groupIds.contains(group->id)) - clipboardText += model::animation_group_to_string(*group); + if (auto group = std::get_if(&entry); group && groupIds.contains(group->id)) + clipboardText += animation_group_to_string(*group); for (int i = 0; i < model.animations_count_get(); ++i) { auto groupId = model.animation_group_id_get(i); if (selection.contains(i) || groupIds.contains(groupId)) - clipboardText += model::animation_to_string(*model.animation_get(i), groupId); + clipboardText += animation_to_string(*model.animation_get(i), groupId); } return clipboardText; } - void animations_insert(PanelState& state, Document& document, const std::string& text, int start, int targetGroupId, + static void animations_insert(PanelState& state, Document& document, const std::string& text, int start, int targetGroupId, StringType edit) { std::set groupIds{}; std::string errorString{}; document.edit_apply(edit, - [&](model::Model& model) + [&](Model& model) { - auto uids = edit::animations_paste(model, text, start, targetGroupId, groupIds, &errorString); + auto uids = animations_paste(model, text, start, targetGroupId, groupIds, &errorString); if (uids.empty()) return uids; auto indices = animation_indices_get(document, uids); animations_selection_set(document, groupIds.empty() ? indices : std::set{}, groupIds); @@ -199,13 +194,13 @@ namespace anm2ed::imgui } // Merges into options.reference; without a merge-popup selection, the selected animations merge into the first. - int animations_merge(Document& document, const AnimationMergeOptions& options) + static int animations_merge(Document& document, const AnimationMergeOptions& options) { auto isQuick = options.selection.empty(); auto target = options.reference; auto sources = isQuick ? animation_selected_indices_get(document) : animation_merge_indices_get(document, options.selection, target); - auto type = isQuick ? merge::APPEND : options.type; + auto type = isQuick ? MERGE_APPEND : options.type; auto isDeleteAfter = isQuick || options.isDeleteAnimationsAfter; auto ungroupIds = isQuick ? animation_groups_selected_get(document) : std::set{}; @@ -223,10 +218,10 @@ namespace anm2ed::imgui int merged{-1}; document.edit_apply(EDIT_MERGE_ANIMATIONS, - [&](model::Model& model) + [&](Model& model) { animation_overlay_reset(document, sources); - auto uids = edit::animations_merge(model, target, sources, type, isDeleteAfter, ungroupIds); + auto uids = animations_merge(model, target, sources, type, isDeleteAfter, ungroupIds); auto indices = animation_indices_get(document, uids); if (indices.empty()) return uids; merged = *indices.begin(); @@ -237,7 +232,7 @@ namespace anm2ed::imgui return merged; } - AnimationDropZone animation_drop_zone_get(ImVec2 min, ImVec2 max) + static AnimationDropZone animation_drop_zone_get(ImVec2 min, ImVec2 max) { auto zoneHeight = (max.y - min.y) * DROP_ZONE_FRACTION; auto mouseY = ImGui::GetIO().MousePos.y; @@ -246,8 +241,8 @@ namespace anm2ed::imgui return AnimationDropZone::INSIDE; } - void animation_move_command_push(const Panel& panel, std::vector items, - edit::AnimationTarget target) + static void animation_move_command_push(const Panel& panel, std::vector items, + AnimationTarget target) { if (items.empty()) return; command_push(panel, @@ -258,9 +253,9 @@ namespace anm2ed::imgui for (auto item : items) (item.isGroup ? groupIds : indices).insert(item.id); document.edit_apply(EDIT_MOVE_ANIMATIONS, - [&](model::Model& model) + [&](Model& model) { - auto uids = edit::animations_move(model, indices, groupIds, target); + auto uids = animations_move(model, indices, groupIds, target); if (uids.empty() && groupIds.empty()) return; animations_selection_set(document, animation_indices_get(document, uids), groupIds); @@ -268,7 +263,7 @@ namespace anm2ed::imgui }); } - void animation_drag_drop_source_update(const Document& document, AnimationDragDropItem fallback) + static void animation_drag_drop_source_update(const Document& document, AnimationDragDropItem fallback) { if (!ImGui::BeginDragDropSource(DRAG_DROP_SOURCE_FLAGS)) return; @@ -288,7 +283,7 @@ namespace anm2ed::imgui ImGui::EndDragDropSource(); } - std::vector animation_drag_drop_target_items_get() + static std::vector animation_drag_drop_target_items_get() { auto payload = ImGui::AcceptDragDropPayload(ANIMATION_DRAG_DROP, ImGuiDragDropFlags_AcceptBeforeDelivery | ImGuiDragDropFlags_AcceptNoDrawDefaultRect); @@ -297,7 +292,7 @@ namespace anm2ed::imgui return {items, items + payload->DataSize / sizeof(AnimationDragDropItem)}; } - bool animation_group_drag_drop_update(const Panel& panel, int groupId, ImVec2 itemMin, ImVec2 itemMax) + static bool animation_group_drag_drop_update(const Panel& panel, int groupId, ImVec2 itemMin, ImVec2 itemMax) { if (!ImGui::BeginDragDropTarget()) return false; auto items = animation_drag_drop_target_items_get(); @@ -322,7 +317,7 @@ namespace anm2ed::imgui return isDelivered; } - bool animation_row_drag_drop_update(const Panel& panel, int index) + static bool animation_row_drag_drop_update(const Panel& panel, int index) { animation_drag_drop_source_update(panel.document, {false, index}); if (!ImGui::BeginDragDropTarget()) return false; @@ -342,7 +337,7 @@ namespace anm2ed::imgui return isDelivered; } - void animation_group_set_push(const Panel& panel, int groupId, StringType edit, std::optional name, + static void animation_group_set_push(const Panel& panel, int groupId, StringType edit, std::optional name, std::optional isExpanded) { command_push(panel, @@ -354,7 +349,7 @@ namespace anm2ed::imgui isExpanded.value_or(group->isExpanded) == group->isExpanded)) return; document.edit_apply(edit, - [&](model::Model& model) + [&](Model& model) { auto group = model.animation_group_edit(first); group->name = name.value_or(group->name); @@ -364,8 +359,8 @@ namespace anm2ed::imgui } // A group's tree node (renamable, a drop target) and, when expanded, its animations' rows. - bool animation_group_draw(Panel& panel, std::set& selection, std::set& groupSelection, int& focus, - const ListRows& rows, const model::AnimationGroup& group, int firstIndex, int arrowKey) + static bool animation_group_draw(Panel& panel, std::set& selection, std::set& groupSelection, int& focus, + const ListRows& rows, const AnimationGroup& group, int firstIndex, int arrowKey) { auto& state = panel.state; auto key = group_key_get(group.id); @@ -435,7 +430,7 @@ namespace anm2ed::imgui return isRowsDone; } - void animations_merge_popup_update(Panel& panel, AnimationsPanel& animations) + static void animations_merge_popup_update(Panel& panel, AnimationsPanel& animations) { auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; auto& popup = animations.mergePopup; @@ -451,13 +446,13 @@ namespace anm2ed::imgui std::string label{}; }; std::vector candidates{}; - auto candidate_animation_push = [&](const model::Animation& animation, int animationIndex, bool isGrouped) + auto candidate_animation_push = [&](const Animation& animation, int animationIndex, bool isGrouped) { if (animationIndex != mergeReference) candidates.push_back({animationIndex, isGrouped ? std::format(" {}", animation.name) : animation.name}); }; animation_entries_each(document.model, - [&](int index, const model::Animation* animation, const model::AnimationGroup* group) + [&](int index, const Animation* animation, const AnimationGroup* group) { if (animation) return candidate_animation_push(*animation, index, false); auto isReferenceOnly = group->animations.size() == 1 && index == mergeReference; @@ -500,15 +495,15 @@ namespace anm2ed::imgui auto size = ImVec2(optionsSize.x * MERGE_OPTIONS_HALF, optionsSize.y - ImGui::GetStyle().WindowPadding.y * 2); if (ImGui::BeginChild("##Merge Options 1", size)) { - ImGui::RadioButton(localize.get(LABEL_APPEND_FRAMES), &settings.mergeType, merge::APPEND); - ImGui::RadioButton(localize.get(LABEL_PREPEND_FRAMES), &settings.mergeType, merge::PREPEND); + ImGui::RadioButton(localize.get(LABEL_APPEND_FRAMES), &settings.mergeType, MERGE_APPEND); + ImGui::RadioButton(localize.get(LABEL_PREPEND_FRAMES), &settings.mergeType, MERGE_PREPEND); } ImGui::EndChild(); ImGui::SameLine(); if (ImGui::BeginChild("##Merge Options 2", size)) { - ImGui::RadioButton(localize.get(LABEL_REPLACE_FRAMES), &settings.mergeType, merge::REPLACE); - ImGui::RadioButton(localize.get(LABEL_IGNORE_FRAMES), &settings.mergeType, merge::IGNORE); + ImGui::RadioButton(localize.get(LABEL_REPLACE_FRAMES), &settings.mergeType, MERGE_REPLACE); + ImGui::RadioButton(localize.get(LABEL_IGNORE_FRAMES), &settings.mergeType, MERGE_IGNORE); } ImGui::EndChild(); } @@ -525,7 +520,7 @@ namespace anm2ed::imgui command_push(panel, [options = AnimationMergeOptions{.selection = mergeSelection, .reference = mergeReference, - .type = (merge::Type)settings.mergeType, + .type = (Merge)settings.mergeType, .isDeleteAnimationsAfter = settings.mergeIsDeleteAnimationsAfter}]( Document& document) { animations_merge(document, options); }); if (result != PopupButton::NONE) @@ -546,7 +541,7 @@ namespace anm2ed::imgui { auto selection = document.animations_selected_get(); auto groupSelection = animation_groups_selected_get(document); - auto groupIds = edit::animation_group_ids_get(model); + auto groupIds = animation_group_ids_get(model); auto count = model.animations_count_get(); auto isItemSelected = [&]() { return !selection.empty() || !groupSelection.empty(); }; // A single selected group is where adds and pastes go. @@ -556,7 +551,7 @@ namespace anm2ed::imgui }; auto group_end_get = [&](int groupId) { - auto indices = groupId != -1 ? edit::animation_group_indices_get(model, groupId) : std::set{}; + auto indices = groupId != -1 ? animation_group_indices_get(model, groupId) : std::set{}; return indices.empty() ? count : std::min(*indices.rbegin() + 1, count); }; @@ -574,9 +569,9 @@ namespace anm2ed::imgui [&state, index, groupId](Document& document) { document.edit_apply(EDIT_ADD_ANIMATION, - [&](model::Model& model) + [&](Model& model) { - auto uids = edit::animation_add( + auto uids = animation_add( model, index, groupId, document.reference_get().animationIndex, localize.get(TEXT_NEW_ANIMATION)); animations_selection_set(document, {index}, {}); @@ -622,12 +617,12 @@ namespace anm2ed::imgui command_push(panel, [&state, targets = std::set(targets.begin(), targets.end())](Document& document) { - auto groupIds = edit::animation_group_ids_get(document.model); + auto groupIds = animation_group_ids_get(document.model); auto groupId = groupIds.empty() ? 0 : *groupIds.rbegin() + 1; document.edit_apply(EDIT_GROUP_ITEMS, - [&](model::Model& model) + [&](Model& model) { - auto uids = edit::animations_group(model, targets, + auto uids = animations_group(model, targets, localize.get(TEXT_NEW_GROUP)); animations_selection_set(document, targets, {groupId}); document.reference_set({*targets.begin()}); @@ -657,7 +652,7 @@ namespace anm2ed::imgui { auto animation = document.model.animation_get(index); if (!animation) return; - document.edit_apply(EDIT_DEFAULT_ANIMATION, [name = animation->name](model::Model& model) + document.edit_apply(EDIT_DEFAULT_ANIMATION, [name = animation->name](Model& model) { model.animations.defaultAnimation = name; }); }); }, @@ -702,7 +697,7 @@ namespace anm2ed::imgui [index, name](Document& document) { document.edit_apply(SNAPSHOT_RENAME_ANIMATION, - [&](model::Model& model) + [&](Model& model) { auto animation = model.animation_edit(index); if (!animation) return; @@ -718,10 +713,10 @@ namespace anm2ed::imgui auto animation = model.animation_get(index); auto isDefault = animation && model.animations.defaultAnimation == animation->name; auto isFocused = document.reference_get().animationIndex == index; - return isDefault && isFocused ? font::BOLD_ITALICS - : isDefault ? font::BOLD - : isFocused ? font::ITALICS - : font::REGULAR; + return isDefault && isFocused ? FONT_BOLD_ITALICS + : isDefault ? FONT_BOLD + : isFocused ? FONT_ITALICS + : FONT_REGULAR; }, .tooltip_draw = [&](int index) @@ -730,7 +725,7 @@ namespace anm2ed::imgui tooltip_name_draw(resources, animation.name); if (model.animations.defaultAnimation == animation.name) { - ImGui::PushFont(resources.fonts[font::ITALICS].get(), font::SIZE); + ImGui::PushFont(resources.fonts[FONT_ITALICS].get(), FONT_SIZE); ImGui::TextUnformatted(localize.get(BASIC_DEFAULT)); ImGui::PopFont(); } @@ -759,7 +754,7 @@ namespace anm2ed::imgui for (int i = 0; i < count; ++i) state.keys.push_back(i); animation_entries_each(model, - [&](int index, const model::Animation* animation, const model::AnimationGroup* group) + [&](int index, const Animation* animation, const AnimationGroup* group) { if (animation) visibleKeys.push_back(index); if (group && group->isExpanded) @@ -771,7 +766,7 @@ namespace anm2ed::imgui auto arrowKey = list_select_begin(panel, selection, focus, rows, visibleKeys); auto isRowsDone = false; animation_entries_each(model, - [&](int index, const model::Animation* animation, const model::AnimationGroup* group) + [&](int index, const Animation* animation, const AnimationGroup* group) { if (isRowsDone) return; if (group) @@ -789,8 +784,8 @@ namespace anm2ed::imgui animations_merge_popup_update(panel, animations); - auto isNext = shortcut(manager.chords[SHORTCUT_NEXT_ANIMATION], shortcut::GLOBAL); - auto isPrevious = shortcut(manager.chords[SHORTCUT_PREVIOUS_ANIMATION], shortcut::GLOBAL); + auto isNext = shortcut(manager.chords[SHORTCUT_NEXT_ANIMATION], SCOPE_GLOBAL); + auto isPrevious = shortcut(manager.chords[SHORTCUT_PREVIOUS_ANIMATION], SCOPE_GLOBAL); auto count = model.animations_count_get(); if ((!isPrevious && !isNext) || count <= 0) return; auto reference = document.reference_get(); @@ -799,4 +794,3 @@ namespace anm2ed::imgui animations_selection_set(document, {reference.animationIndex}, animation_groups_selected_get(document)); state.scrollId = reference.animationIndex; } -} diff --git a/src/ui/autosave_restore.cpp b/src/ui/autosave_restore.cpp index 9f7e21a..98c80f7 100644 --- a/src/ui/autosave_restore.cpp +++ b/src/ui/autosave_restore.cpp @@ -5,11 +5,6 @@ #include "path.h" #include "ui/layout.h" -using namespace anm2ed::resource; -using namespace anm2ed::util; - -namespace anm2ed::imgui -{ void AutosaveRestore::update(Manager& manager) { if (!isInitialized) @@ -32,7 +27,7 @@ namespace anm2ed::imgui { for (auto& file : manager.autosaveFiles) { - auto label = std::format(FILE_LABEL_FORMAT, path::to_utf8(file.filename()), path::to_utf8(file)); + auto label = std::format(FILE_LABEL_FORMAT, path_to_utf8(file.filename()), path_to_utf8(file)); ImGui::TextUnformatted(label.c_str()); } } @@ -59,4 +54,3 @@ namespace anm2ed::imgui ImGui::EndPopup(); } } -} diff --git a/src/ui/autosave_restore.h b/src/ui/autosave_restore.h index 316bd94..b6d0d1f 100644 --- a/src/ui/autosave_restore.h +++ b/src/ui/autosave_restore.h @@ -3,15 +3,12 @@ #include "manager.h" #include "localization.h" -namespace anm2ed::imgui -{ class AutosaveRestore { - PopupHelper popup{PopupHelper(LABEL_WELCOME_RESTORE_POPUP, imgui::POPUP_SMALL_NO_HEIGHT)}; + PopupHelper popup{PopupHelper(LABEL_WELCOME_RESTORE_POPUP, POPUP_SMALL_NO_HEIGHT)}; bool isInitialized{}; bool isRestoreAvailable{}; public: void update(Manager&); }; -} diff --git a/src/ui/canvas_view.cpp b/src/ui/canvas_view.cpp index 6fc8bc4..0789552 100644 --- a/src/ui/canvas_view.cpp +++ b/src/ui/canvas_view.cpp @@ -8,12 +8,8 @@ #include "ui/layout.h" #include "ui/shortcut.h" -using namespace anm2ed::types; -using namespace anm2ed::util; using namespace glm; -namespace anm2ed::imgui -{ CanvasInput canvas_input_get(Manager& manager, bool isFocused) { auto key_axis_get = [](ImGuiKey negative, ImGuiKey positive) @@ -40,8 +36,8 @@ namespace anm2ed::imgui .isRightDown = ImGui::IsMouseDown(ImGuiMouseButton_Right), .isRightReleased = ImGui::IsMouseReleased(ImGuiMouseButton_Right), .isMiddleDown = ImGui::IsMouseDown(ImGuiMouseButton_Middle), - .isZoomIn = isFocused && shortcut(manager.chords[SHORTCUT_ZOOM_IN], shortcut::GLOBAL), - .isZoomOut = isFocused && shortcut(manager.chords[SHORTCUT_ZOOM_OUT], shortcut::GLOBAL), + .isZoomIn = isFocused && shortcut(manager.chords[SHORTCUT_ZOOM_IN], SCOPE_GLOBAL), + .isZoomOut = isFocused && shortcut(manager.chords[SHORTCUT_ZOOM_OUT], SCOPE_GLOBAL), .isMod = isMod}; } @@ -64,7 +60,7 @@ namespace anm2ed::imgui void frames_change_push(Manager& manager, const std::set& frames, FrameChange change, ChangeType type) { manager.command_push({manager.selected, [=](Manager&, Document& document) - { edit::frames_change_apply(document.model, {.references = frames}, change, type); }}); + { frames_change_apply(document.model, {.references = frames}, change, type); }}); } // The rectangle spanned by two corners, grown outward to the grid when snapping, in whole pixels. @@ -93,19 +89,19 @@ namespace anm2ed::imgui // The tool's cursor, or a not-allowed cursor and (while in use) why: the tool belongs to the other canvas, or needs // a spritesheet or a frame first. - void tool_cursor_update(tool::Type type, tool::AreaType area, bool isFrameAvailable, bool isSpritesheetAvailable, + void tool_cursor_update(Tool type, ToolArea area, bool isFrameAvailable, bool isSpritesheetAvailable, bool isUsing, StringType frameHint) { - auto& info = tool::INFO[type]; - auto isAreaAllowed = info.areaType == tool::ALL || info.areaType == area; + auto& info = TOOLS[type]; + auto isAreaAllowed = info.areaType == TOOL_AREA_ALL || info.areaType == area; auto isFrameMissing = info.isFrameRequired && !isFrameAvailable; auto isSpritesheetMissing = info.isSpritesheetRequired && !isSpritesheetAvailable; auto isAvailable = isAreaAllowed && !isFrameMissing && !isSpritesheetMissing; ImGui::SetMouseCursor(isAvailable ? info.cursor : ImGuiMouseCursor_NotAllowed); ImGui::SetKeyboardFocusHere(); - if (!isUsing || type == tool::PAN || isAvailable) return; + if (!isUsing || type == TOOL_PAN || isAvailable) return; auto hint = !isAreaAllowed - ? (area == tool::ANIMATION_PREVIEW ? TEXT_TOOL_SPRITESHEET_EDITOR : TEXT_TOOL_ANIMATION_PREVIEW) + ? (area == TOOL_AREA_ANIMATION_PREVIEW ? TEXT_TOOL_SPRITESHEET_EDITOR : TEXT_TOOL_ANIMATION_PREVIEW) : isSpritesheetMissing ? TEXT_SELECT_SPRITESHEET : frameHint; tooltip_lines_draw({localize.get(hint)}); @@ -198,4 +194,3 @@ namespace anm2ed::imgui actions.add(ACTION_ZOOM_OUT, []() { return true; }, [&]() { zoom_center_step(-ZOOM_LEVEL_STEP); }); actions_context_window_draw(label, actions, settings); } -} diff --git a/src/ui/canvas_view.h b/src/ui/canvas_view.h index e38f8aa..e73c583 100644 --- a/src/ui/canvas_view.h +++ b/src/ui/canvas_view.h @@ -13,8 +13,6 @@ #include "settings.h" #include "tool.h" -namespace anm2ed::imgui -{ // One frame of canvas input. `arrow` is the arrow keys pressed this frame (with key repeat), x right and y down. struct CanvasInput { @@ -44,7 +42,7 @@ namespace anm2ed::imgui void frames_change_push(Manager&, const std::set&, FrameChange, ChangeType = ChangeType::ADJUST); std::pair rect_snap(glm::vec2, glm::vec2, bool, glm::ivec2, glm::ivec2); void tooltip_lines_draw(std::initializer_list); - void tool_cursor_update(tool::Type, tool::AreaType, bool, bool, bool, StringType); + void tool_cursor_update(Tool, ToolArea, bool, bool, bool, StringType); class CanvasView : public Canvas { @@ -69,4 +67,3 @@ namespace anm2ed::imgui CanvasView(); bool is_focused_get() const; }; -} diff --git a/src/ui/change_all_frame_properties.cpp b/src/ui/change_all_frame_properties.cpp index 8ff00bf..99a0321 100644 --- a/src/ui/change_all_frame_properties.cpp +++ b/src/ui/change_all_frame_properties.cpp @@ -14,11 +14,8 @@ #include "ui/input.h" #include "ui/layout.h" -using namespace anm2ed::util::math; using namespace glm; -namespace anm2ed::imgui::wizard -{ constexpr int CHANGE_TYPE_COUNT = 5; constexpr const char* COLOR_COMPONENT_FORMATS[] = {"R:%d", "G:%d", "B:%d", "A:%d"}; @@ -52,14 +49,14 @@ namespace anm2ed::imgui::wizard bool isLayerOnly; }; - void property_toggle_begin(bool& isEnabled) + static void property_toggle_begin(bool& isEnabled) { ImGui::Checkbox("##Is Enabled", &isEnabled); ImGui::SameLine(); ImGui::BeginDisabled(!isEnabled); } - void components_draw(const ComponentRow& row, bool isColor) + static void components_draw(const ComponentRow& row, bool isColor) { auto count = (int)row.isEnabled.size(); auto label = localize.get(row.label); @@ -139,14 +136,14 @@ namespace anm2ed::imgui::wizard : isItemsDestination ? std::ranges::any_of(selectedItemReferences, is_layer) : settings.changeIsLayers; // Child properties reach animation layers only; their choices are every such layer's animations. - auto animation_layer_get = [&](const Reference& reference) -> const model::Layer* + auto animation_layer_get = [&](const Reference& reference) -> const Layer* { - auto layer = is_layer(reference) ? model::item_get(document.model.content.layers, reference.itemID) : nullptr; + auto layer = is_layer(reference) ? item_get(document.model.content.layers, reference.itemID) : nullptr; return layer && layer->is_animation() ? layer : nullptr; }; std::set childAnimations{}; bool isChildPropertyAvailable{}; - auto child_layer_add = [&](const model::Layer* layer) + auto child_layer_add = [&](const Layer* layer) { if (!layer || !layer->is_animation()) return; isChildPropertyAvailable = true; @@ -327,15 +324,15 @@ namespace anm2ed::imgui::wizard [=, queuedAnimations = std::set(animations.begin(), animations.end()), isRoot = settings.changeIsRoot, isLayers = settings.changeIsLayers, isNulls = settings.changeIsNulls](Manager&, Document& document) { - edit::ChangeTargets targets{.isRoot = isRoot, .isLayers = isLayers, .isNulls = isNulls}; + ChangeTargets targets{.isRoot = isRoot, .isLayers = isLayers, .isNulls = isNulls}; if (isFramesDestination) targets.references = {selectedFrameReferences.begin(), selectedFrameReferences.end()}; else if (isItemsDestination) targets.references = {selectedItemReferences.begin(), selectedItemReferences.end()}; else targets.animations = queuedAnimations; - document.edit_apply(EDIT_CHANGE_FRAME_PROPERTIES, [&](model::Model& model) - { return edit::frames_change_apply(model, targets, frameChange, changeType); }); + document.edit_apply(EDIT_CHANGE_FRAME_PROPERTIES, [&](Model& model) + { return frames_change_apply(model, targets, frameChange, changeType); }); }}); isChanged = true; }; @@ -414,4 +411,3 @@ namespace anm2ed::imgui::wizard } ImGui::EndDisabled(); } -} diff --git a/src/ui/change_all_frame_properties.h b/src/ui/change_all_frame_properties.h index 0ebcd0c..0fcd3ac 100644 --- a/src/ui/change_all_frame_properties.h +++ b/src/ui/change_all_frame_properties.h @@ -4,8 +4,6 @@ #include "manager.h" #include "settings.h" -namespace anm2ed::imgui::wizard -{ inline constexpr StringType INTERPOLATION_LABELS[] = {BASIC_NONE, BASIC_LINEAR, BASIC_EASE_IN, BASIC_EASE_OUT, BASIC_EASE_IN_OUT}; inline constexpr StringType CHILD_MODE_LABELS[] = {LABEL_LOOP, LABEL_ONCE, LABEL_HOLD}; @@ -17,4 +15,3 @@ namespace anm2ed::imgui::wizard void update(Manager&, Document&, Settings&, bool = false); }; -} diff --git a/src/ui/configure.cpp b/src/ui/configure.cpp index 28579eb..4a1acfe 100644 --- a/src/ui/configure.cpp +++ b/src/ui/configure.cpp @@ -7,11 +7,6 @@ #include "ui/shortcut.h" #include "ui/theme.h" -using namespace anm2ed::types; -using namespace anm2ed::util; - -namespace anm2ed::imgui::wizard -{ void Configure::reset(Settings& settings) { temporary = settings; } void Configure::update(Manager& manager, Settings& settings) @@ -49,9 +44,9 @@ namespace anm2ed::imgui::wizard ImGui::SeparatorText(localize.get(LABEL_THEME)); - for (int i = 0; i < theme::COUNT; i++) + for (int i = 0; i < THEME_COUNT; i++) { - ImGui::RadioButton(localize.get(theme::STRINGS[i]), &temporary.theme, i); + ImGui::RadioButton(localize.get(THEME_STRINGS[i]), &temporary.theme, i); ImGui::SameLine(); } } @@ -144,7 +139,7 @@ namespace anm2ed::imgui::wizard ImGui::PushID(i); ImGui::TableNextRow(); ImGui::TableSetColumnIndex(0); - ImGui::TextUnformatted(localize.get(::anm2ed::SHORTCUT_STRING_TYPES[i])); + ImGui::TextUnformatted(localize.get(SHORTCUT_STRING_TYPES[i])); ImGui::TableSetColumnIndex(1); if (ImGui::Selectable(chordString.c_str(), isSelected)) selectedShortcut = i; @@ -191,18 +186,18 @@ namespace anm2ed::imgui::wizard shortcut(manager.chords[SHORTCUT_CONFIRM]); if (ImGui::Button(localize.get(BASIC_SAVE), widgetSize)) { - auto settingsPath = util::sdl::preferences_directory_get() / "settings.ini"; + auto settingsPath = preferences_directory_get() / "settings.ini"; settings = temporary; ImGui::GetIO().KeyRepeatDelay = settings.keyboardRepeatDelay; ImGui::GetIO().KeyRepeatRate = settings.keyboardRepeatRate; - ImGui::GetStyle().FontScaleMain = math::percent_to_unit(settings.uiScale); + ImGui::GetStyle().FontScaleMain = percent_to_unit(settings.uiScale); if (settings.isDetachableWindows) ImGui::GetIO().ConfigFlags |= ImGuiConfigFlags_ViewportsEnable; else ImGui::GetIO().ConfigFlags &= ~ImGuiConfigFlags_ViewportsEnable; SnapshotStack::max_size_set(settings.fileSnapshotStackSize); - imgui::theme_set((theme::Type)settings.theme); + theme_set((Theme)settings.theme); localize.language = (Language)settings.language; manager.settings_apply(settings); @@ -226,4 +221,3 @@ namespace anm2ed::imgui::wizard if (ImGui::Button(localize.get(LABEL_CLOSE), widgetSize)) isSet = true; ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CLOSE_SETTINGS)); } -} diff --git a/src/ui/configure.h b/src/ui/configure.h index 98840a5..3479880 100644 --- a/src/ui/configure.h +++ b/src/ui/configure.h @@ -2,8 +2,6 @@ #include "manager.h" -namespace anm2ed::imgui::wizard -{ class Configure { Settings temporary{}; @@ -15,4 +13,3 @@ namespace anm2ed::imgui::wizard void reset(Settings&); void update(Manager&, Settings&); }; -} \ No newline at end of file diff --git a/src/ui/dockspace.cpp b/src/ui/dockspace.cpp index f236ab4..ab424d4 100644 --- a/src/ui/dockspace.cpp +++ b/src/ui/dockspace.cpp @@ -1,7 +1,5 @@ #include "ui/dockspace.h" -namespace anm2ed::imgui -{ bool Dockspace::is_canvas_focused_get() const { return isCanvasFocused; } void Dockspace::tick(Manager& manager, Settings& settings, float deltaSeconds) @@ -92,4 +90,3 @@ namespace anm2ed::imgui } ImGui::End(); } -} diff --git a/src/ui/dockspace.h b/src/ui/dockspace.h index a7d33a6..14283c1 100644 --- a/src/ui/dockspace.h +++ b/src/ui/dockspace.h @@ -9,8 +9,6 @@ #include "ui/spritesheet_editor.h" #include "ui/timeline.h" -namespace anm2ed::imgui -{ class Dockspace { AnimationPreview animationPreview; @@ -36,4 +34,3 @@ namespace anm2ed::imgui void tick(Manager&, Settings&, float); void update(Taskbar&, Documents&, Manager&, Settings&, Resources&, Dialog&, Clipboard&); }; -} diff --git a/src/ui/documents.cpp b/src/ui/documents.cpp index a47bff6..61f2a0d 100644 --- a/src/ui/documents.cpp +++ b/src/ui/documents.cpp @@ -15,12 +15,6 @@ #include "ui/layout.h" #include "ui/shortcut.h" -using namespace anm2ed::resource; -using namespace anm2ed::types; -using namespace anm2ed::util; - -namespace anm2ed::imgui -{ struct DocumentTab { ImGuiID imguiId{}; @@ -46,16 +40,16 @@ namespace anm2ed::imgui #undef ANM2_DRAG_DROP_MERGE_PRESETS - void anm2_drag_drop_merge_queue(Manager& manager, const std::vector& paths, + static void anm2_drag_drop_merge_queue(Manager& manager, const std::vector& paths, FileMergePreset preset) { manager.command_push({manager.selected, [paths, preset](Manager&, Document& document) { document.edit_apply(EDIT_MERGE_ANM2, - [&](model::Model& model) + [&](Model& model) { for (auto& path : paths) - edit::file_merge(model, path, document.directory_get(), preset); + file_merge(model, path, document.directory_get(), preset); }); }}); } @@ -132,7 +126,7 @@ namespace anm2ed::imgui auto viewport = ImGui::GetMainViewport(); auto windowHeight = ImGui::GetFrameHeightWithSpacing(); - bool isLightTheme = settings.theme == theme::LIGHT; + bool isLightTheme = settings.theme == THEME_LIGHT; bool pushedStyle = false; ImGui::SetNextWindowViewport(viewport->ID); @@ -152,7 +146,7 @@ namespace anm2ed::imgui if (isDirty) { document.lastAutosaveTime += ImGui::GetIO().DeltaTime; - if (document.lastAutosaveTime > time::SECOND_M) + if (document.lastAutosaveTime > SECOND_MINUTES) { manager.command_push({i, [](Manager& manager, Document& document) { manager.autosave(document); }}); } @@ -170,7 +164,7 @@ namespace anm2ed::imgui if (ImGui::BeginTabBar("##Documents Bar", ImGuiTabBarFlags_Reorderable)) { auto documentsCount = (int)manager.documents.size(); - bool isCloseShortcut = shortcut(manager.chords[SHORTCUT_CLOSE], shortcut::GLOBAL) && !closePopup.is_open(); + bool isCloseShortcut = shortcut(manager.chords[SHORTCUT_CLOSE], SCOPE_GLOBAL) && !closePopup.is_open(); int closeShortcutIndex = isCloseShortcut && manager.selected >= 0 && manager.selected < documentsCount ? manager.selected : -1; @@ -210,8 +204,8 @@ namespace anm2ed::imgui } auto isRequested = i == manager.pendingSelected; - auto font = isDocumentDirty ? font::ITALICS : font::REGULAR; - auto filename = path::to_utf8(document.filename_get()); + auto font = isDocumentDirty ? FONT_ITALICS : FONT_REGULAR; + auto filename = path_to_utf8(document.filename_get()); auto string = isDocumentDirty ? std::vformat(localize.get(FORMAT_NOT_SAVED), std::make_format_args(filename)) : filename; auto label = std::format("{}###Document{}", string, document.tabId); @@ -221,7 +215,7 @@ namespace anm2ed::imgui auto flags = isDocumentDirty ? ImGuiTabItemFlags_UnsavedDocument : 0; if (isRequested) flags |= ImGuiTabItemFlags_SetSelected; - ImGui::PushFont(resources.fonts[font].get(), font::SIZE); + ImGui::PushFont(resources.fonts[font].get(), FONT_SIZE); if (ImGui::BeginTabItem(label.c_str(), &document.isOpen, flags)) { if (manager.selected != i) manager.set(i); @@ -230,7 +224,7 @@ namespace anm2ed::imgui ImGui::EndTabItem(); } - auto pathUtf8 = path::to_utf8(document.path); + auto pathUtf8 = path_to_utf8(document.path); ImGui::SetItemTooltip("%s", pathUtf8.c_str()); ImGui::PopFont(); @@ -278,7 +272,7 @@ namespace anm2ed::imgui { auto& closeDocument = manager.documents[closeDocumentIndex]; - auto filename = path::to_utf8(closeDocument.filename_get()); + auto filename = path_to_utf8(closeDocument.filename_get()); auto isDocumentDirty = closeDocument.is_dirty() || closeDocument.isForceDirty; auto isSpritesheetDirty = closeDocument.spritesheet_any_dirty(); auto promptLabel = @@ -288,7 +282,7 @@ namespace anm2ed::imgui auto prompt = std::vformat(localize.get(promptLabel), std::make_format_args(filename)); ImGui::TextUnformatted(prompt.c_str()); - auto widgetSize = imgui::widget_size_with_row_get(3); + auto widgetSize = widget_size_with_row_get(3); auto close = [&]() { @@ -310,9 +304,9 @@ namespace anm2ed::imgui auto texture = closeDocument.texture_get(id); if (texture && closeDocument.spritesheet_is_dirty(id)) { - auto pathString = path::to_utf8(spritesheet.path); + auto pathString = path_to_utf8(spritesheet.path); auto savePath = closeDocument.directory_get() / spritesheet.path; - path::ensure_directory(savePath.parent_path()); + path_ensure_directory(savePath.parent_path()); if (texture->write(savePath)) { closeDocument.spritesheet_hash_set_saved(id); @@ -475,4 +469,3 @@ namespace anm2ed::imgui } } -} diff --git a/src/ui/documents.h b/src/ui/documents.h index 77abc18..06397c3 100644 --- a/src/ui/documents.h +++ b/src/ui/documents.h @@ -9,13 +9,11 @@ #include "localization.h" #include "ui/taskbar.h" -namespace anm2ed::imgui -{ class Documents { int closeDocumentIndex{-1}; std::vector pendingDocumentTabIds{}; - imgui::PopupHelper closePopup{imgui::PopupHelper(LABEL_DOCUMENT_CLOSE, imgui::POPUP_TO_CONTENT)}; + PopupHelper closePopup{PopupHelper(LABEL_DOCUMENT_CLOSE, POPUP_TO_CONTENT)}; public: float height{}; @@ -23,4 +21,3 @@ namespace anm2ed::imgui void pending_document_order_apply(Manager&); void update(Taskbar&, Manager&, Settings&, Resources&, bool&); }; -} diff --git a/src/ui/draw.cpp b/src/ui/draw.cpp index 1356963..cc6ce14 100644 --- a/src/ui/draw.cpp +++ b/src/ui/draw.cpp @@ -4,8 +4,6 @@ #include -namespace anm2ed::imgui -{ constexpr ImU32 DROP_LINE_COLOR = IM_COL32(255, 255, 0, 255); constexpr float DROP_LINE_THICKNESS = 2.0f; @@ -15,7 +13,7 @@ namespace anm2ed::imgui long long index{}; }; - CheckerStart checker_start(float minCoord, float offset, float step) + static CheckerStart checker_start(float minCoord, float offset, float step) { float world = minCoord + offset; long long index = static_cast(std::floor(world / step)); @@ -44,7 +42,7 @@ namespace anm2ed::imgui drawList->AddLine(ImVec2(min.x, y), ImVec2(max.x, y), DROP_LINE_COLOR, DROP_LINE_THICKNESS); } - void image_premultiplied_blend_set(const ImDrawList*, const ImDrawCmd*) + static void image_premultiplied_blend_set(const ImDrawList*, const ImDrawCmd*) { glBlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA); } @@ -91,4 +89,3 @@ namespace anm2ed::imgui } } } -} diff --git a/src/ui/draw.h b/src/ui/draw.h index b09a72b..5e2c55c 100644 --- a/src/ui/draw.h +++ b/src/ui/draw.h @@ -3,12 +3,9 @@ #include #include -namespace anm2ed::imgui -{ bool is_drop_after(ImVec2, ImVec2); void drop_box_draw(ImDrawList*, ImVec2, ImVec2); void drop_line_draw(ImDrawList*, ImVec2, ImVec2, bool); void image_premultiplied_draw(ImTextureID, ImVec2); void image_premultiplied_draw(ImDrawList*, ImTextureID, ImVec2, ImVec2); void render_checker_background(ImDrawList*, ImVec2, ImVec2, glm::vec2, float); -} diff --git a/src/ui/frame_properties.cpp b/src/ui/frame_properties.cpp index 8f6ac3b..f6132ff 100644 --- a/src/ui/frame_properties.cpp +++ b/src/ui/frame_properties.cpp @@ -12,12 +12,8 @@ #include "ui/input.h" #include "ui/layout.h" -using namespace anm2ed::util::math; -using namespace anm2ed::types; using namespace glm; -namespace anm2ed::imgui -{ constexpr int TRIGGER_EVENTS_ROWS = 3; struct Vec2Field @@ -25,17 +21,17 @@ namespace anm2ed::imgui StringType label; StringType tooltip; StringType edit; - vec2 model::Frame::* member; + vec2 Frame::* member; bool isRegionField; }; constexpr Vec2Field VEC2_FIELDS[] = { - {BASIC_CROP, TOOLTIP_CROP, EDIT_FRAME_CROP, &model::Frame::crop, true}, - {BASIC_SIZE, TOOLTIP_SIZE, EDIT_FRAME_SIZE, &model::Frame::size, true}, - {BASIC_POSITION, TOOLTIP_POSITION, EDIT_FRAME_POSITION, &model::Frame::position, false}, - {BASIC_PIVOT, TOOLTIP_PIVOT, EDIT_FRAME_PIVOT, &model::Frame::pivot, true}, - {BASIC_SCALE, TOOLTIP_SCALE, EDIT_FRAME_SCALE, &model::Frame::scale, false}, - {BASIC_SKEW, TOOLTIP_SKEW, EDIT_FRAME_SKEW, &model::Frame::skew, false}}; + {BASIC_CROP, TOOLTIP_CROP, EDIT_FRAME_CROP, &Frame::crop, true}, + {BASIC_SIZE, TOOLTIP_SIZE, EDIT_FRAME_SIZE, &Frame::size, true}, + {BASIC_POSITION, TOOLTIP_POSITION, EDIT_FRAME_POSITION, &Frame::position, false}, + {BASIC_PIVOT, TOOLTIP_PIVOT, EDIT_FRAME_PIVOT, &Frame::pivot, true}, + {BASIC_SCALE, TOOLTIP_SCALE, EDIT_FRAME_SCALE, &Frame::scale, false}, + {BASIC_SKEW, TOOLTIP_SKEW, EDIT_FRAME_SKEW, &Frame::skew, false}}; struct FlipButton { @@ -68,17 +64,17 @@ namespace anm2ed::imgui auto& type = reference.itemType; auto frame = model.frame_get(reference); - auto frame_edit = [&](edit_state::Type state, StringType message, auto behavior) + auto frame_edit = [&](EditState state, StringType message, auto behavior) { - if (state == edit_state::NONE) return; + if (state == EDIT_STATE_NONE) return; manager.command_push({manager.selected, [=, queuedReference = reference](Manager&, Document& document) mutable { if (!document.model.frame_get(queuedReference)) return; - if (state == edit_state::START || state == edit_state::COMPLETE) + if (state == EDIT_STATE_START || state == EDIT_STATE_COMPLETE) document.edit_begin(message); auto item = document.model.track_edit(queuedReference); behavior(document, item->frames[queuedReference.frameIndex], item, queuedReference); - if (state == edit_state::END || state == edit_state::COMPLETE) document.change(); + if (state == EDIT_STATE_END || state == EDIT_STATE_COMPLETE) document.change(); }}); }; @@ -87,7 +83,7 @@ namespace anm2ed::imgui auto sounds = document.choices_get(SelectionKind::SOUNDS); auto shaders = document.choices_get(SelectionKind::SHADERS); std::vector interpolationLabels{}; - for (auto label : wizard::INTERPOLATION_LABELS) + for (auto label : INTERPOLATION_LABELS) interpolationLabels.push_back(localize.get(label)); auto mode_selector_draw = [&]() @@ -108,7 +104,7 @@ namespace anm2ed::imgui } else if (!isMultiFrameSelection) { - auto useFrame = frame ? *frame : model::Frame(); + auto useFrame = frame ? *frame : Frame(); auto displayFrame = frame && type == LAYER && reference.itemID != -1 ? model.frame_effective(reference.itemID, *frame) : useFrame; @@ -123,14 +119,14 @@ namespace anm2ed::imgui frame) { auto atFrame = useFrame.atFrame; - frame_edit(edit_state::COMPLETE, EDIT_TRIGGER_AT_FRAME, - [atFrame](Document& document, model::Frame& frame, model::Track* item, const Reference&) + frame_edit(EDIT_STATE_COMPLETE, EDIT_TRIGGER_AT_FRAME, + [atFrame](Document& document, Frame& frame, Track* item, const Reference&) { frame.atFrame = atFrame; if (!item) return; - model::frames_sort_by_at_frame(*item); + frames_sort_by_at_frame(*item); auto reference = document.reference_get(); - reference.frameIndex = model::frame_index_from_at_frame_get(*item, atFrame); + reference.frameIndex = frame_index_from_at_frame_get(*item, atFrame); document.reference_set(reference); document.frame_references_set({reference}); }); @@ -141,14 +137,14 @@ namespace anm2ed::imgui frame) { auto isVisible = useFrame.isVisible; - frame_edit(edit_state::COMPLETE, EDIT_TRIGGER_VISIBILITY, - [isVisible](Document&, model::Frame& frame, model::Track*, const Reference&) + frame_edit(EDIT_STATE_COMPLETE, EDIT_TRIGGER_VISIBILITY, + [isVisible](Document&, Frame& frame, Track*, const Reference&) { frame.isVisible = isVisible; }); } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_TRIGGER_VISIBILITY)); // A trigger's events or sounds: a combo for each, then Add and Remove (the last). - auto trigger_ids_draw = [&](StringType label, std::vector model::Frame::* member, + auto trigger_ids_draw = [&](StringType label, std::vector Frame::* member, const Choices& choices, ImVec2 size, StringType tooltip, StringType setEdit, StringType addEdit, StringType addTooltip, StringType removeEdit, StringType removeTooltip) @@ -160,8 +156,8 @@ namespace anm2ed::imgui { ImGui::PushID(i); if (combo_id_mapped("##Choice", &id, choices.ids, choices.labels) && frame) - frame_edit(edit_state::COMPLETE, setEdit, - [index = (std::size_t)i, id, member](Document&, model::Frame& frame, model::Track*, + frame_edit(EDIT_STATE_COMPLETE, setEdit, + [index = (std::size_t)i, id, member](Document&, Frame& frame, Track*, const Reference&) { if (index < (frame.*member).size()) (frame.*member)[index] = id; @@ -171,17 +167,17 @@ namespace anm2ed::imgui } ImGui::EndChild(); - auto widgetSize = imgui::widget_size_with_row_get(2); + auto widgetSize = widget_size_with_row_get(2); if (ImGui::Button(localize.get(BASIC_ADD), widgetSize) && frame) - frame_edit(edit_state::COMPLETE, addEdit, - [member](Document&, model::Frame& frame, model::Track*, const Reference&) + frame_edit(EDIT_STATE_COMPLETE, addEdit, + [member](Document&, Frame& frame, Track*, const Reference&) { (frame.*member).push_back(-1); }); ImGui::SetItemTooltip("%s", localize.get(addTooltip)); ImGui::SameLine(); ImGui::BeginDisabled((useFrame.*member).empty()); if (ImGui::Button(localize.get(BASIC_REMOVE), widgetSize) && frame) - frame_edit(edit_state::COMPLETE, removeEdit, - [member](Document&, model::Frame& frame, model::Track*, const Reference&) + frame_edit(EDIT_STATE_COMPLETE, removeEdit, + [member](Document&, Frame& frame, Track*, const Reference&) { if (!(frame.*member).empty()) (frame.*member).pop_back(); }); @@ -190,16 +186,16 @@ namespace anm2ed::imgui ImGui::PopID(); }; - trigger_ids_draw(LABEL_EVENTS, &model::Frame::eventIds, events, child_size_get(TRIGGER_EVENTS_ROWS), + trigger_ids_draw(LABEL_EVENTS, &Frame::eventIds, events, child_size_get(TRIGGER_EVENTS_ROWS), TOOLTIP_TRIGGER_EVENT, EDIT_TRIGGER_EVENT, EDIT_ADD_TRIGGER_EVENT, TOOLTIP_ADD_TRIGGER_EVENT, EDIT_REMOVE_TRIGGER_EVENT, TOOLTIP_REMOVE_TRIGGER_EVENT); - trigger_ids_draw(LABEL_SOUNDS, &model::Frame::soundIds, sounds, imgui::size_without_footer_get(), + trigger_ids_draw(LABEL_SOUNDS, &Frame::soundIds, sounds, size_without_footer_get(), TOOLTIP_TRIGGER_SOUND, EDIT_TRIGGER_SOUND, EDIT_ADD_TRIGGER_SOUND, TOOLTIP_ADD_TRIGGER_SOUND, EDIT_REMOVE_TRIGGER_SOUND, TOOLTIP_REMOVE_TRIGGER_SOUND); } else { - auto layer = type == LAYER ? model::item_get(model.content.layers, reference.itemID) : nullptr; + auto layer = type == LAYER ? item_get(model.content.layers, reference.itemID) : nullptr; auto isAnimationLayer = layer && layer->is_animation(); bool isRegionSet = frame && displayFrame.regionId != -1 && displayFrame.crop == frame->crop && displayFrame.size == frame->size && displayFrame.pivot == frame->pivot; @@ -209,12 +205,12 @@ namespace anm2ed::imgui auto value = frame ? source.*field.member : vec2(); // An animation layer's pivot is where its child's origin goes; it has no crop or size. ImGui::BeginDisabled(field.isRegionField && (type == ROOT || type == NULL_ || isRegionSet || - (isAnimationLayer && field.member != &model::Frame::pivot))); + (isAnimationLayer && field.member != &Frame::pivot))); auto state = drag_float2_persistent(localize.get(field.label), frame ? &value : &dummy_value(), DRAG_SPEED, 0.0f, 0.0f, frame ? vec2_format_get(source.*field.member) : ""); frame_edit(state, field.edit, - [value, member = field.member](Document&, model::Frame& frame, model::Track*, const Reference&) + [value, member = field.member](Document&, Frame& frame, Track*, const Reference&) { frame.*member = value; }); ImGui::SetItemTooltip("%s", localize.get(field.tooltip)); ImGui::EndDisabled(); @@ -224,7 +220,7 @@ namespace anm2ed::imgui drag_float_persistent(localize.get(BASIC_ROTATION), frame ? &useFrame.rotation : &dummy_value(), DRAG_SPEED, 0.0f, 0.0f, frame ? float_format_get(frame->rotation) : ""); frame_edit(rotationEdit, EDIT_FRAME_ROTATION, - [rotation = useFrame.rotation](Document&, model::Frame& frame, model::Track*, const Reference&) + [rotation = useFrame.rotation](Document&, Frame& frame, Track*, const Reference&) { frame.rotation = rotation; }); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROTATION)); @@ -234,8 +230,8 @@ namespace anm2ed::imgui frame) { auto duration = useFrame.duration; - frame_edit(edit_state::COMPLETE, EDIT_FRAME_DURATION, - [duration](Document&, model::Frame& frame, model::Track*, const Reference&) + frame_edit(EDIT_STATE_COMPLETE, EDIT_FRAME_DURATION, + [duration](Document&, Frame& frame, Track*, const Reference&) { frame.duration = duration; }); } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_DURATION)); @@ -247,8 +243,8 @@ namespace anm2ed::imgui frame) { auto depth = useFrame.depth; - frame_edit(edit_state::COMPLETE, EDIT_FRAME_DEPTH, - [depth](Document&, model::Frame& frame, model::Track*, const Reference&) + frame_edit(EDIT_STATE_COMPLETE, EDIT_FRAME_DEPTH, + [depth](Document&, Frame& frame, Track*, const Reference&) { frame.depth = depth; }); } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_DEPTH)); @@ -257,14 +253,14 @@ namespace anm2ed::imgui auto tintEdit = color_edit4_persistent(localize.get(BASIC_TINT), frame ? &useFrame.tint : &dummy_value()); frame_edit(tintEdit, EDIT_FRAME_TINT, - [tint = useFrame.tint](Document&, model::Frame& frame, model::Track*, const Reference&) + [tint = useFrame.tint](Document&, Frame& frame, Track*, const Reference&) { frame.tint = tint; }); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_TINT)); auto colorOffsetEdit = color_edit4_persistent(localize.get(BASIC_COLOR_OFFSET), frame ? &useFrame.colorOffset : &dummy_value()); frame_edit(colorOffsetEdit, EDIT_FRAME_COLOR_OFFSET, - [colorOffset = useFrame.colorOffset](Document&, model::Frame& frame, model::Track*, + [colorOffset = useFrame.colorOffset](Document&, Frame& frame, Track*, const Reference&) { frame.colorOffset = colorOffset; }); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_COLOR_OFFSET)); @@ -273,7 +269,7 @@ namespace anm2ed::imgui drag_float_persistent(localize.get(BASIC_BLUR), frame ? &useFrame.blur : &dummy_value(), DRAG_SPEED, 0.0f, FRAME_BLUR_MAX, frame ? float_format_get(frame->blur) : ""); frame_edit(blurEdit, EDIT_FRAME_BLUR, - [blur = useFrame.blur](Document&, model::Frame& frame, model::Track*, const Reference&) + [blur = useFrame.blur](Document&, Frame& frame, Track*, const Reference&) { frame.blur = std::clamp(blur, 0.0f, FRAME_BLUR_MAX); }); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BLUR)); ImGui::EndDisabled(); @@ -284,8 +280,8 @@ namespace anm2ed::imgui frame) { auto regionId = useFrame.regionId; - frame_edit(edit_state::COMPLETE, EDIT_SET_REGION_PROPERTIES, - [regionId](Document& document, model::Frame& frame, model::Track*, const Reference& reference) + frame_edit(EDIT_STATE_COMPLETE, EDIT_SET_REGION_PROPERTIES, + [regionId](Document& document, Frame& frame, Track*, const Reference& reference) { frame.regionId = regionId; auto effectiveFrame = document.model.frame_effective(reference.itemID, frame); @@ -301,8 +297,8 @@ namespace anm2ed::imgui if (ImGui::Combo(localize.get(BASIC_INTERPOLATED), &interpolationValue, interpolationLabels.data(), (int)interpolationLabels.size()) && frame) - frame_edit(edit_state::COMPLETE, EDIT_FRAME_INTERPOLATION, - [interpolationValue](Document&, model::Frame& frame, model::Track*, const Reference&) + frame_edit(EDIT_STATE_COMPLETE, EDIT_FRAME_INTERPOLATION, + [interpolationValue](Document&, Frame& frame, Track*, const Reference&) { frame.interpolation = static_cast(interpolationValue); }); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FRAME_INTERPOLATION)); @@ -312,8 +308,8 @@ namespace anm2ed::imgui frame) { auto shaderId = useFrame.shaderId; - frame_edit(edit_state::COMPLETE, EDIT_FRAME_SHADER, - [shaderId](Document&, model::Frame& frame, model::Track*, const Reference&) + frame_edit(EDIT_STATE_COMPLETE, EDIT_FRAME_SHADER, + [shaderId](Document&, Frame& frame, Track*, const Reference&) { frame.shaderId = shaderId; }); } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FRAME_SHADER)); @@ -323,8 +319,8 @@ namespace anm2ed::imgui frame) { auto isVisible = useFrame.isVisible; - frame_edit(edit_state::COMPLETE, EDIT_FRAME_VISIBILITY, - [isVisible](Document&, model::Frame& frame, model::Track*, const Reference&) + frame_edit(EDIT_STATE_COMPLETE, EDIT_FRAME_VISIBILITY, + [isVisible](Document&, Frame& frame, Track*, const Reference&) { frame.isVisible = isVisible; }); } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FRAME_VISIBILITY)); @@ -335,9 +331,9 @@ namespace anm2ed::imgui { if (axis > 0) ImGui::SameLine(); if (ImGui::Button(localize.get(FLIP_BUTTONS[axis].label), widgetSize) && frame) - frame_edit(edit_state::COMPLETE, FLIP_BUTTONS[axis].edit, - [axis, isPositionFlipped = ImGui::IsKeyDown(ImGuiMod_Ctrl)](Document&, model::Frame& frame, - model::Track*, const Reference&) + frame_edit(EDIT_STATE_COMPLETE, FLIP_BUTTONS[axis].edit, + [axis, isPositionFlipped = ImGui::IsKeyDown(ImGuiMod_Ctrl)](Document&, Frame& frame, + Track*, const Reference&) { frame.scale[axis] = -frame.scale[axis]; if (isPositionFlipped) frame.position[axis] = -frame.position[axis]; @@ -357,7 +353,7 @@ namespace anm2ed::imgui ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CHILD_ANIMATION)); std::vector modeLabels{}; - for (auto label : wizard::CHILD_MODE_LABELS) + for (auto label : CHILD_MODE_LABELS) modeLabels.push_back(localize.get(label)); auto mode = (int)useFrame.childMode; if (ImGui::Combo(localize.get(BASIC_MODE), &mode, modeLabels.data(), (int)modeLabels.size())) @@ -380,9 +376,9 @@ namespace anm2ed::imgui ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_CHILD_RESTART)); if (isChildChanged) - frame_edit(edit_state::COMPLETE, EDIT_FRAME_CHILD, - [child = useFrame](Document&, model::Frame& frame, model::Track*, const Reference&) - { edit::frame_property_copy(frame, child, edit::FrameProperty::CHILD); }); + frame_edit(EDIT_STATE_COMPLETE, EDIT_FRAME_CHILD, + [child = useFrame](Document&, Frame& frame, Track*, const Reference&) + { frame_property_copy(frame, child, FrameProperty::CHILD); }); } ImGui::Separator(); @@ -405,4 +401,3 @@ namespace anm2ed::imgui dummy_value() = vec2(); dummy_value() = vec4(); } -} diff --git a/src/ui/generate_animation_from_grid.cpp b/src/ui/generate_animation_from_grid.cpp index 0afee97..e9fd792 100644 --- a/src/ui/generate_animation_from_grid.cpp +++ b/src/ui/generate_animation_from_grid.cpp @@ -11,12 +11,8 @@ #include #include -using namespace anm2ed::types; -using namespace anm2ed::util; using namespace glm; -namespace anm2ed::imgui::wizard -{ GenerateAnimationFromGrid::GenerateAnimationFromGrid() : Canvas(vec2()) {} void GenerateAnimationFromGrid::update(Manager& manager, Document& document, Resources& resources, Settings& settings) @@ -48,7 +44,7 @@ namespace anm2ed::imgui::wizard { ImGui::InputInt2(localize.get(LABEL_GENERATE_START_POSITION), value_ptr(startPosition)); ImGui::InputInt2(localize.get(LABEL_GENERATE_FRAME_SIZE), value_ptr(size)); - ImGui::InputFloat2(localize.get(BASIC_PIVOT), value_ptr(pivot), math::vec2_format_get(pivot)); + ImGui::InputFloat2(localize.get(BASIC_PIVOT), value_ptr(pivot), vec2_format_get(pivot)); ImGui::InputInt(localize.get(LABEL_GENERATE_ROWS), &rows, STEP, STEP_FAST); ImGui::InputInt(localize.get(LABEL_GENERATE_COLUMNS), &columns, STEP, STEP_FAST); @@ -76,7 +72,7 @@ namespace anm2ed::imgui::wizard { auto& backgroundColor = settings.previewBackgroundColor; auto& isTransparent = settings.animationPreviewTransparent; - auto& shaderTexture = resources.shaders[resource::shader::TEXTURE]; + auto& shaderTexture = resources.shaders[SHADER_TEXTURE]; auto previewSize = ImVec2(ImGui::GetContentRegionAvail().x, size_without_footer_get(2).y); auto previewMin = ImGui::GetCursorScreenPos(); @@ -89,16 +85,16 @@ namespace anm2ed::imgui::wizard if (!layerReferences.empty()) { - auto layer = model::item_get(model.content.layers, previewReference.itemID); + auto layer = item_get(model.content.layers, previewReference.itemID); auto sourceTexture = layer ? document.texture_get(layer->spritesheetId) : nullptr; if (sourceTexture && sourceTexture->is_valid()) { - model::Track previewTrack{}; - model::frames_generate_from_grid(previewTrack, startPosition, size, pivot, columns, count, delay); + Track previewTrack{}; + frames_generate_from_grid(previewTrack, startPosition, size, pivot, columns, count, delay); - auto length = std::max(model::track_length_get(previewTrack), FRAME_DURATION_MIN); + auto length = std::max(track_length_get(previewTrack), FRAME_DURATION_MIN); auto sampleTime = std::min(time * (float)length, (float)length - 0.001f); - auto frame = model::frame_generate(previewTrack, sampleTime); + auto frame = frame_generate(previewTrack, sampleTime); auto textureSize = vec2(sourceTexture->size); if (textureSize.x > 0.0f && textureSize.y > 0.0f && frame.size.x > 0.0f && frame.size.y > 0.0f) @@ -106,12 +102,12 @@ namespace anm2ed::imgui::wizard auto uvMin = frame.crop / textureSize; 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.skew)); - auto vertices = math::uv_vertices_get(uvMin, uvMax); + transform_get(zoom) * quad_model_get(frame.size, frame.position, frame.pivot, + percent_to_unit(frame.scale), frame.rotation, + percent_to_unit(frame.skew)); + auto vertices = uv_vertices_get(uvMin, uvMax); - texture_render(shaderTexture, resource::texture::id_get(*sourceTexture), transform, frame.tint, + texture_render(shaderTexture, texture_id_get(*sourceTexture), transform, frame.tint, frame.colorOffset, vertices.data()); } } @@ -151,10 +147,10 @@ namespace anm2ed::imgui::wizard manager.command_push( {manager.selected, [=](Manager&, Document& document) { - edit::GridOptions options{queuedStartPosition, queuedSize, queuedPivot, queuedColumns, + GridOptions options{queuedStartPosition, queuedSize, queuedPivot, queuedColumns, queuedCount, queuedDelay, queuedIsMakeRegions, queuedRegionNameFormat}; - document.edit_apply(EDIT_GENERATE_ANIMATION_FROM_GRID, [&](model::Model& model) - { return edit::animation_grid_generate(model, queuedLayerReferences, options); }); + document.edit_apply(EDIT_GENERATE_ANIMATION_FROM_GRID, [&](Model& model) + { return animation_grid_generate(model, queuedLayerReferences, options); }); }}); isEnd = true; } @@ -164,4 +160,3 @@ namespace anm2ed::imgui::wizard if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) isEnd = true; } -} diff --git a/src/ui/generate_animation_from_grid.h b/src/ui/generate_animation_from_grid.h index 20def10..c241443 100644 --- a/src/ui/generate_animation_from_grid.h +++ b/src/ui/generate_animation_from_grid.h @@ -6,8 +6,6 @@ #include "resources.h" #include "settings.h" -namespace anm2ed::imgui::wizard -{ class GenerateAnimationFromGrid : public Canvas { float time{}; @@ -18,4 +16,3 @@ namespace anm2ed::imgui::wizard GenerateAnimationFromGrid(); void update(Manager&, Document&, Resources&, Settings&); }; -} diff --git a/src/ui/input.cpp b/src/ui/input.cpp index b07b0df..367b80d 100644 --- a/src/ui/input.cpp +++ b/src/ui/input.cpp @@ -9,12 +9,8 @@ #include "path.h" -using namespace anm2ed::types; -using namespace anm2ed::util; using namespace glm; -namespace anm2ed::imgui -{ int input_text_callback(ImGuiInputTextCallbackData* data) { if (data->EventFlag == ImGuiInputTextFlags_CallbackResize) @@ -36,9 +32,9 @@ namespace anm2ed::imgui { if (!path) return false; - auto pathUtf8 = path::to_utf8(*path); + auto pathUtf8 = path_to_utf8(*path); auto edited = input_text_string(label, &pathUtf8, flags); - if (edited) *path = path::from_utf8(pathUtf8); + if (edited) *path = path_from_utf8(pathUtf8); return edited; } @@ -82,7 +78,7 @@ namespace anm2ed::imgui return isActivated; } - edit_state::Type drag_float_persistent(const char* label, float* value, float speed, float min, float max, + EditState drag_float_persistent(const char* label, float* value, float speed, float min, float max, const char* format, ImGuiSliderFlags flags) { static bool isEditing{}; @@ -90,30 +86,30 @@ namespace anm2ed::imgui auto persistent = value ? *value : 0; ImGui::DragFloat(label, &persistent, speed, min, max, format, flags); - if (!value) return edit_state::NONE; + if (!value) return EDIT_STATE_NONE; if (ImGui::IsItemActivated() && persistent != start) { isEditing = true; start = *value; - return edit_state::START; + return EDIT_STATE_START; } else if (ImGui::IsItemDeactivatedAfterEdit()) { isEditing = false; *value = persistent; start = NAN; - return edit_state::END; + return EDIT_STATE_END; } else if (isEditing) { *value = persistent; - return edit_state::DURING; + return EDIT_STATE_DURING; } - return edit_state::NONE; + return EDIT_STATE_NONE; } - edit_state::Type drag_float2_persistent(const char* label, vec2* value, float speed, float min, float max, + EditState drag_float2_persistent(const char* label, vec2* value, float speed, float min, float max, const char* format, ImGuiSliderFlags flags) { static bool isEditing{}; @@ -121,57 +117,57 @@ namespace anm2ed::imgui auto persistent = value ? *value : vec2(); ImGui::DragFloat2(label, value_ptr(persistent), speed, min, max, format, flags); - if (!value) return edit_state::NONE; + if (!value) return EDIT_STATE_NONE; if (ImGui::IsItemActivated() && persistent != start) { isEditing = true; start = *value; - return edit_state::START; + return EDIT_STATE_START; } else if (ImGui::IsItemDeactivatedAfterEdit()) { isEditing = false; *value = persistent; start = vec2{NAN}; - return edit_state::END; + return EDIT_STATE_END; } else if (isEditing) { *value = persistent; - return edit_state::DURING; + return EDIT_STATE_DURING; } - return edit_state::NONE; + return EDIT_STATE_NONE; } - edit_state::Type color_edit4_persistent(const char* label, vec4* value, ImGuiColorEditFlags flags) + EditState color_edit4_persistent(const char* label, vec4* value, ImGuiColorEditFlags flags) { static bool isEditing{}; static vec4 start{NAN}; auto persistent = value ? *value : vec4(); ImGui::ColorEdit4(label, value_ptr(persistent), flags); - if (!value) return edit_state::NONE; + if (!value) return EDIT_STATE_NONE; if (ImGui::IsItemActivated() && persistent != start) { isEditing = true; start = *value; - return edit_state::START; + return EDIT_STATE_START; } else if (ImGui::IsItemDeactivatedAfterEdit()) { isEditing = false; *value = persistent; start = vec4{NAN}; - return edit_state::END; + return EDIT_STATE_END; } else if (isEditing) { *value = persistent; - return edit_state::DURING; + return EDIT_STATE_DURING; } - return edit_state::NONE; + return EDIT_STATE_NONE; } bool radio_button_icon(const char* label, int* value, int buttonValue, ImTextureID texture, ImVec2 size, ImVec4 tint) @@ -208,4 +204,3 @@ namespace anm2ed::imgui value = glm::clamp(value, min, max); return isActivated; } -} diff --git a/src/ui/input.h b/src/ui/input.h index e67b961..d042317 100644 --- a/src/ui/input.h +++ b/src/ui/input.h @@ -9,8 +9,6 @@ #include "types.h" -namespace anm2ed::imgui -{ constexpr auto DRAG_SPEED = 0.25f; constexpr auto DRAG_SPEED_FAST = 1.00f; constexpr auto STEP = 1.0f; @@ -23,13 +21,12 @@ namespace anm2ed::imgui bool input_int2_range(const char*, glm::ivec2&, glm::ivec2, glm::ivec2, ImGuiInputTextFlags = 0); bool input_float_range(const char*, float&, float, float, float = STEP, float = STEP_FAST, const char* = "%.3f", ImGuiInputTextFlags = 0); - types::edit_state::Type drag_float_persistent(const char*, float*, float = DRAG_SPEED, float = {}, float = {}, + EditState drag_float_persistent(const char*, float*, float = DRAG_SPEED, float = {}, float = {}, const char* = "%.3f", ImGuiSliderFlags = 0); - types::edit_state::Type drag_float2_persistent(const char*, glm::vec2*, float = DRAG_SPEED, float = {}, float = {}, + EditState drag_float2_persistent(const char*, glm::vec2*, float = DRAG_SPEED, float = {}, float = {}, const char* = "%.3f", ImGuiSliderFlags = 0); - types::edit_state::Type color_edit4_persistent(const char*, glm::vec4*, ImGuiColorEditFlags = 0); + EditState color_edit4_persistent(const char*, glm::vec4*, ImGuiColorEditFlags = 0); bool radio_button_icon(const char*, int*, int, ImTextureID, ImVec2, ImVec4 = ImVec4(1.0f, 1.0f, 1.0f, 1.0f)); bool combo_id_mapped(const std::string&, int*, const std::vector&, const std::vector&); bool combo_string_mapped(const std::string&, std::string*, const std::vector&, const std::vector&); -} diff --git a/src/ui/item_properties.cpp b/src/ui/item_properties.cpp index b6461e9..c5e2105 100644 --- a/src/ui/item_properties.cpp +++ b/src/ui/item_properties.cpp @@ -7,11 +7,6 @@ #include "ui/layout.h" #include "ui/shortcut.h" -using namespace anm2ed::resource; -using namespace anm2ed::types; - -namespace anm2ed::imgui::popup -{ constexpr int EXISTING_ITEMS_ROWS = 6; void ItemProperties::reset() { edit = {}; } @@ -80,13 +75,13 @@ namespace anm2ed::imgui::popup spaced_pair( [&]() { - ImGui::RadioButton(localize.get(LABEL_NEW), &source, source::NEW); + ImGui::RadioButton(localize.get(LABEL_NEW), &source, SOURCE_NEW); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_NEW_ITEM)); }, [&]() { ImGui::BeginDisabled(!isUnusedItems); - ImGui::RadioButton(localize.get(LABEL_EXISTING), &source, source::EXISTING); + ImGui::RadioButton(localize.get(LABEL_EXISTING), &source, SOURCE_EXISTING); ImGui::EndDisabled(); ImGui::SetItemTooltip("%s", isUnusedItems ? localize.get(TOOLTIP_USE_EXISTING_ITEM) : localize.get(TOOLTIP_NO_UNUSED_ITEMS)); @@ -97,16 +92,16 @@ namespace anm2ed::imgui::popup spaced_pair( [&]() { - ImGui::RadioButton(localize.get(LABEL_ALL_ANIMATIONS), &destination, destination::ALL); + ImGui::RadioButton(localize.get(LABEL_ALL_ANIMATIONS), &destination, DESTINATION_ALL); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ITEM_ALL_ANIMATIONS)); }, [&]() { - ImGui::RadioButton(localize.get(LABEL_THIS_ANIMATION), &destination, destination::THIS); + ImGui::RadioButton(localize.get(LABEL_THIS_ANIMATION), &destination, DESTINATION_THIS); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ITEM_THIS_ANIMATION)); }); - if (source == source::NEW) + if (source == SOURCE_NEW) { ImGui::SeparatorText(localize.get(LABEL_OPTIONS)); @@ -138,7 +133,7 @@ namespace anm2ed::imgui::popup if (type == LAYER) { - if (auto layer = model::item_get(model.content.layers, id)) + if (auto layer = item_get(model.content.layers, id)) { if (ImGui::Selectable(layer_label_get(*layer).c_str(), isSelected)) { @@ -148,7 +143,7 @@ namespace anm2ed::imgui::popup } else if (type == NULL_) { - if (auto null = model::item_get(model.content.nulls, id)) + if (auto null = item_get(model.content.nulls, id)) { auto label = std::vformat(localize.get(FORMAT_NULL), std::make_format_args(id, null->name)); if (ImGui::Selectable(label.c_str(), isSelected)) @@ -168,7 +163,7 @@ namespace anm2ed::imgui::popup auto widgetSize = widget_size_with_row_get(2); - ImGui::BeginDisabled(source == source::EXISTING && edit.id == -1); + ImGui::BeginDisabled(source == SOURCE_EXISTING && edit.id == -1); shortcut(manager.chords[SHORTCUT_CONFIRM]); if (ImGui::Button(localize.get(BASIC_ADD), widgetSize)) { @@ -176,7 +171,7 @@ namespace anm2ed::imgui::popup auto queuedDestination = destination; auto queuedAnimationIndex = reference.animationIndex; auto queuedInsertBeforeID = reference.itemType == LAYER && type == LAYER ? reference.itemID : -1; - auto queuedAddItemID = source == source::NEW ? -1 : edit.id; + auto queuedAddItemID = source == SOURCE_NEW ? -1 : edit.id; auto queuedLayer = item_edit_layer_get(edit); auto queuedNull = item_edit_null_get(edit); @@ -184,12 +179,12 @@ namespace anm2ed::imgui::popup { int addId{-1}; document.edit_apply(EDIT_ADD_ITEM, - [&](model::Model& model) + [&](Model& model) { - addId = edit::item_add( + addId = item_add( model, (ItemType)queuedType, queuedAnimationIndex, queuedAddItemID, queuedLayer, queuedNull, - queuedInsertBeforeID, (destination::Type)queuedDestination); + queuedInsertBeforeID, (Destination)queuedDestination); }); if (addId != -1) @@ -198,7 +193,7 @@ namespace anm2ed::imgui::popup document.selected_set(SelectionKind::TRACKS, {document.reference_get()}); document.frame_references_clear(); if (queuedType == LAYER) - if (auto layer = model::item_get(document.model.content.layers, addId)) + if (auto layer = item_get(document.model.content.layers, addId)) document.focused_id_set(SelectionKind::SPRITESHEETS, layer->spritesheetId); } }}); @@ -220,4 +215,3 @@ namespace anm2ed::imgui::popup return isAdded; } -} diff --git a/src/ui/item_properties.h b/src/ui/item_properties.h index 193d568..2c4c6fb 100644 --- a/src/ui/item_properties.h +++ b/src/ui/item_properties.h @@ -7,8 +7,6 @@ #include "settings.h" #include "localization.h" -namespace anm2ed::imgui::popup -{ class ItemProperties { PopupHelper popup{PopupHelper(LABEL_TIMELINE_PROPERTIES_POPUP, POPUP_SMALL_NO_HEIGHT)}; @@ -20,4 +18,3 @@ namespace anm2ed::imgui::popup void open(); bool update(Manager&, Settings&, Document&, Reference&); }; -} diff --git a/src/ui/items.cpp b/src/ui/items.cpp index 937a4ed..bc01d3e 100644 --- a/src/ui/items.cpp +++ b/src/ui/items.cpp @@ -6,25 +6,21 @@ #include "ui/input.h" #include "ui/layout.h" -using namespace anm2ed::types; - -namespace anm2ed::imgui -{ constexpr int NULL_PROPERTIES_ROWS = 2; constexpr int LAYER_PROPERTIES_ROWS = 6; - auto& layers_get(model::Model& model) { return model.content.layers; } - auto& nulls_get(model::Model& model) { return model.content.nulls; } - auto& events_get(model::Model& model) { return model.content.events; } + static auto& layers_get(Model& model) { return model.content.layers; } + static auto& nulls_get(Model& model) { return model.content.nulls; } + static auto& events_get(Model& model) { return model.content.events; } - void item_tooltip_draw(Resources& resources, const std::string& name, int id) + static void item_tooltip_draw(Resources& resources, const std::string& name, int id) { tooltip_name_draw(resources, name); ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(id)).c_str()); } // "#id name", then what the layer shows: its spritesheet or its animation. - std::string layer_label_get(const model::Layer& layer) + std::string layer_label_get(const Layer& layer) { if (layer.is_animation()) return std::vformat(localize.get(FORMAT_LAYER_ANIMATION), @@ -33,15 +29,15 @@ namespace anm2ed::imgui } // Tooltip lines for what a layer shows: its spritesheet, or its animation and the library it's from. - void layer_source_tooltip_draw(const Document& document, const model::Layer& layer) + void layer_source_tooltip_draw(const Document& document, const Layer& layer) { if (!layer.is_animation()) { ImGui::TextUnformatted(localize_format(FORMAT_SPRITESHEET_ID, layer.spritesheetId).c_str()); return; } - auto library = model::item_get(document.model.content.libraries, layer.libraryId); - auto libraryLabel = library ? std::format("#{} {}", library->id, util::path::to_utf8(library->path)) + auto library = item_get(document.model.content.libraries, layer.libraryId); + auto libraryLabel = library ? std::format("#{} {}", library->id, path_to_utf8(library->path)) : std::string(localize.get(TEXT_SELF)); ImGui::TextUnformatted(localize_format(FORMAT_LAYER_ANIMATION_NAME, layer.animation).c_str()); ImGui::TextUnformatted(localize_format(FORMAT_LAYER_LIBRARY, libraryLabel).c_str()); @@ -49,7 +45,7 @@ namespace anm2ed::imgui ImGui::TextUnformatted(localize.get(TOOLTIP_LAYER_ANIMATION_MISSING)); } - model::Layer item_edit_layer_get(const Manager::ItemEdit& edit) + Layer item_edit_layer_get(const Manager::ItemEdit& edit) { return {.name = edit.name, .spritesheetId = edit.spritesheetId, @@ -57,7 +53,7 @@ namespace anm2ed::imgui .animation = edit.isAnimation ? edit.animation : std::string{}}; } - model::Null item_edit_null_get(const Manager::ItemEdit& edit) + Null item_edit_null_get(const Manager::ItemEdit& edit) { return {.name = edit.name, .isShowRect = edit.isShowRect}; } @@ -119,7 +115,7 @@ namespace anm2ed::imgui if (result == PopupButton::CONFIRM) { Item item{}; - if constexpr (std::is_same_v) + if constexpr (std::is_same_v) item = item_edit_layer_get(edit); else item = item_edit_null_get(edit); @@ -129,10 +125,10 @@ namespace anm2ed::imgui { auto changedId = id; document.edit_apply(id == -1 ? addEdit : propertiesEdit, - [&](model::Model& model) + [&](Model& model) { auto& items = items_get(model); - if (auto target = model::item_get(items, id)) + if (auto target = item_get(items, id)) { auto uid = target->uid; *target = item; @@ -141,7 +137,7 @@ namespace anm2ed::imgui return; } if (id != -1) return; - changedId = model::item_next_id_get(items); + changedId = item_next_id_get(items); items.push_back(item); items.back().id = changedId; state.newId = changedId; @@ -179,16 +175,16 @@ namespace anm2ed::imgui if (ImGui::Begin(localize.get(LABEL_LAYERS_WINDOW), &settings.windowIsLayers)) { Actions actions{}; - track_items_actions_add(actions, panel, SelectionKind::LAYERS, ElementType::LAYER_ELEMENT, + track_items_actions_add(actions, panel, SelectionKind::LAYERS, ElementType::LAYER_ELEMENT, TOOLTIP_ADD_LAYER, EDIT_PASTE_LAYERS, TOAST_DESERIALIZE_LAYERS_FAILED, layers_get); - ListRows rows{.label_get = [&](int id) { return layer_label_get(*model::item_get(layers, id)); }, + ListRows rows{.label_get = [&](int id) { return layer_label_get(*item_get(layers, id)); }, .is_invalid = [&](int id) - { return document.is_layer_animation_missing(*model::item_get(layers, id)); }, + { return document.is_layer_animation_missing(*item_get(layers, id)); }, .tooltip_draw = [&](int id) { - auto layer = model::item_get(layers, id); + auto layer = item_get(layers, id); item_tooltip_draw(resources, layer->name, id); layer_source_tooltip_draw(document, *layer); }, @@ -198,7 +194,7 @@ namespace anm2ed::imgui } ImGui::End(); - item_properties_update(panel, 0, LAYER_PROPERTIES_ROWS, SelectionKind::LAYERS, TOOLTIP_ITEM_NAME, + item_properties_update(panel, 0, LAYER_PROPERTIES_ROWS, SelectionKind::LAYERS, TOOLTIP_ITEM_NAME, EDIT_ADD_LAYER, EDIT_SET_LAYER_PROPERTIES, layers_get, [&](Manager::ItemEdit& layer) { @@ -214,16 +210,16 @@ namespace anm2ed::imgui if (ImGui::Begin(localize.get(LABEL_NULLS_WINDOW), &settings.windowIsNulls)) { Actions actions{}; - track_items_actions_add(actions, panel, SelectionKind::NULLS, ElementType::NULL_ELEMENT, + track_items_actions_add(actions, panel, SelectionKind::NULLS, ElementType::NULL_ELEMENT, TOOLTIP_ADD_NULL, EDIT_PASTE_NULLS, TOAST_DESERIALIZE_NULLS_FAILED, nulls_get); ListRows rows{.label_get = [&](int id) { - auto name = model::item_get(nulls, id)->name; + auto name = item_get(nulls, id)->name; return std::vformat(localize.get(FORMAT_NULL), std::make_format_args(id, name)); }, - .tooltip_draw = [&](int id) { item_tooltip_draw(resources, model::item_get(nulls, id)->name, id); }, + .tooltip_draw = [&](int id) { item_tooltip_draw(resources, item_get(nulls, id)->name, id); }, .activate = [&](int id) { manager.item_properties_open(ElementType::NULL_ELEMENT, id); }, .isFocusItalic = true}; list_panel_draw(panel, actions, {{ACTION_ADD, ACTION_REMOVE}}, @@ -231,7 +227,7 @@ namespace anm2ed::imgui } ImGui::End(); - item_properties_update(panel, 1, NULL_PROPERTIES_ROWS, SelectionKind::NULLS, TOOLTIP_NULL_NAME, + item_properties_update(panel, 1, NULL_PROPERTIES_ROWS, SelectionKind::NULLS, TOOLTIP_NULL_NAME, EDIT_ADD_NULL, EDIT_SET_NULL_PROPERTIES, nulls_get, [](Manager::ItemEdit& null) { @@ -261,10 +257,10 @@ namespace anm2ed::imgui { int id{}; document.edit_apply(EDIT_ADD_EVENT, - [&](model::Model& model) + [&](Model& model) { auto& events = model.content.events; - id = model::item_next_id_get(events); + id = item_next_id_get(events); events.push_back({.id = id, .name = localize.get(TEXT_NEW_EVENT)}); }); document.selected_ids_set(SelectionKind::EVENTS, {id}); @@ -274,10 +270,10 @@ namespace anm2ed::imgui }, TOOLTIP_ADD_EVENT); content_remove_action_add(actions, panel, ElementType::EVENT_ELEMENT, SelectionKind::EVENTS); - items_clipboard_actions_add(actions, panel, SelectionKind::EVENTS, EDIT_PASTE_EVENTS, + items_clipboard_actions_add(actions, panel, SelectionKind::EVENTS, EDIT_PASTE_EVENTS, TOAST_DESERIALIZE_EVENTS_FAILED, events_get); - ListRows rows{.label_get = [&](int id) { return model::item_get(events, id)->name; }, - .name_get = [&](int id) { return model::item_get(events, id)->name; }, + ListRows rows{.label_get = [&](int id) { return item_get(events, id)->name; }, + .name_get = [&](int id) { return item_get(events, id)->name; }, .rename = [&](int id, const std::string& name) { @@ -285,18 +281,17 @@ namespace anm2ed::imgui [id, name](Document& document) { document.edit_apply(EDIT_RENAME_EVENT, - [&](model::Model& model) + [&](Model& model) { - if (auto event = model::item_get(model.content.events, id)) + if (auto event = item_get(model.content.events, id)) event->name = name; }); }); }, .tooltip_draw = [&](int id) - { item_tooltip_draw(resources, model::item_get(events, id)->name, id); }}; + { item_tooltip_draw(resources, item_get(events, id)->name, id); }}; list_panel_draw(panel, actions, {{ACTION_ADD, ACTION_REMOVE}}, [&]() { content_list_draw(panel, SelectionKind::EVENTS, item_ids_get(events), rows); }); } ImGui::End(); } -} diff --git a/src/ui/layout.cpp b/src/ui/layout.cpp index 353775e..312bd61 100644 --- a/src/ui/layout.cpp +++ b/src/ui/layout.cpp @@ -2,8 +2,6 @@ #include "localization.h" -namespace anm2ed::imgui -{ float row_widget_width_get(int count, float width) { return (width - (ImGui::GetStyle().ItemSpacing.x * (float)(count - 1))) / (float)count; @@ -42,4 +40,3 @@ namespace anm2ed::imgui { ImGui::SetItemTooltip("%s", localize_format(FORMAT_TOOLTIP_SHORTCUT, tooltip, shortcut).c_str()); } -} diff --git a/src/ui/layout.h b/src/ui/layout.h index 6eecf2d..a7936eb 100644 --- a/src/ui/layout.h +++ b/src/ui/layout.h @@ -5,8 +5,6 @@ #include #include -namespace anm2ed::imgui -{ constexpr ImVec2 to_imvec2(const glm::vec2& v) noexcept { return {v.x, v.y}; } constexpr glm::vec2 to_vec2(const ImVec2& v) noexcept { return {v.x, v.y}; } constexpr glm::ivec2 to_ivec2(const ImVec2& v) noexcept { return {v.x, v.y}; } @@ -33,4 +31,3 @@ namespace anm2ed::imgui ImVec2 child_size_get(int = 1); ImVec2 icon_size_get(); void set_item_tooltip_shortcut(const char*, const std::string& = {}); -} diff --git a/src/ui/libraries.cpp b/src/ui/libraries.cpp index ded554c..5ac853c 100644 --- a/src/ui/libraries.cpp +++ b/src/ui/libraries.cpp @@ -4,15 +4,9 @@ #include "path.h" -using namespace anm2ed::resource; -using namespace anm2ed::types; -using namespace anm2ed::util; - -namespace anm2ed::imgui -{ constexpr int LIBRARY_CARD_LINES = 2; - auto& libraries_get(model::Model& model) { return model.content.libraries; } + static auto& libraries_get(Model& model) { return model.content.libraries; } void libraries_update(Panel& panel) { @@ -49,7 +43,7 @@ namespace anm2ed::imgui Actions actions{}; actions.add(ACTION_OPEN, isOne, [&]() { open(*selection.begin()); }, TOOLTIP_LIBRARY_OPEN); actions.add(ACTION_OPEN_DIRECTORY, isOne, - [&]() { directory_open(dialog, document, model::item_get(libraries, *selection.begin())->path); }); + [&]() { directory_open(dialog, document, item_get(libraries, *selection.begin())->path); }); actions.add(ACTION_ADD, {}, [&]() { dialog.file_open(Dialog::LIBRARY_OPEN, true); }, TOOLTIP_LIBRARY_ADD); content_remove_action_add(actions, panel, ElementType::LIBRARY, SelectionKind::LIBRARIES); actions.add( @@ -60,29 +54,29 @@ namespace anm2ed::imgui [selection](Document& document) { for (auto id : selection) - if (auto library = model::item_get(document.model.content.libraries, id)) + if (auto library = item_get(document.model.content.libraries, id)) { document.library_reload(id); - toast_log(Level::INFO, TOAST_RELOAD_LIBRARY, id, path::to_utf8(library->path)); + toast_log(Level::INFO, TOAST_RELOAD_LIBRARY, id, path_to_utf8(library->path)); } }); }, TOOLTIP_RELOAD_LIBRARIES); - items_clipboard_actions_add(actions, panel, SelectionKind::LIBRARIES, EDIT_PASTE_LIBRARIES, + items_clipboard_actions_add(actions, panel, SelectionKind::LIBRARIES, EDIT_PASTE_LIBRARIES, TOAST_DESERIALIZE_LIBRARIES_FAILED, libraries_get); ListRows rows{ .label_get = [&](int id) { - auto pathString = path::to_utf8(model::item_get(libraries, id)->path); + auto pathString = path_to_utf8(item_get(libraries, id)->path); return std::vformat(localize.get(FORMAT_SOUND), std::make_format_args(id, pathString)); }, .tooltip_draw = [&](int id) { auto loaded = loaded_get(id); - tooltip_name_draw(resources, path::to_utf8(model::item_get(libraries, id)->path)); + tooltip_name_draw(resources, path_to_utf8(item_get(libraries, id)->path)); ImGui::Text("%s: %d", localize.get(BASIC_ID), id); if (loaded && loaded->model.isValid) { @@ -106,7 +100,7 @@ namespace anm2ed::imgui { auto loaded = loaded_get(id); auto isValid = loaded && loaded->model.isValid; - auto& texture = resources.icons[isValid ? icon::ANIMATION : icon::NONE]; + auto& texture = resources.icons[isValid ? ICON_ANIMATION : ICON_NONE]; return CardImage{.texture = &texture, .size = glm::vec2(texture.size), .isValid = isValid}; }, .activate = open, @@ -117,4 +111,3 @@ namespace anm2ed::imgui } ImGui::End(); } -} diff --git a/src/ui/multiselect.cpp b/src/ui/multiselect.cpp index 6186be6..2da562e 100644 --- a/src/ui/multiselect.cpp +++ b/src/ui/multiselect.cpp @@ -1,7 +1,5 @@ #include "ui/multiselect.h" -namespace anm2ed::imgui -{ void external_storage_set(ImGuiSelectionExternalStorage* self, int id, bool isSelected) { auto* storage = static_cast(self->UserData); @@ -38,4 +36,3 @@ namespace anm2ed::imgui if (index < 0 || index >= (int)indexMap->size()) return index; return (*indexMap)[index]; } -} diff --git a/src/ui/multiselect.h b/src/ui/multiselect.h index 04b2dce..17daddf 100644 --- a/src/ui/multiselect.h +++ b/src/ui/multiselect.h @@ -5,8 +5,6 @@ #include -namespace anm2ed::imgui -{ class MultiSelectStorage : public std::set { public: @@ -33,4 +31,3 @@ namespace anm2ed::imgui }; void external_storage_set(ImGuiSelectionExternalStorage*, int, bool); -} diff --git a/src/ui/onionskin.cpp b/src/ui/onionskin.cpp index eb12fa7..418ac95 100644 --- a/src/ui/onionskin.cpp +++ b/src/ui/onionskin.cpp @@ -7,11 +7,8 @@ #include "ui/layout.h" #include "ui/shortcut.h" -using namespace anm2ed::types; using namespace glm; -namespace anm2ed::imgui -{ constexpr auto FRAMES_MAX = 100; void onionskin_update(Manager& manager, Settings& settings) @@ -57,7 +54,6 @@ namespace anm2ed::imgui } ImGui::End(); - if (shortcut(manager.chords[SHORTCUT_ONIONSKIN], shortcut::GLOBAL)) isEnabled = !isEnabled; + if (shortcut(manager.chords[SHORTCUT_ONIONSKIN], SCOPE_GLOBAL)) isEnabled = !isEnabled; } -} diff --git a/src/ui/panel.cpp b/src/ui/panel.cpp index 07ce4f6..e9c92c8 100644 --- a/src/ui/panel.cpp +++ b/src/ui/panel.cpp @@ -9,13 +9,8 @@ #include "ui/layout.h" #include "ui/shortcut.h" -using namespace anm2ed::resource; -using namespace anm2ed::types; -using namespace anm2ed::util; using namespace glm; -namespace anm2ed::imgui -{ constexpr float SCROLL_CENTER = 0.5f; constexpr std::size_t REMOVE_LINES_MAX = 10; constexpr float TOOLTIP_PADDING_MULTIPLIER = 4.0f; @@ -30,13 +25,13 @@ namespace anm2ed::imgui {panel.manager.selected, [run = std::move(run)](Manager&, Document& document) { run(document); }}); } - void row_select(std::set&, int& focus, const ListRows& rows, int key) + static void row_select(std::set&, int& focus, const ListRows& rows, int key) { focus = key; if (rows.select) rows.select(key); } - void row_scroll_update(PanelState& state, int key, int arrowKey) + static void row_scroll_update(PanelState& state, int key, int arrowKey) { if ((state.newId != key && state.scrollId != key && arrowKey != key) || is_drag_drop_active()) return; ImGui::SetScrollHereY(SCROLL_CENTER); @@ -59,7 +54,7 @@ namespace anm2ed::imgui ImGui::PopStyleVar(2); } - void row_tooltip_update(const PanelState& state, const ListRows& rows, int key) + static void row_tooltip_update(const PanelState& state, const ListRows& rows, int key) { if (!rows.tooltip_draw || !tooltip_begin(state)) return; rows.tooltip_draw(key); @@ -67,7 +62,7 @@ namespace anm2ed::imgui } // Arrow keys move a single selection through the keys. - int arrow_key_get(const std::vector& keys, const std::set& selection, int focus) + static int arrow_key_get(const std::vector& keys, const std::set& selection, int focus) { if (keys.empty() || !ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows) || !(ImGui::IsKeyPressed(ImGuiKey_UpArrow, true) || ImGui::IsKeyPressed(ImGuiKey_DownArrow, true))) @@ -110,7 +105,7 @@ namespace anm2ed::imgui selection = {arrowKey}; row_select(selection, focus, rows, arrowKey); } - if (shortcut(panel.manager.chords[SHORTCUT_CONFIRM], shortcut::FOCUSED) && selection.size() == 1 && rows.activate) + if (shortcut(panel.manager.chords[SHORTCUT_CONFIRM], SCOPE_FOCUSED) && selection.size() == 1 && rows.activate) rows.activate(*selection.begin()); } @@ -120,13 +115,13 @@ namespace anm2ed::imgui auto& state = panel.state; auto isSelected = selection.contains(key) || arrowKey == key; auto isFocused = rows.isFocusItalic && (focus == key || arrowKey == key); - auto font = rows.font_get ? rows.font_get(key) : isFocused ? font::ITALICS : font::REGULAR; + auto font = rows.font_get ? rows.font_get(key) : isFocused ? FONT_ITALICS : FONT_REGULAR; auto label = rows.label_get(key); auto isInvalid = rows.is_invalid && rows.is_invalid(key); ImGui::PushID(key); ImGui::SetNextItemSelectionUserData(index); - if (font != font::REGULAR) ImGui::PushFont(panel.resources.fonts[font].get(), font::SIZE); + if (font != FONT_REGULAR) ImGui::PushFont(panel.resources.fonts[font].get(), FONT_SIZE); if (isInvalid) ImGui::PushStyleColor(ImGuiCol_Text, CARD_TINT_INVALID); if (arrowKey == key) ImGui::SetKeyboardFocusHere(); @@ -161,7 +156,7 @@ namespace anm2ed::imgui if (isActivated || ImGui::IsItemClicked(ImGuiMouseButton_Left) || ImGui::IsItemClicked(ImGuiMouseButton_Right)) row_select(selection, focus, rows, key); if (isInvalid) ImGui::PopStyleColor(); - if (font != font::REGULAR) ImGui::PopFont(); + if (font != FONT_REGULAR) ImGui::PopFont(); row_scroll_update(state, key, arrowKey); if (state.newId == key) state.newId = -1; @@ -174,7 +169,7 @@ namespace anm2ed::imgui return isBreak; } - void card_draw(Panel& panel, std::set& selection, int& focus, const ListRows& rows, int key, int index, + static void card_draw(Panel& panel, std::set& selection, int& focus, const ListRows& rows, int key, int index, int arrowKey, bool& isBreak) { auto cardSize = ImVec2(ImGui::GetContentRegionAvail().x, ImGui::GetTextLineHeightWithSpacing() * rows.cardLines); @@ -227,12 +222,12 @@ namespace anm2ed::imgui else imageSize.y = imageSize.x / aspectRatio; ImGui::SetCursorPos(cursorPos); - ImGui::ImageWithBg(resource::texture::id_get(*image.texture), imageSize, to_imvec2(image.uvMin), + ImGui::ImageWithBg(texture_id_get(*image.texture), imageSize, to_imvec2(image.uvMin), to_imvec2(image.uvMax), ImVec4(), image.isValid ? CARD_TINT_VALID : CARD_TINT_INVALID); ImGui::SetCursorPos( ImVec2(cardSize.y + style.ItemSpacing.x, cardSize.y - cardSize.y / 2 - ImGui::GetTextLineHeight() / 2)); - if (isFocused) ImGui::PushFont(panel.resources.fonts[font::ITALICS].get(), font::SIZE); + if (isFocused) ImGui::PushFont(panel.resources.fonts[FONT_ITALICS].get(), FONT_SIZE); ImGui::TextUnformatted(label.c_str()); if (isFocused) ImGui::PopFont(); } @@ -275,7 +270,7 @@ namespace anm2ed::imgui // The list in a bordered child with its context menu and shortcuts, then the footer buttons. // The confirmation's lines: the items by name, then what goes with them. - std::vector remove_lines_get(const model::Model& model, ElementType type, const std::set& ids, + static std::vector remove_lines_get(const Model& model, ElementType type, const std::set& ids, int spritesheetId) { auto& content = model.content; @@ -283,10 +278,10 @@ namespace anm2ed::imgui auto names_add = [&](const auto& items, auto&& name_get) { for (auto id : ids) - if (auto item = model::item_get(items, id)) lines.push_back(std::format("\"{}\"", name_get(*item))); + if (auto item = item_get(items, id)) lines.push_back(std::format("\"{}\"", name_get(*item))); }; auto name_get = [](const auto& item) { return item.name; }; - auto path_get = [](const auto& item) { return path::to_utf8(item.path); }; + auto path_get = [](const auto& item) { return path_to_utf8(item.path); }; auto count_add = [&](StringType format, int count) { if (count > 0) lines.push_back(localize_format(format, count)); @@ -341,14 +336,14 @@ namespace anm2ed::imgui count_add(FORMAT_REMOVE_SHADER_USES, uses); break; case ElementType::REGION: - if (auto spritesheet = model::item_get(content.spritesheets, spritesheetId)) + if (auto spritesheet = item_get(content.spritesheets, spritesheetId)) names_add(spritesheet->regions, name_get); count_add(FORMAT_REMOVE_REGION_USES, uses); break; case ElementType::SPRITESHEET: { names_add(content.spritesheets, path_get); - auto layerIds = layers_add(FORMAT_REMOVE_LAYER, [&](const model::Layer& layer) + auto layerIds = layers_add(FORMAT_REMOVE_LAYER, [&](const Layer& layer) { return !layer.is_animation() && ids.contains(layer.spritesheetId); }); count_add(FORMAT_REMOVE_TRACKS, model.uses_count(ElementType::LAYER_ELEMENT, layerIds)); break; @@ -356,21 +351,21 @@ namespace anm2ed::imgui default: names_add(content.libraries, path_get); layers_add(FORMAT_REMOVE_FLATTENED_LAYER, - [&](const model::Layer& layer) { return ids.contains(layer.libraryId); }); + [&](const Layer& layer) { return ids.contains(layer.libraryId); }); break; } return lines; } - void content_remove_apply(Panel& panel) + static void content_remove_apply(Panel& panel) { command_push(panel, [removal = panel.state.removal](Document& document) { document.edit_apply(EDIT_REMOVE_ITEMS, - [&](model::Model& model) + [&](Model& model) { - return edit::content_remove( + return content_remove( model, removal.type, removal.ids, removal.spritesheetId, document.library_resolver_get(), document.spritesheet_path_resolver_get()); }); @@ -398,7 +393,7 @@ namespace anm2ed::imgui TOOLTIP_REMOVE_CONTENT); } - void content_remove_popup_draw(Panel& panel) + static void content_remove_popup_draw(Panel& panel) { auto& popup = panel.state.removePopup; popup.trigger(); @@ -457,7 +452,7 @@ namespace anm2ed::imgui void tooltip_name_draw(Resources& resources, const std::string& name) { - ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); + ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE); ImGui::TextUnformatted(name.c_str()); ImGui::PopFont(); } @@ -472,7 +467,7 @@ namespace anm2ed::imgui auto noScrollFlags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse; ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, ImVec2()); if (ImGui::BeginChild("##Tooltip Image Child", to_imvec2(previewSize), childFlags, noScrollFlags)) - ImGui::ImageWithBg(resource::texture::id_get(*image.texture), to_imvec2(previewSize), to_imvec2(image.uvMin), + ImGui::ImageWithBg(texture_id_get(*image.texture), to_imvec2(previewSize), to_imvec2(image.uvMin), to_imvec2(image.uvMax), ImVec4(), image.isValid ? CARD_TINT_VALID : CARD_TINT_INVALID); ImGui::EndChild(); ImGui::PopStyleVar(); @@ -486,7 +481,7 @@ namespace anm2ed::imgui std::filesystem::path asset_path_get(Document& document, const std::filesystem::path& path) { - return path::backslash_replace(path::make_relative(path::backslash_handle(path), document.directory_get())); + return path_backslash_replace(path_make_relative(path_backslash_handle(path), document.directory_get())); } // Shows a resource's file selected in the file manager (or the nearest folder there is, when it's missing). @@ -519,4 +514,3 @@ namespace anm2ed::imgui if (ImGui::Button(localize.get(cancelLabel), widgetSize)) result = PopupButton::CANCEL; return result; } -} diff --git a/src/ui/panel.h b/src/ui/panel.h index d83259e..244bf69 100644 --- a/src/ui/panel.h +++ b/src/ui/panel.h @@ -19,8 +19,6 @@ #include "ui/change_all_frame_properties.h" // Panels are plain functions: each draws from the document and its selection, and queues edits as commands. -namespace anm2ed::imgui -{ inline constexpr auto DRAG_DROP_SOURCE_FLAGS = ImGuiDragDropFlags_SourceNoPreviewTooltip | ImGuiDragDropFlags_SourceNoHoldToOpenOthers; inline constexpr ImVec4 CARD_TINT_INVALID = ImVec4(1.0f, 0.25f, 0.25f, 1.0f); @@ -30,7 +28,7 @@ namespace anm2ed::imgui struct CardImage { - const resource::Image* texture{}; + const Image* texture{}; glm::vec2 size{}; glm::vec2 uvMin{}; glm::vec2 uvMax{1.0f}; @@ -82,7 +80,7 @@ namespace anm2ed::imgui std::function name_get{}; std::function rename{}; std::function is_invalid{}; - std::function font_get{}; + std::function font_get{}; std::function tooltip_draw{}; std::function image_get{}; std::function select{}; @@ -132,7 +130,7 @@ namespace anm2ed::imgui PanelState state{}; PopupHelper propertiesPopup{PopupHelper(LABEL_REGION_PROPERTIES, POPUP_SMALL_NO_HEIGHT)}; PopupHelper exportPopup{PopupHelper(LABEL_EXPORT_REGION, POPUP_SMALL_NO_HEIGHT)}; - model::Region editRegion{}; + Region editRegion{}; int editId{-1}; int exportId{-1}; }; @@ -148,7 +146,7 @@ namespace anm2ed::imgui struct FramePropertiesPanel { - wizard::ChangeAllFrameProperties changeAllFrameProperties{}; + ChangeAllFrameProperties changeAllFrameProperties{}; bool isBatchMode{}; }; @@ -160,11 +158,11 @@ namespace anm2ed::imgui void nulls_update(Panel&); void events_update(Panel&); void sounds_update(Panel&); - std::string layer_label_get(const model::Layer&); - void layer_source_tooltip_draw(const Document&, const model::Layer&); - void layer_source_tooltip_draw(const Document&, const model::Layer&); - model::Layer item_edit_layer_get(const Manager::ItemEdit&); - model::Null item_edit_null_get(const Manager::ItemEdit&); + std::string layer_label_get(const Layer&); + void layer_source_tooltip_draw(const Document&, const Layer&); + void layer_source_tooltip_draw(const Document&, const Layer&); + Layer item_edit_layer_get(const Manager::ItemEdit&); + Null item_edit_null_get(const Manager::ItemEdit&); void layer_source_draw(Document&, Manager::ItemEdit&); void libraries_update(Panel&); void spritesheets_update(Panel&, SpritesheetsPanel&); @@ -186,7 +184,7 @@ namespace anm2ed::imgui { std::string text{}; for (auto id : ids) - if (auto item = model::item_get(items, id)) text += model::item_to_string(*item); + if (auto item = item_get(items, id)) text += item_to_string(*item); if (!text.empty()) clipboard.set(text); } @@ -200,15 +198,15 @@ namespace anm2ed::imgui [&state, kind, edit, failToast, text, items_get](Document& document) { std::string errorString{}; - auto pasted = model::items_from_string(text, &errorString); + auto pasted = items_from_string(text, &errorString); if (pasted.empty()) return toast_log(Level::ERROR, failToast, errorString); document.edit_apply(edit, - [&](model::Model& model) + [&](Model& model) { auto& items = items_get(model); for (auto& item : pasted) { - item.id = model::item_next_id_get(items); + item.id = item_next_id_get(items); items.push_back(std::move(item)); } }); @@ -234,4 +232,3 @@ namespace anm2ed::imgui [&panel, kind, pasteEdit, failToast, items_get]() { items_paste(panel, kind, pasteEdit, failToast, items_get); }); } -} diff --git a/src/ui/popup.cpp b/src/ui/popup.cpp index dd3ebfd..56e176f 100644 --- a/src/ui/popup.cpp +++ b/src/ui/popup.cpp @@ -6,8 +6,6 @@ #include "types.h" -namespace anm2ed::imgui -{ int PopupHelper::nextId = 1; #define POPUP_LIST \ @@ -83,4 +81,3 @@ namespace anm2ed::imgui void PopupHelper::end() { isJustOpened = false; } void PopupHelper::close() { isOpen = false; } -} diff --git a/src/ui/popup.h b/src/ui/popup.h index 5b262e8..2b55490 100644 --- a/src/ui/popup.h +++ b/src/ui/popup.h @@ -4,8 +4,6 @@ #include "localization.h" -namespace anm2ed::imgui -{ #define POPUP_LIST \ X(POPUP_SMALL, 0.25f, true) \ X(POPUP_NORMAL, 0.5f, true) \ @@ -50,4 +48,3 @@ namespace anm2ed::imgui }; #undef POPUP_LIST -} diff --git a/src/ui/regions.cpp b/src/ui/regions.cpp index 2faaff5..a89e146 100644 --- a/src/ui/regions.cpp +++ b/src/ui/regions.cpp @@ -13,18 +13,13 @@ #include "vector.h" #include "working_directory.h" -using namespace anm2ed::resource; -using namespace anm2ed::types; -using namespace anm2ed::util; using namespace glm; -namespace anm2ed::imgui -{ constexpr int REGION_CARD_LINES = 2; constexpr int REGION_POPUP_ROWS = 5; constexpr const char* REGION_DRAG_DROP = "Region Drag Drop"; constexpr const char* REGION_EXPORT_NAME_DEFAULT = "region"; - constexpr const char* PNG_EXTENSION = ".png"; + constexpr const char* REGION_EXPORT_EXTENSION = ".png"; constexpr ImVec2 DRAG_TOOLTIP_OFFSET = ImVec2(16.0f, 16.0f); constexpr StringType ORIGIN_LABELS[] = {LABEL_REGION_ORIGIN_CUSTOM, LABEL_REGION_ORIGIN_TOP_LEFT, @@ -40,19 +35,19 @@ namespace anm2ed::imgui bool isRemoveCurrent{}; }; - void region_pivot_apply(model::Region& region) + static void region_pivot_apply(Region& region) { if (region.origin == Origin::TOP_LEFT) region.pivot = {}; if (region.origin == Origin::CENTER) region.pivot = region.size * 0.5f; } - const model::Spritesheet* region_spritesheet_get(Document& document) + static const Spritesheet* region_spritesheet_get(Document& document) { - return model::item_get(document.model.content.spritesheets, document.focused_id_get(SelectionKind::SPRITESHEETS)); + return item_get(document.model.content.spritesheets, document.focused_id_get(SelectionKind::SPRITESHEETS)); } // New regions go after the last selected (or focused) one. - int region_insert_index_get(Document& document) + static int region_insert_index_get(Document& document) { auto spritesheet = region_spritesheet_get(document); if (!spritesheet) return 0; @@ -67,7 +62,7 @@ namespace anm2ed::imgui return index; } - void region_select(Document& document, int id) + static void region_select(Document& document, int id) { document.editTarget = Document::EditTarget::REGION; document.selected_ids_set(SelectionKind::REGIONS, {id}); @@ -76,10 +71,10 @@ namespace anm2ed::imgui document.frame_references_clear(); } - CardImage region_image_get(Document& document, Resources& resources, const model::Region& region) + static CardImage region_image_get(Document& document, Resources& resources, const Region& region) { auto texture = document.texture_get(document.focused_id_get(SelectionKind::SPRITESHEETS)); - if (!texture || !texture->is_valid()) return {.texture = &resources.icons[icon::NONE], .size = region.size}; + if (!texture || !texture->is_valid()) return {.texture = &resources.icons[ICON_NONE], .size = region.size}; return {.texture = texture, .size = region.size, .uvMin = region.crop / vec2(texture->size), @@ -87,17 +82,17 @@ namespace anm2ed::imgui .isValid = true}; } - bool region_export(Document& document, const RegionExportOptions& options) + static bool region_export(Document& document, const RegionExportOptions& options) { - auto pathString = options.path.empty() ? std::string("in memory") : path::to_utf8(options.path); + auto pathString = options.path.empty() ? std::string("in memory") : path_to_utf8(options.path); if (options.path.empty() && !options.isMakeSpritesheet) { toast_log(Level::ERROR, TOAST_EXPORT_REGION_PATH_EMPTY); return false; } - auto spritesheet = model::item_get(document.model.content.spritesheets, options.spritesheetId); - auto region = spritesheet ? model::item_get(spritesheet->regions, options.regionId) : nullptr; + auto spritesheet = item_get(document.model.content.spritesheets, options.spritesheetId); + auto region = spritesheet ? item_get(spritesheet->regions, options.regionId) : nullptr; auto texture = document.texture_get(options.spritesheetId); auto minPoint = region ? ivec2(glm::min(region->crop, region->crop + region->size)) : ivec2(); auto exportSize = region ? ivec2(glm::max(region->crop, region->crop + region->size)) - minPoint : ivec2(); @@ -112,10 +107,10 @@ namespace anm2ed::imgui auto outputPath = options.path; if (!outputPath.empty()) { - outputPath = asset_path_get(document, outputPath.replace_extension(PNG_EXTENSION)); - pathString = path::to_utf8(outputPath); + outputPath = asset_path_get(document, outputPath.replace_extension(REGION_EXPORT_EXTENSION)); + pathString = path_to_utf8(outputPath); WorkingDirectory workingDirectory(document.directory_get()); - path::ensure_directory(outputPath.parent_path()); + path_ensure_directory(outputPath.parent_path()); if (!exportedImage.write_png(outputPath)) { toast_log(Level::ERROR, TOAST_EXPORT_REGION_FAILED, sourceRegion.name, pathString); @@ -129,19 +124,19 @@ namespace anm2ed::imgui if (options.isRemoveCurrent) { - if (auto source = model::item_get(document.model.content.spritesheets, options.spritesheetId)) - std::erase_if(source->regions, [&](const model::Region& region) { return region.id == options.regionId; }); - edit::region_frames_sync(document.model); + if (auto source = item_get(document.model.content.spritesheets, options.spritesheetId)) + std::erase_if(source->regions, [&](const Region& region) { return region.id == options.regionId; }); + region_frames_sync(document.model); document.selected_clear(SelectionKind::REGIONS); } if (options.isMakeSpritesheet) { auto& spritesheets = document.model.content.spritesheets; - model::Spritesheet exported{.id = model::item_next_id_get(spritesheets), .path = outputPath}; + Spritesheet exported{.id = item_next_id_get(spritesheets), .path = outputPath}; auto exportedRegion = sourceRegion; - exportedRegion.uid = util::uid_next(); + exportedRegion.uid = uid_next(); exportedRegion.id = 0; exportedRegion.crop = {}; exportedRegion.size = vec2(exportSize); @@ -167,7 +162,7 @@ namespace anm2ed::imgui return true; } - bool region_drag_drop_update(Panel& panel, int id, int index) + static bool region_drag_drop_update(Panel& panel, int id, int index) { auto& state = panel.state; auto selection = panel.document.selected_ids_get(SelectionKind::REGIONS); @@ -192,7 +187,7 @@ namespace anm2ed::imgui std::vector indices{}; auto payloadIds = (const int*)payload->Data; for (int i = 0; i < payload->DataSize / (int)sizeof(int); i++) - if (auto keyIndex = vector::find_index(state.keys, payloadIds[i]); keyIndex != -1) indices.push_back(keyIndex); + if (auto keyIndex = vector_index_find(state.keys, payloadIds[i]); keyIndex != -1) indices.push_back(keyIndex); if (!indices.empty() && payload->IsDelivery()) { @@ -201,13 +196,13 @@ namespace anm2ed::imgui [indices, movedIds = state.dragIds, targetIndex = index + (isAfter ? 1 : 0), spritesheetId = panel.document.focused_id_get(SelectionKind::SPRITESHEETS)](Document& document) { - if (!model::item_get(document.model.content.spritesheets, spritesheetId)) return; + if (!item_get(document.model.content.spritesheets, spritesheetId)) return; document.edit_apply( EDIT_MOVE_REGIONS, - [&](model::Model& model) + [&](Model& model) { - auto spritesheet = model::item_get(model.content.spritesheets, spritesheetId); - vector::move_indices_to_position(spritesheet->regions, indices, targetIndex); + auto spritesheet = item_get(model.content.spritesheets, spritesheetId); + vector_indices_move(spritesheet->regions, indices, targetIndex); }); document.selected_ids_set(SelectionKind::REGIONS, {movedIds.begin(), movedIds.end()}); }); @@ -218,7 +213,7 @@ namespace anm2ed::imgui return isMoved; } - void region_drag_tooltip_update(Panel& panel) + static void region_drag_tooltip_update(Panel& panel) { auto& state = panel.state; auto payload = ImGui::GetDragDropPayload(); @@ -238,21 +233,21 @@ namespace anm2ed::imgui ImGui::SetNextWindowPos(ImVec2(mousePos.x + DRAG_TOOLTIP_OFFSET.x, mousePos.y + DRAG_TOOLTIP_OFFSET.y)); if (!tooltip_begin(state, false)) return; for (auto regionId : state.dragIds) - if (auto region = model::item_get(spritesheet->regions, regionId)) ImGui::TextUnformatted(region->name.c_str()); + if (auto region = item_get(spritesheet->regions, regionId)) ImGui::TextUnformatted(region->name.c_str()); tooltip_end(); } - void region_properties_open(RegionsPanel& regions, Document& document, int id) + static void region_properties_open(RegionsPanel& regions, Document& document, int id) { auto spritesheet = region_spritesheet_get(document); - auto region = spritesheet ? model::item_get(spritesheet->regions, id) : nullptr; + auto region = spritesheet ? item_get(spritesheet->regions, id) : nullptr; if (id != -1 && !region) return; regions.editId = id; - regions.editRegion = region ? *region : model::Region{}; + regions.editRegion = region ? *region : Region{}; regions.propertiesPopup.open(); } - void region_properties_popup_update(Panel& panel, RegionsPanel& regions) + static void region_properties_popup_update(Panel& panel, RegionsPanel& regions) { auto& popup = regions.propertiesPopup; popup.trigger(); @@ -265,12 +260,12 @@ namespace anm2ed::imgui input_text_string(localize.get(BASIC_NAME), ®ion.name); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ITEM_NAME)); ImGui::DragFloat2(localize.get(BASIC_CROP), value_ptr(region.crop), DRAG_SPEED, 0.0f, 0.0f, - math::vec2_format_get(region.crop)); + vec2_format_get(region.crop)); ImGui::DragFloat2(localize.get(BASIC_SIZE), value_ptr(region.size), DRAG_SPEED, 0.0f, 0.0f, - math::vec2_format_get(region.size)); + vec2_format_get(region.size)); ImGui::BeginDisabled(region.origin != Origin::CUSTOM); ImGui::DragFloat2(localize.get(BASIC_PIVOT), value_ptr(region.pivot), DRAG_SPEED, 0.0f, 0.0f, - math::vec2_format_get(region.pivot)); + vec2_format_get(region.pivot)); ImGui::EndDisabled(); const char* originOptions[std::size(ORIGIN_COMBO_ORDER)]{}; @@ -295,13 +290,13 @@ namespace anm2ed::imgui { auto changedId = id; document.edit_apply(id == -1 ? EDIT_ADD_REGION : EDIT_SET_REGION_PROPERTIES, - [&](model::Model& model) + [&](Model& model) { auto spritesheet = - model::item_get(model.content.spritesheets, spritesheetId); + item_get(model.content.spritesheets, spritesheetId); if (!spritesheet) return; auto& items = spritesheet->regions; - if (auto target = model::item_get(items, id)) + if (auto target = item_get(items, id)) { auto uid = target->uid; *target = edited; @@ -310,10 +305,10 @@ namespace anm2ed::imgui return; } if (id != -1) return; - changedId = model::item_next_id_get(items); + changedId = item_next_id_get(items); auto& added = *items.insert( items.begin() + std::min(insertIndex, (int)items.size()), edited); - added.uid = util::uid_next(); + added.uid = uid_next(); added.id = changedId; state.newId = changedId; }); @@ -325,11 +320,11 @@ namespace anm2ed::imgui popup.end(); } - void region_export_popup_update(Panel& panel, RegionsPanel& regions) + static void region_export_popup_update(Panel& panel, RegionsPanel& regions) { auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; auto spritesheet = region_spritesheet_get(document); - auto region = spritesheet ? model::item_get(spritesheet->regions, regions.exportId) : nullptr; + auto region = spritesheet ? item_get(spritesheet->regions, regions.exportId) : nullptr; auto& popup = regions.exportPopup; popup.trigger(); @@ -338,10 +333,10 @@ namespace anm2ed::imgui if (!region) popup.close(); if (region && popup.isJustOpened) { - auto filename = path::from_utf8(region->name).filename(); + auto filename = path_from_utf8(region->name).filename(); settings.exportRegionPath = settings.exportRegionPath.parent_path() / - (filename.empty() ? std::filesystem::path(REGION_EXPORT_NAME_DEFAULT) : filename).concat(PNG_EXTENSION); + (filename.empty() ? std::filesystem::path(REGION_EXPORT_NAME_DEFAULT) : filename).concat(REGION_EXPORT_EXTENSION); } if (dialog.is_selected(Dialog::REGION_EXPORT_PATH_SET)) { @@ -351,7 +346,7 @@ namespace anm2ed::imgui if (ImGui::BeginChild("##Export Region Child", child_size_get(REGION_POPUP_ROWS), ImGuiChildFlags_Borders)) { - if (ImGui::ImageButton("##Export Region Path Set", resources.icon_id_get(icon::FOLDER), icon_size_get())) + if (ImGui::ImageButton("##Export Region Path Set", resources.icon_id_get(ICON_FOLDER), icon_size_get())) dialog.file_save(Dialog::REGION_EXPORT_PATH_SET, settings.exportRegionPath); ImGui::SameLine(); input_text_path(localize.get(LABEL_OUTPUT_PATH), &settings.exportRegionPath); @@ -370,7 +365,7 @@ namespace anm2ed::imgui auto result = popup_buttons_draw(manager, localize.get(BASIC_CONFIRM), isValid); if (result == PopupButton::CONFIRM) { - if (!settings.exportRegionPath.empty()) settings.exportRegionPath.replace_extension(PNG_EXTENSION); + if (!settings.exportRegionPath.empty()) settings.exportRegionPath.replace_extension(REGION_EXPORT_EXTENSION); RegionExportOptions options{.spritesheetId = spritesheetId, .regionId = regions.exportId, .path = settings.exportRegionPath, @@ -423,7 +418,7 @@ namespace anm2ed::imgui [spritesheetId, selection](Document& document) { document.edit_apply(EDIT_TRIM_REGIONS, - [&](model::Model&) + [&](Model&) { if (!document.regions_trim(spritesheetId, selection)) return; document.reference_set({document.reference_get().animationIndex}); @@ -451,30 +446,30 @@ namespace anm2ed::imgui [&state, spritesheetId, text = clipboard.get(), insertIndex = region_insert_index_get(document)](Document& document) { - auto spritesheet_regions_get = [&]() -> const std::vector* + auto spritesheet_regions_get = [&]() -> const std::vector* { - auto spritesheet = model::item_get(document.model.content.spritesheets, spritesheetId); + auto spritesheet = item_get(document.model.content.spritesheets, spritesheetId); return spritesheet ? &spritesheet->regions : nullptr; }; if (!spritesheet_regions_get()) return; - auto nextId = model::item_next_id_get(*spritesheet_regions_get()); + auto nextId = item_next_id_get(*spritesheet_regions_get()); std::string errorString{}; document.edit_apply( - EDIT_PASTE_REGIONS, [&](model::Model& model) - { return edit::regions_paste(model, spritesheetId, text, insertIndex, &errorString); }); + EDIT_PASTE_REGIONS, [&](Model& model) + { return regions_paste(model, spritesheetId, text, insertIndex, &errorString); }); if (!errorString.empty()) toast_log(Level::ERROR, TOAST_DESERIALIZE_REGIONS_FAILED, errorString); - auto lastId = model::item_next_id_get(*spritesheet_regions_get()) - 1; + auto lastId = item_next_id_get(*spritesheet_regions_get()) - 1; if (lastId < nextId) return; state.newId = lastId; region_select(document, lastId); }); }); - ListRows rows{.label_get = [&](int id) { return model::item_get(spritesheet->regions, id)->name; }, + ListRows rows{.label_get = [&](int id) { return item_get(spritesheet->regions, id)->name; }, .tooltip_draw = [&](int id) { - auto& region = *model::item_get(spritesheet->regions, id); + auto& region = *item_get(spritesheet->regions, id); tooltip_image_draw( region_image_get(document, resources, region), [&]() @@ -496,7 +491,7 @@ namespace anm2ed::imgui }); }, .image_get = [&](int id) - { return region_image_get(document, resources, *model::item_get(spritesheet->regions, id)); }, + { return region_image_get(document, resources, *item_get(spritesheet->regions, id)); }, .select = [&](int) { @@ -522,4 +517,3 @@ namespace anm2ed::imgui region_properties_popup_update(panel, regions); region_export_popup_update(panel, regions); } -} diff --git a/src/ui/render_animation.cpp b/src/ui/render_animation.cpp index 9ffdf3f..e870b13 100644 --- a/src/ui/render_animation.cpp +++ b/src/ui/render_animation.cpp @@ -14,11 +14,6 @@ #include "ui/layout.h" #include "ui/shortcut.h" -using namespace anm2ed::resource; -using namespace anm2ed::util; - -namespace anm2ed::imgui::wizard -{ void RenderAnimation::range_to_animation_set(Manager& manager, Document& document) { if (auto animation = document.model.animation_get(document.reference_get().animationIndex)) @@ -61,7 +56,7 @@ namespace anm2ed::imgui::wizard void RenderAnimation::reset(Manager& manager, Document& document, Settings& settings) { if (!manager.isRecordingRange) range_to_animation_set(manager, document); - settings.renderPath.replace_extension(render::EXTENSIONS[settings.renderType]); + settings.renderPath.replace_extension(RENDER_EXTENSIONS[settings.renderType]); } void RenderAnimation::update(Manager& manager, Document& document, Resources& resources, Settings& settings, @@ -92,13 +87,13 @@ namespace anm2ed::imgui::wizard start = std::clamp(start, 0, frameMax); end = std::clamp(end, start, frameMax); auto animationFps = std::max(document.model.info.fps, 1); - if (renderFpsMode < render::FPS_ANIMATION || renderFpsMode >= render::FPS_COUNT) - renderFpsMode = render::FPS_ANIMATION; - auto renderFps = render::fps_get(renderFpsMode, animationFps, settings.playbackTickRate); + if (renderFpsMode < FPS_ANIMATION || renderFpsMode >= FPS_COUNT) + renderFpsMode = FPS_ANIMATION; + auto renderFps = fps_get(renderFpsMode, animationFps, settings.playbackTickRate); auto render_frame_count_get = [&]() { - if (isRange) return render::frame_count_get(start, end, animationFps, renderFps); - return render::frame_count_get(0, frameMax, animationFps, renderFps); + if (isRange) return frame_count_get(start, end, animationFps, renderFps); + return frame_count_get(0, frameMax, animationFps, renderFps); }; auto renderFrameNum = render_frame_count_get(); @@ -107,22 +102,22 @@ namespace anm2ed::imgui::wizard Dialog::Type dialogType{Dialog::NONE}; switch (type) { - case render::PNGS: + case RENDER_PNGS: dialogType = Dialog::PNG_DIRECTORY_SET; break; - case render::SPRITESHEET: + case RENDER_SPRITESHEET: dialogType = Dialog::PNG_PATH_SET; break; - case render::GIF: + case RENDER_GIF: dialogType = Dialog::GIF_PATH_SET; break; - case render::WEBM: + case RENDER_WEBM: dialogType = Dialog::WEBM_PATH_SET; break; - case render::OGV: + case RENDER_OGV: dialogType = Dialog::OGV_PATH_SET; break; - case render::MP4: + case RENDER_MP4: dialogType = Dialog::MP4_PATH_SET; break; default: @@ -130,7 +125,7 @@ namespace anm2ed::imgui::wizard break; } - if (ImGui::ImageButton("##FFmpeg Path Set", resources.icon_id_get(icon::FOLDER), icon_size_get())) + if (ImGui::ImageButton("##FFmpeg Path Set", resources.icon_id_get(ICON_FOLDER), icon_size_get())) dialog.file_open(Dialog::FFMPEG_PATH_SET); ImGui::SameLine(); input_text_path(localize.get(LABEL_FFMPEG_PATH), &ffmpegPath); @@ -142,7 +137,7 @@ namespace anm2ed::imgui::wizard dialog.reset(); } - if (ImGui::ImageButton("##Path Set", resources.icon_id_get(icon::FOLDER), icon_size_get())) + if (ImGui::ImageButton("##Path Set", resources.icon_id_get(ICON_FOLDER), icon_size_get())) { if (dialogType == Dialog::PNG_DIRECTORY_SET) dialog.folder_open(dialogType); @@ -151,7 +146,7 @@ namespace anm2ed::imgui::wizard } ImGui::SameLine(); - auto pathLabel = type == render::PNGS ? LABEL_OUTPUT_DIRECTORY : LABEL_OUTPUT_PATH; + auto pathLabel = type == RENDER_PNGS ? LABEL_OUTPUT_DIRECTORY : LABEL_OUTPUT_PATH; input_text_path(localize.get(pathLabel), &path); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_OUTPUT_PATH)); @@ -161,19 +156,19 @@ namespace anm2ed::imgui::wizard dialog.reset(); } - if (ImGui::Combo(localize.get(LABEL_TYPE), &type, render::STRINGS, render::COUNT)) - path.replace_extension(render::EXTENSIONS[type]); + if (ImGui::Combo(localize.get(LABEL_TYPE), &type, RENDER_STRINGS, RENDER_COUNT)) + path.replace_extension(RENDER_EXTENSIONS[type]); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_RENDER_TYPE)); - if (type == render::PNGS || type == render::SPRITESHEET) ImGui::Separator(); + if (type == RENDER_PNGS || type == RENDER_SPRITESHEET) ImGui::Separator(); - if (type == render::PNGS) + if (type == RENDER_PNGS) { input_text_path(localize.get(LABEL_FORMAT), &format); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FORMAT)); } - else if (type == render::SPRITESHEET) + else if (type == RENDER_SPRITESHEET) { input_int_range(localize.get(LABEL_GENERATE_ROWS), rows, 1, renderFrameNum); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ROWS)); @@ -210,9 +205,9 @@ namespace anm2ed::imgui::wizard ImGui::EndDisabled(); renderFrameNum = render_frame_count_get(); - if (type == render::SPRITESHEET) + if (type == RENDER_SPRITESHEET) { - auto layout = render::spritesheet_layout_get(rows, columns, renderFrameNum); + auto layout = spritesheet_layout_get(rows, columns, renderFrameNum); rows = layout.rows; columns = layout.columns; } @@ -241,11 +236,11 @@ namespace anm2ed::imgui::wizard ImGui::Combo(localize.get(LABEL_RENDER_FPS), &renderFpsMode, renderFpsOptions, IM_ARRAYSIZE(renderFpsOptions)); ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_RENDER_FPS)); - renderFps = render::fps_get(renderFpsMode, animationFps, settings.playbackTickRate); + renderFps = fps_get(renderFpsMode, animationFps, settings.playbackTickRate); renderFrameNum = render_frame_count_get(); - if (type == render::SPRITESHEET) + if (type == RENDER_SPRITESHEET) { - auto layout = render::spritesheet_layout_get(rows, columns, renderFrameNum); + auto layout = spritesheet_layout_get(rows, columns, renderFrameNum); rows = layout.rows; columns = layout.columns; } @@ -257,18 +252,18 @@ namespace anm2ed::imgui::wizard ImGui::Separator(); - imgui::shortcut(manager.chords[SHORTCUT_CONFIRM]); + shortcut(manager.chords[SHORTCUT_CONFIRM]); if (ImGui::Button(localize.get(LABEL_RENDER), widgetSize)) { - path.replace_extension(render::EXTENSIONS[type]); + path.replace_extension(RENDER_EXTENSIONS[type]); auto render_is_valid = [&]() { auto ffmpeg_is_valid = [&]() { - if (!path::is_executable(ffmpegPath)) return false; + if (!is_path_executable(ffmpegPath)) return false; - auto testCommand = std::string("\"") + path::to_utf8(ffmpegPath) + "\" -version"; + auto testCommand = std::string("\"") + path_to_utf8(ffmpegPath) + "\" -version"; Process process(testCommand.c_str(), "r"); auto result = process.output_get_and_close(); @@ -289,7 +284,7 @@ namespace anm2ed::imgui::wizard auto png_format_valid_check = [&]() { - auto formatString = path::to_utf8(format); + auto formatString = path_to_utf8(format); if (!formatString.contains("{}")) { toast_log(Level::ERROR, TOAST_PNG_FORMAT_INVALID); @@ -310,7 +305,7 @@ namespace anm2ed::imgui::wizard auto png_directory_valid_check = [&]() { - if (!path::ensure_directory(path)) + if (!path_ensure_directory(path)) { toast_log(Level::ERROR, TOAST_PNG_DIRECTORY_INVALID); return false; @@ -332,18 +327,18 @@ namespace anm2ed::imgui::wizard switch (type) { - case render::PNGS: + case RENDER_PNGS: if (!png_format_valid_check()) return false; if (!png_directory_valid_check()) return false; - format.replace_extension(render::EXTENSIONS[render::SPRITESHEET]); + format.replace_extension(RENDER_EXTENSIONS[RENDER_SPRITESHEET]); break; - case render::SPRITESHEET: + case RENDER_SPRITESHEET: if (!spritesheet_valid_check()) return false; break; - case render::GIF: - case render::WEBM: - case render::OGV: - case render::MP4: + case RENDER_GIF: + case RENDER_WEBM: + case RENDER_OGV: + case RENDER_MP4: if (!ffmpeg_valid_check()) return false; break; default: @@ -367,7 +362,6 @@ namespace anm2ed::imgui::wizard ImGui::SameLine(); - imgui::shortcut(manager.chords[SHORTCUT_CANCEL]); + shortcut(manager.chords[SHORTCUT_CANCEL]); if (ImGui::Button(localize.get(BASIC_CANCEL), widgetSize)) isEnd = true; } -} diff --git a/src/ui/render_animation.h b/src/ui/render_animation.h index 77f20da..c2345a6 100644 --- a/src/ui/render_animation.h +++ b/src/ui/render_animation.h @@ -4,8 +4,6 @@ #include "manager.h" #include "resources.h" -namespace anm2ed::imgui::wizard -{ class RenderAnimation { @@ -17,4 +15,3 @@ namespace anm2ed::imgui::wizard void reset(Manager&, Document&, Settings&); void update(Manager&, Document&, Resources&, Settings&, Dialog&); }; -} diff --git a/src/ui/selectable.cpp b/src/ui/selectable.cpp index 3911f54..f360be8 100644 --- a/src/ui/selectable.cpp +++ b/src/ui/selectable.cpp @@ -4,8 +4,6 @@ #include "ui/input.h" -namespace anm2ed::imgui -{ bool isSelectableInputTextRenaming = false; std::string& selectable_input_text_id() @@ -64,4 +62,3 @@ namespace anm2ed::imgui return isActivated; } -} diff --git a/src/ui/selectable.h b/src/ui/selectable.h index 5f33544..6efda69 100644 --- a/src/ui/selectable.h +++ b/src/ui/selectable.h @@ -5,8 +5,6 @@ #include -namespace anm2ed::imgui -{ enum RenameState { RENAME_SELECTABLE, @@ -20,4 +18,3 @@ namespace anm2ed::imgui bool input_text_rename_update(std::string&, RenameState&, float = -FLT_MIN); bool selectable_input_text(const std::string&, const std::string&, std::string&, bool, ImGuiSelectableFlags, RenameState&); -} diff --git a/src/ui/shaders.cpp b/src/ui/shaders.cpp index 4be1c40..f5f7447 100644 --- a/src/ui/shaders.cpp +++ b/src/ui/shaders.cpp @@ -12,39 +12,27 @@ #include "ui/input.h" #include "ui/layout.h" -using namespace anm2ed::resource; -using namespace anm2ed::util; - -namespace anm2ed::imgui -{ constexpr int SHADER_CARD_LINES = 2; #define SHADER_UNIFORM_BINDING_COMBO_VALUES \ - X(resource::shader::UNIFORM_BINDING_IGNORE) \ - X(resource::shader::UNIFORM_BINDING_MANUAL) \ - X(resource::shader::UNIFORM_BINDING_COLOR_OFFSET) \ - X(resource::shader::UNIFORM_BINDING_FRAME_TINT) \ - X(resource::shader::UNIFORM_BINDING_MAIN_TEXTURE) \ - X(resource::shader::UNIFORM_BINDING_COMPONENTS) \ - X(resource::shader::UNIFORM_BINDING_PLAYBACK_TIME) \ - X(resource::shader::UNIFORM_BINDING_TEXTURE_SIZE) \ - X(resource::shader::UNIFORM_BINDING_TRANSFORM) + X(UNIFORM_BINDING_IGNORE) \ + X(UNIFORM_BINDING_MANUAL) \ + X(UNIFORM_BINDING_COLOR_OFFSET) \ + X(UNIFORM_BINDING_FRAME_TINT) \ + X(UNIFORM_BINDING_MAIN_TEXTURE) \ + X(UNIFORM_BINDING_COMPONENTS) \ + X(UNIFORM_BINDING_PLAYBACK_TIME) \ + X(UNIFORM_BINDING_TEXTURE_SIZE) \ + X(UNIFORM_BINDING_TRANSFORM) - inline constexpr resource::shader::UniformBinding SHADER_UNIFORM_BINDING_COMBO_ORDER[] = { + inline constexpr UniformBinding SHADER_UNIFORM_BINDING_COMBO_ORDER[] = { #define X(binding) binding, SHADER_UNIFORM_BINDING_COMBO_VALUES #undef X }; #undef SHADER_UNIFORM_BINDING_COMBO_VALUES - std::filesystem::path shader_absolute_path_get(Document& document, const std::filesystem::path& shaderPath) - { - auto loadPath = path::backslash_handle(shaderPath); - if (loadPath.empty() || loadPath.is_absolute()) return loadPath; - return document.directory_get() / loadPath; - } - - bool is_shader_reload_needed(Document& document, model::Shader* shader) + static bool is_shader_reload_needed(Document& document, Shader* shader) { if (!shader || shader->fragment.empty()) return false; if (!document.shader_get(shader->id)) return true; @@ -54,30 +42,30 @@ namespace anm2ed::imgui document.shaderFragmentPaths.at(shader->id) != shader->fragment; } - model::Shader* shader_element_get(Document& document, int id) + static Shader* shader_element_get(Document& document, int id) { - return model::item_get(document.model.content.shaders, id); + return item_get(document.model.content.shaders, id); } - std::filesystem::path shader_asset_path_get(Document& document, const std::filesystem::path& path) + static std::filesystem::path shader_asset_path_get(Document& document, const std::filesystem::path& path) { - auto loadPath = path::backslash_handle(path); - return path::backslash_replace(path::make_relative(loadPath, document.directory_get())); + auto loadPath = path_backslash_handle(path); + return path_backslash_replace(path_make_relative(loadPath, document.directory_get())); } - void shader_path_edit(Document& document, int shaderId, std::filesystem::path model::Shader::* member, + static void shader_path_edit(Document& document, int shaderId, std::filesystem::path Shader::* member, const std::filesystem::path& value) { auto shader = shader_element_get(document, shaderId); if (shader) { - shader->*member = path::backslash_replace(value); + shader->*member = path_backslash_replace(value); document.change(); } } - void shader_dialog_update(ShadersPanel& window, Manager& manager, Dialog& dialog, Dialog::Type type, - std::filesystem::path model::Shader::* member) + static void shader_dialog_update(ShadersPanel& window, Manager& manager, Dialog& dialog, Dialog::Type type, + std::filesystem::path Shader::* member) { if (!dialog.is_selected(type)) return; @@ -90,16 +78,16 @@ namespace anm2ed::imgui dialog.reset(); } - void shader_path_row_update(ShadersPanel& window, Document& document, Resources& resources, Dialog& dialog, - model::Shader* shader, std::filesystem::path model::Shader::* member, + static void shader_path_row_update(ShadersPanel& window, Document& document, Resources& resources, Dialog& dialog, + Shader* shader, std::filesystem::path Shader::* member, Dialog::Type dialogType, StringType label) { auto shaderPath = shader ? shader->*member : std::filesystem::path{}; auto isDefault = shaderPath.empty(); - auto displayPath = isDefault ? path::from_utf8(localize.get(BASIC_DEFAULT)) : shaderPath; + auto displayPath = isDefault ? path_from_utf8(localize.get(BASIC_DEFAULT)) : shaderPath; if (ImGui::ImageButton(std::format("##{} Path Set", localize.get(label)).c_str(), - resources.icon_id_get(icon::FOLDER), icon_size_get())) + resources.icon_id_get(ICON_FOLDER), icon_size_get())) { if (shader) { @@ -123,40 +111,40 @@ namespace anm2ed::imgui ImGui::TextUnformatted(localize.get(label)); } - void shader_uniform_config_save(Document& document, model::Shader& shaderElement, - const resource::shader::Uniform& uniform) + static void shader_uniform_config_save(Document& document, Shader& shaderElement, + const ShaderUniform& uniform) { - resource::shader::uniform_config_save(shaderElement, uniform); + uniform_config_save(shaderElement, uniform); document.change(); } - void shader_uniform_components_from_value_set(resource::shader::Uniform& uniform) + static void shader_uniform_components_from_value_set(ShaderUniform& uniform) { for (int i = 0; i < (int)uniform.components.size(); ++i) uniform.components[i].value = uniform.value[i]; } - void shader_uniform_value_from_components_set(resource::shader::Uniform& uniform) + static void shader_uniform_value_from_components_set(ShaderUniform& uniform) { for (int i = 0; i < (int)uniform.components.size(); ++i) uniform.value[i] = uniform.components[i].value; } - bool shader_uniform_value_update(resource::shader::Uniform& uniform) + static bool shader_uniform_value_update(ShaderUniform& uniform) { ImGui::SetNextItemWidth(-1.0f); switch (uniform.valueType) { - case resource::shader::UNIFORM_VALUE_FLOAT: + case UNIFORM_VALUE_FLOAT: return ImGui::DragFloat("##Value", &uniform.value.x, 0.01f); - case resource::shader::UNIFORM_VALUE_INT: - case resource::shader::UNIFORM_VALUE_SAMPLER2D: + case UNIFORM_VALUE_INT: + case UNIFORM_VALUE_SAMPLER2D: return ImGui::InputInt("##Value", &uniform.intValue); - case resource::shader::UNIFORM_VALUE_VEC2: + case UNIFORM_VALUE_VEC2: return ImGui::DragFloat2("##Value", &uniform.value.x, 0.01f); - case resource::shader::UNIFORM_VALUE_VEC3: + case UNIFORM_VALUE_VEC3: return ImGui::DragFloat3("##Value", &uniform.value.x, 0.01f); - case resource::shader::UNIFORM_VALUE_VEC4: + case UNIFORM_VALUE_VEC4: return ImGui::DragFloat4("##Value", &uniform.value.x, 0.01f); default: ImGui::TextUnformatted(localize.get(BASIC_NONE)); @@ -164,19 +152,19 @@ namespace anm2ed::imgui } } - bool shader_uniform_component_binding_update(resource::shader::Uniform::Component& component) + static bool shader_uniform_component_binding_update(ShaderUniform::Component& component) { - auto bindingLabel = resource::shader::uniform_binding_label_get(component.binding); + auto bindingLabel = uniform_binding_label_get(component.binding); ImGui::SetNextItemWidth(ImGui::GetFrameHeight() * 5.0f); if (!ImGui::BeginCombo("##Component Binding", bindingLabel.data())) return false; bool isChanged{}; - constexpr resource::shader::UniformBinding bindings[] = {resource::shader::UNIFORM_BINDING_MANUAL, - resource::shader::UNIFORM_BINDING_PLAYBACK_TIME}; + constexpr UniformBinding bindings[] = {UNIFORM_BINDING_MANUAL, + UNIFORM_BINDING_PLAYBACK_TIME}; for (auto binding : bindings) { auto isSelected = component.binding == binding; - auto label = resource::shader::uniform_binding_label_get(binding); + auto label = uniform_binding_label_get(binding); if (ImGui::Selectable(label.data(), isSelected)) { component.binding = binding; @@ -188,11 +176,11 @@ namespace anm2ed::imgui return isChanged; } - bool shader_uniform_components_update(resource::shader::Uniform& uniform) + static bool shader_uniform_components_update(ShaderUniform& uniform) { bool isChanged{}; constexpr const char* labels[] = {"X", "Y", "Z", "W"}; - auto componentCount = resource::shader::UNIFORM_VALUE_TYPE_INFOS[uniform.valueType].componentCount; + auto componentCount = UNIFORM_VALUE_TYPE_INFOS[uniform.valueType].componentCount; for (int index = 0; index < componentCount; ++index) { @@ -203,7 +191,7 @@ namespace anm2ed::imgui ImGui::SameLine(); if (shader_uniform_component_binding_update(component)) isChanged = true; ImGui::SameLine(); - ImGui::BeginDisabled(component.binding != resource::shader::UNIFORM_BINDING_MANUAL); + ImGui::BeginDisabled(component.binding != UNIFORM_BINDING_MANUAL); ImGui::SetNextItemWidth(-1.0f); if (ImGui::DragFloat("##Component Value", &component.value, 0.01f)) isChanged = true; ImGui::EndDisabled(); @@ -214,7 +202,7 @@ namespace anm2ed::imgui return isChanged; } - void shader_uniforms_update(Document& document, model::Shader* shaderElement, resource::Shader* runtime, + static void shader_uniforms_update(Document& document, Shader* shaderElement, ShaderProgram* runtime, ImVec2 tableSize) { if (!shaderElement) return; @@ -243,22 +231,22 @@ namespace anm2ed::imgui ImGui::TextUnformatted(uniform.name.c_str()); ImGui::TableNextColumn(); - ImGui::TextUnformatted(resource::shader::uniform_value_type_label_get(uniform.valueType).data()); + ImGui::TextUnformatted(uniform_value_type_label_get(uniform.valueType).data()); ImGui::TableNextColumn(); - auto bindingLabel = resource::shader::uniform_binding_label_get(uniform.binding); + auto bindingLabel = uniform_binding_label_get(uniform.binding); ImGui::SetNextItemWidth(-1.0f); if (ImGui::BeginCombo("##Binding", bindingLabel.data())) { for (auto binding : SHADER_UNIFORM_BINDING_COMBO_ORDER) { - if (!resource::shader::is_uniform_binding_valid(binding, uniform.valueType)) continue; + if (!is_uniform_binding_valid(binding, uniform.valueType)) continue; auto isSelected = uniform.binding == binding; - auto label = resource::shader::uniform_binding_label_get(binding); + auto label = uniform_binding_label_get(binding); if (ImGui::Selectable(label.data(), isSelected)) { uniform.binding = binding; - if (uniform.binding == resource::shader::UNIFORM_BINDING_COMPONENTS) + if (uniform.binding == UNIFORM_BINDING_COMPONENTS) shader_uniform_components_from_value_set(uniform); shader_uniform_config_save(document, *shaderElement, uniform); } @@ -268,13 +256,13 @@ namespace anm2ed::imgui } ImGui::TableNextColumn(); - if (uniform.binding == resource::shader::UNIFORM_BINDING_COMPONENTS) + if (uniform.binding == 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); + ImGui::BeginDisabled(uniform.binding != UNIFORM_BINDING_MANUAL); if (shader_uniform_value_update(uniform)) { shader_uniform_components_from_value_set(uniform); @@ -289,8 +277,6 @@ namespace anm2ed::imgui ImGui::EndTable(); } - auto& shaders_get(model::Model& model) { return model.content.shaders; } - void shaders_update(Panel& panel, ShadersPanel& shaders) { auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; @@ -298,8 +284,8 @@ namespace anm2ed::imgui auto& status = shaders.status; auto& propertiesPopup = shaders.propertiesPopup; auto& popupShaderId = shaders.popupShaderId; - shader_dialog_update(shaders, manager, dialog, Dialog::SHADER_VERTEX_PATH_SET, &model::Shader::vertex); - shader_dialog_update(shaders, manager, dialog, Dialog::SHADER_FRAGMENT_PATH_SET, &model::Shader::fragment); + shader_dialog_update(shaders, manager, dialog, Dialog::SHADER_VERTEX_PATH_SET, &Shader::vertex); + shader_dialog_update(shaders, manager, dialog, Dialog::SHADER_FRAGMENT_PATH_SET, &Shader::fragment); if (ImGui::Begin(localize.get(LABEL_SHADERS_WINDOW), &settings.windowIsShaders)) { @@ -321,10 +307,10 @@ namespace anm2ed::imgui { int id{}; document.edit_apply(EDIT_ADD_SHADER, - [&](model::Model& model) + [&](Model& model) { auto& shaders = model.content.shaders; - id = model::item_next_id_get(shaders); + id = item_next_id_get(shaders); shaders.push_back({.id = id, .name = localize.get(TEXT_NEW_SHADER)}); }); document.selected_ids_set(SelectionKind::SHADERS, {id}); @@ -351,7 +337,7 @@ namespace anm2ed::imgui auto image_get = [&](int id) { auto isValid = document.shader_get(id) != nullptr; - auto& image = resources.icons[isValid ? icon::SHADER : icon::NONE]; + auto& image = resources.icons[isValid ? ICON_SHADER : ICON_NONE]; return CardImage{.texture = &image, .size = glm::vec2(image.size), .isValid = isValid}; }; ListRows rows{.label_get = @@ -366,8 +352,8 @@ namespace anm2ed::imgui auto& shader = *shader_element_get(document, id); tooltip_name_draw(resources, shader.name); 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()); + 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 (image_get(id).isValid) return; ImGui::Spacing(); ImGui::TextWrapped("%s", localize.get(TOOLTIP_SHADER_INVALID)); @@ -401,9 +387,9 @@ namespace anm2ed::imgui ImGui::SeparatorText(localize.get(LABEL_FILES)); - shader_path_row_update(shaders, document, resources, dialog, shader, &model::Shader::vertex, + shader_path_row_update(shaders, document, resources, dialog, shader, &Shader::vertex, Dialog::SHADER_VERTEX_PATH_SET, LABEL_VERTEX); - shader_path_row_update(shaders, document, resources, dialog, shader, &model::Shader::fragment, + shader_path_row_update(shaders, document, resources, dialog, shader, &Shader::fragment, Dialog::SHADER_FRAGMENT_PATH_SET, LABEL_FRAGMENT); if (is_shader_reload_needed(document, shader)) @@ -446,4 +432,3 @@ namespace anm2ed::imgui } ImGui::End(); } -} diff --git a/src/ui/shaders.h b/src/ui/shaders.h index 9af14b3..3b19c9c 100644 --- a/src/ui/shaders.h +++ b/src/ui/shaders.h @@ -2,8 +2,6 @@ #include "ui/panel.h" -namespace anm2ed::imgui -{ struct ShadersPanel { PanelState state{}; @@ -14,4 +12,3 @@ namespace anm2ed::imgui }; void shaders_update(Panel&, ShadersPanel&); -} diff --git a/src/ui/shortcut.cpp b/src/ui/shortcut.cpp index 4af8596..aa32e99 100644 --- a/src/ui/shortcut.cpp +++ b/src/ui/shortcut.cpp @@ -6,8 +6,6 @@ #include -namespace anm2ed::imgui -{ const std::vector> CANONICAL_KEY_NAMES = { {ImGuiKey_A, "A"}, {ImGuiKey_B, "B"}, @@ -102,7 +100,7 @@ namespace anm2ed::imgui {ImGuiKey_GraveAccent, "GraveAccent"}, }; - const char* shortcut_canonical_key_name(ImGuiKey key) + static const char* shortcut_canonical_key_name(ImGuiKey key) { for (const auto& [mappedKey, name] : CANONICAL_KEY_NAMES) if (mappedKey == key) return name; @@ -156,19 +154,19 @@ namespace anm2ed::imgui return chord; } - bool shortcut(ImGuiKeyChord chord, types::shortcut::Type type) + bool shortcut(ImGuiKeyChord chord, ShortcutScope type) { if (chord == ImGuiKey_None) return false; if (ImGui::GetTopMostPopupModal() != nullptr && - (type == types::shortcut::GLOBAL || type == types::shortcut::GLOBAL_SET)) + (type == SCOPE_GLOBAL || type == SCOPE_GLOBAL_SET)) return false; - int flags = type == types::shortcut::GLOBAL || type == types::shortcut::GLOBAL_SET ? ImGuiInputFlags_RouteGlobal + int flags = type == SCOPE_GLOBAL || type == SCOPE_GLOBAL_SET ? ImGuiInputFlags_RouteGlobal : ImGuiInputFlags_RouteFocused; flags |= ImGuiInputFlags_Repeat; - if (type == types::shortcut::GLOBAL_SET || type == types::shortcut::FOCUSED_SET) + if (type == SCOPE_GLOBAL_SET || type == SCOPE_FOCUSED_SET) { ImGui::SetNextItemShortcut(chord, flags); return false; @@ -176,4 +174,3 @@ namespace anm2ed::imgui return ImGui::Shortcut(chord, flags); } -} diff --git a/src/ui/shortcut.h b/src/ui/shortcut.h index 33a4b5a..bd735e9 100644 --- a/src/ui/shortcut.h +++ b/src/ui/shortcut.h @@ -7,8 +7,6 @@ #include "types.h" -namespace anm2ed::imgui -{ inline const std::unordered_map KEY_MAP = { {"A", ImGuiKey_A}, {"B", ImGuiKey_B}, @@ -133,5 +131,4 @@ namespace anm2ed::imgui std::string chord_to_string(ImGuiKeyChord); ImGuiKeyChord string_to_chord(const std::string&); - bool shortcut(ImGuiKeyChord, types::shortcut::Type = types::shortcut::FOCUSED_SET); -} + bool shortcut(ImGuiKeyChord, ShortcutScope = SCOPE_FOCUSED_SET); diff --git a/src/ui/sounds.cpp b/src/ui/sounds.cpp index c559738..9250b2d 100644 --- a/src/ui/sounds.cpp +++ b/src/ui/sounds.cpp @@ -4,15 +4,9 @@ #include "path.h" -using namespace anm2ed::resource; -using namespace anm2ed::types; -using namespace anm2ed::util; - -namespace anm2ed::imgui -{ constexpr int SOUND_CARD_LINES = 2; - auto& sounds_get(model::Model& model) { return model.content.sounds; } + static auto& sounds_get(Model& model) { return model.content.sounds; } void sounds_update(Panel& panel) { @@ -37,15 +31,15 @@ namespace anm2ed::imgui command_push(panel, [id = *selection.begin(), dialogPath = dialog.path](Document& document) { - if (!model::item_get(document.model.content.sounds, id)) return; + if (!item_get(document.model.content.sounds, id)) return; document.edit_apply(EDIT_REPLACE_SOUND, - [&](model::Model& model) + [&](Model& model) { - auto sound = model::item_get(model.content.sounds, id); + auto sound = item_get(model.content.sounds, id); sound->path = asset_path_get(document, dialogPath); document.sound_reload(id); toast_log(Level::INFO, TOAST_REPLACE_SOUND, id, - path::to_utf8(sound->path)); + path_to_utf8(sound->path)); }); }); dialog.reset(); @@ -56,11 +50,11 @@ namespace anm2ed::imgui auto isOne = [selection]() { return selection.size() == 1; }; auto play = [&](int id) { - if (auto audio = document.sound_get(id)) resource::audio::play(*audio); + if (auto audio = document.sound_get(id)) audio_play(*audio); }; auto open = [&](int id) { - if (auto sound = model::item_get(sounds, id)) directory_open(dialog, document, sound->path); + if (auto sound = item_get(sounds, id)) directory_open(dialog, document, sound->path); }; Actions actions{}; @@ -76,34 +70,34 @@ namespace anm2ed::imgui [selection](Document& document) { document.edit_apply(EDIT_RELOAD_SOUNDS, - [&](model::Model& model) + [&](Model& model) { for (auto id : selection) - if (auto sound = model::item_get(model.content.sounds, id)) + if (auto sound = item_get(model.content.sounds, id)) { document.sound_reload(id); toast_log(Level::INFO, TOAST_RELOAD_SOUND, id, - path::to_utf8(sound->path)); + path_to_utf8(sound->path)); } }); }); }, TOOLTIP_RELOAD_SOUNDS); actions.add(ACTION_REPLACE, isOne, [&]() { dialog.file_open(Dialog::SOUND_REPLACE); }, TOOLTIP_REPLACE_SOUND); - items_clipboard_actions_add(actions, panel, SelectionKind::SOUNDS, TOAST_SOUNDS_PASTE, + items_clipboard_actions_add(actions, panel, SelectionKind::SOUNDS, TOAST_SOUNDS_PASTE, TOAST_SOUNDS_DESERIALIZE_ERROR, sounds_get); ListRows rows{.label_get = [&](int id) { - auto pathString = path::to_utf8(model::item_get(sounds, id)->path); + auto pathString = path_to_utf8(item_get(sounds, id)->path); return std::vformat(localize.get(FORMAT_SOUND), std::make_format_args(id, pathString)); }, .tooltip_draw = [&](int id) { auto audio = document.sound_get(id); - tooltip_name_draw(resources, path::to_utf8(model::item_get(sounds, id)->path)); + tooltip_name_draw(resources, path_to_utf8(item_get(sounds, id)->path)); ImGui::Text("%s: %d", localize.get(BASIC_ID), id); if (audio && audio->is_valid()) ImGui::TextUnformatted(localize.get(TEXT_OPEN_DIRECTORY)); @@ -118,7 +112,7 @@ namespace anm2ed::imgui { auto audio = document.sound_get(id); auto isValid = audio && audio->is_valid(); - auto& texture = resources.icons[isValid ? icon::SOUND : icon::NONE]; + auto& texture = resources.icons[isValid ? ICON_SOUND : ICON_NONE]; return CardImage{.texture = &texture, .size = glm::vec2(texture.size), .isValid = isValid}; }, .select = @@ -134,4 +128,3 @@ namespace anm2ed::imgui } ImGui::End(); } -} diff --git a/src/ui/spritesheet_editor.cpp b/src/ui/spritesheet_editor.cpp index 143a406..5f5d32c 100644 --- a/src/ui/spritesheet_editor.cpp +++ b/src/ui/spritesheet_editor.cpp @@ -19,13 +19,8 @@ #include "ui/layout.h" #include "ui/shortcut.h" -using namespace anm2ed::types; -using namespace anm2ed::resource; -using namespace anm2ed::util; using namespace glm; -namespace anm2ed::imgui -{ void SpritesheetEditor::update(Manager& manager, Settings& settings, Resources& resources) { isFocused = false; @@ -45,14 +40,14 @@ namespace anm2ed::imgui auto& isGridSnap = settings.editorIsGridSnap; auto& isBorder = settings.editorIsBorder; auto& isTransparent = settings.editorIsTransparent; - auto spritesheet = model::item_get(model.content.spritesheets, referenceSpritesheet); + auto spritesheet = item_get(model.content.spritesheets, referenceSpritesheet); auto baseTexture = document.texture_get(referenceSpritesheet); auto texture = baseTexture; auto& tool = settings.tool; - auto& shaderGrid = resources.shaders[shader::GRID]; - auto& shaderTexture = resources.shaders[shader::TEXTURE]; - auto& shaderLine = resources.shaders[shader::LINE]; - auto& dashedShader = resources.shaders[shader::DASHED]; + auto& shaderGrid = resources.shaders[SHADER_GRID]; + auto& shaderTexture = resources.shaders[SHADER_TEXTURE]; + auto& shaderLine = resources.shaders[SHADER_LINE]; + auto& dashedShader = resources.shaders[SHADER_DASHED]; auto regionReference = document.focused_id_get(SelectionKind::REGIONS); auto regionSelection = document.selected_ids_get(SelectionKind::REGIONS); @@ -65,13 +60,13 @@ namespace anm2ed::imgui set_to_rect(zoom, pan, {0, 0, (float)fitTexture->size.x, (float)fitTexture->size.y}); }; - auto region_get = [&](int id) { return spritesheet ? model::item_get(spritesheet->regions, id) : nullptr; }; + auto region_get = [&](int id) { return spritesheet ? item_get(spritesheet->regions, id) : nullptr; }; if (ImGui::Begin(localize.get(LABEL_SPRITESHEET_EDITOR_WINDOW), &settings.windowIsSpritesheetEditor)) { isFocused = ImGui::IsWindowFocused(ImGuiFocusedFlags_RootAndChildWindows); - auto childSize = ImVec2(imgui::row_widget_width_get(3), + auto childSize = ImVec2(row_widget_width_get(3), (ImGui::GetTextLineHeightWithSpacing() * 4) + (ImGui::GetStyle().WindowPadding.y * 2)); grid_child_draw(childSize, isGrid, gridColor, gridSize, gridOffset, &isGridSnap); @@ -152,7 +147,7 @@ namespace anm2ed::imgui if (!selectedFrameReferences.contains(reference) && !selectedFrameReferences.empty()) editReference = *selectedFrameReferences.begin(); auto frame = model.frame_get(editReference); - auto layer = model::item_get(model.content.layers, editReference.itemID); + auto layer = item_get(model.content.layers, editReference.itemID); bool isReferenceLayerOnSpritesheet = frame && editReference.itemID > -1 && layer && layer->spritesheetId == referenceSpritesheet; if (selectedFrameReferences.empty() && isReferenceLayerOnSpritesheet) @@ -163,34 +158,34 @@ namespace anm2ed::imgui auto pivot_snap = [&](vec2 value, vec2 current) { return isGridSnap ? vec2(ivec2(value)) : glm::floor(value) + (current - glm::floor(current)); }; // Region edits apply to the given regions of the edited spritesheet when the command runs. - auto regions_update = [&](std::set ids, std::function update) + auto regions_update = [&](std::set ids, std::function update) { manager.command_push( {manager.selected, [=, spritesheetId = referenceSpritesheet](Manager&, Document& document) { - auto spritesheet = model::item_get(document.model.content.spritesheets, spritesheetId); + auto spritesheet = item_get(document.model.content.spritesheets, spritesheetId); for (auto id : ids) - if (auto region = spritesheet ? model::item_get(spritesheet->regions, id) : nullptr) update(*region); + if (auto region = spritesheet ? item_get(spritesheet->regions, id) : nullptr) update(*region); }}); }; auto region_pivot_update = [&](std::function pivot_get) { regions_update({regionReference}, - [=](model::Region& region) + [=](Region& region) { region.origin = Origin::CUSTOM; region.pivot = pivot_get(region.pivot); }); }; - auto useTool = (tool::Type)tool; - if (input.isMiddleDown) useTool = tool::PAN; - if (tool == tool::MOVE && input.isRightDown) useTool = tool::CROP; - if (tool == tool::CROP && input.isRightDown) useTool = tool::MOVE; - if (tool == tool::DRAW && input.isRightDown) useTool = tool::ERASE; - if (tool == tool::ERASE && input.isRightDown) useTool = tool::DRAW; + auto useTool = (Tool)tool; + if (input.isMiddleDown) useTool = TOOL_PAN; + if (tool == TOOL_MOVE && input.isRightDown) useTool = TOOL_CROP; + if (tool == TOOL_CROP && input.isRightDown) useTool = TOOL_MOVE; + if (tool == TOOL_DRAW && input.isRightDown) useTool = TOOL_ERASE; + if (tool == TOOL_ERASE && input.isRightDown) useTool = TOOL_DRAW; - if (useTool == tool::PAN && spritesheet && texture && texture->is_valid()) + if (useTool == TOOL_PAN && spritesheet && texture && texture->is_valid()) for (auto& region : spritesheet->regions) { auto minPoint = glm::min(region.crop, region.crop + region.size); @@ -206,21 +201,21 @@ namespace anm2ed::imgui auto isRegionEditTarget = document.editTarget == Document::EditTarget::REGION; auto toolFrames = isRegionEditTarget ? std::set{} : selectedFrameReferences; bool isRegionInUse = !isRegionEditTarget && toolFrames.size() <= 1 && frame && frame->regionId != -1 && - (useTool == tool::CROP || useTool == tool::MOVE); + (useTool == TOOL_CROP || useTool == TOOL_MOVE); auto isRegionTool = isRegionEditTarget || isRegionInUse || toolFrames.empty(); auto isFrameTool = frame && !toolFrames.empty() && !isRegionInUse; - bool isFrameAvailable = isFrameTool || (useTool == tool::CROP && !regionSelection.empty()) || - (useTool == tool::MOVE && regionReference != -1); + bool isFrameAvailable = isFrameTool || (useTool == TOOL_CROP && !regionSelection.empty()) || + (useTool == TOOL_MOVE && regionReference != -1); auto frames_change = [&](FrameChange change, ChangeType type = ChangeType::ADJUST) { frames_change_push(manager, toolFrames, change, type); }; - tool_cursor_update(useTool, tool::SPRITESHEET_EDITOR, isFrameAvailable, texture && texture->is_valid(), + tool_cursor_update(useTool, TOOL_AREA_SPRITESHEET_EDITOR, isFrameAvailable, texture && texture->is_valid(), isMouseDown || input.isArrowDown, isRegionInUse ? TEXT_REGION_IN_USE - : useTool == tool::CROP ? TEXT_SELECT_FRAME_OR_REGION + : useTool == TOOL_CROP ? TEXT_SELECT_FRAME_OR_REGION : TEXT_SELECT_FRAME); - if (useTool == tool::PAN) + if (useTool == TOOL_PAN) { if (input.isLeftClicked && hoveredRegionId != -1) { @@ -247,7 +242,7 @@ namespace anm2ed::imgui } auto region = isRegionTool ? region_get(regionReference) : nullptr; - if (useTool == tool::MOVE && region) + if (useTool == TOOL_MOVE && region) { if (isBegin) edit_begin_push(manager, EDIT_REGION_MOVE); if (isMouseDown) @@ -258,7 +253,7 @@ namespace anm2ed::imgui if (isDuring) tooltip_lines_draw({localize_format(FORMAT_PIVOT, region->pivot.x, region->pivot.y)}); if (isEnd) document_change_push(manager); } - else if (useTool == tool::MOVE && isFrameTool) + else if (useTool == TOOL_MOVE && isFrameTool) { if (isBegin) edit_begin_push(manager, EDIT_FRAME_PIVOT); if (isMouseDown) @@ -272,14 +267,14 @@ namespace anm2ed::imgui } auto isRegionCrop = isRegionTool && !regionSelection.empty() && spritesheet; - if (useTool == tool::CROP && (isRegionCrop || isFrameTool)) + if (useTool == TOOL_CROP && (isRegionCrop || isFrameTool)) { if (isBegin) edit_begin_push(manager, isRegionCrop ? EDIT_REGION_CROP : EDIT_FRAME_CROP); auto rect_set = [&](vec2 crop, vec2 cropSize) { if (isRegionCrop) regions_update(regionSelection, - [=](model::Region& region) + [=](Region& region) { region.crop = crop; region.size = cropSize; @@ -304,7 +299,7 @@ namespace anm2ed::imgui } if (isArrow && isRegionCrop) regions_update(regionSelection, - [=](model::Region& region) + [=](Region& region) { region.crop = vec2(ivec2(region.crop + gridArrow)); region.size = vec2(ivec2(region.size)); @@ -315,7 +310,7 @@ namespace anm2ed::imgui // Arrow nudges are snapped (and the rectangle normalized) when the command runs, after the nudge. if (isDuring && !isMouseDown && isRegionCrop) regions_update(regionSelection, - [=, this](model::Region& region) + [=, this](Region& region) { auto [minPoint, maxPoint] = rect_snap(region.crop, region.crop + region.size, isGridSnap, gridSize, gridOffset); @@ -329,7 +324,7 @@ namespace anm2ed::imgui if (!source) return; auto [minPoint, maxPoint] = rect_snap(source->crop, source->crop + source->size, isGridSnap, gridSize, gridOffset); - edit::frames_change_apply(document.model, {.references = toolFrames}, + frames_change_apply(document.model, {.references = toolFrames}, {.regionId = -1, .cropX = minPoint.x, .cropY = minPoint.y, @@ -347,7 +342,7 @@ namespace anm2ed::imgui if (isEnd) document_change_push(manager); } - auto isDrawTool = useTool == tool::DRAW || useTool == tool::ERASE; + auto isDrawTool = useTool == TOOL_DRAW || useTool == TOOL_ERASE; if (isDrawTool && texture && texture->is_vector()) { ImGui::SetMouseCursor(ImGuiMouseCursor_NotAllowed); @@ -355,10 +350,10 @@ namespace anm2ed::imgui } else if (isDrawTool && texture) { - if (isMouseClicked) edit_begin_push(manager, useTool == tool::DRAW ? EDIT_DRAW : EDIT_ERASE); + if (isMouseClicked) edit_begin_push(manager, useTool == TOOL_DRAW ? EDIT_DRAW : EDIT_ERASE); if (isMouseDown) manager.command_push({manager.selected, [start = ivec2(previousMousePos), end = ivec2(mousePos), - color = useTool == tool::DRAW ? toolColor : vec4(), + color = useTool == TOOL_DRAW ? toolColor : vec4(), spritesheetId = referenceSpritesheet](Manager&, Document& document) { if (auto texture = document.texture_edit(spritesheetId)) @@ -369,7 +364,7 @@ namespace anm2ed::imgui { document.texture_change(spritesheetId); }}); } - if (useTool == tool::COLOR_PICKER && texture && isDuring) + if (useTool == TOOL_COLOR_PICKER && texture && isDuring) { toolColor = texture->pixel_read(mousePos); if (ImGui::BeginTooltip()) @@ -385,10 +380,10 @@ namespace anm2ed::imgui } } - if (tool == tool::PAN && hoveredRegionId != -1 && spritesheet) + if (tool == TOOL_PAN && hoveredRegionId != -1 && spritesheet) if (auto region = region_get(hoveredRegionId); region && ImGui::BeginTooltip()) { - ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); + ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE); ImGui::TextUnformatted(region->name.c_str()); ImGui::PopFont(); auto originLabel = localize.get(region->origin == Origin::TOP_LEFT ? LABEL_REGION_ORIGIN_TOP_LEFT @@ -422,32 +417,32 @@ namespace anm2ed::imgui { auto transform = transform_get(zoom, pan); - auto spritesheetModel = math::quad_model_get(viewTexture->size); + auto spritesheetModel = quad_model_get(viewTexture->size); auto spritesheetTransform = transform * spritesheetModel; if (baseTexture && baseTexture->is_valid()) texture_render( shaderTexture, - resource::texture::id_get(*document.vector_image_get(baseTexture, math::percent_to_unit(zoom))), + texture_id_get(*document.vector_image_get(baseTexture, percent_to_unit(zoom))), spritesheetTransform); if (isGrid) grid_render(shaderGrid, zoom, pan, gridSize, gridOffset, gridColor); if (isBorder) - rect_render(dashedShader, spritesheetTransform, spritesheetModel, color::WHITE, BORDER_DASH_LENGTH, + rect_render(dashedShader, spritesheetTransform, spritesheetModel, COLOR_WHITE, BORDER_DASH_LENGTH, BORDER_DASH_GAP, BORDER_DASH_OFFSET); if (hoveredRegionId != -1) { if (auto region = region_get(hoveredRegionId)) { - auto cropModel = math::quad_model_get(region->size, region->crop); + auto cropModel = quad_model_get(region->size, region->crop); auto cropTransform = transform * cropModel; rect_fill_render(shaderLine, cropTransform, cropModel, vec4(1.0f, 1.0f, 1.0f, 0.5f)); } } - auto layer = model::item_get(model.content.layers, reference.itemID); + auto layer = item_get(model.content.layers, reference.itemID); bool isReferenceLayerOnSpritesheet = frame && reference.itemID > -1 && layer && layer->spritesheetId == referenceSpritesheet; @@ -465,9 +460,9 @@ namespace anm2ed::imgui highlightedRegionId = regionReference; } - auto draw_region_rect = [&](const model::Region& region, vec4 regionColor) + auto draw_region_rect = [&](const Region& region, vec4 regionColor) { - auto cropModel = math::quad_model_get(region.size, region.crop); + auto cropModel = quad_model_get(region.size, region.crop); auto cropTransform = transform * cropModel; rect_render(dashedShader, cropTransform, cropModel, regionColor, BORDER_DASH_LENGTH, BORDER_DASH_GAP, BORDER_DASH_OFFSET); @@ -477,35 +472,35 @@ namespace anm2ed::imgui { auto id = region.id; if (id == highlightedRegionId) continue; - draw_region_rect(region, color::WHITE); + draw_region_rect(region, COLOR_WHITE); auto pivotTransform = - transform * math::quad_model_get(PIVOT_SIZE, region.crop + region.pivot, PIVOT_SIZE * 0.5f); - texture_render(shaderTexture, resources.icon_id_get(icon::PIVOT), pivotTransform, color::WHITE); + transform * quad_model_get(PIVOT_SIZE, region.crop + region.pivot, PIVOT_SIZE * 0.5f); + texture_render(shaderTexture, resources.icon_id_get(ICON_PIVOT), pivotTransform, COLOR_WHITE); } if (highlightedRegionId != -1) { if (auto region = region_get(highlightedRegionId)) { - draw_region_rect(*region, color::RED); + draw_region_rect(*region, COLOR_RED); auto pivotTransform = - transform * math::quad_model_get(PIVOT_SIZE, region->crop + region->pivot, PIVOT_SIZE * 0.5f); - texture_render(shaderTexture, resources.icon_id_get(icon::PIVOT), pivotTransform, PIVOT_COLOR); + transform * quad_model_get(PIVOT_SIZE, region->crop + region->pivot, PIVOT_SIZE * 0.5f); + texture_render(shaderTexture, resources.icon_id_get(ICON_PIVOT), pivotTransform, PIVOT_COLOR); } } bool isFrameOnSpritesheet = isReferenceLayerOnSpritesheet; if (isFrameOnSpritesheet && frame->regionId == -1) { - auto frameModel = math::quad_model_get(frame->size, frame->crop); + auto frameModel = quad_model_get(frame->size, frame->crop); auto frameTransform = transform * frameModel; - rect_render(shaderLine, frameTransform, frameModel, color::RED); + rect_render(shaderLine, frameTransform, frameModel, COLOR_RED); auto pivotTransform = - transform * math::quad_model_get(PIVOT_SIZE, frame->crop + frame->pivot, PIVOT_SIZE * 0.5f); - texture_render(shaderTexture, resources.icon_id_get(icon::PIVOT), pivotTransform, PIVOT_COLOR); + transform * quad_model_get(PIVOT_SIZE, frame->crop + frame->pivot, PIVOT_SIZE * 0.5f); + texture_render(shaderTexture, resources.icon_id_get(ICON_PIVOT), pivotTransform, PIVOT_COLOR); } } @@ -519,7 +514,7 @@ namespace anm2ed::imgui image_premultiplied_draw(this->texture, to_imvec2(size)); } - if (tool == tool::PAN) + if (tool == TOOL_PAN) view_context_menu_draw("##Spritesheet Editor Context Menu", manager, settings, document, zoom, pan, center_view, fit_view, (baseTexture && baseTexture->is_valid()) || (texture && texture->is_valid())); @@ -538,4 +533,3 @@ namespace anm2ed::imgui ImGui::End(); } -} diff --git a/src/ui/spritesheet_editor.h b/src/ui/spritesheet_editor.h index 909afa7..f3cf2be 100644 --- a/src/ui/spritesheet_editor.h +++ b/src/ui/spritesheet_editor.h @@ -5,8 +5,6 @@ #include "resources.h" #include "settings.h" -namespace anm2ed::imgui -{ class SpritesheetEditor : public CanvasView { glm::vec2 previousMousePos{}; @@ -16,4 +14,3 @@ namespace anm2ed::imgui public: void update(Manager&, Settings&, Resources&); }; -} diff --git a/src/ui/spritesheets.cpp b/src/ui/spritesheets.cpp index a1afd3b..96cb9ef 100644 --- a/src/ui/spritesheets.cpp +++ b/src/ui/spritesheets.cpp @@ -7,41 +7,35 @@ #include "ui/layout.h" #include "working_directory.h" -using namespace anm2ed::resource; -using namespace anm2ed::types; -using namespace anm2ed::util; - -namespace anm2ed::imgui -{ constexpr int SPRITESHEET_CARD_LINES = 4; constexpr int MERGE_OPTIONS_ROWS = 6; constexpr int PADDING_MAX = 100; // The merge region origin setting indexes this (top-left or center). constexpr Origin MERGE_REGION_ORIGINS[] = {Origin::TOP_LEFT, Origin::CENTER}; - auto& spritesheets_get(model::Model& model) { return model.content.spritesheets; } + static auto& spritesheets_get(Model& model) { return model.content.spritesheets; } - const model::Spritesheet* spritesheet_get(Document& document, int id) + static const Spritesheet* spritesheet_get(Document& document, int id) { - return model::item_get(document.model.content.spritesheets, id); + return item_get(document.model.content.spritesheets, id); } - bool is_spritesheet_regions(Document& document, int id) + static bool is_spritesheet_regions(Document& document, int id) { auto spritesheet = spritesheet_get(document, id); return spritesheet && !spritesheet->regions.empty(); } - void spritesheets_save(Document& document, const std::set& ids) + static void spritesheets_save(Document& document, const std::set& ids) { for (auto id : ids) { auto spritesheet = spritesheet_get(document, id); auto texture = document.texture_get(id); if (!spritesheet || !texture) continue; - auto pathString = path::to_utf8(spritesheet->path); + auto pathString = path_to_utf8(spritesheet->path); WorkingDirectory workingDirectory(document.directory_get()); - path::ensure_directory(spritesheet->path.parent_path()); + path_ensure_directory(spritesheet->path.parent_path()); auto isSaved = texture->write(spritesheet->path); if (isSaved) document.spritesheet_hash_set_saved(id); toast_log(isSaved ? Level::INFO : Level::ERROR, isSaved ? TOAST_SAVE_SPRITESHEET : TOAST_SAVE_SPRITESHEET_FAILED, @@ -50,21 +44,21 @@ namespace anm2ed::imgui } // Points a spritesheet at a new file: replacing loads it, setting the path writes the current texture there. - void spritesheet_path_change(Document& document, int id, const std::filesystem::path& dialogPath, StringType edit, + static void spritesheet_path_change(Document& document, int id, const std::filesystem::path& dialogPath, StringType edit, bool isWritten) { auto texture = document.texture_get(id); if (!spritesheet_get(document, id) || (isWritten && !texture)) return; document.edit_apply(edit, - [&](model::Model& model) + [&](Model& model) { - auto spritesheet = model::item_get(model.content.spritesheets, id); + auto spritesheet = item_get(model.content.spritesheets, id); auto newPath = asset_path_get(document, dialogPath); - auto pathString = path::to_utf8(newPath); + auto pathString = path_to_utf8(newPath); if (isWritten) { WorkingDirectory workingDirectory(document.directory_get()); - path::ensure_directory(newPath.parent_path()); + path_ensure_directory(newPath.parent_path()); if (!texture->write(newPath)) return toast_log(Level::ERROR, TOAST_SAVE_SPRITESHEET_FAILED, id, pathString); } @@ -79,7 +73,7 @@ namespace anm2ed::imgui }); } - void spritesheet_textures_edit(Document& document, StringType edit, const std::function& behavior, + static void spritesheet_textures_edit(Document& document, StringType edit, const std::function& behavior, StringType successToast, StringType failToast) { document.edit_begin(edit); @@ -88,7 +82,7 @@ namespace anm2ed::imgui document.change(); } - void spritesheets_dialog_update(Panel& panel) + static void spritesheets_dialog_update(Panel& panel) { auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; if (dialog.is_selected(Dialog::SPRITESHEET_OPEN)) @@ -116,7 +110,7 @@ namespace anm2ed::imgui } } - void spritesheets_merge_popup_update(Panel& panel, SpritesheetsPanel& spritesheets) + static void spritesheets_merge_popup_update(Panel& panel, SpritesheetsPanel& spritesheets) { auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; auto& popup = spritesheets.mergePopup; @@ -179,7 +173,7 @@ namespace anm2ed::imgui popup.end(); } - void spritesheets_pack_popup_update(Panel& panel, SpritesheetsPanel& spritesheets) + static void spritesheets_pack_popup_update(Panel& panel, SpritesheetsPanel& spritesheets) { auto& [manager, settings, resources, dialog, clipboard, document, state] = panel; auto& popup = spritesheets.packPopup; @@ -206,7 +200,7 @@ namespace anm2ed::imgui popup.end(); } - void spritesheets_overwrite_popup_update(Panel& panel, SpritesheetsPanel& spritesheets) + static void spritesheets_overwrite_popup_update(Panel& panel, SpritesheetsPanel& spritesheets) { auto& popup = spritesheets.overwritePopup; popup.trigger(); @@ -290,7 +284,7 @@ namespace anm2ed::imgui spritesheets.overwritePopup.open(); }, TOOLTIP_SAVE_SPRITESHEETS); - items_clipboard_actions_add(actions, panel, SelectionKind::SPRITESHEETS, + items_clipboard_actions_add(actions, panel, SelectionKind::SPRITESHEETS, EDIT_PASTE_SPRITESHEETS, TOAST_DESERIALIZE_SPRITESHEETS_FAILED, spritesheets_get); @@ -298,14 +292,14 @@ namespace anm2ed::imgui { auto texture = document.texture_get(id); auto isValid = texture && texture->is_valid(); - auto& image = isValid ? *texture : resources.icons[icon::NONE]; + auto& image = isValid ? *texture : resources.icons[ICON_NONE]; return CardImage{.texture = &image, .size = glm::vec2(image.size), .isValid = isValid}; }; ListRows rows{ .label_get = [&](int id) { - auto pathString = path::to_utf8(spritesheet_get(document, id)->path); + auto pathString = path_to_utf8(spritesheet_get(document, id)->path); auto label = std::vformat(localize.get(FORMAT_SPRITESHEET), std::make_format_args(id, pathString)); return document.spritesheet_is_dirty(id) ? std::vformat(localize.get(FORMAT_SPRITESHEET_NOT_SAVED), std::make_format_args(label)) @@ -318,7 +312,7 @@ namespace anm2ed::imgui tooltip_image_draw(image, [&]() { - tooltip_name_draw(resources, path::to_utf8(spritesheet_get(document, id)->path)); + tooltip_name_draw(resources, path_to_utf8(spritesheet_get(document, id)->path)); ImGui::TextUnformatted( std::vformat(localize.get(FORMAT_ID), std::make_format_args(id)).c_str()); if (image.isValid) @@ -350,4 +344,3 @@ namespace anm2ed::imgui spritesheets_pack_popup_update(panel, spritesheets); spritesheets_overwrite_popup_update(panel, spritesheets); } -} diff --git a/src/ui/taskbar.cpp b/src/ui/taskbar.cpp index 5975e94..604571a 100644 --- a/src/ui/taskbar.cpp +++ b/src/ui/taskbar.cpp @@ -18,13 +18,8 @@ #include "ui/layout.h" #include "ui/shortcut.h" -using namespace anm2ed::resource; -using namespace anm2ed::types; -using namespace anm2ed::util; using namespace glm; -namespace anm2ed::imgui -{ constexpr auto GENERATE_REGIONS_TARGET_SELECTION = 0; constexpr auto GENERATE_REGIONS_TARGET_ALL = 1; @@ -52,7 +47,7 @@ namespace anm2ed::imgui { // Rebirth can't load SVG spritesheets: offer to convert them (the request waits in isaacSave either way). if (!settings.fileIsJson && !document->isVectorKept && - !model::spritesheets_vector_used_get(document->model).empty()) + !spritesheets_vector_used_get(document->model).empty()) { isaacSave = request; vectorPopup.open(); @@ -60,7 +55,7 @@ namespace anm2ed::imgui } // The game can't read JSON, or its copy would differ from the document: ask first. if (settings.fileIsWarnIsaac && - (settings.fileIsJson || model::isaac_issues_get(document->model) != model::IsaacIssues{})) + (settings.fileIsJson || isaac_issues_get(document->model) != IsaacIssues{})) { isaacSave = request; isaacPopup.open(); @@ -104,8 +99,8 @@ namespace anm2ed::imgui for (auto [i, file] : std::views::enumerate(recentFiles)) { ImGui::PushID((int)i); - auto fileNameUtf8 = path::to_utf8(file.filename()); - auto filePathUtf8 = path::to_utf8(file); + auto fileNameUtf8 = path_to_utf8(file.filename()); + auto filePathUtf8 = path_to_utf8(file); auto label = std::format(FILE_LABEL_FORMAT, fileNameUtf8, filePathUtf8); if (ImGui::MenuItem(label.c_str())) manager.command_push({.runManager = [file](Manager& manager) { manager.open(file); }}); @@ -175,7 +170,7 @@ namespace anm2ed::imgui manager.command_push({manager.selected, [](Manager&, Document& document) { document.edit_apply(EDIT_SCAN_AND_SET_REGIONS, - [](model::Model& model) { return edit::regions_scan(model); }); + [](Model& model) { return regions_scan(model); }); }}); toast_log(Level::INFO, TOAST_SCAN_AND_SET_REGIONS); } @@ -217,7 +212,7 @@ namespace anm2ed::imgui for (int i = 0; i < WINDOW_COUNT; i++) { auto member = WINDOW_MEMBERS[i]; - ImGui::MenuItem(localize.get(::anm2ed::WINDOW_STRING_TYPES[i]), nullptr, &(settings.*member)); + ImGui::MenuItem(localize.get(WINDOW_STRING_TYPES[i]), nullptr, &(settings.*member)); } ImGui::EndMenu(); @@ -286,9 +281,9 @@ namespace anm2ed::imgui { if (queuedAnimationIndices.empty()) return; document.edit_apply(EDIT_GENERATE_REGIONS_FROM_ANIMATIONS, - [&](model::Model& model) + [&](Model& model) { - return edit::regions_generate(model, queuedAnimationIndices, {}, + return regions_generate(model, queuedAnimationIndices, {}, queuedFormat, queuedMapping); }); }}); @@ -347,7 +342,7 @@ namespace anm2ed::imgui } if (auto* music = resources.music_track_if_loaded()) - if (resource::audio::is_playing(*music) && !aboutPopup.isOpen) resource::audio::stop(*music); + if (is_audio_playing(*music) && !aboutPopup.isOpen) audio_stop(*music); overwritePopup.trigger(); @@ -384,7 +379,7 @@ namespace anm2ed::imgui shortcut(manager.chords[isConverted ? SHORTCUT_CONFIRM : SHORTCUT_CANCEL]); if (!ImGui::Button(localize.get(label), widgetSize) || !document) continue; if (isConverted) - document->spritesheets_vector_convert(model::spritesheets_vector_used_get(document->model)); + document->spritesheets_vector_convert(spritesheets_vector_used_get(document->model)); else document->isVectorKept = true; vectorPopup.close(); @@ -402,7 +397,7 @@ namespace anm2ed::imgui else if (auto document = manager.get(isaacSave.index)) { ImGui::TextWrapped("%s", localize.get(TEXT_ISAAC_ISSUES)); - auto issues = model::isaac_issues_get(document->model); + auto issues = isaac_issues_get(document->model); for (auto [count, format] : {std::pair{issues.easedFrames, FORMAT_ISAAC_EASED_FRAMES}, {issues.groupTransforms, FORMAT_ISAAC_GROUP_TRANSFORMS}, {issues.animationLayers, FORMAT_ISAAC_ANIMATION_LAYERS}, @@ -428,7 +423,7 @@ namespace anm2ed::imgui manager.command_push({isaacSave.index, [isIgnored = *isIgnored](Manager&, Document& document) { if (document.model.info.isIsaacIgnored == isIgnored) return; - document.edit_apply(EDIT_ISAAC_COMPATIBILITY, [&](model::Model& model) + document.edit_apply(EDIT_ISAAC_COMPATIBILITY, [&](Model& model) { model.info.isIsaacIgnored = isIgnored; }); }}); save_enqueue(manager, isaacSave); @@ -449,16 +444,15 @@ namespace anm2ed::imgui } isaacPopup.end(); - if (shortcut(manager.chords[SHORTCUT_NEW], shortcut::GLOBAL)) dialog.file_save(Dialog::ANM2_CREATE); - if (shortcut(manager.chords[SHORTCUT_OPEN], shortcut::GLOBAL)) dialog.file_open(Dialog::ANM2_OPEN, true); - if (shortcut(manager.chords[SHORTCUT_SAVE], shortcut::GLOBAL)) + if (shortcut(manager.chords[SHORTCUT_NEW], SCOPE_GLOBAL)) dialog.file_save(Dialog::ANM2_CREATE); + if (shortcut(manager.chords[SHORTCUT_OPEN], SCOPE_GLOBAL)) dialog.file_open(Dialog::ANM2_OPEN, true); + if (shortcut(manager.chords[SHORTCUT_SAVE], SCOPE_GLOBAL)) { if (settings.fileIsWarnOverwrite) overwritePopup.open(); else save_request(manager, settings, manager.selected, {}, true); } - if (shortcut(manager.chords[SHORTCUT_SAVE_AS], shortcut::GLOBAL)) dialog.file_save(Dialog::ANM2_SAVE); - if (shortcut(manager.chords[SHORTCUT_EXIT], shortcut::GLOBAL)) isQuitting = true; + if (shortcut(manager.chords[SHORTCUT_SAVE_AS], SCOPE_GLOBAL)) dialog.file_save(Dialog::ANM2_SAVE); + if (shortcut(manager.chords[SHORTCUT_EXIT], SCOPE_GLOBAL)) isQuitting = true; } -} diff --git a/src/ui/taskbar.h b/src/ui/taskbar.h index a0e4ff4..dc8844f 100644 --- a/src/ui/taskbar.h +++ b/src/ui/taskbar.h @@ -16,8 +16,6 @@ #include "ui/generate_animation_from_grid.h" #include "ui/render_animation.h" -namespace anm2ed::imgui -{ class Taskbar { struct PendingSave @@ -27,22 +25,22 @@ namespace anm2ed::imgui bool isQueued{}; }; - wizard::ChangeAllFrameProperties changeAllFrameProperties{}; - wizard::About about{}; - wizard::Configure configure{}; - wizard::GenerateAnimationFromGrid generateAnimationFromGrid{}; - wizard::RenderAnimation renderAnimation{}; + ChangeAllFrameProperties changeAllFrameProperties{}; + About about{}; + Configure configure{}; + GenerateAnimationFromGrid generateAnimationFromGrid{}; + RenderAnimation renderAnimation{}; Canvas generate; PopupHelper generatePopup{PopupHelper(LABEL_TASKBAR_GENERATE_ANIMATION_FROM_GRID)}; PopupHelper generateRegionsPopup{ - PopupHelper(LABEL_TASKBAR_GENERATE_REGIONS_FROM_ANIMATIONS, imgui::POPUP_SMALL_NO_HEIGHT)}; - PopupHelper changePopup{PopupHelper(LABEL_CHANGE_ALL_FRAME_PROPERTIES, imgui::POPUP_NORMAL_NO_HEIGHT)}; - PopupHelper overwritePopup{PopupHelper(LABEL_TASKBAR_OVERWRITE_FILE, imgui::POPUP_SMALL_NO_HEIGHT)}; - PopupHelper isaacPopup{PopupHelper(LABEL_ISAAC_COMPATIBILITY_WARNING, imgui::POPUP_SMALL_NO_HEIGHT)}; + PopupHelper(LABEL_TASKBAR_GENERATE_REGIONS_FROM_ANIMATIONS, POPUP_SMALL_NO_HEIGHT)}; + PopupHelper changePopup{PopupHelper(LABEL_CHANGE_ALL_FRAME_PROPERTIES, POPUP_NORMAL_NO_HEIGHT)}; + PopupHelper overwritePopup{PopupHelper(LABEL_TASKBAR_OVERWRITE_FILE, POPUP_SMALL_NO_HEIGHT)}; + PopupHelper isaacPopup{PopupHelper(LABEL_ISAAC_COMPATIBILITY_WARNING, POPUP_SMALL_NO_HEIGHT)}; PendingSave isaacSave{}; - PopupHelper vectorPopup{PopupHelper(LABEL_CONVERT_SVG_POPUP, imgui::POPUP_SMALL_NO_HEIGHT)}; - PopupHelper renderPopup{PopupHelper(LABEL_TASKBAR_RENDER_ANIMATION, imgui::POPUP_SMALL_NO_HEIGHT)}; + PopupHelper vectorPopup{PopupHelper(LABEL_CONVERT_SVG_POPUP, POPUP_SMALL_NO_HEIGHT)}; + PopupHelper renderPopup{PopupHelper(LABEL_TASKBAR_RENDER_ANIMATION, POPUP_SMALL_NO_HEIGHT)}; PopupHelper configurePopup{PopupHelper(LABEL_TASKBAR_CONFIGURE)}; PopupHelper aboutPopup{PopupHelper(LABEL_TASKBAR_ABOUT)}; Settings editSettings{}; @@ -60,4 +58,3 @@ namespace anm2ed::imgui void update(Manager&, Settings&, Resources&, Dialog&, bool&); bool save_manual(Manager&, Settings&, int = -1, const std::filesystem::path& = {}); }; -}; diff --git a/src/ui/theme.cpp b/src/ui/theme.cpp index 8b0288d..526c34e 100644 --- a/src/ui/theme.cpp +++ b/src/ui/theme.cpp @@ -2,8 +2,6 @@ #include -namespace anm2ed::imgui -{ constexpr ImVec4 COLOR_LIGHT_BUTTON{0.98f, 0.98f, 0.98f, 1.0f}; constexpr ImVec4 COLOR_LIGHT_TITLE_BG{0.78f, 0.78f, 0.78f, 1.0f}; constexpr ImVec4 COLOR_LIGHT_TITLE_BG_ACTIVE{0.64f, 0.64f, 0.64f, 1.0f}; @@ -19,18 +17,18 @@ namespace anm2ed::imgui constexpr ImVec4 COLOR_LIGHT_CHECK_MARK{0.0f, 0.0f, 0.0f, 1.0f}; constexpr auto FRAME_BORDER_SIZE = 1.0f; - void theme_set(theme::Type theme) + void theme_set(Theme theme) { switch (theme) { - case theme::LIGHT: + case THEME_LIGHT: ImGui::StyleColorsLight(); break; - case theme::DARK: + case THEME_DARK: default: ImGui::StyleColorsDark(); break; - case theme::CLASSIC: + case THEME_CLASSIC: ImGui::StyleColorsClassic(); break; } @@ -38,7 +36,7 @@ namespace anm2ed::imgui style.FrameBorderSize = FRAME_BORDER_SIZE; style.Colors[ImGuiCol_WindowBg].w = 1.0f; // windows detached into their own OS windows can't be see-through - if (theme == theme::LIGHT) + if (theme == THEME_LIGHT) { auto& colors = style.Colors; colors[ImGuiCol_Button] = COLOR_LIGHT_BUTTON; @@ -56,4 +54,3 @@ namespace anm2ed::imgui colors[ImGuiCol_CheckMark] = COLOR_LIGHT_CHECK_MARK; } } -} diff --git a/src/ui/theme.h b/src/ui/theme.h index 07c2c9d..ea8d4a1 100644 --- a/src/ui/theme.h +++ b/src/ui/theme.h @@ -2,31 +2,25 @@ #include "localization.h" -namespace anm2ed::imgui::theme -{ #define THEMES \ - X(LIGHT, LABEL_THEME_LIGHT) \ - X(DARK, LABEL_THEME_DARK) \ - X(CLASSIC, LABEL_THEME_CLASSIC) + X(THEME_LIGHT, LABEL_THEME_LIGHT) \ + X(THEME_DARK, LABEL_THEME_DARK) \ + X(THEME_CLASSIC, LABEL_THEME_CLASSIC) - enum Type + enum Theme { #define X(symbol, string) symbol, THEMES #undef X - COUNT + THEME_COUNT }; - constexpr StringType STRINGS[] = { + constexpr StringType THEME_STRINGS[] = { #define X(symbol, string) string, THEMES #undef X }; #undef THEMES -} -namespace anm2ed::imgui -{ - void theme_set(theme::Type); -} + void theme_set(Theme); diff --git a/src/ui/timeline.cpp b/src/ui/timeline.cpp index 59f7fa1..b011831 100644 --- a/src/ui/timeline.cpp +++ b/src/ui/timeline.cpp @@ -1,7 +1,5 @@ #include "ui/timeline_context.h" -namespace anm2ed::imgui -{ Timeline::Timeline() = default; Timeline::~Timeline() = default; @@ -19,7 +17,7 @@ namespace anm2ed::imgui rowFrameChildHeight = ImGui::GetTextLineHeightWithSpacing() + ImGui::GetStyle().WindowPadding.y * 1.5f; style = ImGui::GetStyle(); - isLightTheme = settings.theme == theme::LIGHT; + isLightTheme = settings.theme == THEME_LIGHT; isTextPushed = false; if (isLightTheme) { @@ -76,8 +74,8 @@ namespace anm2ed::imgui edit_push(EDIT_GENERATE_REGIONS_FROM_ANIMATIONS, [targetFrames = makeManyRegionReferences, format = settings.generateRegionNameFormat, mapping = isMakeManyRegionsMapFrames ? RegionFrameMapping::SET - : RegionFrameMapping::PRESERVE](model::Model& model) - { return edit::regions_generate(model, {}, targetFrames, format, mapping); }); + : RegionFrameMapping::PRESERVE](Model& model) + { return regions_generate(model, {}, targetFrames, format, mapping); }); if (result != PopupButton::NONE) makeManyRegionsPopup.close(); ImGui::EndPopup(); @@ -186,18 +184,18 @@ namespace anm2ed::imgui { if (!animation) return; - if (shortcut(manager.chords[SHORTCUT_PLAY_PAUSE], shortcut::GLOBAL)) playback.toggle(); - if (shortcut(manager.chords[SHORTCUT_START_MARKER], shortcut::GLOBAL)) marker_set(true, (int)playback.time); - if (shortcut(manager.chords[SHORTCUT_END_MARKER], shortcut::GLOBAL)) marker_set(false, (int)playback.time); + if (shortcut(manager.chords[SHORTCUT_PLAY_PAUSE], SCOPE_GLOBAL)) playback.toggle(); + if (shortcut(manager.chords[SHORTCUT_START_MARKER], SCOPE_GLOBAL)) marker_set(true, (int)playback.time); + if (shortcut(manager.chords[SHORTCUT_END_MARKER], SCOPE_GLOBAL)) marker_set(false, (int)playback.time); - if (shortcut(manager.chords[SHORTCUT_MOVE_PLAYHEAD_BACK], shortcut::GLOBAL)) + if (shortcut(manager.chords[SHORTCUT_MOVE_PLAYHEAD_BACK], SCOPE_GLOBAL)) { playback_stop(); playback.decrement(settings.playbackIsClamp ? animation->frameNum : FRAME_NUM_MAX); document.frameTime = playback.time; } - if (shortcut(manager.chords[SHORTCUT_MOVE_PLAYHEAD_FORWARD], shortcut::GLOBAL)) + if (shortcut(manager.chords[SHORTCUT_MOVE_PLAYHEAD_FORWARD], SCOPE_GLOBAL)) { playback_stop(); playback.increment(settings.playbackIsClamp ? animation->frameNum : FRAME_NUM_MAX); @@ -215,7 +213,7 @@ namespace anm2ed::imgui for (int i = 0; i < (int)std::size(FRAME_RESIZES); ++i) { auto resize = FRAME_RESIZES[i]; - auto isPressed = shortcut(manager.chords[resize.shortcut], shortcut::GLOBAL); + auto isPressed = shortcut(manager.chords[resize.shortcut], SCOPE_GLOBAL); auto selectedFrames = isPressed ? document.frame_references_get(Document::FrameReferenceFallback::NONE) : std::set{}; std::erase_if(selectedFrames, is_trigger_reference); @@ -234,10 +232,10 @@ namespace anm2ed::imgui resizeChordTabIds[i] = isPressed ? document.tabId : 0; } - auto isPreviousFrame = shortcut(manager.chords[SHORTCUT_PREVIOUS_FRAME], shortcut::GLOBAL); - auto isNextFrame = shortcut(manager.chords[SHORTCUT_NEXT_FRAME], shortcut::GLOBAL); - auto isPreviousItem = shortcut(manager.chords[SHORTCUT_PREVIOUS_ITEM], shortcut::GLOBAL); - auto isNextItem = shortcut(manager.chords[SHORTCUT_NEXT_ITEM], shortcut::GLOBAL); + auto isPreviousFrame = shortcut(manager.chords[SHORTCUT_PREVIOUS_FRAME], SCOPE_GLOBAL); + auto isNextFrame = shortcut(manager.chords[SHORTCUT_NEXT_FRAME], SCOPE_GLOBAL); + auto isPreviousItem = shortcut(manager.chords[SHORTCUT_PREVIOUS_ITEM], SCOPE_GLOBAL); + auto isNextItem = shortcut(manager.chords[SHORTCUT_NEXT_ITEM], SCOPE_GLOBAL); if (isPreviousFrame || isNextFrame) if (auto item = selected_item_get(); item && !item->frames.empty()) @@ -247,10 +245,9 @@ namespace anm2ed::imgui glm::clamp(reference.frameIndex + (int)isNextFrame - (int)isPreviousFrame, 0, (int)item->frames.size() - 1); reference_set(frameReference); document.frame_focus_select(); - document.frameTime = model::frame_time_from_index_get(*item, reference.frameIndex); + document.frameTime = frame_time_from_index_get(*item, reference.frameIndex); } if (isPreviousItem) reference_set_adjacent_item(-1); if (isNextItem) reference_set_adjacent_item(1); } -} diff --git a/src/ui/timeline.h b/src/ui/timeline.h index 7f6a849..f85983f 100644 --- a/src/ui/timeline.h +++ b/src/ui/timeline.h @@ -15,8 +15,6 @@ #include "localization.h" #include "ui/popup.h" -namespace anm2ed::imgui -{ inline const glm::vec4 ROOT_COLOR = glm::vec4(0.140f, 0.310f, 0.560f, 1.000f); inline const glm::vec4 ROOT_COLOR_ACTIVE = glm::vec4(0.240f, 0.520f, 0.880f, 1.000f); inline const glm::vec4 ROOT_COLOR_HOVERED = glm::vec4(0.320f, 0.640f, 1.000f, 1.000f); @@ -34,11 +32,11 @@ namespace anm2ed::imgui inline const glm::vec4 TRIGGER_COLOR_HOVERED = glm::vec4(0.950f, 0.330f, 0.490f, 1.000f); #define ANM2_ITEM_TYPES \ - X(NONE, STRING_UNDEFINED, resource::icon::NONE, glm::vec4(), glm::vec4(), glm::vec4()) \ - X(ROOT, BASIC_ROOT, resource::icon::ROOT, ROOT_COLOR, ROOT_COLOR_ACTIVE, ROOT_COLOR_HOVERED) \ - X(LAYER, BASIC_LAYER_ANIMATION, resource::icon::LAYER, LAYER_COLOR, LAYER_COLOR_ACTIVE, LAYER_COLOR_HOVERED) \ - X(NULL_, BASIC_NULL_ANIMATION, resource::icon::NULL_, NULL_COLOR, NULL_COLOR_ACTIVE, NULL_COLOR_HOVERED) \ - X(TRIGGER, BASIC_TRIGGERS, resource::icon::TRIGGERS, TRIGGER_COLOR, TRIGGER_COLOR_ACTIVE, TRIGGER_COLOR_HOVERED) + X(NONE, STRING_UNDEFINED, ICON_NONE, glm::vec4(), glm::vec4(), glm::vec4()) \ + X(ROOT, BASIC_ROOT, ICON_ROOT, ROOT_COLOR, ROOT_COLOR_ACTIVE, ROOT_COLOR_HOVERED) \ + X(LAYER, BASIC_LAYER_ANIMATION, ICON_LAYER, LAYER_COLOR, LAYER_COLOR_ACTIVE, LAYER_COLOR_HOVERED) \ + X(NULL_, BASIC_NULL_ANIMATION, ICON_NULL, NULL_COLOR, NULL_COLOR_ACTIVE, NULL_COLOR_HOVERED) \ + X(TRIGGER, BASIC_TRIGGERS, ICON_TRIGGERS, TRIGGER_COLOR, TRIGGER_COLOR_ACTIVE, TRIGGER_COLOR_HOVERED) constexpr StringType TYPE_STRINGS[] = { #define X(symbol, string, icon, color, colorActive, colorHovered) string, @@ -46,7 +44,7 @@ namespace anm2ed::imgui #undef X }; - constexpr resource::icon::Type TYPE_ICONS[] = { + constexpr Icon TYPE_ICONS[] = { #define X(symbol, string, icon, color, colorActive, colorHovered) icon, ANM2_ITEM_TYPES #undef X @@ -125,7 +123,7 @@ namespace anm2ed::imgui int markerTime{}; bool isWindowHovered{}; bool isHorizontalScroll{}; - popup::ItemProperties itemProperties{}; + ItemProperties itemProperties{}; PopupHelper bakePopup{PopupHelper(LABEL_TIMELINE_BAKE_POPUP, POPUP_SMALL_NO_HEIGHT)}; PopupHelper bakeIntoOtherFramesPopup{PopupHelper(LABEL_BAKE_INTO_OTHER_FRAMES, POPUP_SMALL_NO_HEIGHT)}; PopupHelper makeManyRegionsPopup{PopupHelper(LABEL_MAKE_MANY_REGIONS, POPUP_SMALL_NO_HEIGHT)}; @@ -176,4 +174,3 @@ namespace anm2ed::imgui ~Timeline(); void update(Manager&, Settings&, Resources&, Clipboard&); }; -} diff --git a/src/ui/timeline_children.cpp b/src/ui/timeline_children.cpp index 9ac0e06..17d0e60 100644 --- a/src/ui/timeline_children.cpp +++ b/src/ui/timeline_children.cpp @@ -2,8 +2,6 @@ // Animation layers in the timeline: their child's tracks under them (read only, timed as the parent plays them), // stepping into the child, and the breadcrumb back out. -namespace anm2ed::imgui -{ constexpr auto BREADCRUMB_SEPARATOR = ">"; // The child animation's tracks (root, layers top-down, nulls, triggers) when an animation layer row is expanded. @@ -12,21 +10,21 @@ namespace anm2ed::imgui std::vector rows{}; if (row.isGroup || row.type != LAYER) return rows; auto track = item_get(LAYER, row.id, row.groupType, row.groupId); - auto layer = model::item_get(model.content.layers, row.id); + auto layer = ::item_get(model.content.layers, row.id); if (!track || !layer || !layer->is_animation() || !expandedLayerTracks.contains(track->uid)) return rows; - auto [source, child] = model::child_get(model, *layer, {}, document.library_resolver_get()); + auto [source, child] = child_get(model, *layer, {}, document.library_resolver_get()); if (!child) return rows; - auto row_add = [&](const model::Track& childTrack) + auto row_add = [&](const Track& childTrack) { if (settings.timelineIsShowUnused || !childTrack.frames.empty()) rows.push_back({source, child, &childTrack}); }; row_add(child->root); - std::vector layers{}; - model::tracks_each(child->layers, [&](const model::Track& childTrack, auto*) { layers.push_back(&childTrack); }); + std::vector layers{}; + tracks_each(child->layers, [&](const Track& childTrack, auto*) { layers.push_back(&childTrack); }); for (auto it = layers.rbegin(); it != layers.rend(); ++it) row_add(**it); - model::tracks_each(child->nulls, [&](const model::Track& childTrack, auto*) { row_add(childTrack); }); + tracks_each(child->nulls, [&](const Track& childTrack, auto*) { row_add(childTrack); }); row_add(child->triggers); return rows; } @@ -42,9 +40,9 @@ namespace anm2ed::imgui auto type = (int)peek.track->type; auto label = std::string(localize.get(TYPE_STRINGS[type])); if (type == LAYER) - if (auto layer = model::item_get(peek.source->content.layers, peek.track->id)) label = layer_label_get(*layer); + if (auto layer = ::item_get(peek.source->content.layers, peek.track->id)) label = layer_label_get(*layer); if (type == NULL_) - if (auto null = model::item_get(peek.source->content.nulls, peek.track->id)) label = null->name; + if (auto null = ::item_get(peek.source->content.nulls, peek.track->id)) label = null->name; ImGui::PushID(index); ImGui::PushStyleColor(ImGuiCol_ChildBg, to_imvec4(color_get(COLOR_ITEM_BASE, type) * COLOR_HIDDEN_MULTIPLIER)); @@ -81,7 +79,7 @@ namespace anm2ed::imgui auto origin = ImGui::GetCursorScreenPos(); auto frameSize = ImVec2(ImGui::GetTextLineHeight(), ImGui::GetContentRegionAvail().y); auto track = item_get(LAYER, row.id, row.groupType, row.groupId); - auto layer = model::item_get(model.content.layers, row.id); + auto layer = ::item_get(model.content.layers, row.id); auto type = (int)peek.track->type; auto isTrigger = type == TRIGGER; auto color = ImGui::GetColorU32(to_imvec4(color_get(COLOR_FRAME_BASE, type) * COLOR_HIDDEN_MULTIPLIER)); @@ -89,11 +87,11 @@ namespace anm2ed::imgui auto key_get = [&](int time) { - auto frame = model::frame_generate(*track, (float)time); - if (!frame.isVisible || model::child_get(model, *layer, frame, libraryGet).second != peek.child) return -1; - auto childTime = model::child_time_get(*track, (float)time, peek.child->frameNum, layer->id); - return isTrigger ? model::frame_index_from_at_frame_get(*peek.track, (int)childTime) - : model::frame_index_from_time_get(*peek.track, childTime); + auto frame = frame_generate(*track, (float)time); + if (!frame.isVisible || child_get(model, *layer, frame, libraryGet).second != peek.child) return -1; + auto childTime = child_time_get(*track, (float)time, peek.child->frameNum, layer->id); + return isTrigger ? frame_index_from_at_frame_get(*peek.track, (int)childTime) + : frame_index_from_time_get(*peek.track, childTime); }; auto cell_draw = [&](int start, int end, int key) { @@ -101,7 +99,7 @@ namespace anm2ed::imgui auto max = ImVec2(origin.x + frameSize.x * (float)end, origin.y + frameSize.y); drawList->AddRectFilled(min, max, color, FRAME_ROUNDING); drawList->AddRect(min, max, ImGui::GetColorU32(frameBorderColor), FRAME_ROUNDING); - auto icon = isTrigger ? icon::TRIGGER : INTERPOLATION_ICONS[(int)peek.track->frames[key].interpolation]; + auto icon = isTrigger ? ICON_TRIGGER : INTERPOLATION_ICONS[(int)peek.track->frames[key].interpolation]; auto iconSize = icon_size_get(); auto iconMin = ImVec2(min.x, origin.y + (frameSize.y - iconSize.y) / 2); drawList->AddImage((ImTextureID)(intptr_t)resources.icon_id_get(icon), iconMin, @@ -156,4 +154,3 @@ namespace anm2ed::imgui ImGui::TextUnformatted(steps.back().layerName.c_str()); ImGui::PopStyleVar(2); } -} diff --git a/src/ui/timeline_context.h b/src/ui/timeline_context.h index 5e58f6b..b39b929 100644 --- a/src/ui/timeline_context.h +++ b/src/ui/timeline_context.h @@ -26,14 +26,8 @@ #include "vector.h" #include "ui/panel.h" -using namespace anm2ed::resource; -using namespace anm2ed::types; -using namespace anm2ed::util; using namespace glm; -namespace anm2ed::imgui -{ - constexpr auto WIDTH_MULTIPLIER = 1.25f; constexpr auto COLOR_HIDDEN_MULTIPLIER = vec4(0.5f, 0.5f, 0.5f, 1.000f); @@ -48,13 +42,13 @@ namespace anm2ed::imgui constexpr auto FRAME_ROUNDING = 3.0f; constexpr auto ICON_TINT_DEFAULT_DARK = ImVec4(1.0f, 1.0f, 1.0f, 1.0f); constexpr auto ICON_TINT_DEFAULT_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); - constexpr auto ITEM_TEXT_COLOR_DARK = to_imvec4(color::WHITE); + constexpr auto ITEM_TEXT_COLOR_DARK = to_imvec4(COLOR_WHITE); constexpr auto ITEM_TEXT_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); constexpr auto PLAYHEAD_ICON_TINT_LIGHT = ImVec4(0.3922f, 0.7843f, 0.5882f, 1.0f); - constexpr auto PLAYHEAD_LINE_COLOR_DARK = to_imvec4(color::WHITE); + constexpr auto PLAYHEAD_LINE_COLOR_DARK = to_imvec4(COLOR_WHITE); constexpr auto PLAYHEAD_LINE_COLOR_LIGHT = ImVec4(0.1961f, 0.5882f, 0.3922f, 1.0f); constexpr auto PLAYHEAD_LINE_THICKNESS = 4.0f; - constexpr auto TEXT_MULTIPLE_COLOR_DARK = to_imvec4(color::WHITE); + constexpr auto TEXT_MULTIPLE_COLOR_DARK = to_imvec4(COLOR_WHITE); constexpr auto TEXT_MULTIPLE_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 1.0f); constexpr auto TIMELINE_BACKGROUND_COLOR_LIGHT = ImVec4(0.5490f, 0.5490f, 0.5882f, 1.0f); constexpr auto TIMELINE_PLAYHEAD_RECT_COLOR_DARK = ImVec4(0.60f, 0.45f, 0.30f, 1.0f); @@ -133,16 +127,16 @@ namespace anm2ed::imgui inline bool is_trigger_reference(const Reference& reference) { return reference.itemType == TRIGGER; } - constexpr resource::icon::Type INTERPOLATION_ICONS[] = {resource::icon::UNINTERPOLATED, resource::icon::INTERPOLATED, - resource::icon::EASE_IN, resource::icon::EASE_OUT, - resource::icon::EASE_IN_OUT}; + constexpr Icon INTERPOLATION_ICONS[] = {ICON_UNINTERPOLATED, ICON_INTERPOLATED, + ICON_EASE_IN, ICON_EASE_OUT, + ICON_EASE_IN_OUT}; // A read-only row under an expanded animation layer: one track of the child animation it plays. struct PeekRow { - const model::Model* source{}; - const model::Animation* child{}; - const model::Track* track{}; + const Model* source{}; + const Animation* child{}; + const Track* track{}; }; Reference row_item_reference_get(const TimelineRow&); @@ -155,10 +149,10 @@ namespace anm2ed::imgui Resources& resources; Clipboard& clipboard; Document& document; - model::Model& model; + Model& model; Playback& playback; Reference reference; - const model::Animation* animation{}; + const Animation* animation{}; float rowFrameChildHeight{}; bool isLightTheme{}; bool isTextPushed{}; @@ -185,17 +179,17 @@ namespace anm2ed::imgui ImVec2 frameBoxClipMax{}; bool isFrameBoxClipSet{}; - const model::Track* item_get(int type, int id = -1, int groupType = NONE, int groupId = -1); - const model::Frame* frame_get(); - const model::Track* selected_item_get(); - const model::TrackGroup* track_group_get(int type, int groupId); + const Track* item_get(int type, int id = -1, int groupType = NONE, int groupId = -1); + const Frame* frame_get(); + const Track* selected_item_get(); + const TrackGroup* track_group_get(int type, int groupId); bool is_track_group_visible(int type, int groupId); - const model::TrackGroup* row_group_get(const TimelineRow& row); + const TrackGroup* row_group_get(const TimelineRow& row); glm::vec4 color_get(TimelineColor, int); std::set drag_frame_references_get(const Reference&); // Queues an edit on the document; its result is selected (frames by default). template - void edit_push(StringType label, Operation operation, std::function select = {}) + void edit_push(StringType label, Operation operation, std::function select = {}) { command_push( [=, this](Manager&, Document& document) mutable @@ -223,7 +217,7 @@ namespace anm2ed::imgui void frames_bake(); std::set selected_root_frame_references_get(); std::set item_references_for_bake_into_other_frames_get(const Document& targetDocument, - const model::Animation& targetAnimation, + const Animation& targetAnimation, BakeIntoOtherFramesTarget target, bool isLayers, bool isNulls); bool is_bake_into_other_frames_ready(); @@ -252,14 +246,14 @@ namespace anm2ed::imgui void paste(); std::optional property_source_get(); std::set property_targets_get(); - std::optional property_clipboard_frame_get(); - bool is_property_pasteable(edit::FrameProperty); - void property_copy(edit::FrameProperty); - void property_cut(edit::FrameProperty); - void property_paste(edit::FrameProperty); + std::optional property_clipboard_frame_get(); + bool is_property_pasteable(FrameProperty); + void property_copy(FrameProperty); + void property_cut(FrameProperty); + void property_paste(FrameProperty); void context_menu(); void item_base_properties_open(int type, int id); - void group_properties_open(const TimelineRow& row, const model::TrackGroup& group); + void group_properties_open(const TimelineRow& row, const TrackGroup& group); void group_properties_update(); void item_context_menu(); std::vector peek_rows_get(const TimelineRow&); @@ -284,4 +278,3 @@ namespace anm2ed::imgui void shortcuts_update(); void draw(); }; -} diff --git a/src/ui/timeline_edit.cpp b/src/ui/timeline_edit.cpp index 7ad155b..625071d 100644 --- a/src/ui/timeline_edit.cpp +++ b/src/ui/timeline_edit.cpp @@ -1,13 +1,11 @@ #include "ui/timeline_context.h" -namespace anm2ed::imgui -{ void TimelineContext::frame_insert() { auto targetReference = reference; auto time = (int)document.frameTime; if (!animation || !document.model.track_get(targetReference)) return; - edit_push(EDIT_INSERT_FRAME, [=](model::Model& model) { return edit::frame_insert(model, targetReference, time); }); + edit_push(EDIT_INSERT_FRAME, [=](Model& model) { return ::frame_insert(model, targetReference, time); }); } void TimelineContext::frames_delete_action() @@ -15,8 +13,8 @@ namespace anm2ed::imgui auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); if (selectedFrames.empty()) return; edit_push( - EDIT_DELETE_FRAMES, [=](model::Model& model) { return edit::frames_delete(model, selectedFrames); }, - [this](Document& document, const edit::Uids&) { document.frame_focus_select(); }); + EDIT_DELETE_FRAMES, [=](Model& model) { return frames_delete(model, selectedFrames); }, + [this](Document& document, const Uids&) { document.frame_focus_select(); }); } void TimelineContext::frames_duplicate() @@ -24,8 +22,8 @@ namespace anm2ed::imgui auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); std::erase_if(selectedFrames, is_trigger_reference); if (selectedFrames.empty()) return; - edit_push(EDIT_DUPLICATE_FRAMES, [=, focus = reference](model::Model& model) - { return edit::frames_duplicate(model, selectedFrames, focus); }); + edit_push(EDIT_DUPLICATE_FRAMES, [=, focus = reference](Model& model) + { return ::frames_duplicate(model, selectedFrames, focus); }); } bool TimelineContext::is_frames_reverse_available(std::set selectedFrames) @@ -45,7 +43,7 @@ namespace anm2ed::imgui auto selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE); std::erase_if(selectedFrames, is_trigger_reference); if (!is_frames_reverse_available(selectedFrames)) return; - edit_push(EDIT_REVERSE_FRAMES, [=](model::Model& model) { return edit::frames_reverse(model, selectedFrames); }); + edit_push(EDIT_REVERSE_FRAMES, [=](Model& model) { return ::frames_reverse(model, selectedFrames); }); } void TimelineContext::frames_bake() @@ -54,8 +52,8 @@ namespace anm2ed::imgui std::erase_if(selectedFrames, is_trigger_reference); if (selectedFrames.empty()) return; edit_push(EDIT_BAKE_FRAMES, [=, interval = settings.bakeInterval, isRoundScale = settings.bakeIsRoundScale, - isRoundRotation = settings.bakeIsRoundRotation](model::Model& model) - { return edit::frames_bake(model, selectedFrames, interval, isRoundScale, isRoundRotation); }); + isRoundRotation = settings.bakeIsRoundRotation](Model& model) + { return ::frames_bake(model, selectedFrames, interval, isRoundScale, isRoundRotation); }); } std::set TimelineContext::selected_root_frame_references_get() @@ -66,7 +64,7 @@ namespace anm2ed::imgui } std::set TimelineContext::item_references_for_bake_into_other_frames_get( - const Document& targetDocument, const model::Animation& targetAnimation, BakeIntoOtherFramesTarget target, + const Document& targetDocument, const Animation& targetAnimation, BakeIntoOtherFramesTarget target, bool isLayers, bool isNulls) { std::set result{}; @@ -81,8 +79,8 @@ namespace anm2ed::imgui for (auto itemType : {LAYER, NULL_}) { if (!(itemType == LAYER ? isLayers : isNulls)) continue; - model::tracks_each(model::animation_entries_get(targetAnimation, itemType), - [&](const model::Track& track, const model::TrackGroup* group) + tracks_each(animation_entries_get(targetAnimation, itemType), + [&](const Track& track, const TrackGroup* group) { result.insert(Reference{animationIndex, itemType, track.id, -1, group ? itemType : NONE, group ? group->id : -1}); @@ -106,10 +104,10 @@ namespace anm2ed::imgui if (selectedRootFrames.empty() || !animation) return; auto targetItems = item_references_for_bake_into_other_frames_get( document, *animation, bakeIntoOtherFramesTarget, isBakeIntoOtherFramesLayers, isBakeIntoOtherFramesNulls); - edit::RootBakeOptions options{settings.bakeIsRoundScale, settings.bakeIsRoundRotation, + RootBakeOptions options{settings.bakeIsRoundScale, settings.bakeIsRoundRotation, settings.bakeIsMatchRootInterpolation, settings.bakeIsUseRootPivot}; - edit_push(EDIT_BAKE_INTO_OTHER_FRAMES, [=](model::Model& model) - { return edit::root_bake_into(model, selectedRootFrames, targetItems, options); }); + edit_push(EDIT_BAKE_INTO_OTHER_FRAMES, [=](Model& model) + { return root_bake_into(model, selectedRootFrames, targetItems, options); }); } void TimelineContext::frame_split() @@ -118,7 +116,7 @@ namespace anm2ed::imgui std::erase_if(selectedFrames, is_trigger_reference); if (selectedFrames.empty()) return; auto time = frameSplitTimeAtCursor.value_or((int)std::floor(playback.time)); - edit_push(EDIT_SPLIT_FRAME, [=](model::Model& model) { return edit::frames_split(model, selectedFrames, time); }); + edit_push(EDIT_SPLIT_FRAME, [=](Model& model) { return frames_split(model, selectedFrames, time); }); } void TimelineContext::item_remove() @@ -129,9 +127,9 @@ namespace anm2ed::imgui if (row.type == LAYER || row.type == NULL_) (row.isGroup ? groupIds : ids)[row.type].insert(row.id); if (!animation || (ids.empty() && groupIds.empty())) return; edit_push( - EDIT_REMOVE_ITEMS, [=, animationIndex = reference.animationIndex](model::Model& model) - { return edit::items_remove(model, animationIndex, ids, groupIds); }, - [this](Document& document, const edit::Uids&) + EDIT_REMOVE_ITEMS, [=, animationIndex = reference.animationIndex](Model& model) + { return items_remove(model, animationIndex, ids, groupIds); }, + [this](Document& document, const Uids&) { document.focus_clear(); group_selection_reset_for(document); @@ -171,9 +169,9 @@ namespace anm2ed::imgui edit_push( EDIT_GROUP_ITEMS, [=, animationIndex = reference.animationIndex, type = targetReferences.front().itemType, - name = std::string(localize.get(TEXT_NEW_GROUP))](model::Model& model) - { return edit::items_group(model, animationIndex, type, ids, name); }, - [=, this](Document& document, const edit::Uids& uids) + name = std::string(localize.get(TEXT_NEW_GROUP))](Model& model) + { return items_group(model, animationIndex, type, ids, name); }, + [=, this](Document& document, const Uids& uids) { if (uids.empty()) return; document.selected_set(SelectionKind::TRACKS, {targetReferences.begin(), targetReferences.end()}); @@ -198,7 +196,7 @@ namespace anm2ed::imgui std::set groupIds{}; for (const auto& row : draggedRows) (row.isGroup ? groupIds : ids).insert(row.id); - edit::RowTarget target{targetRow.isGroup, targetRow.type, targetRow.id, + RowTarget target{targetRow.isGroup, targetRow.type, targetRow.id, targetRow.type == ROOT ? -1 : targetRow.groupId}; auto animationIndex = reference.animationIndex; std::set tracks{}; @@ -212,12 +210,12 @@ namespace anm2ed::imgui edit_push( EDIT_MOVE_ITEMS, - [=](model::Model& model) + [=](Model& model) { - return edit::items_move(model, animationIndex, targetType, ids, groupIds, target, isDropAfter, + return items_move(model, animationIndex, targetType, ids, groupIds, target, isDropAfter, isDropIntoGroup); }, - [=, this](Document& document, const edit::Uids&) + [=, this](Document& document, const Uids&) { document.selection.uids[SelectionKind::TRACKS] = moved.uids.at(SelectionKind::TRACKS); document.selection.uids[SelectionKind::GROUPS] = moved.uids.at(SelectionKind::GROUPS); @@ -232,8 +230,8 @@ namespace anm2ed::imgui void TimelineContext::fit_animation_length() { if (!animation) return; - edit_push(EDIT_FIT_ANIMATION_LENGTH, [animationIndex = reference.animationIndex](model::Model& model) - { return edit::animation_length_fit(model, animationIndex); }); + edit_push(EDIT_FIT_ANIMATION_LENGTH, [animationIndex = reference.animationIndex](Model& model) + { return animation_length_fit(model, animationIndex); }); } void TimelineContext::frame_references_copy(const std::set& selectedFrames) @@ -245,7 +243,7 @@ namespace anm2ed::imgui { auto frame = model.frame_get(frameReference); if (!frame) continue; - clipboardString += model::frame_to_string(*frame, (ItemType)frameReference.itemType); + clipboardString += frame_to_string(*frame, (ItemType)frameReference.itemType); } if (clipboardString.empty()) return; clipboard.set(clipboardString); @@ -266,8 +264,8 @@ namespace anm2ed::imgui if (selectedFrames.empty()) return; frame_references_copy(selectedFrames); edit_push( - EDIT_CUT_FRAMES, [=](model::Model& model) { return edit::frames_delete(model, selectedFrames); }, - [this](Document& document, const edit::Uids&) { document.frame_focus_select(); }); + EDIT_CUT_FRAMES, [=](Model& model) { return frames_delete(model, selectedFrames); }, + [this](Document& document, const Uids&) { document.frame_focus_select(); }); } void TimelineContext::paste() @@ -285,14 +283,14 @@ namespace anm2ed::imgui EDIT_PASTE_FRAMES, [=, targetReference = reference, selectedFrames = document.frame_references_get(Document::FrameReferenceFallback::NONE), - time = hoveredTime](model::Model& model) - { return edit::frames_paste(model, targetReference, selectedFrames, text, time, errorString.get()); }, - [=, this](Document& document, const edit::Uids& uids) + time = hoveredTime](Model& model) + { return frames_paste(model, targetReference, selectedFrames, text, time, errorString.get()); }, + [=, this](Document& document, const Uids& uids) { if (errorString->empty()) return document.frames_select(uids); toasts.push(std::format("{} {}", localize.get(TOAST_DESERIALIZE_FRAMES_FAILED), *errorString)); logger.error( - std::format("{} {}", localize.get(TOAST_DESERIALIZE_FRAMES_FAILED, anm2ed::ENGLISH), *errorString)); + std::format("{} {}", localize.get(TOAST_DESERIALIZE_FRAMES_FAILED, ENGLISH), *errorString)); }); } @@ -301,7 +299,7 @@ namespace anm2ed::imgui { if (!animation) return; edit_push(isStart ? EDIT_START_MARKER : EDIT_END_MARKER, - [=, animationIndex = reference.animationIndex](model::Model& model) + [=, animationIndex = reference.animationIndex](Model& model) { auto animation = model.animation_edit(animationIndex); if (!animation) return; @@ -315,7 +313,7 @@ namespace anm2ed::imgui void TimelineContext::markers_remove() { edit_push(EDIT_REMOVE_MARKERS, - [animationIndex = reference.animationIndex](model::Model& model) + [animationIndex = reference.animationIndex](Model& model) { if (auto animation = model.animation_edit(animationIndex)) animation->startMarker = animation->endMarker = -1; @@ -341,19 +339,19 @@ namespace anm2ed::imgui } // The frame this timeline put on the clipboard, while it is still there. - std::optional TimelineContext::property_clipboard_frame_get() + std::optional TimelineContext::property_clipboard_frame_get() { if (frameClipboard.text.empty() || clipboard.get() != frameClipboard.text) return {}; - auto frames = model::frames_from_string(frameClipboard.text, (ItemType)frameClipboard.itemType); + auto frames = frames_from_string(frameClipboard.text, (ItemType)frameClipboard.itemType); if (frames.empty()) return {}; return frames.front(); } // Every target frame has the property, and what it refers to (a region, shader, event, sound) exists for it. - bool TimelineContext::is_property_pasteable(edit::FrameProperty property) + bool TimelineContext::is_property_pasteable(FrameProperty property) { if (frameClipboard.property != -1 && frameClipboard.property != (int)property) return false; - if (!edit::is_frame_property_valid(property, (ItemType)frameClipboard.itemType)) return false; + if (!is_frame_property_valid(property, (ItemType)frameClipboard.itemType)) return false; auto source = property_clipboard_frame_get(); auto targets = property_targets_get(); if (!source || targets.empty()) return false; @@ -361,27 +359,27 @@ namespace anm2ed::imgui auto& content = model.content; for (auto target : targets) { - if (!edit::is_frame_property_valid(property, (ItemType)target.itemType)) return false; - if (property == edit::FrameProperty::REGION && source->regionId != -1) + if (!is_frame_property_valid(property, (ItemType)target.itemType)) return false; + if (property == FrameProperty::REGION && source->regionId != -1) { - auto layer = model::item_get(content.layers, target.itemID); - auto spritesheet = layer ? model::item_get(content.spritesheets, layer->spritesheetId) : nullptr; - if (!spritesheet || !model::item_get(spritesheet->regions, source->regionId)) return false; + auto layer = ::item_get(content.layers, target.itemID); + auto spritesheet = layer ? ::item_get(content.spritesheets, layer->spritesheetId) : nullptr; + if (!spritesheet || !::item_get(spritesheet->regions, source->regionId)) return false; } } - if (property == edit::FrameProperty::SHADER && source->shaderId != -1 && - !model::item_get(content.shaders, source->shaderId)) + if (property == FrameProperty::SHADER && source->shaderId != -1 && + !::item_get(content.shaders, source->shaderId)) return false; - if (property == edit::FrameProperty::EVENT) + if (property == FrameProperty::EVENT) for (auto eventId : source->eventIds) - if (eventId != -1 && !model::item_get(content.events, eventId)) return false; - if (property == edit::FrameProperty::SOUNDS) + if (eventId != -1 && !::item_get(content.events, eventId)) return false; + if (property == FrameProperty::SOUNDS) for (auto soundId : source->soundIds) - if (soundId != -1 && !model::item_get(content.sounds, soundId)) return false; + if (soundId != -1 && !::item_get(content.sounds, soundId)) return false; return true; } - void TimelineContext::property_copy(edit::FrameProperty property) + void TimelineContext::property_copy(FrameProperty property) { auto source = property_source_get(); if (!source) return; @@ -390,19 +388,18 @@ namespace anm2ed::imgui } // Copies the property, then sets it back to its default on the targets. - void TimelineContext::property_cut(edit::FrameProperty property) + void TimelineContext::property_cut(FrameProperty property) { auto targets = property_targets_get(); property_copy(property); edit_push(EDIT_CUT_FRAME_PROPERTY, - [=](model::Model& model) { return edit::frames_property_set(model, targets, property, model::Frame{}); }); + [=](Model& model) { return frames_property_set(model, targets, property, Frame{}); }); } - void TimelineContext::property_paste(edit::FrameProperty property) + void TimelineContext::property_paste(FrameProperty property) { auto source = property_clipboard_frame_get(); if (!source || !is_property_pasteable(property)) return; - edit_push(EDIT_PASTE_FRAME_PROPERTY, [=, targets = property_targets_get(), source = *source](model::Model& model) - { return edit::frames_property_set(model, targets, property, source); }); + edit_push(EDIT_PASTE_FRAME_PROPERTY, [=, targets = property_targets_get(), source = *source](Model& model) + { return frames_property_set(model, targets, property, source); }); } -} diff --git a/src/ui/timeline_frames.cpp b/src/ui/timeline_frames.cpp index 628c195..2980fe0 100644 --- a/src/ui/timeline_frames.cpp +++ b/src/ui/timeline_frames.cpp @@ -1,7 +1,5 @@ #include "ui/timeline_context.h" -namespace anm2ed::imgui -{ // Moves the dragged frames to `target`'s track, before its frame index. void TimelineContext::frames_move_to(Reference target) { @@ -14,13 +12,13 @@ namespace anm2ed::imgui auto insertIndex = std::exchange(target.frameIndex, -1); edit_push( - EDIT_MOVE_FRAMES, [frames, target, insertIndex](model::Model& model) - { return edit::frames_move(model, frames, target, insertIndex); }, - [=, this](Document& document, const edit::Uids& uids) + EDIT_MOVE_FRAMES, [frames, target, insertIndex](Model& model) + { return frames_move(model, frames, target, insertIndex); }, + [=, this](Document& document, const Uids& uids) { document.frames_select(uids); if (target.itemType == LAYER) - if (auto layer = model::item_get(document.model.content.layers, target.itemID)) + if (auto layer = ::item_get(document.model.content.layers, target.itemID)) document.focused_id_set(SelectionKind::SPRITESHEETS, layer->spritesheetId); }); } @@ -230,7 +228,7 @@ namespace anm2ed::imgui if (length > 0 && animation) { auto x_get = [&](int time) { return cursorScreenPos.x + frameSize.x * (float)time; }; - auto range = model::animation_play_range_get(*animation); + auto range = animation_play_range_get(*animation); auto bottom = cursorScreenPos.y + frameSize.y; if (animation->startMarker != -1) drawList->AddRectFilled(cursorScreenPos, ImVec2(x_get(range.x), bottom), MARKER_OUTSIDE_COLOR); @@ -241,7 +239,7 @@ namespace anm2ed::imgui markerTint.w *= MARKER_ALPHA; for (auto marker : {animation->startMarker, animation->endMarker}) if (marker != -1) - drawList->AddImage((ImTextureID)(intptr_t)resources.icon_id_get(icon::PLAYHEAD), + drawList->AddImage((ImTextureID)(intptr_t)resources.icon_id_get(ICON_PLAYHEAD), ImVec2(x_get(marker), cursorScreenPos.y), ImVec2(x_get(marker) + frameSize.x, bottom), ImVec2(0, 0), ImVec2(1, 1), ImGui::GetColorU32(markerTint)); } @@ -272,13 +270,13 @@ namespace anm2ed::imgui if (length > 0) { ImGui::SetCursorPos(ImVec2(cursorPos.x + frameSize.x * floorf(playback.time), cursorPos.y)); - ImGui::Image(resources.icon_id_get(icon::PLAYHEAD), frameSize); + ImGui::Image(resources.icon_id_get(ICON_PLAYHEAD), frameSize); auto playheadMin = ImGui::GetItemRectMin(); auto playheadMax = ImGui::GetItemRectMax(); playheadLineCenterX = (playheadMin.x + playheadMax.x) * 0.5f; playheadLineTopY = playheadMax.y; isPlayheadLineSet = true; - overlay_icon(resources.icon_id_get(icon::PLAYHEAD), playheadIconTint, true); + overlay_icon(resources.icon_id_get(ICON_PLAYHEAD), playheadIconTint, true); } } else if (animation) @@ -407,7 +405,7 @@ namespace anm2ed::imgui if (ImGui::Selectable("##Frame Button", isSelected, ImGuiSelectableFlags_None, buttonSize)) { if (type == LAYER) - if (auto layer = model::item_get(model.content.layers, id)) + if (auto layer = ::item_get(model.content.layers, id)) document.focused_id_set(SelectionKind::SPRITESHEETS, layer->spritesheetId); if (type != TRIGGER) @@ -416,7 +414,7 @@ namespace anm2ed::imgui { auto targetReference = frameReference; edit_push(EDIT_FRAME_INTERPOLATION, - [=](model::Model& model) + [=](Model& model) { if (auto frame = model.frame_edit(targetReference)) frame->interpolation = frame->interpolation == Interpolation::NONE ? Interpolation::LINEAR @@ -496,7 +494,7 @@ namespace anm2ed::imgui auto borderThickness = isReferenced ? FRAME_BORDER_THICKNESS_REFERENCED : FRAME_BORDER_THICKNESS; drawList->AddRect(rectMin, rectMax, ImGui::GetColorU32(borderColor), FRAME_ROUNDING, 0, borderThickness); - auto icon = type == TRIGGER ? icon::TRIGGER : INTERPOLATION_ICONS[(int)frame.interpolation]; + auto icon = type == TRIGGER ? ICON_TRIGGER : INTERPOLATION_ICONS[(int)frame.interpolation]; auto iconPos = ImVec2(cursorPos.x + (frameTime * frameSize.x), cursorPos.y + (frameSize.y / 2) - (icon_size_get().y / 2)); ImGui::SetCursorPos(iconPos); @@ -567,7 +565,7 @@ namespace anm2ed::imgui auto atFrame = glm::clamp(hoveredTime, 0, settings.playbackIsClamp && animation ? animation->frameNum - 1 : FRAME_NUM_MAX - 1); command_push([=](Manager&, Document& document) - { edit::trigger_at_frame_set(document.model, targetReference, atFrame); }); + { trigger_at_frame_set(document.model, targetReference, atFrame); }); } else { @@ -575,7 +573,7 @@ namespace anm2ed::imgui if (draggedFrameStartDurations.empty()) durations[targetReference] = draggedFrameStartDuration + durationDelta; for (auto frameDuration : draggedFrameStartDurations) durations[frameDuration.reference] = frameDuration.duration + durationDelta; - command_push([=](Manager&, Document& document) { edit::frame_durations_set(document.model, durations); }); + command_push([=](Manager&, Document& document) { frame_durations_set(document.model, durations); }); } } @@ -587,7 +585,7 @@ namespace anm2ed::imgui [=, this](Manager&, Document& document) { auto item = document.model.track_edit(targetReference); - if (targetType == TRIGGER && item) model::frames_sort_by_at_frame(*item); + if (targetType == TRIGGER && item) frames_sort_by_at_frame(*item); document.change(); }); isDraggedFrameActive = false; @@ -619,7 +617,7 @@ namespace anm2ed::imgui { int length{}; for (auto [index, item] : model.animations_get()) - length = std::max(length, model::animation_length_get(*item)); + length = std::max(length, animation_length_get(*item)); return length; }(); auto childWidth = animationsLength * ImGui::GetTextLineHeight(); @@ -862,7 +860,7 @@ namespace anm2ed::imgui { auto animationIndex = animationLengthEditIndex != -1 ? animationLengthEditIndex : currentAnimationIndex; edit_push(EDIT_ANIMATION_LENGTH, - [=](model::Model& model) + [=](Model& model) { if (auto animation = model.animation_edit(animationIndex)) animation->frameNum = frameNum; }); @@ -878,7 +876,7 @@ namespace anm2ed::imgui { auto animationIndex = reference.animationIndex; edit_push(EDIT_LOOP, - [=](model::Model& model) + [=](Model& model) { if (auto animation = model.animation_edit(animationIndex)) animation->isLoop = isLoop; }); @@ -893,7 +891,7 @@ namespace anm2ed::imgui ImGui::SetNextItemWidth(widgetSize.x); if (input_int_range(localize.get(LABEL_FPS), fps, FPS_MIN, FPS_MAX)) { - edit_push(EDIT_FPS, [=](model::Model& model) { model.info.fps = fps; }); + edit_push(EDIT_FPS, [=](Model& model) { model.info.fps = fps; }); } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_FPS)); @@ -903,7 +901,7 @@ namespace anm2ed::imgui ImGui::SetNextItemWidth(widgetSize.x); if (input_text_string(localize.get(LABEL_AUTHOR), &createdBy)) { - edit_push(EDIT_AUTHOR, [=](model::Model& model) { model.info.createdBy = createdBy; }); + edit_push(EDIT_AUTHOR, [=](Model& model) { model.info.createdBy = createdBy; }); } ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_AUTHOR)); @@ -919,4 +917,3 @@ namespace anm2ed::imgui ImGui::SetCursorPos(cursorPos); } -} diff --git a/src/ui/timeline_menus.cpp b/src/ui/timeline_menus.cpp index b3a6fa3..13c26ba 100644 --- a/src/ui/timeline_menus.cpp +++ b/src/ui/timeline_menus.cpp @@ -1,12 +1,10 @@ #include "ui/timeline_context.h" -namespace anm2ed::imgui -{ constexpr StringType FRAME_PROPERTY_LABELS[] = { BASIC_POSITION, BASIC_SCALE, BASIC_ROTATION, BASIC_SKEW, BASIC_PIVOT, BASIC_CROP, BASIC_SIZE, BASIC_REGION, BASIC_TINT, BASIC_COLOR_OFFSET, BASIC_VISIBLE, BASIC_INTERPOLATED, BASIC_DURATION, BASIC_SHADER, BASIC_DEPTH, BASIC_BLUR, LABEL_CHILD, LABEL_EVENTS, LABEL_SOUNDS}; - static_assert(std::size(FRAME_PROPERTY_LABELS) == (std::size_t)edit::FrameProperty::COUNT); + static_assert(std::size(FRAME_PROPERTY_LABELS) == (std::size_t)FrameProperty::COUNT); void TimelineContext::frame_begin() { @@ -47,12 +45,12 @@ namespace anm2ed::imgui ImGui::PushStyleVar(ImGuiStyleVar_WindowPadding, style.WindowPadding); ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, style.ItemSpacing); - if (shortcut(manager.chords[SHORTCUT_CUT], shortcut::FOCUSED)) cut(); - if (shortcut(manager.chords[SHORTCUT_COPY], shortcut::FOCUSED)) copy(); - if (shortcut(manager.chords[SHORTCUT_PASTE], shortcut::FOCUSED)) paste(); - if (shortcut(manager.chords[SHORTCUT_SPLIT], shortcut::FOCUSED)) frame_split(); - if (shortcut(manager.chords[SHORTCUT_BAKE], shortcut::FOCUSED)) frames_bake(); - if (shortcut(manager.chords[SHORTCUT_FIT], shortcut::FOCUSED)) fit_animation_length(); + if (shortcut(manager.chords[SHORTCUT_CUT], SCOPE_FOCUSED)) cut(); + if (shortcut(manager.chords[SHORTCUT_COPY], SCOPE_FOCUSED)) copy(); + if (shortcut(manager.chords[SHORTCUT_PASTE], SCOPE_FOCUSED)) paste(); + if (shortcut(manager.chords[SHORTCUT_SPLIT], SCOPE_FOCUSED)) frame_split(); + if (shortcut(manager.chords[SHORTCUT_BAKE], SCOPE_FOCUSED)) frames_bake(); + if (shortcut(manager.chords[SHORTCUT_FIT], SCOPE_FOCUSED)) fit_animation_length(); auto make_region = [&]() { @@ -60,11 +58,11 @@ namespace anm2ed::imgui auto frame = frame_get(); if (!frame || targetReference.itemType != LAYER || targetReference.itemID == -1) return; if (frame->regionId != -1) return; - auto layer = model::item_get(model.content.layers, targetReference.itemID); + auto layer = ::item_get(model.content.layers, targetReference.itemID); if (!layer) return; auto spritesheetID = layer->spritesheetId; - if (!model::item_get(model.content.spritesheets, spritesheetID)) return; + if (!::item_get(model.content.spritesheets, spritesheetID)) return; auto settingsPtr = &settings; command_push( @@ -72,13 +70,13 @@ namespace anm2ed::imgui { auto frame = document.model.frame_get(targetReference); if (!frame || frame->regionId != -1) return; - auto layer = model::item_get(document.model.content.layers, targetReference.itemID); + auto layer = ::item_get(document.model.content.layers, targetReference.itemID); if (!layer) return; auto spritesheetID = layer->spritesheetId; - if (!model::item_get(document.model.content.spritesheets, spritesheetID)) return; + if (!::item_get(document.model.content.spritesheets, spritesheetID)) return; - model::Region region{.crop = frame->crop, .size = frame->size, .pivot = frame->pivot}; + Region region{.crop = frame->crop, .size = frame->size, .pivot = frame->pivot}; document.focused_id_set(SelectionKind::SPRITESHEETS, spritesheetID); settingsPtr->windowIsRegions = true; @@ -98,9 +96,9 @@ namespace anm2ed::imgui { if (frameReference.itemType != LAYER || frameReference.frameIndex < 0) return false; auto frame = document.model.frame_get(frameReference); - auto layer = model::item_get(model.content.layers, frameReference.itemID); + auto layer = ::item_get(model.content.layers, frameReference.itemID); return frame && frame->regionId == -1 && layer && - model::item_get(model.content.spritesheets, layer->spritesheetId); + ::item_get(model.content.spritesheets, layer->spritesheetId); }; auto selectedRegionFrames = selectedFrames; std::erase_if(selectedRegionFrames, @@ -137,7 +135,7 @@ namespace anm2ed::imgui actions.add( {.label = LABEL_FIT_ANIMATION_LENGTH, .shortcut = SHORTCUT_FIT, - .isEnabled = [&]() { return animation && animation->frameNum != model::animation_length_get(*animation); }, + .isEnabled = [&]() { return animation && animation->frameNum != animation_length_get(*animation); }, .run = [&]() { fit_animation_length(); }}); actions.separator(); actions.add({.label = isMakeManyRegions ? LABEL_MAKE_MANY_REGIONS : LABEL_MAKE_REGION, @@ -161,14 +159,14 @@ namespace anm2ed::imgui auto sourceFrame = source ? model.frame_get(*source) : nullptr; auto clipboardFrame = property_clipboard_frame_get(); // A submenu of the properties a frame type has. - auto properties_get = [&](int itemType, std::function is_property_enabled, - std::function property_run) + auto properties_get = [&](int itemType, std::function is_property_enabled, + std::function property_run) { Action properties{.label = LABEL_PROPERTY}; - for (int i = 0; i < (int)edit::FrameProperty::COUNT; ++i) + for (int i = 0; i < (int)FrameProperty::COUNT; ++i) { - auto property = (edit::FrameProperty)i; - if (!edit::is_frame_property_valid(property, (ItemType)itemType)) continue; + auto property = (FrameProperty)i; + if (!is_frame_property_valid(property, (ItemType)itemType)) continue; properties.children.push_back({.label = FRAME_PROPERTY_LABELS[i], .isEnabled = [=]() { return is_property_enabled(property); }, .run = [=]() { property_run(property); }}); @@ -188,15 +186,15 @@ namespace anm2ed::imgui property}}); }; auto sourceType = source ? source->itemType : NONE; - auto is_source = [=](edit::FrameProperty) { return sourceFrame != nullptr; }; + auto is_source = [=](FrameProperty) { return sourceFrame != nullptr; }; clipboard_menu_add( ACTION_CUT, [=, this]() { return !selectedFrames.empty(); }, [this]() { cut(); }, - properties_get(sourceType, is_source, [this](edit::FrameProperty property) { property_cut(property); })); + properties_get(sourceType, is_source, [this](FrameProperty property) { property_cut(property); })); clipboard_menu_add( ACTION_COPY, [=, this]() { return !copyFrames.empty(); }, [this]() { copy(); }, - properties_get(sourceType, is_source, [this](edit::FrameProperty property) { property_copy(property); })); + properties_get(sourceType, is_source, [this](FrameProperty property) { property_copy(property); })); // Only one property is ever on the clipboard, so pasting one is a single item. - auto clipboardProperty = (edit::FrameProperty)frameClipboard.property; + auto clipboardProperty = (FrameProperty)frameClipboard.property; clipboard_menu_add( ACTION_PASTE, [&]() { return !clipboard.is_empty(); }, [this]() { paste(); }, {.label = LABEL_PROPERTY, @@ -218,7 +216,7 @@ namespace anm2ed::imgui manager.item_properties_open(type == LAYER ? ElementType::LAYER_ELEMENT : ElementType::NULL_ELEMENT, id); } - void TimelineContext::group_properties_open(const TimelineRow& row, const model::TrackGroup& group) + void TimelineContext::group_properties_open(const TimelineRow& row, const TrackGroup& group) { groupName = group.name.empty() ? std::string(localize.get(TEXT_NEW_GROUP)) : group.name; groupAnimationIndex = reference.animationIndex; @@ -250,7 +248,7 @@ namespace anm2ed::imgui auto targetType = groupType; auto targetId = groupId; edit_push(EDIT_RENAME_GROUP, - [=](model::Model& model) + [=](Model& model) { if (auto group = model.track_group_edit(targetAnimationIndex, targetType, targetId)) group->name = targetName; @@ -276,7 +274,7 @@ namespace anm2ed::imgui auto selectedGroupableItems = item_references_groupable_get(); auto copyFrames = copy_frame_references_get(); TimelineRow selectedGroupRow{}; - const model::TrackGroup* selectedGroup{}; + const TrackGroup* selectedGroup{}; if (selectedRows.size() == 1 && selectedRows.front().isGroup) { auto row = selectedRows.front(); @@ -315,12 +313,11 @@ namespace anm2ed::imgui actions.add(ACTION_CUT, [=, this]() { return !copyFrames.empty() && isRemoveAvailable; }, item_cut); actions.add(ACTION_COPY, [=, this]() { return !copyFrames.empty(); }, [this]() { copy(); }); actions.add(ACTION_PASTE, [&]() { return item && !clipboard.is_empty(); }, [this]() { paste(); }); - if (shortcut(manager.chords[SHORTCUT_CUT], shortcut::FOCUSED) && !copyFrames.empty() && isRemoveAvailable) + if (shortcut(manager.chords[SHORTCUT_CUT], SCOPE_FOCUSED) && !copyFrames.empty() && isRemoveAvailable) item_cut(); - if (shortcut(manager.chords[SHORTCUT_COPY], shortcut::FOCUSED) && !copyFrames.empty()) copy(); - if (shortcut(manager.chords[SHORTCUT_PASTE], shortcut::FOCUSED) && item && !clipboard.is_empty()) paste(); + if (shortcut(manager.chords[SHORTCUT_COPY], SCOPE_FOCUSED) && !copyFrames.empty()) copy(); + if (shortcut(manager.chords[SHORTCUT_PASTE], SCOPE_FOCUSED) && item && !clipboard.is_empty()) paste(); actions_popup_draw("##Items Context Menu", actions, settings); ImGui::PopStyleVar(2); } -} diff --git a/src/ui/timeline_selection.cpp b/src/ui/timeline_selection.cpp index 1d5592d..bb73599 100644 --- a/src/ui/timeline_selection.cpp +++ b/src/ui/timeline_selection.cpp @@ -1,15 +1,13 @@ #include "ui/timeline_context.h" -namespace anm2ed::imgui -{ - const model::Track* TimelineContext::item_get(int type, int id, int groupType, int groupId) + const Track* TimelineContext::item_get(int type, int id, int groupType, int groupId) { - return animation ? model::animation_track_get(*animation, type, id, groupType, groupId) : nullptr; + return animation ? animation_track_get(*animation, type, id, groupType, groupId) : nullptr; } - const model::TrackGroup* TimelineContext::track_group_get(int type, int groupId) + const TrackGroup* TimelineContext::track_group_get(int type, int groupId) { - return animation ? model::animation_track_group_get(*animation, type, groupId) : nullptr; + return animation ? animation_track_group_get(*animation, type, groupId) : nullptr; } bool TimelineContext::is_track_group_visible(int type, int groupId) @@ -19,14 +17,14 @@ namespace anm2ed::imgui return !group || group->isVisible; } - const model::TrackGroup* TimelineContext::row_group_get(const TimelineRow& row) + const TrackGroup* TimelineContext::row_group_get(const TimelineRow& row) { return row.isGroup ? track_group_get(row.type, row.id) : nullptr; } - const model::Frame* TimelineContext::frame_get() { return document.model.frame_get(reference); } + const Frame* TimelineContext::frame_get() { return document.model.frame_get(reference); } - const model::Track* TimelineContext::selected_item_get() { return document.model.track_get(reference); } + const Track* TimelineContext::selected_item_get() { return document.model.track_get(reference); } glm::vec4 TimelineContext::color_get(TimelineColor color, int type) { @@ -114,7 +112,7 @@ namespace anm2ed::imgui std::vector rows{}; if (!animation) return rows; - auto is_track_shown = [&](const model::Track& track) + auto is_track_shown = [&](const Track& track) { return settings.timelineIsShowUnused || !track.frames.empty(); }; // Layers are listed top-down in reverse file order; nulls in file order. auto order_get = [](int count, bool isReversed) @@ -128,16 +126,16 @@ namespace anm2ed::imgui rows.push_back({.type = ROOT}); for (auto type : {LAYER, NULL_}) { - auto& entries = model::animation_entries_get(*animation, type); + auto& entries = animation_entries_get(*animation, type); auto isReversed = type == LAYER; for (auto index : order_get((int)entries.size(), isReversed)) { - if (auto track = std::get_if(&entries[index])) + if (auto track = std::get_if(&entries[index])) { if (is_track_shown(*track)) rows.push_back({.type = type, .id = track->id, .index = index}); continue; } - auto& group = std::get(entries[index]); + auto& group = std::get(entries[index]); rows.push_back({.type = type, .id = group.id, .index = index, .isGroup = true}); if (!group.isExpanded) continue; rows.push_back({.type = ROOT, .groupType = type, .groupId = group.id, .depth = 1}); @@ -181,7 +179,7 @@ namespace anm2ed::imgui return row.isGroup ? Reference{row.animationIndex, row.type, row.id} : row_item_reference_get(row); } - SelectionKind row_kind_get(const TimelineRow& row) + static SelectionKind row_kind_get(const TimelineRow& row) { return row.isGroup ? SelectionKind::GROUPS : SelectionKind::TRACKS; } @@ -215,7 +213,7 @@ namespace anm2ed::imgui else { if (row.type == LAYER) - if (auto layer = model::item_get(model.content.layers, row.id)) + if (auto layer = ::item_get(model.content.layers, row.id)) document.focused_id_set(SelectionKind::SPRITESHEETS, layer->spritesheetId); reference_set(row_item_reference_get(rowReference)); } @@ -306,4 +304,3 @@ namespace anm2ed::imgui if (rows.empty()) rows = {clicked}; return rows; } -} diff --git a/src/ui/timeline_tracks.cpp b/src/ui/timeline_tracks.cpp index 6b3a40a..6dc3b69 100644 --- a/src/ui/timeline_tracks.cpp +++ b/src/ui/timeline_tracks.cpp @@ -1,7 +1,5 @@ #include "ui/timeline_context.h" -namespace anm2ed::imgui -{ void TimelineContext::item_child(const TimelineRow& row, int index) { ImGui::PushID(index); @@ -41,7 +39,7 @@ namespace anm2ed::imgui auto targetRow = row; auto targetAnimationIndex = reference.animationIndex; edit_push(EDIT_TOGGLE_GROUP_EXPANDED, - [=](model::Model& model) + [=](Model& model) { if (auto group = model.track_group_edit(targetAnimationIndex, targetRow.type, targetRow.id)) group->isExpanded = !group->isExpanded; @@ -109,7 +107,7 @@ namespace anm2ed::imgui } ImGui::SetCursorPos(cursorPos); - auto folderIcon = group->isExpanded ? icon::FOLDER_OPEN : icon::FOLDER; + auto folderIcon = group->isExpanded ? ICON_FOLDER_OPEN : ICON_FOLDER; ImGui::Image(resources.icon_id_get(folderIcon), icon_size_get()); auto iconMin = ImGui::GetItemRectMin(); auto iconMax = ImGui::GetItemRectMax(); @@ -128,7 +126,7 @@ namespace anm2ed::imgui ImGui::SetCursorPos(ImVec2(itemSize.x - ImGui::GetTextLineHeightWithSpacing() - ImGui::GetStyle().ItemSpacing.x, (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); - int visibleIcon = isGroupVisible ? icon::VISIBLE : icon::INVISIBLE; + int visibleIcon = isGroupVisible ? ICON_VISIBLE : ICON_INVISIBLE; if (ImGui::ImageButton("##Group Visible Toggle", resources.icon_id_get(visibleIcon), icon_size_get())) { auto targetAnimationIndex = reference.animationIndex; @@ -136,7 +134,7 @@ namespace anm2ed::imgui auto targetGroupId = group->id; auto targetVisible = !isGroupVisible; edit_push(EDIT_TOGGLE_ITEM_VISIBILITY, - [=](model::Model& model) + [=](Model& model) { if (auto group = model.track_group_edit(targetAnimationIndex, targetType, targetGroupId)) group->isVisible = targetVisible; @@ -155,7 +153,7 @@ namespace anm2ed::imgui if (isGroupTooltipDelayed && !isVisibleButtonHovered) { ImGui::BeginTooltip(); - ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); + ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE); ImGui::TextUnformatted(label.c_str()); ImGui::PopFont(); ImGui::TextUnformatted(std::vformat(localize.get(FORMAT_ID), std::make_format_args(group->id)).c_str()); @@ -201,13 +199,13 @@ namespace anm2ed::imgui { if (type == LAYER) { - auto layer = model::item_get(model.content.layers, id); + auto layer = ::item_get(model.content.layers, id); if (!layer) return localize.get(TYPE_STRINGS[type]); return layer_label_get(*layer); } if (type == NULL_) { - auto null = model::item_get(model.content.nulls, id); + auto null = ::item_get(model.content.nulls, id); if (!null) return localize.get(TYPE_STRINGS[type]); return std::vformat(localize.get(FORMAT_NULL), std::make_format_args(id, null->name)); } @@ -269,7 +267,7 @@ namespace anm2ed::imgui } } - auto animationLayer = type == LAYER ? model::item_get(model.content.layers, id) : nullptr; + auto animationLayer = type == LAYER ? ::item_get(model.content.layers, id) : nullptr; if (animationLayer && !animationLayer->is_animation()) animationLayer = nullptr; if (isItemButtonHovered) { @@ -299,7 +297,7 @@ namespace anm2ed::imgui { case ROOT: { - ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); + ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE); ImGui::TextUnformatted(localize.get(BASIC_ROOT)); ImGui::PopFont(); @@ -314,9 +312,9 @@ namespace anm2ed::imgui } case LAYER: { - auto layer = model::item_get(model.content.layers, id); + auto layer = ::item_get(model.content.layers, id); if (!layer) break; - ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); + ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE); ImGui::TextUnformatted(layer->name.c_str()); ImGui::PopFont(); @@ -330,9 +328,9 @@ namespace anm2ed::imgui } case NULL_: { - auto nullInfo = model::item_get(model.content.nulls, id); + auto nullInfo = ::item_get(model.content.nulls, id); if (!nullInfo) break; - ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); + ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE); ImGui::TextUnformatted(nullInfo->name.c_str()); ImGui::PopFont(); @@ -348,7 +346,7 @@ namespace anm2ed::imgui } case TRIGGER: { - ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE); + ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE); ImGui::TextUnformatted(localize.get(BASIC_TRIGGERS)); ImGui::PopFont(); @@ -372,7 +370,7 @@ namespace anm2ed::imgui // An animation layer's icon is a folder that shows (or hides) its child's tracks. auto isExpanded = item && expandedLayerTracks.contains(item->uid); - if (animationLayer) icon = isExpanded ? icon::FOLDER_OPEN : icon::FOLDER; + if (animationLayer) icon = isExpanded ? ICON_FOLDER_OPEN : ICON_FOLDER; ImGui::Image(resources.icon_id_get(icon), icon_size_get()); auto mousePos = ImGui::GetIO().MousePos; auto iconMin = ImGui::GetItemRectMin(); @@ -389,7 +387,7 @@ namespace anm2ed::imgui } overlay_icon(resources.icon_id_get(icon), iconTintCurrent, false); ImGui::SameLine(); - if (isReferenced) ImGui::PushFont(resources.fonts[font::ITALICS].get(), font::SIZE); + if (isReferenced) ImGui::PushFont(resources.fonts[FONT_ITALICS].get(), FONT_SIZE); ImGui::PushStyleColor(ImGuiCol_Text, itemTextColor); ImGui::TextUnformatted(label.c_str()); ImGui::PopStyleColor(); @@ -403,7 +401,7 @@ namespace anm2ed::imgui ImGui::SetCursorPos(ImVec2(itemSize.x - ImGui::GetTextLineHeightWithSpacing() - ImGui::GetStyle().ItemSpacing.x, (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); - int visibleIcon = isItemVisible ? icon::VISIBLE : icon::INVISIBLE; + int visibleIcon = isItemVisible ? ICON_VISIBLE : ICON_INVISIBLE; if (ImGui::ImageButton("##Visible Toggle", resources.icon_id_get(visibleIcon), icon_size_get())) { auto animationIndex = reference.animationIndex; @@ -412,7 +410,7 @@ namespace anm2ed::imgui auto targetGroupType = row.groupType; auto targetGroupId = row.groupId; edit_push(EDIT_TOGGLE_ITEM_VISIBILITY, - [=](model::Model& model) + [=](Model& model) { if (auto item = model.track_edit( Reference{animationIndex, targetType, targetID, -1, targetGroupType, targetGroupId})) @@ -425,10 +423,10 @@ namespace anm2ed::imgui if (type == NULL_) { - if (auto null = model::item_get(model.content.nulls, id)) + if (auto null = ::item_get(model.content.nulls, id)) { auto& isShowRect = null->isShowRect; - auto rectIcon = isShowRect ? icon::SHOW_RECT : icon::HIDE_RECT; + auto rectIcon = isShowRect ? ICON_SHOW_RECT : ICON_HIDE_RECT; ImGui::SetCursorPos( ImVec2(itemSize.x - (ImGui::GetTextLineHeightWithSpacing() * 2) - ImGui::GetStyle().ItemSpacing.x, (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); @@ -436,9 +434,9 @@ namespace anm2ed::imgui { auto nullID = id; edit_push(EDIT_TOGGLE_NULL_RECT, - [=](model::Model& model) + [=](Model& model) { - if (auto null = model::item_get(model.content.nulls, nullID)) + if (auto null = ::item_get(model.content.nulls, nullID)) null->isShowRect = !null->isShowRect; }); } @@ -463,7 +461,7 @@ namespace anm2ed::imgui (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); auto& isShowUnused = settings.timelineIsShowUnused; - auto unusedIcon = isShowUnused ? icon::SHOW_UNUSED : icon::HIDE_UNUSED; + auto unusedIcon = isShowUnused ? ICON_SHOW_UNUSED : ICON_HIDE_UNUSED; if (ImGui::ImageButton("##Unused Toggle", resources.icon_id_get(unusedIcon), icon_size_get())) isShowUnused = !isShowUnused; overlay_icon(resources.icon_id_get(unusedIcon), iconTintCurrent, false); @@ -471,7 +469,7 @@ namespace anm2ed::imgui : localize.get(TOOLTIP_UNUSED_ITEMS_HIDDEN)); auto& showLayersOnly = settings.timelineIsOnlyShowLayers; - auto layersIcon = showLayersOnly ? icon::SHOW_LAYERS : icon::HIDE_LAYERS; + auto layersIcon = showLayersOnly ? ICON_SHOW_LAYERS : ICON_HIDE_LAYERS; ImGui::SetCursorPos( ImVec2(itemSize.x - (ImGui::GetTextLineHeightWithSpacing() * 2) - ImGui::GetStyle().ItemSpacing.x, (itemSize.y - ImGui::GetTextLineHeightWithSpacing()) / 2)); @@ -537,7 +535,7 @@ namespace anm2ed::imgui document.frame_references_clear(); } - if (animation && shortcut(manager.chords[SHORTCUT_GROUP], shortcut::FOCUSED) && + if (animation && shortcut(manager.chords[SHORTCUT_GROUP], SCOPE_FOCUSED) && !item_references_groupable_get().empty()) item_group(); @@ -615,4 +613,3 @@ namespace anm2ed::imgui } ImGui::EndChild(); } -} diff --git a/src/ui/toast.cpp b/src/ui/toast.cpp index 540469f..fd31e7a 100644 --- a/src/ui/toast.cpp +++ b/src/ui/toast.cpp @@ -8,10 +8,6 @@ #include "types.h" -using namespace anm2ed::types; - -namespace anm2ed::imgui -{ constexpr auto LIFETIME = 4.0f; constexpr auto FADE_THRESHOLD = 1.0f; @@ -70,6 +66,5 @@ namespace anm2ed::imgui } void Toasts::push(const std::string& message) { toasts.emplace_back(Toast(message)); } -} -anm2ed::imgui::Toasts toasts; +Toasts toasts; diff --git a/src/ui/toast.h b/src/ui/toast.h index a1ebfad..cd614aa 100644 --- a/src/ui/toast.h +++ b/src/ui/toast.h @@ -7,8 +7,6 @@ #include "log.h" #include "localization.h" -namespace anm2ed::imgui -{ class Toast { public: @@ -27,12 +25,8 @@ namespace anm2ed::imgui void push(const std::string&); }; -} +extern Toasts toasts; -extern anm2ed::imgui::Toasts toasts; - -namespace anm2ed -{ template void toast_log(Level level, StringType type, Args&&... args) { auto format = [&](Language language) -> std::string @@ -45,4 +39,3 @@ namespace anm2ed toasts.push(format(localize.language)); logger.write(level, format(ENGLISH)); } -} diff --git a/src/ui/tools.cpp b/src/ui/tools.cpp index a46e60e..789d4e5 100644 --- a/src/ui/tools.cpp +++ b/src/ui/tools.cpp @@ -9,12 +9,8 @@ #include "ui/layout.h" #include "ui/shortcut.h" -using namespace anm2ed::resource; -using namespace anm2ed::types; using namespace glm; -namespace anm2ed::imgui -{ void tools_update(Manager& manager, Settings& settings, Resources& resources, PopupHelper& colorEditPopup) { auto& document = *manager.get(); @@ -27,19 +23,19 @@ namespace anm2ed::imgui auto size = vec2(ImGui::GetTextLineHeightWithSpacing() * 1.5f); auto usedWidth = ImGui::GetStyle().WindowPadding.x; - auto tool_use = [&](tool::Type type) + auto tool_use = [&](Tool type) { switch (type) { - case tool::UNDO: + case TOOL_UNDO: if (document.is_able_to_undo()) manager.command_push({manager.selected, [](Manager&, Document& document) { document.undo(); }}); break; - case tool::REDO: + case TOOL_REDO: if (document.is_able_to_redo()) manager.command_push({manager.selected, [](Manager&, Document& document) { document.redo(); }}); break; - case tool::COLOR: + case TOOL_COLOR: colorEditPopup.open(); break; default: @@ -48,34 +44,34 @@ namespace anm2ed::imgui } }; - auto iconTint = settings.theme == theme::LIGHT ? ImVec4(0.0f, 0.0f, 0.0f, 1.0f) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f); + auto iconTint = settings.theme == THEME_LIGHT ? ImVec4(0.0f, 0.0f, 0.0f, 1.0f) : ImVec4(1.0f, 1.0f, 1.0f, 1.0f); - for (int i = 0; i < tool::COUNT; i++) + for (int i = 0; i < TOOL_COUNT; i++) { - auto& info = tool::INFO[i]; + auto& info = TOOLS[i]; auto isSelected = settings.tool == i; if (isSelected) ImGui::PushStyleColor(ImGuiCol_Button, ImGui::GetStyleColorVec4(ImGuiCol_ButtonActive)); - if (shortcut(manager.chords[info.shortcut], shortcut::GLOBAL)) tool_use((tool::Type)i); + if (shortcut(manager.chords[info.shortcut], SCOPE_GLOBAL)) tool_use((Tool)i); auto labelText = info.label; - if (i == tool::COLOR) + if (i == TOOL_COLOR) { size += to_vec2(ImGui::GetStyle().FramePadding) * 2.0f; if (ImGui::ColorButton(labelText, to_imvec4(settings.toolColor), ImGuiColorEditFlags_NoTooltip, to_imvec2(size))) - tool_use((tool::Type)i); + tool_use((Tool)i); } else { - if (i == tool::UNDO) ImGui::BeginDisabled(!document.is_able_to_undo()); - if (i == tool::REDO) ImGui::BeginDisabled(!document.is_able_to_redo()); + if (i == TOOL_UNDO) ImGui::BeginDisabled(!document.is_able_to_undo()); + if (i == TOOL_REDO) ImGui::BeginDisabled(!document.is_able_to_redo()); if (ImGui::ImageButton(labelText, resources.icon_id_get(info.icon), to_imvec2(size), ImVec2(0, 0), ImVec2(1, 1), ImVec4(0, 0, 0, 0), iconTint)) - tool_use((tool::Type)i); - if (i == tool::UNDO) ImGui::EndDisabled(); - if (i == tool::REDO) ImGui::EndDisabled(); + tool_use((Tool)i); + if (i == TOOL_UNDO) ImGui::EndDisabled(); + if (i == TOOL_REDO) ImGui::EndDisabled(); } auto widthIncrement = ImGui::GetItemRectSize().x + ImGui::GetStyle().ItemSpacing.x; @@ -102,4 +98,3 @@ namespace anm2ed::imgui } ImGui::End(); } -} diff --git a/src/ui/tree.cpp b/src/ui/tree.cpp index a05f8ce..0b01170 100644 --- a/src/ui/tree.cpp +++ b/src/ui/tree.cpp @@ -1,7 +1,5 @@ #include "ui/tree.h" -namespace anm2ed::imgui -{ TreeNodeInputTextResult tree_node_input_text(const std::string& label, const std::string& id, std::string& text, bool isSelected, ImGuiTreeNodeFlags flags, RenameState& state) { @@ -38,4 +36,3 @@ namespace anm2ed::imgui result.isRenameFinished = state == RENAME_FINISHED; return result; } -} diff --git a/src/ui/tree.h b/src/ui/tree.h index 9d19456..45d2771 100644 --- a/src/ui/tree.h +++ b/src/ui/tree.h @@ -6,8 +6,6 @@ #include "ui/selectable.h" -namespace anm2ed::imgui -{ struct TreeNodeInputTextResult { bool isOpen{}; @@ -19,4 +17,3 @@ namespace anm2ed::imgui TreeNodeInputTextResult tree_node_input_text(const std::string&, const std::string&, std::string&, bool, ImGuiTreeNodeFlags, RenameState&); -} diff --git a/src/ui/welcome.cpp b/src/ui/welcome.cpp index 96fb5bf..d20f5f4 100644 --- a/src/ui/welcome.cpp +++ b/src/ui/welcome.cpp @@ -10,11 +10,6 @@ #include "ui/layout.h" #include "ui/selectable.h" -using namespace anm2ed::util; -using namespace anm2ed::resource; - -namespace anm2ed::imgui -{ void welcome_update(Manager& manager, Resources& resources, Dialog& dialog, Taskbar& taskbar, Documents& documents) { auto viewport = ImGui::GetMainViewport(); @@ -30,7 +25,7 @@ namespace anm2ed::imgui ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoNavFocus | ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse)) { - ImGui::PushFont(resources.fonts[font::BOLD].get(), font::SIZE_LARGE); + ImGui::PushFont(resources.fonts[FONT_BOLD].get(), FONT_SIZE_LARGE); ImGui::TextUnformatted(localize.get(LABEL_APPLICATION_NAME)); ImGui::PopFont(); @@ -51,7 +46,7 @@ namespace anm2ed::imgui { ImGui::PushID(i); - auto label = std::format(FILE_LABEL_FORMAT, path::to_utf8(file.filename()), path::to_utf8(file)); + auto label = std::format(FILE_LABEL_FORMAT, path_to_utf8(file.filename()), path_to_utf8(file)); if (ImGui::Selectable(label.c_str())) { @@ -70,4 +65,3 @@ namespace anm2ed::imgui selectable_input_text_id() = {}; } -} diff --git a/src/uid.h b/src/uid.h index 1c18cc7..863bfe2 100644 --- a/src/uid.h +++ b/src/uid.h @@ -3,12 +3,9 @@ #include #include -namespace anm2ed::util -{ // Process-unique, never reused; 0 means "none". inline std::uint64_t uid_next() { static std::atomic next{1}; return next++; } -} diff --git a/src/vector.h b/src/vector.h index 9d8e567..25a3ff4 100644 --- a/src/vector.h +++ b/src/vector.h @@ -5,24 +5,22 @@ #include #include -namespace anm2ed::util::vector -{ - template T* find(std::vector& v, int index) + template T* vector_find(std::vector& v, int index) { return index >= 0 && index < (int)v.size() ? &v[index] : nullptr; } - template int find_index(const std::vector& v, const T& value) + template int vector_index_find(const std::vector& v, const T& value) { auto it = std::find(v.begin(), v.end(), value); if (it == v.end()) return -1; return (int)(std::distance(v.begin(), it)); } - template bool in_bounds(std::vector& v, int index) { return index >= 0 && index < (int)v.size(); } + template bool is_vector_in_bounds(std::vector& v, int index) { return index >= 0 && index < (int)v.size(); } template - std::set move_indices_to_position(std::vector& v, const std::vector& indices, int insertPos) + std::set vector_indices_move(std::vector& v, const std::vector& indices, int insertPos) { if (indices.empty()) return {}; @@ -54,4 +52,3 @@ namespace anm2ed::util::vector return moveIndices; } -} diff --git a/src/working_directory.cpp b/src/working_directory.cpp index e5308a8..f11da8b 100644 --- a/src/working_directory.cpp +++ b/src/working_directory.cpp @@ -5,8 +5,6 @@ #include "log.h" #include "path.h" -namespace anm2ed::util -{ WorkingDirectory::WorkingDirectory(const std::filesystem::path& path, Type type) { std::error_code ec{}; @@ -25,13 +23,13 @@ namespace anm2ed::util std::filesystem::current_path(parentPath, ec); if (ec) logger.warning( - std::format("Could not set current directory to {}: {}", path::to_utf8(parentPath), ec.message())); + std::format("Could not set current directory to {}: {}", path_to_utf8(parentPath), ec.message())); } else { std::filesystem::current_path(path, ec); if (ec) - logger.warning(std::format("Could not set current directory to {}: {}", path::to_utf8(path), ec.message())); + logger.warning(std::format("Could not set current directory to {}: {}", path_to_utf8(path), ec.message())); } } @@ -43,6 +41,5 @@ namespace anm2ed::util std::filesystem::current_path(previous, ec); if (ec) logger.warning( - std::format("Could not restore current directory to {}: {}", path::to_utf8(previous), ec.message())); + std::format("Could not restore current directory to {}: {}", path_to_utf8(previous), ec.message())); } -} diff --git a/src/working_directory.h b/src/working_directory.h index 55974f0..e99e5d1 100644 --- a/src/working_directory.h +++ b/src/working_directory.h @@ -2,8 +2,6 @@ #include -namespace anm2ed::util -{ class WorkingDirectory { public: @@ -18,4 +16,3 @@ namespace anm2ed::util WorkingDirectory(const std::filesystem::path&, Type type = DIRECTORY); ~WorkingDirectory(); }; -} \ No newline at end of file diff --git a/tests/assets.cpp b/tests/assets.cpp index e080ef8..802d9e2 100644 --- a/tests/assets.cpp +++ b/tests/assets.cpp @@ -8,9 +8,6 @@ #include "image.h" #include "model/xml.h" -using namespace anm2ed; -using namespace anm2ed::resource; - TEST_CASE("Image png round trip and uid tracking") { const std::vector pixels{255, 0, 0, 255, 0, 255, 0, 128, 0, 0, 255, 0, 10, 20, 30, 40}; @@ -66,7 +63,7 @@ TEST_CASE("AssetStore keys assets by content") TEST_CASE("an SVG spritesheet loads in SVG units and draws again at any scale") { - Image image(test::TEST_DIR / "render" / "vector.svg"); + Image image(TEST_DIR / "render" / "vector.svg"); REQUIRE(image.is_valid()); CHECK(image.is_vector()); CHECK(image.size == glm::ivec2(32, 16)); @@ -82,7 +79,7 @@ TEST_CASE("an SVG spritesheet loads in SVG units and draws again at any scale") TEST_CASE("SVG spritesheets compose into SVGs that draw the same") { - Image vector(test::TEST_DIR / "render" / "vector.svg"); + Image vector(TEST_DIR / "render" / "vector.svg"); REQUIRE(vector.is_vector()); // The circle (left half) and the square (right half) swapped: each part is a clipped view of the drawing. @@ -111,7 +108,7 @@ TEST_CASE("an SVG's shapes meet without a seam") )"); auto path = std::filesystem::temp_directory_path() / "anm2ed_seam.svg"; - test::file_save(path, *text); + file_save(path, *text); Image image(path); std::filesystem::remove(path); REQUIRE(image.is_vector()); @@ -123,17 +120,17 @@ TEST_CASE("an SVG's shapes meet without a seam") TEST_CASE("Embedded resources load") { - for (auto& info : friends::FRIENDS) + for (auto& info : FRIENDS) { INFO("friend: ", info.name); - model::Model model{}; + Model model{}; std::string errorString{}; - CHECK(model::model_load_string(model, std::string_view((const char*)info.anm2->data, info.anm2->size), &errorString)); + CHECK(model_load_string(model, std::string_view((const char*)info.anm2->data, info.anm2->size), &errorString)); CHECK(model.animations_count_get() > 0); CHECK(Image(info.png->data, info.png->size).is_valid()); } - for (auto& icon : icon::ICONS) + for (auto& icon : ICONS) CHECK(std::string_view((const char*)icon.svg->data, icon.svg->size).starts_with("size > 0); } diff --git a/tests/common.h b/tests/common.h index 9ef6b0d..63e800a 100644 --- a/tests/common.h +++ b/tests/common.h @@ -12,8 +12,6 @@ #include "model/json.h" #include "model/xml.h" -namespace anm2ed::test -{ inline const std::filesystem::path TEST_DIR = ANM2ED_TEST_DIR; inline const std::filesystem::path CORPUS_DIR = TEST_DIR / "corpus"; inline const std::filesystem::path GOLDEN_DIR = TEST_DIR / "golden"; @@ -22,10 +20,10 @@ namespace anm2ed::test {"editor", SERIALIZE_EDITOR_DEFAULT}, {"isaac", SERIALIZE_ISAAC_DEFAULT}, {"anm2ed", SERIALIZE_ANM2ED_DEFAULT}}; - inline constexpr std::pair MERGES[] = {{"merge_prepend", types::merge::PREPEND}, - {"merge_append", types::merge::APPEND}, - {"merge_replace", types::merge::REPLACE}, - {"merge_ignore", types::merge::IGNORE}}; + inline constexpr std::pair MERGES[] = {{"merge_prepend", MERGE_PREPEND}, + {"merge_append", MERGE_APPEND}, + {"merge_replace", MERGE_REPLACE}, + {"merge_ignore", MERGE_IGNORE}}; using Variant = std::pair; @@ -52,27 +50,27 @@ namespace anm2ed::test return fixtures; } - inline model::Model model_load(const std::string& text) + inline Model model_load(const std::string& text) { - model::Model model{}; - REQUIRE(model::model_load_string(model, text)); + Model model{}; + REQUIRE(model_load_string(model, text)); return model; } // Every serialization and merge the editor can produce for a document; goldens lock each one down. - inline std::vector variants_get(const model::Model& model) + inline std::vector variants_get(const Model& model) { std::vector variants{}; for (auto [name, flags] : PRESETS) - variants.emplace_back(name, model::model_serialize(model, flags)); - variants.emplace_back("save", model::model_to_string(model)); + variants.emplace_back(name, model_serialize(model, flags)); + variants.emplace_back("save", model_to_string(model)); for (auto [name, type] : MERGES) { auto merged = model; std::set sources{0, 1, 2}; - edit::animations_merge(merged, 0, sources, type, type == types::merge::PREPEND || type == types::merge::REPLACE, + animations_merge(merged, 0, sources, type, type == MERGE_PREPEND || type == MERGE_REPLACE, {}); - variants.emplace_back(name, model::model_serialize(merged, SERIALIZE_ANM2ED_DEFAULT)); + variants.emplace_back(name, model_serialize(merged, SERIALIZE_ANM2ED_DEFAULT)); } return variants; } @@ -88,19 +86,19 @@ namespace anm2ed::test } // Save/reload properties every document must hold. - inline void invariants_check(const model::Model& model) + inline void invariants_check(const Model& model) { // The first save may repair invalid input (dangling ids, duplicates); after that, saves must be fixed points. - auto text = model::model_to_string(model); + auto text = model_to_string(model); auto reloaded = model_load(text); - auto resaved = model::model_to_string(reloaded); + auto resaved = model_to_string(reloaded); CHECK(resaved == text); - CHECK(model::model_hash(model_load(resaved)) == model::model_hash(reloaded)); + CHECK(model_hash(model_load(resaved)) == model_hash(reloaded)); // Loading only the game's view and re-saving it for the game must not change it. - auto game = game_document_get(model::model_to_string(model)); - CHECK(model::model_serialize(model_load(game), SERIALIZE_ISAAC_DEFAULT | SERIALIZE_PURGE_DEFAULT_COLORS) == game); + auto game = game_document_get(model_to_string(model)); + CHECK(model_serialize(model_load(game), SERIALIZE_ISAAC_DEFAULT | SERIALIZE_PURGE_DEFAULT_COLORS) == game); } // Compares against a stored golden; ANM2ED_UPDATE_GOLDEN (or a missing golden when isBootstrap) rewrites it. @@ -115,4 +113,3 @@ namespace anm2ed::test REQUIRE(std::filesystem::exists(path)); CHECK(file_load(path) == text); } -} diff --git a/tests/corpus_local.cpp b/tests/corpus_local.cpp index a3bb30e..0e58218 100644 --- a/tests/corpus_local.cpp +++ b/tests/corpus_local.cpp @@ -1,8 +1,5 @@ #include "common.h" -using namespace anm2ed; -using namespace anm2ed::test; - // Private corpus run: ANM2ED_CORPUS=. Baselines are written on first sight to // ANM2ED_CORPUS_BASELINE (default ~/.cache/anm2ed/corpus) and compared on every later run. Nothing here is committed. TEST_CASE("local corpus matches baselines" * doctest::skip(!is_env_set("ANM2ED_CORPUS"))) @@ -17,9 +14,9 @@ TEST_CASE("local corpus matches baselines" * doctest::skip(!is_env_set("ANM2ED_C if (line.empty()) continue; INFO("file: ", line); auto key = std::format("{:016x}", std::hash{}(line)); - model::Model anm2{}; + Model anm2{}; std::string error{}; - if (!model::model_load(anm2, line, &error)) + if (!model_load(anm2, line, &error)) { golden_check(baseline / (key + ".error.txt"), error, true); continue; diff --git a/tests/draw.cpp b/tests/draw.cpp index 0222356..b28f724 100644 --- a/tests/draw.cpp +++ b/tests/draw.cpp @@ -4,36 +4,33 @@ #include "model/draw.h" #include "model/frames.h" -using namespace anm2ed; -using namespace anm2ed::test; - TEST_CASE("draw lists put the root first and each item's onion samples before it") { auto anm2 = model_load(file_load(CORPUS_DIR / "02_items.anm2")); auto& animation = *anm2.animation_get(0); - auto draws = model::animation_draws_get(anm2, animation, {.time = 1.0f, .samples = {{-1.0f}, {1.0f}}}); + auto draws = animation_draws_get(anm2, animation, {.time = 1.0f, .samples = {{-1.0f}, {1.0f}}}); REQUIRE(!draws.empty()); - CHECK(draws.front().type == model::DrawType::ROOT); + CHECK(draws.front().type == DrawType::ROOT); for (int i = 0; i + 1 < (int)draws.size(); ++i) if (draws[i].sample != -1) CHECK((draws[i + 1].id == draws[i].id && draws[i + 1].type == draws[i].type)); - auto layerDraws = std::ranges::count_if(draws, [](const model::Draw& draw) - { return draw.type == model::DrawType::LAYER && draw.sample == -1; }); + auto layerDraws = std::ranges::count_if(draws, [](const Draw& draw) + { return draw.type == DrawType::LAYER && draw.sample == -1; }); CHECK(layerDraws > 0); - CHECK(model::animation_rect(anm2, animation, true) != glm::vec4(-1.0f)); + CHECK(animation_rect(anm2, animation, true) != glm::vec4(-1.0f)); } TEST_CASE("root transforms fold into layer draws") { auto anm2 = model_load(file_load(CORPUS_DIR / "04_group_root_transform.anm2")); auto& animation = *anm2.animation_get(0); - auto plain = model::animation_draws_get(anm2, animation, {}); - auto rooted = model::animation_draws_get(anm2, animation, {.isRootTransform = true}); + auto plain = animation_draws_get(anm2, animation, {}); + auto rooted = animation_draws_get(anm2, animation, {.isRootTransform = true}); REQUIRE(plain.size() == rooted.size()); bool isAnyMoved{}; for (int i = 0; i < (int)plain.size(); ++i) - isAnyMoved |= plain[i].type == model::DrawType::LAYER && plain[i].parent != rooted[i].parent; + isAnyMoved |= plain[i].type == DrawType::LAYER && plain[i].parent != rooted[i].parent; CHECK(isAnyMoved); } @@ -43,8 +40,8 @@ TEST_CASE("a layer frame's depth moves it among the layers for that frame only") auto layer_ids_get = [&](float time) { std::vector ids{}; - for (const auto& draw : model::animation_draws_get(anm2, *anm2.animation_get(0), {.time = time})) - if (draw.type == model::DrawType::LAYER) ids.push_back(draw.id); + for (const auto& draw : animation_draws_get(anm2, *anm2.animation_get(0), {.time = time})) + if (draw.type == DrawType::LAYER) ids.push_back(draw.id); return ids; }; CHECK(layer_ids_get(0.0f) == std::vector{1, 0}); @@ -53,10 +50,10 @@ TEST_CASE("a layer frame's depth moves it among the layers for that frame only") CHECK(layer_ids_get(0.0f) == std::vector{0, 1}); CHECK(layer_ids_get(5.0f) == std::vector{1, 0}); - auto text = model::model_to_string(anm2); + auto text = model_to_string(anm2); CHECK(game_document_get(text).find("Depth") == std::string::npos); CHECK(model_load(text).frame_get({0, LAYER, 0, 0})->depth == -1); - CHECK(model::isaac_issues_get(anm2).depthFrames == 1); + CHECK(isaac_issues_get(anm2).depthFrames == 1); } TEST_CASE("a layer frame's blur reaches its child's draws and stays out of the game's copy") @@ -64,30 +61,30 @@ TEST_CASE("a layer frame's blur reaches its child's draws and stays out of the g auto anm2 = model_load(file_load(TEST_DIR / "render" / "nested.anm2")); anm2.frame_edit({0, LAYER, 1, 0})->blur = 6.0f; bool isAnyChild{}; - for (const auto& draw : model::animation_draws_get(anm2, *anm2.animation_get(0), {})) - if (draw.type == model::DrawType::LAYER && draw.id == 1) + for (const auto& draw : animation_draws_get(anm2, *anm2.animation_get(0), {})) + if (draw.type == DrawType::LAYER && draw.id == 1) { isAnyChild = true; CHECK(draw.frame.blur >= 6.0f); } CHECK(isAnyChild); - auto text = model::model_to_string(anm2); + auto text = model_to_string(anm2); CHECK(game_document_get(text).find("Blur") == std::string::npos); CHECK(model_load(text).frame_get({0, LAYER, 1, 0})->blur == 6.0f); - CHECK(model::isaac_issues_get(anm2).blurFrames == 1); + CHECK(isaac_issues_get(anm2).blurFrames == 1); } TEST_CASE("an animation layer draws its child animation, from this file or a library") { auto anm2 = model_load(file_load(TEST_DIR / "render" / "nested.anm2")); auto spin = model_load(file_load(TEST_DIR / "render" / "spin.anm2")); - model::DrawOptions options{.library_get = [&](const model::Model&, int id) { return id == 0 ? &spin : nullptr; }}; + DrawOptions options{.library_get = [&](const Model&, int id) { return id == 0 ? &spin : nullptr; }}; auto red_position_get = [&](int layerId) { std::optional position{}; - for (const auto& draw : model::animation_draws_get(anm2, *anm2.animation_get(0), options)) - if (draw.type == model::DrawType::LAYER && draw.id == layerId && draw.frame.crop == glm::vec2()) + for (const auto& draw : animation_draws_get(anm2, *anm2.animation_get(0), options)) + if (draw.type == DrawType::LAYER && draw.id == layerId && draw.frame.crop == glm::vec2()) position = glm::vec2(draw.parent * glm::vec4(draw.frame.position, 0.0f, 1.0f)); return position; }; @@ -111,28 +108,28 @@ TEST_CASE("an animation layer draws its child animation, from this file or a lib options.library_get = {}; CHECK_FALSE(red_position_get(0)); - auto text = model::model_serialize(anm2, SERIALIZE_ANM2ED_DEFAULT); - CHECK(model::model_hash(model_load(text)) == model::model_hash(anm2)); - CHECK(model::isaac_issues_get(anm2).animationLayers == 3); - CHECK(game_document_get(model::model_to_string(anm2)).find(" Animation=\"") == std::string::npos); + auto text = model_serialize(anm2, SERIALIZE_ANM2ED_DEFAULT); + CHECK(model_hash(model_load(text)) == model_hash(anm2)); + CHECK(isaac_issues_get(anm2).animationLayers == 3); + CHECK(game_document_get(model_to_string(anm2)).find(" Animation=\"") == std::string::npos); } TEST_CASE("an alpha offset is kept by the editor's copy only") { auto anm2 = model_load(file_load(TEST_DIR / "render" / "spin.anm2")); anm2.frame_edit({0, LAYER, 0, 0})->colorOffset.a = -0.5f; - auto text = model::model_to_string(anm2); + auto text = model_to_string(anm2); CHECK(game_document_get(text).find("AlphaOffset") == std::string::npos); CHECK(model_load(text).frame_get({0, LAYER, 0, 0})->colorOffset.a == doctest::Approx(-127.0f / 255.0f)); - CHECK(model::isaac_issues_get(anm2).alphaOffsetFrames == 1); + CHECK(isaac_issues_get(anm2).alphaOffsetFrames == 1); } TEST_CASE("only SVG spritesheets that layers show count against Rebirth") { auto anm2 = model_load(file_load(TEST_DIR / "render" / "vector.anm2")); - CHECK(model::spritesheets_vector_used_get(anm2) == std::set{0}); + CHECK(spritesheets_vector_used_get(anm2) == std::set{0}); anm2.content.layers.clear(); - CHECK(model::spritesheets_vector_used_get(anm2).empty()); + CHECK(spritesheets_vector_used_get(anm2).empty()); } TEST_CASE("child animations fire their triggers as they reach them") @@ -143,19 +140,19 @@ TEST_CASE("child animations fire their triggers as they reach them") spin.animation_edit(0)->triggers.frames.push_back({.atFrame = 5, .eventIds = {0}}); anm2.content.events.push_back({.id = 0, .name = "inner"}); anm2.animation_edit(1)->triggers.frames.push_back({.atFrame = 0, .eventIds = {0}}); - auto library_get = [&](const model::Model&, int id) { return id == 0 ? &spin : nullptr; }; + auto library_get = [&](const Model&, int id) { return id == 0 ? &spin : nullptr; }; auto sources_get = [&](int time) { - std::vector sources{}; - for (const auto& fire : model::animation_triggers_get(anm2, *anm2.animation_get(0), time, library_get)) + std::vector sources{}; + for (const auto& fire : animation_triggers_get(anm2, *anm2.animation_get(0), time, library_get)) sources.push_back(fire.source); return sources; }; // Inner (held on its first frame) fires once, when the parent starts; the library's Spin, started on its fifth // frame, reaches its sixth (and its trigger) one frame later. - CHECK(sources_get(0) == std::vector{&anm2}); - CHECK(sources_get(1) == std::vector{&spin}); + CHECK(sources_get(0) == std::vector{&anm2}); + CHECK(sources_get(1) == std::vector{&spin}); CHECK(sources_get(2).empty()); } @@ -163,51 +160,51 @@ TEST_CASE("flattening animation layers bakes their children into plain layers th { auto anm2 = model_load(file_load(TEST_DIR / "render" / "nested.anm2")); auto spin = model_load(file_load(TEST_DIR / "render" / "spin.anm2")); - auto library_get = [&](const model::Model&, int id) { return id == 0 ? &spin : nullptr; }; + auto library_get = [&](const Model&, int id) { return id == 0 ? &spin : nullptr; }; auto flat = - edit::animation_layers_flatten(anm2, library_get, [](const model::Model&, const std::filesystem::path& path) + animation_layers_flatten(anm2, library_get, [](const Model&, const std::filesystem::path& path) { return std::filesystem::path("library") / path; }); - CHECK(std::ranges::none_of(flat.content.layers, &model::Layer::is_animation)); + CHECK(std::ranges::none_of(flat.content.layers, &Layer::is_animation)); CHECK(flat.content.spritesheets.back().path == std::filesystem::path("library") / "sheet.png"); // Every frame, the plain layers draw where the animation layers' children did. - auto points_get = [&](const model::Model& model, const model::LibraryGet& get, float time) + auto points_get = [&](const Model& model, const LibraryGet& get, float time) { std::vector points{}; for (const auto& draw : - model::animation_draws_get(model, *model.animation_get(0), {.time = time, .library_get = get})) - if (draw.type == model::DrawType::LAYER) - points.push_back(glm::round(glm::vec2(draw.parent * model::draw_quad_model_get(draw) * glm::vec4(1, 1, 0, 1)))); + animation_draws_get(model, *model.animation_get(0), {.time = time, .library_get = get})) + if (draw.type == DrawType::LAYER) + points.push_back(glm::round(glm::vec2(draw.parent * draw_quad_model_get(draw) * glm::vec4(1, 1, 0, 1)))); std::ranges::sort(points, [](glm::vec2 a, glm::vec2 b) { return std::tie(a.x, a.y) < std::tie(b.x, b.y); }); return points; }; for (float time = 0.0f; time < 8.0f; time += 1.0f) CHECK(points_get(flat, {}, time) == points_get(anm2, library_get, time)); - auto text = model::model_to_string(anm2, {.gameModel = &flat}); + auto text = model_to_string(anm2, {.gameModel = &flat}); auto game = game_document_get(text); CHECK(game.find(" Animation=\"") == std::string::npos); CHECK(game.find("spin/red") != std::string::npos); - CHECK(std::ranges::count_if(model_load(text).content.layers, &model::Layer::is_animation) == 3); + CHECK(std::ranges::count_if(model_load(text).content.layers, &Layer::is_animation) == 3); // Children's triggers join the flattened animation's, their events found (or added) by name. spin.content.events.push_back({.id = 0, .name = "spun"}); spin.animation_edit(0)->triggers.frames.push_back({.atFrame = 5, .eventIds = {0}}); - flat = edit::animation_layers_flatten(anm2, library_get, - [](const model::Model&, const std::filesystem::path& path) { return path; }); + flat = animation_layers_flatten(anm2, library_get, + [](const Model&, const std::filesystem::path& path) { return path; }); auto& triggers = flat.animation_get(0)->triggers.frames; REQUIRE(triggers.size() == 1); CHECK(triggers.front().atFrame == 1); - CHECK(model::item_get(flat.content.events, triggers.front().eventIds.front())->name == "spun"); + CHECK(item_get(flat.content.events, triggers.front().eventIds.front())->name == "spun"); } 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.animation_get(0), 0, 0.0f, true); + auto placement = 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.animation_get(0), 99, 0.0f, true)); + CHECK_FALSE(layer_child_transform_get(*anm2.animation_get(0), 99, 0.0f, true)); } TEST_CASE("the game's copy stands in for depth and alpha offsets") @@ -220,30 +217,30 @@ TEST_CASE("the game's copy stands in for depth and alpha offsets") { "crop": [1, 0], "size": [1, 1], "pos": [8, 0], "delay": 2, "depth": -1 } ] }, { "layer": 1, "frames": [ { "crop": [2, 0], "size": [1, 1], "delay": 6, "depth": -1 } ] }, { "layer": 2, "frames": [ { "crop": [3, 0], "size": [1, 1], "delay": 6, "offset": [0, 0, 0, -64] } ] } ] } } })"); - auto game = edit::isaac_bridge(anm2); + auto game = isaac_bridge(anm2); // Every frame, the same crops draw in the same order and places, with no depth left. - auto draws_get = [](const model::Model& model, float time) + auto draws_get = [](const Model& model, float time) { std::vector> draws{}; - for (const auto& draw : model::animation_draws_get(model, *model.animation_get(0), {.time = time})) - if (draw.type == model::DrawType::LAYER && draw.frame.isVisible) + for (const auto& draw : animation_draws_get(model, *model.animation_get(0), {.time = time})) + if (draw.type == DrawType::LAYER && draw.frame.isVisible) draws.emplace_back(draw.frame.crop, draw.frame.position); return draws; }; for (float time = 0.0f; time < 6.0f; time += 0.5f) CHECK(draws_get(game, time) == draws_get(anm2, time)); - CHECK(model::isaac_issues_get(game).depthFrames == 0); + CHECK(isaac_issues_get(game).depthFrames == 0); CHECK( - std::ranges::any_of(game.content.layers, [](const model::Layer& layer) { return layer.name == "a (depth +2)"; })); + std::ranges::any_of(game.content.layers, [](const Layer& layer) { return layer.name == "a (depth +2)"; })); // The alpha offset joins the alpha tint. auto& offsetFrame = *game.frame_get({0, LAYER, 2, 0}); CHECK(offsetFrame.colorOffset.a == 0.0f); - CHECK(util::math::float_to_uint8(offsetFrame.tint.a) == 255 - 64); + CHECK(float_to_uint8(offsetFrame.tint.a) == 255 - 64); // A document saved with Ignore and Save remembers it, in either format. anm2.info.isIsaacIgnored = true; - CHECK(model_load(model::model_to_string(anm2)).info.isIsaacIgnored); - CHECK(model_load(model::model_to_json(anm2)).info.isIsaacIgnored); + CHECK(model_load(model_to_string(anm2)).info.isIsaacIgnored); + CHECK(model_load(model_to_json(anm2)).info.isIsaacIgnored); } diff --git a/tests/invariants.cpp b/tests/invariants.cpp index 70fcadc..e94c04f 100644 --- a/tests/invariants.cpp +++ b/tests/invariants.cpp @@ -1,8 +1,5 @@ #include "common.h" -using namespace anm2ed; -using namespace anm2ed::test; - TEST_CASE("per-fixture invariants") { for (const auto& fixture : fixtures_get()) @@ -16,11 +13,11 @@ TEST_CASE("saved text escapes what it holds, and reads back the same") { auto model = model_load(file_load(CORPUS_DIR / "11_unknown.anm2")); model.extras.children.emplace_back( - 0, model::XmlNode{.tag = "Note", + 0, XmlNode{.tag = "Note", .attributes = {{"Quote", "it's \"x\" & "}}, .text = "a & b > c 'd' \"e\"", .children = {{.tag = "Inner", .children = {{.tag = "Leaf", .attributes = {{"A", "1"}}}}}}}); - auto text = model::model_to_string(model); + auto text = model_to_string(model); CHECK(text.find("Quote=\"it's "x" & <y>\"") != std::string::npos); CHECK(text.find(">a & b > c 'd' \"e\"<") != std::string::npos); auto reloaded = model_load(text).extras.children; @@ -35,10 +32,10 @@ TEST_CASE("saves leave out default colors, which read back the same") { INFO("fixture: ", fixture.string()); auto model = model_load(file_load(fixture)); - auto text = model::model_to_string(model); + auto text = model_to_string(model); CHECK(text.find("Tint=\"255\"") == std::string::npos); CHECK(text.find("Offset=\"0\"") == std::string::npos); - CHECK(model::model_hash(model_load(text)) == model::model_hash(model)); + CHECK(model_hash(model_load(text)) == model_hash(model)); } } @@ -48,14 +45,14 @@ TEST_CASE("JSON documents read back as the editor's copy") { INFO("fixture: ", fixture.string()); auto model = model_load(file_load(fixture)); - auto text = model::model_to_json(model); + auto text = model_to_json(model); auto reloaded = model_load(text); - CHECK(model::model_to_json(reloaded) == text); + CHECK(model_to_json(reloaded) == text); // Unknown XML, element order, dangling references and repeated animation names are not kept. auto isQuirky = fixture.filename() == "09_legacy_quirks.anm2" || fixture.filename() == "11_unknown.anm2"; if (!isQuirky) - CHECK(model::model_serialize(reloaded, SERIALIZE_ANM2ED_DEFAULT) == - model::model_serialize(model, SERIALIZE_ANM2ED_DEFAULT)); + CHECK(model_serialize(reloaded, SERIALIZE_ANM2ED_DEFAULT) == + model_serialize(model, SERIALIZE_ANM2ED_DEFAULT)); } } @@ -63,7 +60,7 @@ TEST_CASE("JSON animations get unique names") { auto model = model_load(file_load(CORPUS_DIR / "01_minimal.anm2")); model.animations.entries.push_back(model.animations.entries.front()); - auto reloaded = model_load(model::model_to_json(model)); + auto reloaded = model_load(model_to_json(model)); REQUIRE(reloaded.animations_count_get() == 2); CHECK(reloaded.animation_get(1)->name == reloaded.animation_get(0)->name + " 2"); } @@ -71,9 +68,9 @@ TEST_CASE("JSON animations get unique names") TEST_CASE("JSON groups don't renumber an animation sharing their name") { auto model = model_load(file_load(CORPUS_DIR / "01_minimal.anm2")); - auto animation = std::get>(model.animations.entries.front()); - model.animations.entries = {model::AnimationGroup{.name = animation->name, .animations = {animation}}}; - auto reloaded = model_load(model::model_to_json(model)); + auto animation = std::get>(model.animations.entries.front()); + model.animations.entries = {AnimationGroup{.name = animation->name, .animations = {animation}}}; + auto reloaded = model_load(model_to_json(model)); REQUIRE(reloaded.animations_count_get() == 1); CHECK(reloaded.animation_get(0)->name == animation->name); } @@ -81,7 +78,7 @@ TEST_CASE("JSON groups don't renumber an animation sharing their name") TEST_CASE("JSON markers are a pair, and a frame's child an object only when it has one") { auto model = model_load(file_load(CORPUS_DIR / "01_minimal.anm2")); - auto text = model::model_to_json(model); + auto text = model_to_json(model); CHECK(text.find("\"child\"") == std::string::npos); model.animation_edit(0)->startMarker = 2; model.animation_edit(0)->endMarker = 5; @@ -89,12 +86,12 @@ TEST_CASE("JSON markers are a pair, and a frame's child an object only when it h REQUIRE(frame); frame->childMode = ChildMode::HOLD; frame->childStart = 3; - text = model::model_to_json(model); + text = model_to_json(model); CHECK(text.find("\"markers\": [2, 5]") != std::string::npos); CHECK(text.find("\"child\": {\"mode\": \"hold\", \"start\": 3}") != std::string::npos); auto reloaded = model_load(text); CHECK(reloaded.animation_get(0)->endMarker == 5); - CHECK(model::model_to_json(reloaded) == text); + CHECK(model_to_json(reloaded) == text); } TEST_CASE("JSON dates are ISO 8601") @@ -105,7 +102,7 @@ TEST_CASE("JSON dates are ISO 8601") {"12/31/2024 11:59:59 PM", "2024-12-31T23:59:59"}}) { model.info.createdOn = date; - auto text = model::model_to_json(model); + auto text = model_to_json(model); CHECK(text.find(iso) != std::string::npos); CHECK(model_load(text).info.createdOn == date); } @@ -116,9 +113,9 @@ TEST_CASE("JSON that can't be read is reported by where it is, and the rest stil auto text = R"({ "colour": 1, "info": { "fps": "fast" }, "layers": [ { "name": "a", "sheet": 4 } ], "animations": { "Idle": { "length": 3, "root": [ { "pos": [1], "ease": "bouncy", "delay": 3 } ] } } })"; - model::Model model{}; + Model model{}; std::string issues{}; - REQUIRE(model::model_load_string(model, text, &issues)); + REQUIRE(model_load_string(model, text, &issues)); CHECK(model.animation_get(0)->frameNum == 3); CHECK(model.animation_get(0)->root.frames[0].duration == 3); for (auto issue : {"colour: unknown key", "info.fps: expected a number", "layers[0].sheet: no item at index 4", @@ -126,16 +123,16 @@ TEST_CASE("JSON that can't be read is reported by where it is, and the rest stil "animations.Idle.root[0].ease: unknown value \"bouncy\""}) CHECK_MESSAGE(issues.find(issue) != std::string::npos, issue); - CHECK_FALSE(model::model_load_string(model, "{ \"fps\": 30, ", &issues)); + CHECK_FALSE(model_load_string(model, "{ \"fps\": 30, ", &issues)); } TEST_CASE("JSON layers can name a library listed after them in the file") { auto text = R"({ "layers": [ { "name": "shadow", "library": 0, "animation": "Small" } ], "libraries": [ "shared/shadows.anm2" ] })"; - model::Model model{}; + Model model{}; std::string issues{}; - REQUIRE(model::model_load_string(model, text, &issues)); + REQUIRE(model_load_string(model, text, &issues)); CHECK(issues.empty()); CHECK(model.content.layers[0].libraryId == 0); } diff --git a/tests/operations.cpp b/tests/operations.cpp index 6f7c403..d214417 100644 --- a/tests/operations.cpp +++ b/tests/operations.cpp @@ -4,29 +4,26 @@ #include "playback.h" #include "pack.h" -using namespace anm2ed; -using namespace anm2ed::test; +static Model fixture_load(const char* name) { return model_load(file_load(CORPUS_DIR / name)); } -model::Model fixture_load(const char* name) { return model_load(file_load(CORPUS_DIR / name)); } - -void operation_check(const char* name, const model::Model& model) +static void operation_check(const char* name, const Model& model) { golden_check(GOLDEN_DIR / std::format("operation.{}.xml", name), - model::model_serialize(model, SERIALIZE_ANM2ED_DEFAULT)); + model_serialize(model, SERIALIZE_ANM2ED_DEFAULT)); } -model::Track& layer_track_get(model::Model& model, int animationIndex, int layerId) +static Track& layer_track_get(Model& model, int animationIndex, int layerId) { auto track = model.track_edit({animationIndex, LAYER, layerId}); REQUIRE(track); return *track; } -int groups_named_count(const model::Animation& animation, std::string_view name) +static int groups_named_count(const Animation& animation, std::string_view name) { int count{}; for (const auto* entries : {&animation.layers, &animation.nulls}) - model::groups_each(*entries, [&](const model::TrackGroup& group) { count += group.name == name; }); + groups_each(*entries, [&](const TrackGroup& group) { count += group.name == name; }); return count; } @@ -36,7 +33,7 @@ TEST_CASE("animations_merge keeps one group per name") { INFO("merge: ", std::string(name)); auto model = fixture_load("03a_groups_nested.anm2"); - edit::animations_merge(model, 0, {0, 1}, type, false, {}); + animations_merge(model, 0, {0, 1}, type, false, {}); CHECK(groups_named_count(*model.animation_get(0), "Main") == 1); } } @@ -50,7 +47,7 @@ TEST_CASE("file_merge presets") for (auto [name, preset] : PRESETS_FILE_MERGE) { auto model = fixture_load("02_items.anm2"); - CHECK(edit::file_merge(model, CORPUS_DIR / "05_regions.anm2", CORPUS_DIR, preset)); + CHECK(file_merge(model, CORPUS_DIR / "05_regions.anm2", CORPUS_DIR, preset)); operation_check(name, model); } } @@ -58,23 +55,23 @@ TEST_CASE("file_merge presets") TEST_CASE("item_add") { auto model = fixture_load("02_items.anm2"); - CHECK(edit::item_add(model, ItemType::LAYER, 0, -1, {.name = "added", .spritesheetId = 1}, {}, 1, - types::destination::ALL) == 2); - CHECK(edit::item_add(model, ItemType::NULL_, 1, -1, {}, {.name = "thisOnly"}, -1, types::destination::THIS) == 2); + CHECK(item_add(model, ItemType::LAYER, 0, -1, {.name = "added", .spritesheetId = 1}, {}, 1, + DESTINATION_ALL) == 2); + CHECK(item_add(model, ItemType::NULL_, 1, -1, {}, {.name = "thisOnly"}, -1, DESTINATION_THIS) == 2); operation_check("item_add", model); } TEST_CASE("regions_generate and regions_scan") { auto model = fixture_load("02_items.anm2"); - edit::regions_generate(model, {0}, {}, "Region {}", RegionFrameMapping::SET); + regions_generate(model, {0}, {}, "Region {}", RegionFrameMapping::SET); auto generated = model; - edit::regions_generate(model, {0}, {}, "Region {}", RegionFrameMapping::SET); - CHECK(model::is_model_equal(model, generated)); + regions_generate(model, {0}, {}, "Region {}", RegionFrameMapping::SET); + CHECK(is_model_equal(model, generated)); operation_check("regions_generate", model); auto scanned = fixture_load("05_regions.anm2"); - edit::regions_scan(scanned); + regions_scan(scanned); operation_check("regions_scan", scanned); } @@ -92,7 +89,7 @@ TEST_CASE("frames_change") change.duration = 3; change.interpolation = Interpolation::EASE_IN; change.isFlipX = true; - model::frames_change(layer_track_get(model, 0, 0), change, ItemType::LAYER, type, {0, 1}); + frames_change(layer_track_get(model, 0, 0), change, ItemType::LAYER, type, {0, 1}); operation_check(std::format("frames_change_{}", name).c_str(), model); } } @@ -100,17 +97,17 @@ TEST_CASE("frames_change") TEST_CASE("frame_bake and frame_mix") { auto model = fixture_load("07_special_interpolation.anm2"); - model::frame_bake(layer_track_get(model, 0, 0), 0, 2, true, false); - model::frame_bake(layer_track_get(model, 0, 0), 3, 1, false, true); + frame_bake(layer_track_get(model, 0, 0), 0, 2, true, false); + frame_bake(layer_track_get(model, 0, 0), 3, 1, false, true); operation_check("frame_bake", model); - model::Frame from{}; - model::Frame to{}; + Frame from{}; + Frame to{}; to.position = {10.0f, -20.0f}; to.skew = {30.0f, 0.0f}; to.rotation = 90.0f; to.tint = {0.0f, 1.0f, 1.0f, 0.5f}; - model::frame_mix(from, to, 0.5f); + frame_mix(from, to, 0.5f); CHECK(from.position == glm::vec2(5.0f, -10.0f)); CHECK(from.skew == glm::vec2(15.0f, 0.0f)); CHECK(from.rotation == doctest::Approx(45.0f)); @@ -122,7 +119,7 @@ TEST_CASE("rects_pack fits every rect without overlap") std::vector sizes{{16, 16}, {32, 8}, {8, 32}, {5, 7}, {64, 1}, {1, 1}}; glm::ivec2 size{}; std::vector positions{}; - REQUIRE(util::pack::rects_pack(sizes, size, positions)); + REQUIRE(rects_pack(sizes, size, positions)); REQUIRE(positions.size() == sizes.size()); for (std::size_t i = 0; i < sizes.size(); ++i) { @@ -144,90 +141,90 @@ TEST_CASE("edit layer operations") { const char* name; const char* fixture; - std::function operation; + std::function operation; std::size_t uidCount; }; const Reference head{0, LAYER, 0}; const Case CASES[] = { {"frame_insert", "02_items.anm2", - [&](model::Model& anm2) { return edit::frame_insert(anm2, {0, LAYER, 0, 0}, 0); }, 1}, + [&](Model& anm2) { return frame_insert(anm2, {0, LAYER, 0, 0}, 0); }, 1}, {"trigger_insert", "02_items.anm2", - [&](model::Model& anm2) { return edit::frame_insert(anm2, {0, TRIGGER, -1, 0}, 2); }, 1}, + [&](Model& anm2) { return frame_insert(anm2, {0, TRIGGER, -1, 0}, 2); }, 1}, {"frames_delete", "02_items.anm2", - [&](model::Model& anm2) { return edit::frames_delete(anm2, {{0, LAYER, 0, 0}, {0, ROOT, -1, 1}}); }, 0}, - {"frames_duplicate", "02_items.anm2", [&](model::Model& anm2) - { return edit::frames_duplicate(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 1}}, {0, LAYER, 0, 1}); }, 2}, + [&](Model& anm2) { return frames_delete(anm2, {{0, LAYER, 0, 0}, {0, ROOT, -1, 1}}); }, 0}, + {"frames_duplicate", "02_items.anm2", [&](Model& anm2) + { return frames_duplicate(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 1}}, {0, LAYER, 0, 1}); }, 2}, {"frames_reverse", "07_special_interpolation.anm2", - [&](model::Model& anm2) { return edit::frames_reverse(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 2}}); }, 0}, - {"frames_bake", "07_special_interpolation.anm2", [&](model::Model& anm2) - { return edit::frames_bake(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 1}}, 2, true, false); }, 5}, - {"frame_split", "02_items.anm2", [&](model::Model& anm2) { return edit::frame_split(anm2, {0, LAYER, 1, 0}, 2); }, + [&](Model& anm2) { return frames_reverse(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 2}}); }, 0}, + {"frames_bake", "07_special_interpolation.anm2", [&](Model& anm2) + { return frames_bake(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 1}}, 2, true, false); }, 5}, + {"frame_split", "02_items.anm2", [&](Model& anm2) { return frame_split(anm2, {0, LAYER, 1, 0}, 2); }, 1}, {"frames_move", "02_items.anm2", - [&](model::Model& anm2) { return edit::frames_move(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 1, 0}}, head, 2); }, 2}, + [&](Model& anm2) { return frames_move(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 1, 0}}, head, 2); }, 2}, {"frames_paste", "02_items.anm2", - [&](model::Model& anm2) + [&](Model& anm2) { auto frame = anm2.frame_get(Reference{0, LAYER, 1, 0}); - auto text = model::frame_to_string(*frame, ItemType::LAYER) + model::frame_to_string(*frame, ItemType::LAYER); - return edit::frames_paste(anm2, {0, LAYER, 0, 0}, {}, text, 0, nullptr); + auto text = frame_to_string(*frame, ItemType::LAYER) + frame_to_string(*frame, ItemType::LAYER); + return frames_paste(anm2, {0, LAYER, 0, 0}, {}, text, 0, nullptr); }, 2}, {"root_bake_into", "04_group_root_transform.anm2", - [&](model::Model& anm2) + [&](Model& anm2) { - return edit::root_bake_into(anm2, {{0, ROOT, -1, 0}}, {{0, LAYER, 2}}, + return root_bake_into(anm2, {{0, ROOT, -1, 0}}, {{0, LAYER, 2}}, {.isRoundScale = true, .isMatchRootInterpolation = true}); }, 1}, {"items_group", "03b_groups_legacy_flat.anm2", - [&](model::Model& anm2) { return edit::items_group(anm2, 0, LAYER, {2}, "New"); }, 1}, - {"items_move", "03b_groups_legacy_flat.anm2", [&](model::Model& anm2) - { return edit::items_move(anm2, 0, LAYER, {2}, {}, {true, LAYER, 0, -1}, false, true); }, 0}, + [&](Model& anm2) { return items_group(anm2, 0, LAYER, {2}, "New"); }, 1}, + {"items_move", "03b_groups_legacy_flat.anm2", [&](Model& anm2) + { return items_move(anm2, 0, LAYER, {2}, {}, {true, LAYER, 0, -1}, false, true); }, 0}, {"items_remove", "03b_groups_legacy_flat.anm2", - [&](model::Model& anm2) { return edit::items_remove(anm2, 0, {{LAYER, {2}}}, {{NULL_, {3}}}); }, 0}, + [&](Model& anm2) { return items_remove(anm2, 0, {{LAYER, {2}}}, {{NULL_, {3}}}); }, 0}, {"animation_add", "03a_groups_nested.anm2", - [&](model::Model& anm2) { return edit::animation_add(anm2, 1, 0, 0, "Added"); }, 1}, + [&](Model& anm2) { return animation_add(anm2, 1, 0, 0, "Added"); }, 1}, {"animations_remove", "03a_groups_nested.anm2", - [&](model::Model& anm2) { return edit::animations_remove(anm2, {1}, {0}); }, 0}, - {"animations_move", "02_items.anm2", [&](model::Model& anm2) - { return edit::animations_move(anm2, {0}, {}, {.animationIndex = 1, .isAfter = true}); }, 1}, + [&](Model& anm2) { return animations_remove(anm2, {1}, {0}); }, 0}, + {"animations_move", "02_items.anm2", [&](Model& anm2) + { return animations_move(anm2, {0}, {}, {.animationIndex = 1, .isAfter = true}); }, 1}, {"animations_group", "02_items.anm2", - [&](model::Model& anm2) { return edit::animations_group(anm2, {0, 1}, "Group"); }, 0}, + [&](Model& anm2) { return animations_group(anm2, {0, 1}, "Group"); }, 0}, {"animations_paste", "02_items.anm2", - [&](model::Model& anm2) + [&](Model& anm2) { std::set groupIds{}; - auto text = model::animation_to_string(*anm2.animation_get(1)); - return edit::animations_paste(anm2, text, 0, -1, groupIds, nullptr); + auto text = animation_to_string(*anm2.animation_get(1)); + return animations_paste(anm2, text, 0, -1, groupIds, nullptr); }, 1}, {"regions_paste", "05_regions.anm2", - [&](model::Model& anm2) + [&](Model& anm2) { - auto region = model::item_get(model::item_get(anm2.content.spritesheets, 0)->regions, 1); - return edit::regions_paste(anm2, 0, model::item_to_string(*region), 1, nullptr); + auto region = item_get(item_get(anm2.content.spritesheets, 0)->regions, 1); + return regions_paste(anm2, 0, item_to_string(*region), 1, nullptr); }, 0}, {"animation_grid_generate", "05_regions.anm2", - [&](model::Model& anm2) + [&](Model& anm2) { - return edit::animation_grid_generate(anm2, {{0, LAYER, 0}}, + return animation_grid_generate(anm2, {{0, LAYER, 0}}, {{0, 0}, {8, 8}, {4, 4}, 2, 3, 2, true, "Grid {}"}); }, 3}, {"frames_change_apply", "02_items.anm2", - [&](model::Model& anm2) + [&](Model& anm2) { FrameChange change{.positionX = 3.0f, .rotation = 10.0f}; - return edit::frames_change_apply( + return frames_change_apply( anm2, {.references = {{0, LAYER, 0, 1}, {0, NULL_, 0}}, .animations = {1}, .isRoot = true}, change, ChangeType::ADD); }, 0}, {"animations_merge", "03a_groups_nested.anm2", - [&](model::Model& anm2) { return edit::animations_merge(anm2, 0, {1}, types::merge::APPEND, true, {0}); }, 1}, + [&](Model& anm2) { return animations_merge(anm2, 0, {1}, MERGE_APPEND, true, {0}); }, 1}, }; for (const auto& entry : CASES) @@ -237,7 +234,7 @@ TEST_CASE("edit layer operations") auto uids = entry.operation(anm2); CHECK(uids.size() == entry.uidCount); anm2.uids_repair(); - model::UidIndex index(anm2); + UidIndex index(anm2); for (auto uid : uids) CHECK(index.reference_get(uid)); operation_check(entry.name, anm2); @@ -248,11 +245,11 @@ TEST_CASE("spritesheet pixel edits") { auto image_make = [](glm::ivec2 size, std::vector opaque = {}) { - std::vector pixels((std::size_t)size.x * size.y * resource::image::CHANNELS, 0); + std::vector pixels((std::size_t)size.x * size.y * IMAGE_CHANNELS, 0); for (auto point : opaque) - std::fill_n(pixels.begin() + ((std::size_t)point.y * size.x + point.x) * resource::image::CHANNELS, - resource::image::CHANNELS, 255); - return resource::Image(pixels.data(), size); + std::fill_n(pixels.begin() + ((std::size_t)point.y * size.x + point.x) * IMAGE_CHANNELS, + IMAGE_CHANNELS, 255); + return Image(pixels.data(), size); }; auto sheet = image_make({64, 64}, {{4, 6}}); auto other = image_make({16, 16}); @@ -260,8 +257,8 @@ TEST_CASE("spritesheet pixel edits") SUBCASE("regions_trim shrinks to content and keeps the custom pivot in place") { auto model = fixture_load("05_regions.anm2"); - CHECK(edit::regions_trim(model, 0, {0, 1}, sheet)); - auto region = model::item_get(model.content.spritesheets[0].regions, 0); + CHECK(regions_trim(model, 0, {0, 1}, sheet)); + auto region = item_get(model.content.spritesheets[0].regions, 0); CHECK(region->crop == glm::vec2(4, 6)); CHECK(region->size == glm::vec2(1, 1)); CHECK(region->pivot == glm::vec2(-1, -1)); @@ -270,7 +267,7 @@ TEST_CASE("spritesheet pixel edits") SUBCASE("spritesheet_pack returns an image holding every region") { auto model = fixture_load("05_regions.anm2"); - auto packed = edit::spritesheet_pack(model, 0, sheet, 1); + auto packed = spritesheet_pack(model, 0, sheet, 1); REQUIRE(packed); CHECK(packed->is_valid()); for (auto& region : model.content.spritesheets[0].regions) @@ -281,11 +278,11 @@ TEST_CASE("spritesheet pixel edits") { auto model = fixture_load("05_regions.anm2"); auto image_get = [&](int id) { return id == 0 ? &sheet : &other; }; - auto merged = edit::spritesheets_merge(model, {0, 1}, image_get, true, true, false, Origin::TOP_LEFT); + auto merged = spritesheets_merge(model, {0, 1}, image_get, true, true, false, Origin::TOP_LEFT); REQUIRE(merged); CHECK(merged->size == glm::ivec2(80, 64)); CHECK(model.content.spritesheets.size() == 1); - CHECK(model::item_get(model.content.layers, 1)->spritesheetId == 0); + CHECK(item_get(model.content.layers, 1)->spritesheetId == 0); operation_check("spritesheets_merge", model); } } @@ -298,9 +295,9 @@ TEST_CASE("markers stay in the editor's copy and bound playback") animation->frameNum = 10; animation->startMarker = 2; animation->endMarker = 5; - CHECK(model::animation_play_range_get(*animation) == glm::ivec2(2, 6)); + CHECK(animation_play_range_get(*animation) == glm::ivec2(2, 6)); - auto text = model::model_to_string(model); + auto text = model_to_string(model); CHECK(game_document_get(text).find("Marker") == std::string::npos); auto reloaded = model_load(text); CHECK(reloaded.animation_get(0)->startMarker == 2); @@ -316,36 +313,36 @@ TEST_CASE("markers stay in the editor's copy and bound playback") TEST_CASE("isaac_issues_get counts what the game's copy changes") { - CHECK(model::isaac_issues_get(fixture_load("01_minimal.anm2")) == model::IsaacIssues{}); - CHECK(model::isaac_issues_get(fixture_load("07_special_interpolation.anm2")).easedFrames == 5); - CHECK(model::isaac_issues_get(fixture_load("04_group_root_transform.anm2")).groupTransforms > 0); - auto shaders = model::isaac_issues_get(fixture_load("06_shaders.anm2")); + CHECK(isaac_issues_get(fixture_load("01_minimal.anm2")) == IsaacIssues{}); + CHECK(isaac_issues_get(fixture_load("07_special_interpolation.anm2")).easedFrames == 5); + CHECK(isaac_issues_get(fixture_load("04_group_root_transform.anm2")).groupTransforms > 0); + auto shaders = isaac_issues_get(fixture_load("06_shaders.anm2")); CHECK(shaders.shaderFrames > 0); CHECK(shaders.skewFrames > 0); - CHECK(model::isaac_issues_get(fixture_load("02_items.anm2")).triggerSounds > 0); + CHECK(isaac_issues_get(fixture_load("02_items.anm2")).triggerSounds > 0); } TEST_CASE("frames_property_set copies one property to the frames that have it") { auto model = fixture_load("02_items.anm2"); - model::Frame source{.crop = {7, 8}, .position = {3, 4}}; + Frame source{.crop = {7, 8}, .position = {3, 4}}; Reference layer{0, LAYER, 0, 0}; Reference null{0, NULL_, 0, 0}; REQUIRE(model.frame_get(layer)); REQUIRE(model.frame_get(null)); auto nullCrop = model.frame_get(null)->crop; - edit::frames_property_set(model, {layer, null}, edit::FrameProperty::POSITION, source); + frames_property_set(model, {layer, null}, FrameProperty::POSITION, source); CHECK(model.frame_get(layer)->position == glm::vec2(3, 4)); CHECK(model.frame_get(null)->position == glm::vec2(3, 4)); - edit::frames_property_set(model, {layer, null}, edit::FrameProperty::CROP, source); + frames_property_set(model, {layer, null}, FrameProperty::CROP, source); CHECK(model.frame_get(layer)->crop == glm::vec2(7, 8)); CHECK(model.frame_get(null)->crop == nullCrop); - CHECK_FALSE(edit::is_frame_property_valid(edit::FrameProperty::EVENT, ItemType::LAYER)); - CHECK(edit::is_frame_property_valid(edit::FrameProperty::SOUNDS, ItemType::TRIGGER)); - CHECK_FALSE(edit::is_frame_property_valid(edit::FrameProperty::POSITION, ItemType::TRIGGER)); + CHECK_FALSE(is_frame_property_valid(FrameProperty::EVENT, ItemType::LAYER)); + CHECK(is_frame_property_valid(FrameProperty::SOUNDS, ItemType::TRIGGER)); + CHECK_FALSE(is_frame_property_valid(FrameProperty::POSITION, ItemType::TRIGGER)); } TEST_CASE("frames_split splits every selected frame that spans the time") @@ -360,7 +357,7 @@ TEST_CASE("frames_split splits every selected frame that spans the time") REQUIRE(layerTrack->frames[0].duration > 1); REQUIRE(nullTrack->frames[0].duration > 1); - auto uids = edit::frames_split(model, {{0, LAYER, 0, 0}, {0, NULL_, 0, 0}}, 0); + auto uids = frames_split(model, {{0, LAYER, 0, 0}, {0, NULL_, 0, 0}}, 0); CHECK(uids.size() == 2); CHECK(model.track_get({0, LAYER, 0})->frames.size() == layerCount + 1); CHECK(model.track_get({0, NULL_, 0})->frames.size() == nullCount + 1); @@ -372,8 +369,8 @@ TEST_CASE("change all frame properties changes layer depth only") auto model = fixture_load("02_items.anm2"); Reference layer{0, LAYER, 0, 0}; Reference null{0, NULL_, 0, 0}; - edit::frames_change_apply(model, {.references = {layer, null}}, {.depth = 2}, ChangeType::ADD); - edit::frames_change_apply(model, {.references = {layer, null}}, {.depth = 1}, ChangeType::SUBTRACT); + frames_change_apply(model, {.references = {layer, null}}, {.depth = 2}, ChangeType::ADD); + frames_change_apply(model, {.references = {layer, null}}, {.depth = 1}, ChangeType::SUBTRACT); CHECK(model.frame_get(layer)->depth == 1); CHECK(model.frame_get(null)->depth == 0); } @@ -384,7 +381,7 @@ TEST_CASE("change all frame properties blurs layers and changes only animation l Reference animationLayer{0, LAYER, 1, 0}; Reference spritesheetLayer{1, LAYER, 2, 0}; REQUIRE(model.frame_get(spritesheetLayer)); - edit::frames_change_apply(model, {.references = {animationLayer, spritesheetLayer}}, + frames_change_apply(model, {.references = {animationLayer, spritesheetLayer}}, {.blur = 8.0f, .childAnimation = "Spin", .childMode = ChildMode::ONCE, .childStart = 3}, ChangeType::ADJUST); auto child = *model.frame_get(animationLayer); @@ -398,7 +395,7 @@ TEST_CASE("change all frame properties blurs layers and changes only animation l CHECK(sprite.childMode == ChildMode::LOOP); CHECK(sprite.childStart == 0); - edit::frames_change_apply(model, {.references = {animationLayer}}, {.blur = 1000.0f}, ChangeType::ADD); + frames_change_apply(model, {.references = {animationLayer}}, {.blur = 1000.0f}, ChangeType::ADD); CHECK(model.frame_get(animationLayer)->blur == FRAME_BLUR_MAX); } @@ -410,26 +407,26 @@ TEST_CASE("animations_merge moves triggers past the animation placed before them auto first = *model.animation_get(0); first.frameNum = 10; auto second = first; - second.uid = util::uid_next(); - second.triggers.frames = {model::Frame{.atFrame = 5}}; - model.animations.entries = {std::make_shared(first), - std::make_shared(second)}; + second.uid = uid_next(); + second.triggers.frames = {Frame{.atFrame = 5}}; + model.animations.entries = {std::make_shared(first), + std::make_shared(second)}; return model; }; auto appended = model_make(); - edit::animations_merge(appended, 0, {0, 1}, types::merge::APPEND, false, {}); + animations_merge(appended, 0, {0, 1}, MERGE_APPEND, false, {}); CHECK(appended.animation_get(0)->triggers.frames.at(0).atFrame == 15); auto prepended = model_make(); - edit::animations_merge(prepended, 1, {0, 1}, types::merge::PREPEND, false, {}); + animations_merge(prepended, 1, {0, 1}, MERGE_PREPEND, false, {}); CHECK(prepended.animation_get(1)->triggers.frames.at(0).atFrame == 15); } TEST_CASE("skew reads from the old Shear attributes too") { auto frames = - model::frames_from_string(R"()", ItemType::NULL_); + frames_from_string(R"()", ItemType::NULL_); REQUIRE(frames.size() == 2); CHECK(frames[0].skew == glm::vec2(5, 6)); CHECK(frames[1].skew.x == 7); @@ -440,38 +437,38 @@ TEST_CASE("a trigger fires several events; the game's copy keeps the first") { auto model = fixture_load("02_items.anm2"); model.frame_edit({0, TRIGGER, -1, 0})->eventIds = {1, 0}; - auto text = model::model_to_string(model); + auto text = model_to_string(model); CHECK(model_load(text).frame_get({0, TRIGGER, -1, 0})->eventIds == std::vector{1, 0}); CHECK(model_load(game_document_get(text)).frame_get({0, TRIGGER, -1, 0})->eventIds == std::vector{1}); - CHECK(model::isaac_issues_get(model).extraEvents == 1); + CHECK(isaac_issues_get(model).extraEvents == 1); } TEST_CASE("SVG spritesheets pack and merge into SVGs") { auto model = model_load(file_load(TEST_DIR / "render" / "vector.anm2")); - resource::Image vector(TEST_DIR / "render" / "vector.svg"); + Image vector(TEST_DIR / "render" / "vector.svg"); auto& regions = model.content.spritesheets.front().regions; regions.push_back({.id = 0, .name = "circle", .crop = {0, 0}, .size = {16, 16}}); regions.push_back({.id = 1, .name = "square", .crop = {16, 0}, .size = {16, 16}}); // Packing keeps the drawing: each region shows the same pixels where it now sits. - auto packed = edit::spritesheet_pack(model, 0, vector, 1); + auto packed = spritesheet_pack(model, 0, vector, 1); REQUIRE(packed); CHECK(packed->is_vector()); for (auto [id, original] : {std::pair{0, glm::vec2(8, 8)}, std::pair{1, glm::vec2(24, 8)}}) { - auto region = model::item_get(model.content.spritesheets.front().regions, id); + auto region = item_get(model.content.spritesheets.front().regions, id); CHECK(packed->pixel_read(region->crop + glm::vec2(8, 8)) == vector.pixel_read(original)); } // A PNG sheet merged after an SVG one: the result is an SVG holding the PNG; a PNG first takes the .svg name. - const std::vector pixels(4 * 4 * resource::image::CHANNELS, 255); - resource::Image raster(pixels.data(), {4, 4}); + const std::vector pixels(4 * 4 * IMAGE_CHANNELS, 255); + Image raster(pixels.data(), {4, 4}); model.content.spritesheets.push_back({.id = 1, .path = "white.png"}); - auto images = std::map{{0, &vector}, {1, &raster}}; + auto images = std::map{{0, &vector}, {1, &raster}}; auto image_get = [&](int id) { return images.at(id); }; auto mixed = model; - auto merged = edit::spritesheets_merge(mixed, {0, 1}, image_get, true, false, false, Origin::TOP_LEFT); + auto merged = spritesheets_merge(mixed, {0, 1}, image_get, true, false, false, Origin::TOP_LEFT); REQUIRE(merged); CHECK(merged->is_vector()); CHECK(merged->size == glm::ivec2(36, 16)); @@ -480,21 +477,21 @@ TEST_CASE("SVG spritesheets pack and merge into SVGs") std::swap(model.content.spritesheets.front().id, model.content.spritesheets.back().id); images = {{1, &vector}, {0, &raster}}; - REQUIRE(edit::spritesheets_merge(model, {0, 1}, image_get, true, false, false, Origin::TOP_LEFT)); - CHECK(model::item_get(model.content.spritesheets, 0)->path == "white.svg"); + REQUIRE(spritesheets_merge(model, {0, 1}, image_get, true, false, false, Origin::TOP_LEFT)); + CHECK(item_get(model.content.spritesheets, 0)->path == "white.svg"); } TEST_CASE("content_remove takes what refers to an item with it") { - auto path_keep = [](const model::Model&, const std::filesystem::path& path) { return path; }; - auto remove = [&](model::Model& model, ElementType type, std::set ids, int spritesheetId = -1, - const model::LibraryGet& library_get = {}) - { edit::content_remove(model, type, ids, spritesheetId, library_get, path_keep); }; - auto tracks_count = [](const model::Model& model, int layerId) + auto path_keep = [](const Model&, const std::filesystem::path& path) { return path; }; + auto remove = [&](Model& model, ElementType type, std::set ids, int spritesheetId = -1, + const LibraryGet& library_get = {}) + { content_remove(model, type, ids, spritesheetId, library_get, path_keep); }; + auto tracks_count = [](const Model& model, int layerId) { int count{}; for (auto [index, animation] : model.animations_get()) - model::tracks_each(animation->layers, [&](const model::Track& track, auto*) { count += track.id == layerId; }); + tracks_each(animation->layers, [&](const Track& track, auto*) { count += track.id == layerId; }); return count; }; @@ -503,7 +500,7 @@ TEST_CASE("content_remove takes what refers to an item with it") auto model = fixture_load("02_items.anm2"); CHECK(model.uses_count(ElementType::LAYER_ELEMENT, {0}) == tracks_count(model, 0)); remove(model, ElementType::LAYER_ELEMENT, {0}); - CHECK_FALSE(model::item_get(model.content.layers, 0)); + CHECK_FALSE(item_get(model.content.layers, 0)); CHECK(tracks_count(model, 0) == 0); CHECK(tracks_count(model, 1) > 0); @@ -546,7 +543,7 @@ TEST_CASE("content_remove takes what refers to an item with it") CHECK(after.crop == before.crop); CHECK(after.size == before.size); CHECK(after.pivot == before.pivot); - CHECK_FALSE(model::item_get(regions.content.spritesheets.front().regions, 0)); + CHECK_FALSE(item_get(regions.content.spritesheets.front().regions, 0)); } SUBCASE("a library's layers, flattened") @@ -555,13 +552,13 @@ TEST_CASE("content_remove takes what refers to an item with it") auto spin = model_load(file_load(TEST_DIR / "render" / "spin.anm2")); CHECK(model.uses_count(ElementType::LIBRARY, {0}) == 1); remove(model, ElementType::LIBRARY, {0}, -1, - [&](const model::Model&, int id) { return id == 0 ? &spin : nullptr; }); + [&](const Model&, int id) { return id == 0 ? &spin : nullptr; }); CHECK(model.content.libraries.empty()); - CHECK_FALSE(model::item_get(model.content.layers, 0)); + CHECK_FALSE(item_get(model.content.layers, 0)); CHECK( - std::ranges::any_of(model.content.layers, [](const model::Layer& layer) { return layer.name == "spin/red"; })); + std::ranges::any_of(model.content.layers, [](const Layer& layer) { return layer.name == "spin/red"; })); // Layers playing this file's animations stay as they are. - CHECK(model::item_get(model.content.layers, 1)->is_animation()); - CHECK(model::item_get(model.content.layers, 3)->is_animation()); + CHECK(item_get(model.content.layers, 1)->is_animation()); + CHECK(item_get(model.content.layers, 3)->is_animation()); } } diff --git a/tests/render/render.cpp b/tests/render/render.cpp index 1bc0811..b38026d 100644 --- a/tests/render/render.cpp +++ b/tests/render/render.cpp @@ -13,10 +13,6 @@ #include "image.h" #include "render.h" -using namespace anm2ed; - -namespace anm2ed::test -{ const std::filesystem::path RENDER_TEST_DIR = std::filesystem::path(ANM2ED_TEST_DIR) / "render"; const std::filesystem::path GOLDEN_DIR = RENDER_TEST_DIR / "golden"; const std::filesystem::path OUTPUT_DIR = ANM2ED_RENDER_DIR; @@ -24,12 +20,9 @@ namespace anm2ed::test constexpr double MISMATCH_RATIO_MAX = 0.01; constexpr float SCALE = 3.0f; constexpr glm::vec4 BACKGROUND = {0.2f, 0.2f, 0.2f, 1.0f}; -} - -using namespace anm2ed::test; // Different OpenGL implementations round a little differently: a few pixels may differ, each only slightly. -void golden_image_check(const std::string& name) +static void golden_image_check(const std::string& name) { auto actualPath = OUTPUT_DIR / name; auto goldenPath = GOLDEN_DIR / name; @@ -39,8 +32,8 @@ void golden_image_check(const std::string& name) std::filesystem::copy_file(actualPath, goldenPath, std::filesystem::copy_options::overwrite_existing); return; } - resource::Image actual(actualPath); - resource::Image golden(goldenPath); + Image actual(actualPath); + Image golden(goldenPath); REQUIRE(golden.is_valid()); REQUIRE(actual.size == golden.size); int mismatches{}; @@ -51,11 +44,11 @@ void golden_image_check(const std::string& name) struct RenderFixture { - render::HeadlessGL gl{}; + HeadlessGL gl{}; std::optional document{}; - std::optional shader{}; + std::optional shader{}; std::optional canvas{}; - const model::Animation* animation{}; + const Animation* animation{}; glm::vec4 bounds{}; explicit RenderFixture(const char* file) @@ -63,18 +56,18 @@ struct RenderFixture if (!gl.is_valid()) return; std::filesystem::create_directories(OUTPUT_DIR); document.emplace(RENDER_TEST_DIR / file, false); - auto& info = resource::shader::SHADERS[resource::shader::TEXTURE]; + auto& info = SHADERS[SHADER_TEXTURE]; shader.emplace(info.vertex, info.fragment); canvas.emplace(glm::vec2(1.0f)); animation = document->model.animation_get(0); - bounds = render::animation_bounds_get(*document, *animation, true); + bounds = animation_bounds_get(*document, *animation, true); } std::vector frame_get(float time) { auto pixels = - render::animation_frame_render(*canvas, *shader, *document, *animation, time, bounds, SCALE, BACKGROUND, true); - render::pixels_unpremultiply(pixels); + animation_frame_render(*canvas, *shader, *document, *animation, time, bounds, SCALE, BACKGROUND, true); + pixels_unpremultiply(pixels); return pixels; } @@ -108,7 +101,7 @@ TEST_CASE("frames draw where the animation puts them") CHECK(blue.b > blue.r + 40); auto framePath = OUTPUT_DIR / "spin_frame_0.png"; - REQUIRE(resource::Image::write_pixels_png(framePath, glm::ivec2(fixture.canvas->size), pixels.data())); + REQUIRE(Image::write_pixels_png(framePath, glm::ivec2(fixture.canvas->size), pixels.data())); golden_image_check("spin_frame_0.png"); } @@ -121,16 +114,16 @@ TEST_CASE("a recorded spritesheet holds every frame") return; } - render::RecorderOptions options{.type = render::SPRITESHEET, + RecorderOptions options{.type = RENDER_SPRITESHEET, .path = OUTPUT_DIR / "spin_sheet.png", .start = 0, .end = fixture.animation->frameNum - 1, .animationFps = fixture.document->model.info.fps, .fps = fixture.document->model.info.fps}; - REQUIRE(render::animation_record(options, *fixture.canvas, *fixture.shader, *fixture.document, *fixture.animation, + REQUIRE(animation_record(options, *fixture.canvas, *fixture.shader, *fixture.document, *fixture.animation, fixture.bounds, SCALE, BACKGROUND, true)); - resource::Image sheet(options.path); - auto layout = render::spritesheet_layout_get(0, 0, fixture.animation->frameNum); + Image sheet(options.path); + auto layout = spritesheet_layout_get(0, 0, fixture.animation->frameNum); CHECK(sheet.size == glm::ivec2(fixture.canvas->size) * glm::ivec2(layout.columns, layout.rows)); golden_image_check("spin_sheet.png"); } @@ -155,7 +148,7 @@ TEST_CASE("animation layers draw their child animations") CHECK(red.g < 80); } - REQUIRE(resource::Image::write_pixels_png(OUTPUT_DIR / "nested_frame_0.png", glm::ivec2(fixture.canvas->size), + REQUIRE(Image::write_pixels_png(OUTPUT_DIR / "nested_frame_0.png", glm::ivec2(fixture.canvas->size), pixels.data())); golden_image_check("nested_frame_0.png"); } @@ -180,7 +173,7 @@ TEST_CASE("a blurred layer spreads past its crop like Flash's blur filter") CHECK(fixture.pixel_get(blurred, OUTSIDE).r > fixture.pixel_get(sharp, OUTSIDE).r + 40); CHECK(fixture.pixel_get(blurred, INSIDE).r + 40 < fixture.pixel_get(sharp, INSIDE).r); - REQUIRE(resource::Image::write_pixels_png(OUTPUT_DIR / "spin_blur_frame_0.png", glm::ivec2(fixture.canvas->size), + REQUIRE(Image::write_pixels_png(OUTPUT_DIR / "spin_blur_frame_0.png", glm::ivec2(fixture.canvas->size), blurred.data())); } @@ -202,7 +195,7 @@ TEST_CASE("SVG spritesheets draw sharp at any scale") CHECK(inside.r > 200); CHECK(outside.r < 80); - REQUIRE(resource::Image::write_pixels_png(OUTPUT_DIR / "vector_frame_0.png", glm::ivec2(fixture.canvas->size), + REQUIRE(Image::write_pixels_png(OUTPUT_DIR / "vector_frame_0.png", glm::ivec2(fixture.canvas->size), pixels.data())); golden_image_check("vector_frame_0.png"); } @@ -222,7 +215,7 @@ TEST_CASE("converting SVG spritesheets writes PNGs beside them") CHECK(std::filesystem::exists(directory / "vector.png")); REQUIRE(document.texture_get(0)); CHECK_FALSE(document.texture_get(0)->is_vector()); - CHECK(model::spritesheets_vector_used_get(document.model).empty()); + CHECK(spritesheets_vector_used_get(document.model).empty()); document.undo(); CHECK(document.model.content.spritesheets.front().path == "vector.svg"); @@ -262,7 +255,7 @@ TEST_CASE("a Rebirth save flattens animation layers for the game") // The game's copy draws what the editor does: skew, blur and a skewed root baked into a spritesheet beside the save. TEST_CASE("the game's copy bakes skew and blur into a spritesheet that draws the same") { - render::HeadlessGL gl{}; + HeadlessGL gl{}; if (!gl.is_valid()) return; auto directory = std::filesystem::temp_directory_path() / "anm2ed_bake"; std::filesystem::remove_all(directory); @@ -297,8 +290,8 @@ TEST_CASE("the game's copy bakes skew and blur into a spritesheet that draws the Document gameDocument(directory / "game.anm2", false); REQUIRE(gameDocument.is_valid()); - auto& info = resource::shader::SHADERS[resource::shader::TEXTURE]; - resource::Shader shader(info.vertex, info.fragment); + auto& info = SHADERS[SHADER_TEXTURE]; + ShaderProgram shader(info.vertex, info.fragment); Canvas canvas(glm::vec2(1.0f)); for (int index = 0; index < document.model.animations_count_get(); ++index) { @@ -306,14 +299,14 @@ TEST_CASE("the game's copy bakes skew and blur into a spritesheet that draws the auto& gameAnimation = *gameDocument.model.animation_get(index); INFO("animation: ", animation.name); // On whole pixels, so the baked images land on the pixels they were drawn on. - auto bounds = render::animation_bounds_get(document, animation, true); + auto bounds = animation_bounds_get(document, animation, true); bounds = glm::vec4(glm::floor(glm::vec2(bounds)) - 8.0f, glm::ceil(glm::vec2(bounds.z, bounds.w)) + 16.0f); for (int time = 0; time < animation.frameNum; ++time) { INFO("time: ", time); - auto expected = render::animation_frame_render(canvas, shader, document, animation, (float)time, bounds, 1.0f, + auto expected = animation_frame_render(canvas, shader, document, animation, (float)time, bounds, 1.0f, glm::vec4(0.0f), true); - auto actual = render::animation_frame_render(canvas, shader, gameDocument, gameAnimation, (float)time, bounds, + auto actual = animation_frame_render(canvas, shader, gameDocument, gameAnimation, (float)time, bounds, 1.0f, glm::vec4(0.0f), true); REQUIRE(actual.size() == expected.size()); CHECK(std::ranges::any_of(expected, [](uint8_t channel) { return channel != 0; })); diff --git a/tests/roundtrip.cpp b/tests/roundtrip.cpp index dd2de8a..0c83284 100644 --- a/tests/roundtrip.cpp +++ b/tests/roundtrip.cpp @@ -1,8 +1,5 @@ #include "common.h" -using namespace anm2ed; -using namespace anm2ed::test; - TEST_CASE("fixtures match goldens") { auto fixtures = fixtures_get(); diff --git a/tests/selection.cpp b/tests/selection.cpp index 63f556f..43b1477 100644 --- a/tests/selection.cpp +++ b/tests/selection.cpp @@ -3,18 +3,15 @@ #include "edit/edit.h" #include "selection.h" -using namespace anm2ed; -using namespace anm2ed::test; - -model::Model fixture_load_with_uids(const char* name) { return model_load(file_load(CORPUS_DIR / name)); } +static Model fixture_load_with_uids(const char* name) { return model_load(file_load(CORPUS_DIR / name)); } // Applies an edit and follows the selection through it, the way a commit does. -void selection_edit(model::Model& anm2, Selection& selection, auto&& edit) +void selection_edit(Model& anm2, Selection& selection, auto&& edit) { - auto before = selection_focus_get(selection, model::UidIndex(anm2)); + auto before = selection_focus_get(selection, UidIndex(anm2)); edit(); anm2.uids_repair(); - selection_follow(selection, anm2, model::UidIndex(anm2), before); + selection_follow(selection, anm2, UidIndex(anm2), before); } TEST_CASE("uids are unique and non-zero after load") @@ -25,8 +22,8 @@ TEST_CASE("uids are unique and non-zero after load") std::set uids{}; bool isUnique{true}; for (auto [index, animation] : anm2.animations_get()) - model::animation_tracks_each(*animation, - [&](const model::Track& track) + animation_tracks_each(*animation, + [&](const Track& track) { isUnique &= uids.insert(track.uid).second; for (const auto& frame : track.frames) @@ -44,10 +41,10 @@ TEST_CASE("selected frames and focus follow inserts and moves") selection_references_set(selection, anm2, SelectionKind::FRAMES, {{0, LAYER, 0, 1}, {0, LAYER, 1, 0}}); selection_focus_set(selection, anm2, {0, LAYER, 0, 1}); - selection_edit(anm2, selection, [&] { edit::frame_insert(anm2, {0, LAYER, 0, -1}, 0); }); - selection_edit(anm2, selection, [&] { edit::frames_reverse(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 1}}); }); + selection_edit(anm2, selection, [&] { frame_insert(anm2, {0, LAYER, 0, -1}, 0); }); + selection_edit(anm2, selection, [&] { frames_reverse(anm2, {{0, LAYER, 0, 0}, {0, LAYER, 0, 1}}); }); - model::UidIndex index(anm2); + UidIndex index(anm2); CHECK(selection_focus_get(selection, index) == Reference{0, LAYER, 0, 0}); CHECK(selection_references_get(selection, index, SelectionKind::FRAMES) == std::set{{0, LAYER, 0, 0}, {0, LAYER, 1, 0}}); @@ -60,23 +57,23 @@ TEST_CASE("a removed focus falls back to its nearest survivor") selection_focus_set(selection, anm2, {0, LAYER, 0, 1}); selection_references_set(selection, anm2, SelectionKind::FRAMES, {{0, LAYER, 0, 1}}); - selection_edit(anm2, selection, [&] { edit::frames_delete(anm2, {{0, LAYER, 0, 1}}); }); - CHECK(selection_focus_get(selection, model::UidIndex(anm2)) == Reference{0, LAYER, 0, 0}); + selection_edit(anm2, selection, [&] { frames_delete(anm2, {{0, LAYER, 0, 1}}); }); + CHECK(selection_focus_get(selection, UidIndex(anm2)) == Reference{0, LAYER, 0, 0}); CHECK(selection.uids[SelectionKind::FRAMES].empty()); - selection_edit(anm2, selection, [&] { edit::items_remove(anm2, 0, {{LAYER, {0}}}, {}); }); - CHECK(selection_focus_get(selection, model::UidIndex(anm2)) == Reference{0, ROOT}); + selection_edit(anm2, selection, [&] { items_remove(anm2, 0, {{LAYER, {0}}}, {}); }); + CHECK(selection_focus_get(selection, UidIndex(anm2)) == Reference{0, ROOT}); selection_focus_set(selection, anm2, {1, ROOT, -1, 0}); - selection_edit(anm2, selection, [&] { edit::animations_remove(anm2, {1}, {}); }); - CHECK(selection_focus_get(selection, model::UidIndex(anm2)) == Reference{0, ROOT}); + selection_edit(anm2, selection, [&] { animations_remove(anm2, {1}, {}); }); + CHECK(selection_focus_get(selection, UidIndex(anm2)) == Reference{0, ROOT}); } TEST_CASE("track and group selection follow regrouping") { auto anm2 = fixture_load_with_uids("03a_groups_nested.anm2"); - const model::TrackGroup* group{}; - model::groups_each(anm2.animation_get(0)->layers, [&](const model::TrackGroup& candidate) { group = &candidate; }); + const TrackGroup* group{}; + groups_each(anm2.animation_get(0)->layers, [&](const TrackGroup& candidate) { group = &candidate; }); REQUIRE(group); auto groupId = group->id; Selection selection{}; @@ -84,9 +81,9 @@ TEST_CASE("track and group selection follow regrouping") selection_references_set(selection, anm2, SelectionKind::GROUPS, {{0, LAYER, groupId}}); selection_edit(anm2, selection, - [&] { edit::items_move(anm2, 0, LAYER, {0}, {}, {false, LAYER, 2, -1}, false, false); }); + [&] { items_move(anm2, 0, LAYER, {0}, {}, {false, LAYER, 2, -1}, false, false); }); - model::UidIndex index(anm2); + UidIndex index(anm2); CHECK(selection_references_get(selection, index, SelectionKind::TRACKS) == std::set{{0, LAYER, 0}}); CHECK(selection_references_get(selection, index, SelectionKind::GROUPS) == std::set{{0, LAYER, groupId}}); } @@ -95,7 +92,7 @@ TEST_CASE("content selection follows items, and regions follow the focused sprit { auto anm2 = fixture_load_with_uids("05_regions.anm2"); Selection selection{}; - auto& regions = model::item_get(anm2.content.spritesheets, 0)->regions; + auto& regions = item_get(anm2.content.spritesheets, 0)->regions; REQUIRE(regions.size() > 1); auto regionId = regions[1].id; @@ -109,7 +106,7 @@ TEST_CASE("content selection follows items, and regions follow the focused sprit CHECK(selection_ids_get(selection, anm2, SelectionKind::REGIONS) == std::set{regionId}); CHECK(selection_focus_id_get(selection, anm2, SelectionKind::REGIONS) == regionId); - std::erase_if(regions, [&](const model::Region& region) { return region.id == regionId; }); + std::erase_if(regions, [&](const Region& region) { return region.id == regionId; }); CHECK(selection_ids_get(selection, anm2, SelectionKind::REGIONS).empty()); CHECK(selection_focus_id_get(selection, anm2, SelectionKind::REGIONS) == -1); } diff --git a/tests/undo.cpp b/tests/undo.cpp index 9e88b72..5336970 100644 --- a/tests/undo.cpp +++ b/tests/undo.cpp @@ -5,16 +5,13 @@ #include "edit/edit.h" #include "snapshots.h" -using namespace anm2ed; -using namespace anm2ed::test; - constexpr int WALK_STEPS = 150; constexpr int WALK_SEED = 1234; constexpr int UNDO_LIMIT = 1000; -std::vector references_all_get(const model::Model& anm2, bool isFrames) +static std::vector references_all_get(const Model& anm2, bool isFrames) { - model::UidIndex index(anm2); + UidIndex index(anm2); std::vector result{}; auto add = [&](std::uint64_t uid) { @@ -23,8 +20,8 @@ std::vector references_all_get(const model::Model& anm2, bool isFrame if (isFrames == (reference->frameIndex >= 0)) result.push_back(*reference); }; for (auto [i, animation] : anm2.animations_get()) - model::animation_tracks_each(*animation, - [&](const model::Track& track) + animation_tracks_each(*animation, + [&](const Track& track) { add(track.uid); for (const auto& frame : track.frames) @@ -34,7 +31,7 @@ std::vector references_all_get(const model::Model& anm2, bool isFrame } // One random edit on randomly chosen live elements; returns false when nothing applicable exists. -bool edit_random_apply(model::Model& anm2, std::mt19937& random) +static bool edit_random_apply(Model& anm2, std::mt19937& random) { auto frames = references_all_get(anm2, true); auto tracks = references_all_get(anm2, false); @@ -47,31 +44,31 @@ bool edit_random_apply(model::Model& anm2, std::mt19937& random) switch (std::uniform_int_distribution(0, 8)(random)) { case 0: - edit::frame_insert(anm2, frame, 0); + frame_insert(anm2, frame, 0); break; case 1: - if (frames.size() > 4) edit::frames_delete(anm2, {frame, other}); + if (frames.size() > 4) frames_delete(anm2, {frame, other}); break; case 2: - edit::frames_duplicate(anm2, {frame, other}, frame); + frames_duplicate(anm2, {frame, other}, frame); break; case 3: - edit::frames_reverse(anm2, {frame, other}); + frames_reverse(anm2, {frame, other}); break; case 4: - edit::frames_bake(anm2, {frame}, 1, false, false); + frames_bake(anm2, {frame}, 1, false, false); break; case 5: - edit::frame_split(anm2, frame, 1); + frame_split(anm2, frame, 1); break; case 6: - if (frame.itemType != ROOT) edit::frames_move(anm2, {frame}, pick(tracks), 0); + if (frame.itemType != ROOT) frames_move(anm2, {frame}, pick(tracks), 0); break; case 7: - edit::animation_add(anm2, 0, -1, frame.animationIndex, "Walk"); + animation_add(anm2, 0, -1, frame.animationIndex, "Walk"); break; default: - edit::animations_move(anm2, {frame.animationIndex}, {}, {.animationIndex = 0}); + animations_move(anm2, {frame.animationIndex}, {}, {.animationIndex = 0}); break; } return true; @@ -88,28 +85,28 @@ TEST_CASE("undo and redo restore every state of a random edit walk") snapshots.current.model = model_load(file_load(CORPUS_DIR / name)); std::mt19937 random(WALK_SEED); - std::vector hashes{model::model_hash(snapshots.current.model)}; + std::vector hashes{model_hash(snapshots.current.model)}; for (int step = 0; step < WALK_STEPS; ++step) { snapshots.push("Edit"); if (!edit_random_apply(snapshots.current.model, random)) break; auto count = snapshots.undoStack.size(); snapshots.commit(); - if (snapshots.undoStack.size() != count) hashes.push_back(model::model_hash(snapshots.current.model)); + if (snapshots.undoStack.size() != count) hashes.push_back(model_hash(snapshots.current.model)); } REQUIRE(hashes.size() > 1); for (auto it = hashes.rbegin() + 1; it != hashes.rend(); ++it) { REQUIRE(snapshots.undo()); - CHECK(model::model_hash(snapshots.current.model) == *it); + CHECK(model_hash(snapshots.current.model) == *it); } CHECK_FALSE(snapshots.undo()); for (auto it = hashes.begin() + 1; it != hashes.end(); ++it) { REQUIRE(snapshots.redo()); - CHECK(model::model_hash(snapshots.current.model) == *it); + CHECK(model_hash(snapshots.current.model) == *it); } } } @@ -123,15 +120,15 @@ TEST_CASE("selection follows its frame through an edit and its undo") selection_references_set(current.selection, current.model, SelectionKind::FRAMES, {{0, LAYER, 0, 1}}); snapshots.push("Insert"); - edit::frame_insert(current.model, {0, LAYER, 0, -1}, 0); + frame_insert(current.model, {0, LAYER, 0, -1}, 0); auto& track = *current.model.track_edit(Reference{0, LAYER, 0}); std::rotate(track.frames.begin(), track.frames.end() - 1, track.frames.end()); snapshots.commit(); - model::UidIndex index(current.model); + UidIndex index(current.model); CHECK(selection_focus_get(current.selection, index) == Reference{0, LAYER, 0, 2}); CHECK(selection_references_get(current.selection, index, SelectionKind::FRAMES) == std::set{{0, LAYER, 0, 2}}); REQUIRE(snapshots.undo()); - CHECK(selection_focus_get(current.selection, model::UidIndex(current.model)) == Reference{0, LAYER, 0, 1}); + CHECK(selection_focus_get(current.selection, UidIndex(current.model)) == Reference{0, LAYER, 0, 1}); }