Replace glm with vec.h

Vec2, IVec2, Vec3, Vec4, IVec4 and a column-major Mat4, with glm's formulas, in one header.
Free functions are vec_ and mat4_ prefixed. The leaked using namespace glm is gone.
Render goldens still match.
This commit is contained in:
shweet committed 2026-11-22 18:15:02 -05:00
1 parent c38a3a9890
commit 03bbb93ba6
79 files changed
+1232 -810

No files matched your search

-3
View File
@@ -1,6 +1,3 @@
[submodule "external/glm"]
path = external/glm
url = https://github.com/g-truc/glm
[submodule "external/imgui"]
path = external/imgui
url = https://github.com/ocornut/imgui
+1 -1
View File
@@ -59,7 +59,7 @@ endforeach()
add_library(anm2ed_core STATIC ${CORE_SOURCES} external/pugixml/src/pugixml.cpp external/imgui/imgui.cpp
external/imgui/imgui_draw.cpp external/imgui/imgui_widgets.cpp external/imgui/imgui_tables.cpp
${CMAKE_BINARY_DIR}/embed/embed.c)
target_include_directories(anm2ed_core PUBLIC external external/imgui external/glm external/stb src
target_include_directories(anm2ed_core PUBLIC external external/imgui external/stb src
${CMAKE_BINARY_DIR}/embed)
target_link_libraries(anm2ed_core PUBLIC lunasvg simdjson SDL3::Headers)
target_compile_definitions(anm2ed_core PUBLIC IMGUI_DISABLE_OBSOLETE_FUNCTIONS
-1
Submodule external/glm deleted from a583c59e16.
+7 -6
View File
@@ -54,10 +54,12 @@ static std::vector<float> samples_decode(const AudioData& data)
int channels = 0;
int frequency = 0;
short* decoded = nullptr;
auto frames = stb_vorbis_decode_memory(data.bytes.data(), (int)data.bytes.size(), &channels, &frequency, &decoded);
auto frames =
stb_vorbis_decode_memory(data.bytes.data(), (int)data.bytes.size(), &channels, &frequency, &decoded);
if (frames <= 0)
return {};
auto samples = samples_convert({SDL_AUDIO_S16, channels, frequency}, decoded, frames * channels * sizeof(short));
auto samples =
samples_convert({SDL_AUDIO_S16, channels, frequency}, decoded, frames * channels * sizeof(short));
free(decoded);
return samples;
}
@@ -84,9 +86,8 @@ static AudioSound* sound_get(const AudioData& data)
static SDL_AudioDeviceID device_get()
{
static SDL_AudioDeviceID device = SDL_InitSubSystem(SDL_INIT_AUDIO)
? SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &AUDIO_SPEC)
: 0;
static SDL_AudioDeviceID device =
SDL_InitSubSystem(SDL_INIT_AUDIO) ? SDL_OpenAudioDevice(SDL_AUDIO_DEVICE_DEFAULT_PLAYBACK, &AUDIO_SPEC) : 0;
return device;
}
@@ -177,7 +178,7 @@ bool is_audio_playing(const AudioData& data)
}
// The left/right loudness (RMS, 0-1) of what the sound played since the last call.
glm::vec2 audio_levels_get(const AudioData& data)
Vec2 audio_levels_get(const AudioData& data)
{
auto it = sounds.find(data.uid);
if (it == sounds.end())
+2 -2
View File
@@ -1,6 +1,6 @@
#pragma once
#include <glm/vec2.hpp>
#include "vec.h"
#include <vector>
#include "audio_data.h"
@@ -19,7 +19,7 @@ enum AudioPlayMode
void audio_play(const AudioData&, AudioPlayMode = AUDIO_ONCE);
void audio_stop(const AudioData&);
bool is_audio_playing(const AudioData&);
glm::vec2 audio_levels_get(const AudioData&);
Vec2 audio_levels_get(const AudioData&);
// Each frame's sounds started on that frame and mixed at `fps`, as interleaved stereo floats.
std::vector<float> audio_mix(const std::vector<std::vector<const AudioData*>>&, int fps);
+62 -65
View File
@@ -1,15 +1,11 @@
#include "canvas.h"
#include <algorithm>
#include <glm/ext/matrix_clip_space.hpp>
#include <glm/ext/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include "vec.h"
#include "math_util.h"
#include "texture.h"
using namespace glm;
static void canvas_blend_premultiplied_set()
{
gl.Enable(GL_BLEND);
@@ -40,14 +36,14 @@ static void vertex_array_make(GLuint& vao, GLuint& vbo, const void* data, GLsize
{
gl.EnableVertexAttribArray(index);
gl.VertexAttribPointer(index++, attributeSize, GL_FLOAT, GL_FALSE, stride * sizeof(float),
(void*)(offset * sizeof(float)));
(void*)(offset * sizeof(float)));
offset += attributeSize;
}
}
Canvas::Canvas() = default;
Canvas::Canvas(vec2 size)
Canvas::Canvas(Vec2 size)
{
Framebuffer::size_set(size);
vertex_array_make(axisVAO, axisVBO, AXIS_VERTICES, sizeof(AXIS_VERTICES), GL_STATIC_DRAW, {2});
@@ -70,28 +66,28 @@ Canvas::~Canvas()
gl.DeleteBuffers(1, &buffer);
}
mat4 Canvas::transform_get(float zoom, vec2 pan) const
Mat4 Canvas::transform_get(float zoom, Vec2 pan) const
{
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};
auto projection = mat4_ortho(0.0f, (float)size.x, 0.0f, (float)size.y, -1.0f, 1.0f);
auto view = Mat4{1.0f};
view = glm::translate(view, vec3((size * 0.5f) + pan, 0.0f));
view = glm::scale(view, vec3(zoomFactor, zoomFactor, 1.0f));
view = mat4_translate(view, Vec3((size * 0.5f) + pan, 0.0f));
view = mat4_scale(view, Vec3(zoomFactor, zoomFactor, 1.0f));
return projection * view;
}
void Canvas::axes_render(ShaderProgram& 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();
auto originNDC = transform_get(zoom, pan) * vec4(0.0f, 0.0f, 0.0f, 1.0f);
auto originNDC = transform_get(zoom, pan) * Vec4(0.0f, 0.0f, 0.0f, 1.0f);
originNDC /= originNDC.w;
gl.UseProgram(shader.id);
gl.Uniform4fv(gl.GetUniformLocation(shader.id, UNIFORM_COLOR), 1, value_ptr(color));
gl.Uniform4fv(gl.GetUniformLocation(shader.id, UNIFORM_COLOR), 1, values_get(color));
gl.Uniform2f(gl.GetUniformLocation(shader.id, UNIFORM_ORIGIN_NDC), originNDC.x, originNDC.y);
gl.BindVertexArray(axisVAO);
@@ -107,15 +103,15 @@ void Canvas::axes_render(ShaderProgram& shader, float zoom, vec2 pan, vec4 color
canvas_blend_straight_set();
}
void Canvas::grid_render(ShaderProgram& 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();
auto transform = glm::inverse(transform_get(zoom, pan));
auto transform = mat4_inverse(transform_get(zoom, pan));
gl.UseProgram(shader.id);
gl.UniformMatrix4fv(gl.GetUniformLocation(shader.id, UNIFORM_TRANSFORM), 1, GL_FALSE, value_ptr(transform));
gl.UniformMatrix4fv(gl.GetUniformLocation(shader.id, UNIFORM_TRANSFORM), 1, GL_FALSE, values_get(transform));
gl.Uniform2f(gl.GetUniformLocation(shader.id, UNIFORM_SIZE), (float)size.x, (float)size.y);
gl.Uniform2f(gl.GetUniformLocation(shader.id, UNIFORM_OFFSET), (float)offset.x, (float)offset.y);
gl.Uniform4f(gl.GetUniformLocation(shader.id, UNIFORM_COLOR), color.r, color.g, color.b, color.a);
@@ -128,42 +124,42 @@ void Canvas::grid_render(ShaderProgram& shader, float zoom, vec2 pan, ivec2 size
canvas_blend_straight_set();
}
static void texture_uniform_set(const ShaderUniform& uniform, vec4 value)
static void texture_uniform_set(const ShaderUniform& uniform, Vec4 value)
{
if (uniform.valueType == UNIFORM_VALUE_INT || uniform.valueType == UNIFORM_VALUE_SAMPLER2D)
return gl.Uniform1i(uniform.location, uniform.intValue);
switch (UNIFORM_VALUE_TYPE_INFOS[uniform.valueType].componentCount)
{
case 2:
return gl.Uniform2fv(uniform.location, 1, value_ptr(value));
return gl.Uniform2fv(uniform.location, 1, values_get(value));
case 3:
return gl.Uniform3fv(uniform.location, 1, value_ptr(value));
return gl.Uniform3fv(uniform.location, 1, values_get(value));
case 4:
return gl.Uniform4fv(uniform.location, 1, value_ptr(value));
return gl.Uniform4fv(uniform.location, 1, values_get(value));
default:
if (uniform.valueType == UNIFORM_VALUE_FLOAT)
gl.Uniform1f(uniform.location, value.x);
}
}
static vec4 texture_uniform_components_get(const ShaderUniform& uniform, float playbackTime)
static Vec4 texture_uniform_components_get(const ShaderUniform& uniform, float playbackTime)
{
vec4 result{};
Vec4 result{};
for (int i = 0; i < (int)uniform.components.size(); ++i)
result[i] =
uniform.components[i].binding == UNIFORM_BINDING_PLAYBACK_TIME ? playbackTime : uniform.components[i].value;
return result;
}
static void texture_uniforms_set(ShaderProgram& 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())
{
gl.Uniform1i(gl.GetUniformLocation(shader.id, UNIFORM_TEXTURE), 0);
gl.Uniform4fv(gl.GetUniformLocation(shader.id, UNIFORM_COLOR_OFFSET), 1, value_ptr(colorOffset));
gl.Uniform4fv(gl.GetUniformLocation(shader.id, UNIFORM_TINT), 1, value_ptr(tint));
gl.UniformMatrix4fv(gl.GetUniformLocation(shader.id, UNIFORM_TRANSFORM), 1, GL_FALSE, value_ptr(transform));
gl.Uniform4fv(gl.GetUniformLocation(shader.id, UNIFORM_COLOR_OFFSET), 1, values_get(colorOffset));
gl.Uniform4fv(gl.GetUniformLocation(shader.id, UNIFORM_TINT), 1, values_get(tint));
gl.UniformMatrix4fv(gl.GetUniformLocation(shader.id, UNIFORM_TRANSFORM), 1, GL_FALSE, values_get(transform));
return;
}
@@ -179,7 +175,7 @@ static void texture_uniforms_set(ShaderProgram& shader, mat4 transform, vec4 tin
break;
case UNIFORM_BINDING_TRANSFORM:
if (uniform.valueType == UNIFORM_VALUE_MAT4)
gl.UniformMatrix4fv(uniform.location, 1, GL_FALSE, value_ptr(transform));
gl.UniformMatrix4fv(uniform.location, 1, GL_FALSE, values_get(transform));
break;
case UNIFORM_BINDING_FRAME_TINT:
texture_uniform_set(uniform, tint);
@@ -188,10 +184,10 @@ static void texture_uniforms_set(ShaderProgram& shader, mat4 transform, vec4 tin
texture_uniform_set(uniform, colorOffset);
break;
case UNIFORM_BINDING_TEXTURE_SIZE:
texture_uniform_set(uniform, vec4(textureSize, 0.0f, 0.0f));
texture_uniform_set(uniform, Vec4(textureSize, 0.0f, 0.0f));
break;
case UNIFORM_BINDING_PLAYBACK_TIME:
texture_uniform_set(uniform, vec4(playbackTime));
texture_uniform_set(uniform, Vec4(playbackTime));
break;
case UNIFORM_BINDING_COMPONENTS:
texture_uniform_set(uniform, texture_uniform_components_get(uniform, playbackTime));
@@ -205,8 +201,8 @@ static void texture_uniforms_set(ShaderProgram& shader, mat4 transform, vec4 tin
}
}
void Canvas::texture_render(ShaderProgram& shader, GLuint texture, mat4 transform, vec4 tint, vec4 colorOffset,
float* vertices, vec2 textureSize, float playbackTime, TextureBlur blur) const
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,10 +211,10 @@ void Canvas::texture_render(ShaderProgram& shader, GLuint texture, mat4 transfor
texture_uniforms_set(shader, transform, tint, colorOffset, textureSize, playbackTime);
// The editor's own texture shader blurs. A custom shader without these uniforms ignores them.
gl.Uniform1f(gl.GetUniformLocation(shader.id, UNIFORM_BLUR), blur.radius);
gl.Uniform4fv(gl.GetUniformLocation(shader.id, UNIFORM_REGION), 1, value_ptr(blur.region));
gl.Uniform4fv(gl.GetUniformLocation(shader.id, UNIFORM_REGION), 1, values_get(blur.region));
gl.Uniform2fv(gl.GetUniformLocation(shader.id, UNIFORM_TEXEL), 1,
value_ptr(textureSize.x > 0 && textureSize.y > 0 ? 1.0f / textureSize : vec2()));
gl.VertexAttrib4fv(2, value_ptr(tint));
values_get(textureSize.x > 0 && textureSize.y > 0 ? 1.0f / textureSize : Vec2()));
gl.VertexAttrib4fv(2, values_get(tint));
gl.BindVertexArray(textureVAO);
@@ -238,14 +234,14 @@ void Canvas::texture_render(ShaderProgram& shader, GLuint texture, mat4 transfor
canvas_blend_straight_set();
}
static void rect_begin(ShaderProgram& 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();
gl.UseProgram(shader.id);
gl.UniformMatrix4fv(gl.GetUniformLocation(shader.id, UNIFORM_TRANSFORM), 1, GL_FALSE, value_ptr(transform));
gl.UniformMatrix4fv(gl.GetUniformLocation(shader.id, UNIFORM_TRANSFORM), 1, GL_FALSE, values_get(transform));
if (auto location = gl.GetUniformLocation(shader.id, UNIFORM_MODEL); location != -1)
gl.UniformMatrix4fv(location, 1, GL_FALSE, value_ptr(model));
gl.Uniform4fv(gl.GetUniformLocation(shader.id, UNIFORM_COLOR), 1, value_ptr(color));
gl.UniformMatrix4fv(location, 1, GL_FALSE, values_get(model));
gl.Uniform4fv(gl.GetUniformLocation(shader.id, UNIFORM_COLOR), 1, values_get(color));
}
static void rect_end(GLuint vao, GLenum mode, int count = 4)
@@ -257,16 +253,16 @@ static void rect_end(GLuint vao, GLenum mode, int count = 4)
canvas_blend_straight_set();
}
void Canvas::dashed_render(ShaderProgram& shader, const mat4& transform, const mat4& model, vec4 color,
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{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)}})
auto origin = model * Vec4(0.0f, 0.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 = gl.GetUniformLocation(shader.id, name); location != -1)
gl.Uniform2fv(location, 1, value_ptr(vec2(model * axis - origin)));
gl.Uniform2fv(location, 1, values_get(Vec2(model * axis - origin)));
for (auto [name, value] : {std::pair{UNIFORM_DASH_LENGTH, dashLength}, std::pair{UNIFORM_DASH_GAP, dashGap},
std::pair{UNIFORM_DASH_OFFSET, dashOffset}})
if (auto location = gl.GetUniformLocation(shader.id, name); location != -1)
@@ -277,15 +273,16 @@ void Canvas::dashed_render(ShaderProgram& shader, const mat4& transform, const m
// 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(ShaderProgram& shader, GLuint texture, vec2 textureSize, const mat4& transform,
const 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)};
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 * draw_quad_model_get(draw))));
auto matrix = draw.parent * draw_quad_model_get(draw);
auto canvasArea = std::abs(matrix[0][0] * matrix[1][1] - matrix[1][0] * matrix[0][1]);
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;
@@ -299,7 +296,7 @@ void Canvas::layer_render(ShaderProgram& shader, GLuint texture, vec2 textureSiz
// An animation's layers alone (no markers or helpers). Spritesheet images are looked up by draw, custom shaders by id.
void Canvas::layers_render(ShaderProgram& shader, const Model& model, const Animation& animation,
const DrawOptions& options, const mat4& transform,
const DrawOptions& options, const Mat4& transform,
const std::function<const Image*(const Draw&)>& image_get,
const std::function<ShaderProgram*(int)>& shader_get) const
{
@@ -309,7 +306,7 @@ void Canvas::layers_render(ShaderProgram& shader, const Model& model, const Anim
continue;
auto& frame = draw.frame;
auto image = image_get(draw);
if (!image || !image->is_valid() || frame.size == vec2())
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,
@@ -317,24 +314,24 @@ void Canvas::layers_render(ShaderProgram& shader, const Model& model, const Anim
}
}
void Canvas::rect_render(ShaderProgram& 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(ShaderProgram& shader, const mat4& transform, vec2 start, vec2 end, vec4 color,
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;
auto normal = glm::length(direction) > 0.0f ? glm::normalize(vec2(-direction.y, direction.x)) : vec2(0.0f, 1.0f);
auto model = mat4(vec4(direction, 0.0f, 0.0f), vec4(normal, 0.0f, 0.0f), vec4(0.0f, 0.0f, 1.0f, 0.0f),
vec4(start, 0.0f, 1.0f));
auto normal = vec_length(direction) > 0.0f ? vec_normalize(Vec2(-direction.y, direction.x)) : Vec2(0.0f, 1.0f);
auto model = Mat4(Vec4(direction, 0.0f, 0.0f), Vec4(normal, 0.0f, 0.0f), Vec4(0.0f, 0.0f, 1.0f, 0.0f),
Vec4(start, 0.0f, 1.0f));
dashed_render(shader, transform, model, color, dashLength, dashGap, dashOffset, GL_LINES, LINE_VERTEX_COUNT);
}
void Canvas::rect_fill_render(ShaderProgram& 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);
@@ -365,7 +362,7 @@ float Canvas::zoom_level_get(float zoom, int levelDelta) const
return ZOOM_LEVELS[std::clamp(levelIndex, 0, levelCount - 1)];
}
void Canvas::zoom_level_adjust(float& zoom, vec2& pan, vec2 focus, int levelDelta) const
void Canvas::zoom_level_adjust(float& zoom, Vec2& pan, Vec2 focus, int levelDelta) const
{
auto zoomFactor = percent_to_unit(zoom);
float newZoom = zoom_level_get(zoom, levelDelta);
@@ -377,23 +374,23 @@ void Canvas::zoom_level_adjust(float& zoom, vec2& pan, vec2 focus, int levelDelt
}
}
vec2 Canvas::position_translate(float& zoom, vec2& pan, vec2 position) const
Vec2 Canvas::position_translate(float& zoom, Vec2& pan, Vec2 position) const
{
auto zoomFactor = percent_to_unit(zoom);
return (position - pan - (size * 0.5f)) / zoomFactor;
}
void Canvas::set_to_rect(float& zoom, vec2& pan, vec4 rect) const
void Canvas::set_to_rect(float& zoom, Vec2& pan, Vec4 rect) const
{
if (rect != vec4(-1.0f) && (rect.z > 0 && rect.w > 0))
if (rect != Vec4(-1.0f) && (rect.z > 0 && rect.w > 0))
{
f32 scaleX = size.x / rect.z;
f32 scaleY = size.y / rect.w;
f32 fitScale = std::min(scaleX, scaleY);
float scaleX = size.x / rect.z;
float scaleY = size.y / rect.w;
float fitScale = std::min(scaleX, scaleY);
zoom = unit_to_percent(fitScale);
vec2 rectCenter = {rect.x + rect.z * 0.5f, rect.y + rect.w * 0.5f};
Vec2 rectCenter = {rect.x + rect.z * 0.5f, rect.y + rect.w * 0.5f};
pan = -rectCenter * fitScale;
}
}
+20 -22
View File
@@ -4,7 +4,7 @@
#include <functional>
#include "gl.h"
#include <glm/glm.hpp>
#include "vec.h"
#include "framebuffer.h"
#include "image.h"
@@ -17,7 +17,7 @@
struct TextureBlur
{
float radius = 0;
glm::vec4 region{};
Vec4 region{};
};
class Canvas : public Framebuffer
@@ -25,7 +25,7 @@ class Canvas : public Framebuffer
public:
static constexpr float TEXTURE_VERTICES[] = {0, 0, 0.0f, 0.0f, 1, 0, 1.0f, 0.0f,
1, 1, 1.0f, 1.0f, 0, 1, 0.0f, 1.0f};
static constexpr auto PIVOT_SIZE = glm::vec2(8, 8);
static constexpr auto PIVOT_SIZE = Vec2(8, 8);
static constexpr auto ZOOM_MIN = 1.0f;
static constexpr auto ZOOM_MAX = 2000.0f;
static constexpr auto DASH_LENGTH = 4.0f;
@@ -64,27 +64,25 @@ public:
GLuint textureEBO = 0;
Canvas();
Canvas(glm::vec2);
Canvas(Vec2);
~Canvas();
glm::mat4 transform_get(float = 100.0f, glm::vec2 = {}) const;
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(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(ShaderProgram&, GLuint, glm::vec2, const glm::mat4&, const Draw&, glm::vec4, glm::vec4) const;
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&,
Mat4 transform_get(float = 100.0f, Vec2 = {}) const;
void axes_render(ShaderProgram&, float, Vec2, Vec4 = Vec4(1.0f)) const;
void grid_render(ShaderProgram&, float, Vec2, IVec2 = IVec2(32, 32), IVec2 = {}, Vec4 = Vec4(1.0f)) const;
void texture_render(ShaderProgram&, GLuint, Mat4 = Mat4(1.0f), Vec4 = Vec4(1.0f), Vec4 = {},
float* = (float*)TEXTURE_VERTICES, Vec2 = {}, float = 0.0f, TextureBlur = {}) const;
void layer_render(ShaderProgram&, GLuint, Vec2, const Mat4&, const Draw&, Vec4, Vec4) const;
void rect_fill_render(ShaderProgram&, const Mat4&, const Mat4&, Vec4 = Vec4(1.0f)) const;
void layers_render(ShaderProgram&, const Model&, const Animation&, const DrawOptions&, const Mat4&,
const std::function<const Image*(const Draw&)>&,
const std::function<ShaderProgram*(int)>& = {}) const;
void dashed_render(ShaderProgram&, const glm::mat4&, const glm::mat4&, glm::vec4, float, float, float, GLenum,
int) const;
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(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;
void dashed_render(ShaderProgram&, const Mat4&, const Mat4&, Vec4, float, float, float, GLenum, int) const;
void rect_render(ShaderProgram&, const Mat4&, const Mat4&, Vec4 = Vec4(1.0f), float dashLength = DASH_LENGTH,
float dashGap = DASH_GAP, float dashOffset = DASH_OFFSET) const;
void line_render(ShaderProgram&, const Mat4&, Vec2, Vec2, Vec4 = 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;
void zoom_level_adjust(float&, Vec2&, Vec2, int) const;
Vec2 position_translate(float&, Vec2&, Vec2) const;
void set_to_rect(float& zoom, Vec2& pan, Vec4 rect) const;
};
+3 -3
View File
@@ -97,7 +97,7 @@ static std::optional<Arguments> arguments_get(int argc, const char** argv)
}
// RRGGBB (opaque) or "transparent".
static glm::vec4 background_get(const Arguments& arguments)
static Vec4 background_get(const Arguments& arguments)
{
auto text = arguments.get("background").value_or("transparent");
if (text.starts_with('#'))
@@ -228,7 +228,7 @@ static int draw_run(const Arguments& arguments)
auto& textureInfo = SHADERS[SHADER_TEXTURE];
ShaderProgram shader(textureInfo.vertex, textureInfo.fragment);
Canvas canvas(glm::vec2(1.0f));
Canvas canvas(Vec2(1.0f));
auto isRootTransform = !arguments.is("no-root-transform");
auto bounds = animation_bounds_get(document, *animation, isRootTransform);
auto scale = arguments.number_get("scale", SCALE_DEFAULT);
@@ -245,7 +245,7 @@ static int draw_run(const Arguments& arguments)
{
auto pixels = frame_render(arguments.number_get("time", 0.0f));
pixels_unpremultiply(pixels);
if (!Image::write_pixels_png(outPath, glm::ivec2(canvas.size), pixels.data()))
if (!Image::write_pixels_png(outPath, IVec2(canvas.size), pixels.data()))
{
std::println(stderr, "could not write {}", *out);
return 1;
-2
View File
@@ -28,8 +28,6 @@
#include "ui/toast.h"
#include "working_directory.h"
using namespace glm;
constexpr std::string_view BAKED_EXTENSION = ".baked.png";
constexpr std::string_view AUTOSAVE_EXTENSION = ".autosave";
constexpr int VECTOR_LEVEL_MAX = 3;
+3 -3
View File
@@ -16,7 +16,7 @@
#include "snapshots.h"
#include "localization.h"
#include <glm/glm.hpp>
#include "vec.h"
#include "shader.h"
@@ -63,8 +63,8 @@ struct DocumentData
int changeAllFramePropertiesShaderId = -1;
float previewZoom = 200;
glm::vec2 previewPan{};
glm::vec2 editorPan{};
Vec2 previewPan{};
Vec2 editorPan{};
float editorZoom = 200;
int overlayIndex = -1;
uint64_t overlayDocumentId = 0;
+2 -2
View File
@@ -20,8 +20,8 @@ std::string region_name_get(const std::string& format, int number)
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);
return IVec2(region.crop) == IVec2(frame.crop) && IVec2(region.size) == IVec2(frame.size) &&
IVec2(region.pivot) == IVec2(frame.pivot);
}
// Every frame of every layer track whose layer has a spritesheet, with that spritesheet's id.
+3 -3
View File
@@ -35,9 +35,9 @@ struct RootBakeOptions
struct GridOptions
{
glm::ivec2 start{};
glm::ivec2 size{};
glm::vec2 pivot{};
IVec2 start{};
IVec2 size{};
Vec2 pivot{};
int columns = 0;
int count = 0;
int delay = 0;
+8 -8
View File
@@ -12,15 +12,15 @@
static Frame draw_frame_bake(const Draw& draw)
{
auto frame = draw.frame;
auto size = glm::max(frame.size, glm::vec2(1.0f));
auto size = vec_max(frame.size, Vec2(1.0f));
auto model = draw.parent * draw_quad_model_get(draw);
auto column0 = glm::vec2(model[0]) / size.x;
auto column1 = glm::vec2(model[1]) / size.y;
auto scaleX = glm::length(column0);
auto column0 = Vec2(model[0]) / size.x;
auto column1 = Vec2(model[1]) / size.y;
auto scaleX = vec_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 = unit_to_percent(glm::vec2(scaleX, scaleX > 0.0f ? determinant / scaleX : 0.0f));
frame.rotation = glm::degrees(std::atan2(column0.y, column0.x));
frame.position = Vec2(model * Vec4(frame.pivot / size, 0.0f, 1.0f));
frame.scale = unit_to_percent(Vec2(scaleX, scaleX > 0.0f ? determinant / scaleX : 0.0f));
frame.rotation = degrees(std::atan2(column0.y, column0.x));
frame.skew = {};
frame.depth = 0;
frame.regionId = -1;
@@ -92,7 +92,7 @@ Model animation_layers_flatten(Model model, const LibraryGet& library_get, const
for (int time = 0; time < source.frameNum; ++time)
for (auto& draw : animation_draws_get(model, source, {.time = (float)time, .library_get = library_get}))
{
if (draw.type != DrawType::LAYER || draw.id != track.id || draw.frame.size == glm::vec2())
if (draw.type != DrawType::LAYER || draw.id != track.id || draw.frame.size == Vec2())
continue;
auto id = layer_id_get(draw);
auto [it, isNew] = frames.try_emplace(id, source.frameNum, Frame{.isVisible = false});
+21 -22
View File
@@ -23,10 +23,10 @@ bool regions_trim(Model& model, int spritesheetId, const std::set<int>& ids, con
if (!region)
continue;
auto minPoint = glm::max(glm::ivec2(glm::min(region->crop, region->crop + region->size)), glm::ivec2(0));
auto maxPoint = glm::min(glm::ivec2(glm::max(region->crop, region->crop + region->size)), source.size);
auto contentMin = glm::ivec2(std::numeric_limits<int>::max());
auto contentMax = glm::ivec2(std::numeric_limits<int>::min());
auto minPoint = vec_max(IVec2(vec_min(region->crop, region->crop + region->size)), IVec2(0));
auto maxPoint = vec_min(IVec2(vec_max(region->crop, region->crop + region->size)), source.size);
auto contentMin = IVec2(std::numeric_limits<int>::max());
auto contentMax = IVec2(std::numeric_limits<int>::min());
for (int y = minPoint.y; y < maxPoint.y; ++y)
for (int x = minPoint.x; x < maxPoint.x; ++x)
@@ -37,15 +37,15 @@ bool regions_trim(Model& model, int spritesheetId, const std::set<int>& ids, con
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));
contentMax = glm::max(contentMax, glm::ivec2(x, y));
contentMin = vec_min(contentMin, IVec2(x, y));
contentMax = vec_max(contentMax, IVec2(x, y));
}
if (contentMin.x == std::numeric_limits<int>::max())
continue;
auto newCrop = glm::vec2(contentMin);
auto newSize = glm::vec2(contentMax - contentMin + 1);
auto newCrop = Vec2(contentMin);
auto newSize = Vec2(contentMax - contentMin + 1);
if (region->crop == newCrop && region->size == newSize)
continue;
@@ -69,8 +69,8 @@ std::optional<Image> spritesheet_pack(Model& model, int id, const Image& sheet,
struct PackItem
{
int regionId = -1;
glm::ivec2 source{};
glm::ivec2 size{};
IVec2 source{};
IVec2 size{};
};
auto spritesheet = item_get(model.content.spritesheets, id);
@@ -81,9 +81,9 @@ std::optional<Image> spritesheet_pack(Model& model, int id, const Image& sheet,
std::vector<PackItem> items;
for (auto& region : spritesheet->regions)
{
auto minPoint = glm::ivec2(glm::min(region.crop, region.crop + region.size));
auto maxPoint = glm::ivec2(glm::max(region.crop, region.crop + region.size));
items.push_back({region.id, minPoint, glm::max(maxPoint - minPoint, glm::ivec2(1))});
auto minPoint = IVec2(vec_min(region.crop, region.crop + region.size));
auto maxPoint = IVec2(vec_max(region.crop, region.crop + region.size));
items.push_back({region.id, minPoint, vec_max(maxPoint - minPoint, IVec2(1))});
}
std::sort(items.begin(), items.end(), [](const PackItem& a, const PackItem& b) {
@@ -92,12 +92,12 @@ std::optional<Image> spritesheet_pack(Model& model, int id, const Image& sheet,
return areaA != areaB ? areaA > areaB : a.regionId < b.regionId;
});
std::vector<glm::ivec2> sizes{};
std::vector<IVec2> sizes{};
for (auto& item : items)
sizes.push_back(item.size + padding * 2);
glm::ivec2 packedSize{};
std::vector<glm::ivec2> positions{};
IVec2 packedSize{};
std::vector<IVec2> positions{};
if (!rects_pack(sizes, packedSize, positions) || packedSize.x <= 0 || packedSize.y <= 0)
return {};
@@ -128,7 +128,7 @@ std::optional<Image> spritesheets_merge(Model& model, const std::set<int>& ids,
std::vector<ImagePart> parts{{image_get(baseId), {}, mergedSize, {}}};
std::unordered_map<int, std::unordered_map<int, int>> regionIdMap;
auto location_region_add = [&](int sourceId, glm::ivec2 crop, glm::ivec2 size) {
auto location_region_add = [&](int sourceId, IVec2 crop, IVec2 size) {
auto source = item_get(model.content.spritesheets, sourceId);
Region region = {};
region.id = item_next_id_get(base->regions);
@@ -136,7 +136,7 @@ std::optional<Image> spritesheets_merge(Model& model, const std::set<int>& ids,
region.name = stem.empty() ? std::format("#{}", sourceId) : stem;
region.crop = crop;
region.size = size;
region.pivot = origin == Origin::CENTER ? glm::vec2(size) * 0.5f : glm::vec2();
region.pivot = origin == Origin::CENTER ? Vec2(size) * 0.5f : Vec2();
region.origin = origin;
base->regions.push_back(region);
};
@@ -148,10 +148,9 @@ std::optional<Image> spritesheets_merge(Model& model, const std::set<int>& ids,
if (id == baseId)
continue;
auto texture = image_get(id);
auto offset = isAppendRight ? glm::ivec2(mergedSize.x, 0) : glm::ivec2(0, mergedSize.y);
mergedSize = isAppendRight
? glm::ivec2(mergedSize.x + texture->size.x, std::max(mergedSize.y, texture->size.y))
: glm::ivec2(std::max(mergedSize.x, texture->size.x), mergedSize.y + texture->size.y);
auto offset = isAppendRight ? IVec2(mergedSize.x, 0) : IVec2(0, mergedSize.y);
mergedSize = isAppendRight ? IVec2(mergedSize.x + texture->size.x, std::max(mergedSize.y, texture->size.y))
: IVec2(std::max(mergedSize.x, texture->size.x), mergedSize.y + texture->size.y);
parts.push_back({texture, {}, texture->size, offset});
if (!isMakeRegions)
continue;
+2 -4
View File
@@ -2,8 +2,6 @@
#include "texture.h"
using namespace glm;
Framebuffer::Framebuffer()
{
gl.GenFramebuffers(1, &fbo);
@@ -49,7 +47,7 @@ void Framebuffer::resize_check()
}
}
void Framebuffer::size_set(vec2 size)
void Framebuffer::size_set(Vec2 size)
{
previousSize = this->size;
this->size = size;
@@ -70,7 +68,7 @@ std::vector<uint8_t> Framebuffer::pixels_get() const
return pixels;
}
void Framebuffer::clear(vec4 color) const
void Framebuffer::clear(Vec4 color) const
{
gl.Enable(GL_BLEND);
gl.ClearColor(color.r, color.g, color.b, color.a);
+6 -5
View File
@@ -1,7 +1,8 @@
#pragma once
#include "gl.h"
#include <glm/glm.hpp>
#include "vec.h"
#include <vector>
class Framebuffer
{
@@ -16,8 +17,8 @@ public:
GLuint fbo = 0;
GLuint rbo = 0;
GLuint texture = 0;
glm::vec2 size{};
glm::vec2 previousSize{};
Vec2 size{};
Vec2 previousSize{};
GLint filter = GL_LINEAR; // how the texture is sampled when drawn scaled. Takes effect on the next resize
Framebuffer();
@@ -25,9 +26,9 @@ public:
void set();
void resize_check();
void size_set(glm::vec2);
void size_set(Vec2);
void viewport_set() const;
void clear(glm::vec4 = glm::vec4(1.0f, 1.0f, 1.0f, 0.0f)) const;
void clear(Vec4 = Vec4(1.0f, 1.0f, 1.0f, 0.0f)) const;
std::vector<uint8_t> pixels_get() const;
bool is_valid() const;
void bind() const;
+6 -6
View File
@@ -1,11 +1,11 @@
#pragma once
#include "embed.h"
#include <glm/ext/vector_int2.hpp>
#include "vec.h"
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);
constexpr auto ICON_SIZE_SMALL = IVec2(64, 64);
constexpr auto ICON_SIZE_NORMAL = IVec2(128, 128);
constexpr auto ICON_SIZE_LARGE = IVec2(256, 256);
constexpr auto ICON_SIZE_HUGE = IVec2(512, 512);
#define SVG_LIST \
X(ICON_NONE, &ICON_NONE_SVG, ICON_SIZE_SMALL) \
@@ -66,7 +66,7 @@ enum Icon
struct IconInfo
{
const Embed* svg = nullptr;
glm::ivec2 size{};
IVec2 size{};
};
constexpr IconInfo ICONS[ICON_COUNT] = {
+29 -33
View File
@@ -36,8 +36,6 @@
#include "path.h"
#include "uid.h"
using namespace glm;
constexpr std::size_t BASE64_GROUP_BYTES = 3;
constexpr int BASE64_DIGIT_BITS = 6;
constexpr std::uint32_t BASE64_DIGIT_MASK = 0x3F;
@@ -66,9 +64,9 @@ bool Image::is_vector() const
return svg != nullptr;
}
glm::vec2 Image::unit_size_get() const
Vec2 Image::unit_size_get() const
{
return glm::vec2(size) / scale;
return Vec2(size) / scale;
}
// Closes the hairline seams an SVG's anti-aliasing leaves where two shapes meet: a partly covered pixel with opaque
@@ -76,20 +74,19 @@ glm::vec2 Image::unit_size_get() const
// Outer edges, with transparency on one side, keep their anti-aliasing.
static void seams_fill(Image& image)
{
constexpr glm::ivec2 AXES[] = {{1, 0}, {0, 1}, {1, 1}, {1, -1}};
constexpr 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<uint8_t> 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 * IMAGE_CHANNELS + ALPHA];
auto index_get = [&](glm::ivec2 point) {
auto index_get = [&](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* {
auto opaque_get = [&](IVec2 point, IVec2 step) -> const uint8_t* {
for (int reach = 1; reach <= SEAM_REACH; ++reach)
{
auto neighbor = point + step * reach;
if (glm::any(glm::lessThan(neighbor, glm::ivec2(0))) ||
glm::any(glm::greaterThanEqual(neighbor, image.size)))
if (!is_within(neighbor, IVec2(0), image.size))
return nullptr;
if (alphas[index_get(neighbor)] >= SEAM_OPAQUE_ALPHA)
return image.pixels.data() + index_get(neighbor) * IMAGE_CHANNELS;
@@ -126,7 +123,7 @@ static Image svg_render(std::shared_ptr<const std::string> svg, float scale)
auto document = svg ? lunasvg::Document::loadFromData(*svg) : nullptr;
if (!document || document->width() <= 0.0f)
return {};
auto size = glm::max(ivec2(glm::ceil(vec2(document->width(), document->height()) * scale)), ivec2(1));
auto size = vec_max(IVec2(vec_ceil(Vec2(document->width(), document->height()) * scale)), IVec2(1));
auto bitmap = document->renderToBitmap(size.x, size.y);
if (bitmap.isNull())
return {};
@@ -148,7 +145,7 @@ 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)
Image::Image(const uint8_t* data, IVec2 size, bool isLinear) : isLinear(isLinear)
{
if (!data || size.x <= 0 || size.y <= 0)
return;
@@ -189,7 +186,7 @@ bool Image::write_png(const std::filesystem::path& path) const
return write_pixels_png(path, size, pixels.empty() ? nullptr : pixels.data());
}
bool Image::write_pixels_png(const std::filesystem::path& path, ivec2 size, const uint8_t* data)
bool Image::write_pixels_png(const std::filesystem::path& path, IVec2 size, const uint8_t* data)
{
if (!data || size.x <= 0 || size.y <= 0)
return false;
@@ -207,15 +204,14 @@ bool Image::write_pixels_png(const std::filesystem::path& path, ivec2 size, cons
}
// Copies a size-sized block between images. Pixels outside either image are skipped.
static void pixels_copy(const Image& from, glm::ivec2 fromMin, Image& to, glm::ivec2 toMin, glm::ivec2 size)
static void pixels_copy(const Image& from, IVec2 fromMin, Image& to, IVec2 toMin, IVec2 size)
{
for (int y = 0; y < size.y; ++y)
for (int x = 0; x < size.x; ++x)
{
auto source = fromMin + glm::ivec2(x, y);
auto target = toMin + glm::ivec2(x, y);
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)))
auto source = fromMin + IVec2(x, y);
auto target = toMin + IVec2(x, y);
if (!is_within(source, IVec2(0), from.size) || !is_within(target, IVec2(0), to.size))
continue;
std::copy_n(from.pixels.data() + ((std::size_t)source.y * from.size.x + source.x) * IMAGE_CHANNELS,
IMAGE_CHANNELS,
@@ -223,13 +219,13 @@ static void pixels_copy(const Image& from, glm::ivec2 fromMin, Image& to, glm::i
}
}
void Image::paste(const Image& source, glm::ivec2 position)
void Image::paste(const Image& source, IVec2 position)
{
pixels_copy(source, {}, *this, position, source.size);
}
// A copy of a block of the image (transparent where it falls outside).
Image Image::region_get(glm::ivec2 min, glm::ivec2 regionSize) const
Image Image::region_get(IVec2 min, IVec2 regionSize) const
{
Image region = {};
region.size = regionSize;
@@ -361,7 +357,7 @@ static void svg_definition_add(pugi::xml_node root, pugi::xml_node defs, const I
// Parts of images placed into one image of `size`: an SVG when `isVector` (each part a clipped view of its image's
// drawing, or of an embedded PNG), otherwise pixels.
Image Image::compose(const std::vector<ImagePart>& parts, glm::ivec2 size, bool isVector)
Image Image::compose(const std::vector<ImagePart>& parts, IVec2 size, bool isVector)
{
if (!isVector)
{
@@ -417,44 +413,44 @@ bool Image::write(const std::filesystem::path& path) const
return write_png(path);
}
vec4 Image::pixel_read(vec2 position) const
Vec4 Image::pixel_read(Vec2 position) const
{
if (pixels.size() < IMAGE_CHANNELS || size.x <= 0 || size.y <= 0)
return vec4(0.0f);
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);
int x = vec_clamp((int)(position.x), 0, size.x - 1);
int y = vec_clamp((int)(position.y), 0, size.y - 1);
auto index = ((size_t)(y) * (size_t)(size.x) + (size_t)(x)) * IMAGE_CHANNELS;
if (index + IMAGE_CHANNELS > pixels.size())
return vec4(0.0f);
return Vec4(0.0f);
vec4 color{uint8_to_float(pixels[index + 0]), uint8_to_float(pixels[index + 1]), uint8_to_float(pixels[index + 2]),
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])};
if (color.a <= 0.0f)
color = vec4(0.0f);
color = Vec4(0.0f);
return color;
}
void Image::pixel_set(ivec2 position, vec4 color)
void Image::pixel_set(IVec2 position, Vec4 color)
{
if (position.x < 0 || position.y < 0 || position.x >= size.x || position.y >= size.y)
return;
uint8 rgba8[4] = {(uint8)float_to_uint8(color.r), (uint8)float_to_uint8(color.g), (uint8)float_to_uint8(color.b),
(uint8)float_to_uint8(color.a)};
uint8_t rgba[4] = {(uint8_t)float_to_uint8(color.r), (uint8_t)float_to_uint8(color.g),
(uint8_t)float_to_uint8(color.b), (uint8_t)float_to_uint8(color.a)};
if (pixels.size() != pixel_size_get())
return;
size_t idx = (position.y * size.x + position.x) * IMAGE_CHANNELS;
memcpy(&pixels[idx], rgba8, 4);
memcpy(&pixels[idx], rgba, 4);
uid = uid_next();
}
void Image::pixel_line(ivec2 start, ivec2 end, vec4 color)
void Image::pixel_line(IVec2 start, IVec2 end, Vec4 color)
{
auto plot = [&](ivec2 pos) {
auto plot = [&](IVec2 pos) {
pixel_set(pos, color);
};
+14 -14
View File
@@ -7,7 +7,7 @@
#include <string>
#include <vector>
#include <glm/glm.hpp>
#include "vec.h"
constexpr auto IMAGE_CHANNELS = 4;
constexpr auto SVG_EXTENSION = "svg";
@@ -19,9 +19,9 @@ class Image;
struct ImagePart
{
const Image* image = nullptr;
glm::ivec2 source{};
glm::ivec2 size{};
glm::ivec2 destination{};
IVec2 source{};
IVec2 size{};
IVec2 destination{};
};
// CPU-side RGBA pixels. uid changes whenever the pixels do, so GPU copies can be cached by it. A vector image keeps
@@ -29,7 +29,7 @@ struct ImagePart
class Image
{
public:
glm::ivec2 size{};
IVec2 size{};
std::vector<uint8_t> pixels;
bool isLinear = false;
std::uint64_t uid = 0;
@@ -37,22 +37,22 @@ public:
float scale = 1.0f;
Image() = default;
Image(const uint8_t*, glm::ivec2, bool = false);
Image(const uint8_t*, IVec2, bool = false);
Image(const unsigned char*, size_t);
Image(const std::filesystem::path&);
bool is_valid() const;
bool is_vector() const;
glm::vec2 unit_size_get() const;
Vec2 unit_size_get() const;
Image vector_render(float) const;
size_t pixel_size_get() const;
bool write_png(const std::filesystem::path&) const;
static bool write_pixels_png(const std::filesystem::path&, glm::ivec2, const uint8_t*);
static bool write_pixels_png(const std::filesystem::path&, IVec2, const uint8_t*);
bool write(const std::filesystem::path&) const;
static Image compose(const std::vector<ImagePart>&, glm::ivec2, bool);
void paste(const Image&, glm::ivec2);
Image region_get(glm::ivec2, glm::ivec2) const;
glm::vec4 pixel_read(glm::vec2) const;
void pixel_set(glm::ivec2, glm::vec4);
void pixel_line(glm::ivec2, glm::ivec2, glm::vec4);
static Image compose(const std::vector<ImagePart>&, IVec2, bool);
void paste(const Image&, IVec2);
Image region_get(IVec2, IVec2) const;
Vec4 pixel_read(Vec2) const;
void pixel_set(IVec2, Vec4);
void pixel_line(IVec2, IVec2, Vec4);
};
+6 -7
View File
@@ -31,7 +31,7 @@ constexpr auto IDLE_UPDATE_INTERVAL_MS = 1000 / 20;
// How long after the last input the window still counts as busy.
constexpr auto IDLE_DELAY_MS = 1000;
constexpr auto TICK_DELTA_MAX_MS = 250;
constexpr auto WINDOW_4K_SIZE = glm::ivec2(3840, 2160);
constexpr auto WINDOW_4K_SIZE = IVec2(3840, 2160);
constexpr auto UI_SCALE_4K_DEFAULT = 150.0f;
constexpr auto WINDOW_DEFAULT_SIZE_MULTIPLIER = 0.90f;
constexpr auto GL_VERSION_MAJOR = 3;
@@ -312,8 +312,8 @@ static void frame_update(App& app, Editor& editor)
document_shortcuts_update(editor.manager);
editor.taskbar.update(editor.manager, settings, editor.resources, editor.dialog, app.isQuitting);
editor.documents.update(editor.taskbar, editor.manager, settings, editor.resources, app.isQuitting);
editor.dockspace.update(editor.taskbar, editor.documents, editor.manager, settings, editor.resources,
editor.dialog, editor.clipboard);
editor.dockspace.update(editor.taskbar, editor.documents, editor.manager, settings, editor.resources, editor.dialog,
editor.clipboard);
ui_scale_update(app, editor);
toasts.update();
editor.manager.commands_run();
@@ -348,11 +348,10 @@ static void frame_render(App& app)
// Idle: no input for a while, nothing playing or recording, no toast fading, no text being typed, no About box.
static bool is_idle(App& app, Editor& editor)
{
if (SDL_GetTicks() - app.inputTime < IDLE_DELAY_MS || ImGui::GetIO().WantTextInput ||
editor.manager.isRecording || !toasts.toasts.empty() || editor.taskbar.aboutPopup.isOpen)
if (SDL_GetTicks() - app.inputTime < IDLE_DELAY_MS || ImGui::GetIO().WantTextInput || editor.manager.isRecording ||
!toasts.toasts.empty() || editor.taskbar.aboutPopup.isOpen)
return false;
return std::ranges::none_of(editor.manager.documents,
[](auto& document) { return document.playback.isPlaying; });
return std::ranges::none_of(editor.manager.documents, [](auto& document) { return document.playback.isPlaying; });
}
// Draws at most every UPDATE_INTERVAL_MS, and ticks playback at the playback tick rate in between.
+26 -28
View File
@@ -1,11 +1,9 @@
#include "math_util.h"
#include <ctime>
#include <glm/ext/matrix_transform.hpp>
#include "vec.h"
#include <string>
using namespace glm;
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};
@@ -30,7 +28,7 @@ const char* float_format_get(float value)
return formatString.c_str();
}
const char* vec2_format_get(const vec2& value)
const char* vec2_format_get(const Vec2& value)
{
static std::string formatString;
int decimalCountX = float_decimals_needed(value.x);
@@ -40,48 +38,48 @@ const char* vec2_format_get(const vec2& value)
return formatString.c_str();
}
static mat4 skew_get(vec2 skew)
static Mat4 skew_get(Vec2 skew)
{
mat4 result(1.0f);
Mat4 result(1.0f);
result[1][0] = skew.x;
result[0][1] = skew.y;
return result;
}
mat4 quad_model_get(vec2 size, vec2 position, vec2 pivot, vec2 scale, float rotation, vec2 skew)
Mat4 quad_model_get(Vec2 size, Vec2 position, Vec2 pivot, Vec2 scale, float rotation, Vec2 skew)
{
vec2 scaleAbsolute = glm::abs(scale);
vec2 scaleSign = glm::sign(scale);
vec2 pivotScaled = pivot * scaleAbsolute;
vec2 sizeScaled = size * scaleAbsolute;
Vec2 scaleAbsolute = vec_abs(scale);
Vec2 scaleSign = vec_sign(scale);
Vec2 pivotScaled = pivot * scaleAbsolute;
Vec2 sizeScaled = size * scaleAbsolute;
float handedness = (scaleSign.x * scaleSign.y) < 0.0f ? -1.0f : 1.0f;
mat4 model(1.0f);
model = glm::translate(model, vec3(position - pivotScaled, 0.0f));
model = glm::translate(model, vec3(pivotScaled, 0.0f));
model = glm::scale(model, vec3(scaleSign, 1.0f));
model = glm::rotate(model, glm::radians(rotation) * handedness, vec3(0, 0, 1));
Mat4 model(1.0f);
model = mat4_translate(model, Vec3(position - pivotScaled, 0.0f));
model = mat4_translate(model, Vec3(pivotScaled, 0.0f));
model = mat4_scale(model, Vec3(scaleSign, 1.0f));
model = mat4_rotate(model, radians(rotation) * handedness);
model *= skew_get(skew);
model = glm::translate(model, vec3(-pivotScaled, 0.0f));
model = glm::scale(model, vec3(sizeScaled, 1.0f));
model = mat4_translate(model, Vec3(-pivotScaled, 0.0f));
model = mat4_scale(model, Vec3(sizeScaled, 1.0f));
return model;
}
mat4 quad_model_parent_get(vec2 position, vec2 pivot, vec2 scale, float rotation, vec2 skew)
Mat4 quad_model_parent_get(Vec2 position, Vec2 pivot, Vec2 scale, float rotation, Vec2 skew)
{
vec2 scaleSign = glm::sign(scale);
vec2 scaleAbsolute = glm::abs(scale);
Vec2 scaleSign = vec_sign(scale);
Vec2 scaleAbsolute = vec_abs(scale);
float handedness = (scaleSign.x * scaleSign.y) < 0.0f ? -1.0f : 1.0f;
mat4 local(1.0f);
local = glm::translate(local, vec3(pivot, 0.0f));
local = glm::scale(local, vec3(scaleSign, 1.0f));
local = glm::rotate(local, glm::radians(rotation) * handedness, vec3(0, 0, 1));
Mat4 local(1.0f);
local = mat4_translate(local, Vec3(pivot, 0.0f));
local = mat4_scale(local, Vec3(scaleSign, 1.0f));
local = mat4_rotate(local, radians(rotation) * handedness);
local *= skew_get(skew);
local = glm::translate(local, vec3(-pivot, 0.0f));
local = glm::scale(local, vec3(scaleAbsolute, 1.0f));
local = mat4_translate(local, Vec3(-pivot, 0.0f));
local = mat4_scale(local, Vec3(scaleAbsolute, 1.0f));
return glm::translate(mat4(1.0f), vec3(position, 0.0f)) * local;
return mat4_translate(Mat4(1.0f), Vec3(position, 0.0f)) * local;
}
float random_unit_get()
+5 -7
View File
@@ -1,7 +1,7 @@
#pragma once
#include <array>
#include <glm/glm/mat4x4.hpp>
#include "vec.h"
template <typename T> constexpr T percent_to_unit(T value)
{
@@ -23,7 +23,7 @@ constexpr int float_to_uint8(float value)
return (int)(value * 255);
}
constexpr std::array<float, 16> uv_vertices_get(glm::vec2 uvMin, glm::vec2 uvMax)
constexpr std::array<float, 16> uv_vertices_get(Vec2 uvMin, Vec2 uvMax)
{
return {0.0f, 0.0f, uvMin.x, uvMin.y, 1.0f, 0.0f, uvMax.x, uvMin.y,
1.0f, 1.0f, uvMax.x, uvMax.y, 0.0f, 1.0f, uvMin.x, uvMax.y};
@@ -33,12 +33,10 @@ int float_decimals_needed(float);
const char* float_format_get(float);
const char* vec2_format_get(const glm::vec2&);
const char* vec2_format_get(const Vec2&);
glm::mat4 quad_model_get(glm::vec2 = {}, glm::vec2 = {}, glm::vec2 = {}, glm::vec2 = glm::vec2(1.0f), float = {},
glm::vec2 = {});
glm::mat4 quad_model_parent_get(glm::vec2 = {}, glm::vec2 = {}, glm::vec2 = glm::vec2(1.0f), float = {},
glm::vec2 = {});
Mat4 quad_model_get(Vec2 = {}, Vec2 = {}, Vec2 = {}, Vec2 = Vec2(1.0f), float = {}, Vec2 = {});
Mat4 quad_model_parent_get(Vec2 = {}, Vec2 = {}, Vec2 = Vec2(1.0f), float = {}, Vec2 = {});
float random_unit_get();
float random_in_range(float min, float max);
+2 -2
View File
@@ -4,7 +4,7 @@
#include <cstdint>
#include <optional>
#include <glm/glm.hpp>
#include "vec.h"
#include "types.h"
@@ -247,7 +247,7 @@ struct Handle
inline float interpolation_factor(Interpolation interpolation, float value)
{
value = glm::clamp(value, 0.0f, 1.0f);
value = vec_clamp(value, 0.0f, 1.0f);
if (interpolation == Interpolation::LINEAR)
return value;
if (interpolation == Interpolation::EASE_IN)
+10 -11
View File
@@ -9,7 +9,7 @@
constexpr unsigned RANDOM_MULTIPLIER_A = 73856093u;
constexpr unsigned RANDOM_MULTIPLIER_B = 19349663u;
glm::mat4 draw_quad_model_get(const Draw& draw)
Mat4 draw_quad_model_get(const Draw& draw)
{
auto& frame = draw.frame;
return quad_model_get(frame.size, frame.position, frame.pivot, percent_to_unit(frame.scale), frame.rotation,
@@ -17,9 +17,9 @@ glm::mat4 draw_quad_model_get(const Draw& draw)
}
// 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)
Mat4 frame_child_model_get(const Frame& frame)
{
return quad_model_get(glm::vec2(1.0f), frame.position, frame.pivot, percent_to_unit(frame.scale), frame.rotation,
return quad_model_get(Vec2(1.0f), frame.position, frame.pivot, percent_to_unit(frame.scale), frame.rotation,
percent_to_unit(frame.skew));
}
@@ -27,8 +27,8 @@ glm::mat4 frame_child_model_get(const Frame& frame)
float draw_scale_get(const Draw& draw)
{
auto model = draw.parent * draw_quad_model_get(draw);
auto size = glm::max(draw.frame.size, glm::vec2(1.0f));
return std::max(glm::length(glm::vec2(model[0])) / size.x, glm::length(glm::vec2(model[1])) / size.y);
auto size = vec_max(draw.frame.size, Vec2(1.0f));
return std::max(vec_length(Vec2(model[0])) / size.x, vec_length(Vec2(model[1])) / size.y);
}
// When an item is drawn: now, and for each sample its time if the track has a frame there.
@@ -151,14 +151,13 @@ std::vector<TriggerFire> animation_triggers_get(const Model& model, const Animat
}
// Where an animation layer track (`layerId`) puts its child at a time, in the animation's space.
std::optional<glm::mat4> layer_child_transform_get(const Animation& animation, int layerId, float time,
bool isRootTransform)
std::optional<Mat4> layer_child_transform_get(const Animation& animation, int layerId, float time, bool isRootTransform)
{
std::optional<glm::mat4> transform{};
std::optional<Mat4> transform{};
tracks_each(animation.layers, [&](const Track& track, const TrackGroup* group) {
if (track.id != layerId || transform)
return;
glm::mat4 parent(1.0f);
Mat4 parent(1.0f);
if (isRootTransform)
{
parent *= frame_parent_model_get(frame_generate(animation.root, time));
@@ -180,7 +179,7 @@ static std::vector<Draw> animation_draws_get(const Model& model, const Animation
std::vector<std::pair<int, int>> layerOrders;
int layerOrder = 0;
auto parent_get = [&](float time, const TrackGroup* group) {
glm::mat4 parent(1.0f);
Mat4 parent(1.0f);
if (!options.isRootTransform)
return parent;
parent *= frame_parent_model_get(frame_generate(animation.root, time));
@@ -190,7 +189,7 @@ static std::vector<Draw> animation_draws_get(const Model& model, const Animation
};
// An animation layer's child animation, placed by the layer's frame (its pivot is the child's origin).
auto child_draws_add = [&](const Track& track, const Layer& layer, int sample, float time, const Frame& frame,
const glm::mat4& parent) {
const Mat4& parent) {
auto [childModel, childAnimation] = child_get(model, layer, frame, options.library_get);
if (!childAnimation || std::ranges::contains(playing, childAnimation))
return;
+4 -4
View File
@@ -46,7 +46,7 @@ struct Draw
int sample = -1;
float time = 0;
Frame frame = {};
glm::mat4 parent{1.0f};
Mat4 parent{1.0f};
const Model* source = nullptr;
int spritesheetId = -1;
int sourceId = -1; // the layer of `source` drawn (a child's, for an animation layer's draws)
@@ -60,11 +60,11 @@ struct TriggerFire
int layerId = -1; // the animation's layer whose child fired it. -1 for the animation's own
};
glm::mat4 draw_quad_model_get(const Draw&);
glm::mat4 frame_child_model_get(const Frame&);
Mat4 draw_quad_model_get(const Draw&);
Mat4 frame_child_model_get(const Frame&);
std::pair<const Model*, const Animation*> child_get(const Model&, const Layer&, const Frame&, const LibraryGet&);
float child_time_get(const Track&, float, int, int);
std::optional<glm::mat4> layer_child_transform_get(const Animation&, int, float, bool);
std::optional<Mat4> layer_child_transform_get(const Animation&, int, float, bool);
float draw_scale_get(const Draw&);
std::vector<Draw> animation_draws_get(const Model&, const Animation&, const DrawOptions&);
std::vector<TriggerFire> animation_triggers_get(const Model&, const Animation&, int, const LibraryGet& = {});
+27 -28
View File
@@ -8,13 +8,13 @@
void frame_mix(Frame& frame, const Frame& next, float amount)
{
frame.rotation = glm::mix(frame.rotation, next.rotation, amount);
frame.position = glm::mix(frame.position, next.position, amount);
frame.scale = glm::mix(frame.scale, next.scale, amount);
frame.skew = glm::mix(frame.skew, next.skew, amount);
frame.colorOffset = glm::mix(frame.colorOffset, next.colorOffset, amount);
frame.tint = glm::mix(frame.tint, next.tint, amount);
frame.blur = glm::mix(frame.blur, next.blur, amount);
frame.rotation = vec_mix(frame.rotation, next.rotation, amount);
frame.position = vec_mix(frame.position, next.position, amount);
frame.scale = vec_mix(frame.scale, next.scale, amount);
frame.skew = vec_mix(frame.skew, next.skew, amount);
frame.colorOffset = vec_mix(frame.colorOffset, next.colorOffset, amount);
frame.tint = vec_mix(frame.tint, next.tint, amount);
frame.blur = vec_mix(frame.blur, next.blur, amount);
}
// Splits an interpolated frame into uninterpolated frames of at most `interval`. The first keeps the frame's uid.
@@ -31,14 +31,14 @@ std::vector<Frame> frame_bake_split(const Frame& original, const Frame& next, in
baked.duration = std::min(interval, total - duration);
baked.interpolation = Interpolation::NONE;
if (isRoundScale)
baked.scale = glm::round(baked.scale);
baked.scale = vec_round(baked.scale);
if (isRoundRotation)
baked.rotation = std::round(baked.rotation);
}
return frames;
}
glm::mat4 frame_parent_model_get(const Frame& frame)
Mat4 frame_parent_model_get(const Frame& frame)
{
return quad_model_parent_get(frame.position, {}, percent_to_unit(frame.scale), frame.rotation,
percent_to_unit(frame.skew));
@@ -48,20 +48,20 @@ void frame_root_transform_apply(Frame& frame, const Frame& rootFrame, bool isRou
bool isUseRootPivot)
{
auto rootScale = percent_to_unit(rootFrame.scale);
auto pivot = isUseRootPivot ? rootFrame.position : glm::vec2();
auto pivot = isUseRootPivot ? rootFrame.position : Vec2();
auto offset = (frame.position - pivot) * rootScale;
auto radians = glm::radians(rootFrame.rotation);
auto cos = std::cos(radians);
auto sin = std::sin(radians);
auto angle = radians(rootFrame.rotation);
auto cos = std::cos(angle);
auto sin = std::sin(angle);
frame.position = rootFrame.position + glm::vec2(offset.x * cos - offset.y * sin, offset.x * sin + offset.y * cos);
frame.position = rootFrame.position + Vec2(offset.x * cos - offset.y * sin, offset.x * sin + offset.y * cos);
frame.scale *= rootScale;
frame.rotation += rootFrame.rotation;
frame.tint *= rootFrame.tint;
frame.colorOffset += rootFrame.colorOffset;
if (isRoundScale)
frame.scale = glm::round(frame.scale);
frame.scale = vec_round(frame.scale);
if (isRoundRotation)
frame.rotation = std::round(frame.rotation);
}
@@ -181,8 +181,8 @@ void frame_bake(Track& track, int index, int interval, bool isRoundScale, bool i
track.frames.insert(track.frames.begin() + index, baked.begin(), baked.end());
}
void frames_generate_from_grid(Track& track, glm::ivec2 startPosition, glm::ivec2 size, glm::vec2 pivot, int columns,
int count, int duration)
void frames_generate_from_grid(Track& track, IVec2 startPosition, IVec2 size, Vec2 pivot, int columns, int count,
int duration)
{
for (int i = 0; i < count; ++i)
{
@@ -190,7 +190,7 @@ void frames_generate_from_grid(Track& track, glm::ivec2 startPosition, glm::ivec
frame.duration = duration;
frame.pivot = pivot;
frame.size = size;
frame.crop = startPosition + glm::ivec2(size.x * (i % columns), size.y * (i / columns));
frame.crop = startPosition + IVec2(size.x * (i % columns), size.y * (i / columns));
}
}
@@ -267,31 +267,30 @@ void frames_change(Track& track, FrameChange change, ItemType itemType, ChangeTy
}
// Bounds of all visible layer frames over the animation's length, or -1 when nothing is drawn.
glm::vec4 animation_rect(const Model& model, const Animation& animation, bool isRootTransform,
const LibraryGet& library_get)
Vec4 animation_rect(const Model& model, const Animation& animation, bool isRootTransform, const LibraryGet& library_get)
{
constexpr glm::ivec2 CORNERS[4] = {{0, 0}, {1, 0}, {1, 1}, {0, 1}};
glm::vec2 min{std::numeric_limits<float>::infinity()};
glm::vec2 max{-std::numeric_limits<float>::infinity()};
constexpr IVec2 CORNERS[4] = {{0, 0}, {1, 0}, {1, 1}, {0, 1}};
Vec2 min{std::numeric_limits<float>::infinity()};
Vec2 max{-std::numeric_limits<float>::infinity()};
bool isAny = false;
for (float time = 0.0f; time < (float)animation.frameNum; time += 1.0f)
for (auto& draw : animation_draws_get(
model, animation, {.time = time, .isRootTransform = isRootTransform, .library_get = library_get}))
{
if (draw.type != DrawType::LAYER || draw.frame.size == glm::vec2())
if (draw.type != DrawType::LAYER || draw.frame.size == Vec2())
continue;
auto transform = draw.parent * draw_quad_model_get(draw);
for (auto& corner : CORNERS)
{
auto world = glm::vec2(transform * glm::vec4(corner, 0.0f, 1.0f));
min = glm::min(min, world);
max = glm::max(max, world);
auto world = Vec2(transform * Vec4(corner, 0.0f, 1.0f));
min = vec_min(min, world);
max = vec_max(max, world);
isAny = true;
}
}
if (!isAny)
return glm::vec4(-1.0f);
return Vec4(-1.0f);
return {min.x, min.y, max.x - min.x, max.y - min.y};
}
+3 -3
View File
@@ -7,7 +7,7 @@
void frame_mix(Frame&, const Frame&, float);
std::vector<Frame> frame_bake_split(const Frame&, const Frame&, int, bool, bool);
glm::mat4 frame_parent_model_get(const Frame&);
Mat4 frame_parent_model_get(const Frame&);
void frame_root_transform_apply(Frame&, const Frame&, bool, bool, bool);
Frame frame_generate(const Track&, float);
void track_group_root_bake(Track&, const Track&, int);
@@ -15,7 +15,7 @@ int frame_index_from_at_frame_get(const Track&, int);
int frame_index_from_time_get(const Track&, float);
float frame_time_from_index_get(const Track&, int);
void frame_bake(Track&, int, int, bool, bool);
void frames_generate_from_grid(Track&, glm::ivec2, glm::ivec2, glm::vec2, int, int, int);
void frames_generate_from_grid(Track&, IVec2, IVec2, Vec2, int, int, int);
void frames_sort_by_at_frame(Track&);
void frames_change(Track&, FrameChange, ItemType, ChangeType, const std::set<int>&, bool isAnimationLayer = false);
glm::vec4 animation_rect(const Model&, const Animation&, bool, const LibraryGet& = {});
Vec4 animation_rect(const Model&, const Animation&, bool, const LibraryGet& = {});
+9 -9
View File
@@ -41,12 +41,12 @@ template <class Items> static int index_get(const Items& items, int id)
return it == items.end() ? -1 : (int)(it - items.begin());
}
static glm::ivec4 color_to_bytes(const glm::vec4& color)
static IVec4 color_to_bytes(const Vec4& color)
{
return {float_to_uint8(color.r), float_to_uint8(color.g), float_to_uint8(color.b), float_to_uint8(color.a)};
}
static glm::vec4 color_from_bytes(const glm::ivec4& bytes)
static Vec4 color_from_bytes(const IVec4& bytes)
{
return {uint8_to_float(bytes.r), uint8_to_float(bytes.g), uint8_to_float(bytes.b), uint8_to_float(bytes.a)};
}
@@ -207,9 +207,9 @@ struct JsonWriter
close(']');
}
template <int L, class T, glm::qualifier Q> void value(const glm::vec<L, T, Q>& value)
template <Vector V> void value(const V& value)
{
array(value, L);
array(value, V::SIZE);
}
template <class T> void value(const std::vector<T>& value)
{
@@ -344,11 +344,11 @@ static std::string_view value_read(dom::element element, std::filesystem::path&
return expected;
}
template <int L, class T, glm::qualifier Q> std::string_view value_read(dom::element element, glm::vec<L, T, Q>& value)
template <Vector V> std::string_view value_read(dom::element element, V& value)
{
static const auto EXPECTED = std::format("an array of {} numbers", L);
static const auto EXPECTED = std::format("an array of {} numbers", V::SIZE);
dom::array array;
if (element.get(array) || array.size() != L)
if (element.get(array) || array.size() != V::SIZE)
return EXPECTED;
auto read = value;
int i = 0;
@@ -637,8 +637,8 @@ template <class Io, class A> static void animation_io(Io& io, A& animation)
{
io.field("length", animation.frameNum, 1);
io.field("loop", animation.isLoop, true);
glm::ivec2 markers{animation.startMarker, animation.endMarker};
io.field("markers", markers, glm::ivec2{-1});
IVec2 markers{animation.startMarker, animation.endMarker};
io.field("markers", markers, IVec2{-1});
if constexpr (Io::IS_READING)
std::tie(animation.startMarker, animation.endMarker) = std::tie(markers.x, markers.y);
frames_io(io, "root", animation.root.frames, ItemType::ROOT);
+1 -1
View File
@@ -435,7 +435,7 @@ int track_length_get(const Track& track)
}
// The frames playback stays within: [start, end), from the markers (or the whole animation).
glm::ivec2 animation_play_range_get(const Animation& animation)
IVec2 animation_play_range_get(const Animation& animation)
{
auto length = std::max(animation.frameNum, 1);
auto start = animation.startMarker != -1 ? std::clamp(animation.startMarker, 0, length - 1) : 0;
+12 -12
View File
@@ -40,15 +40,15 @@ struct Extras
struct Frame
{
std::uint64_t uid = uid_next();
glm::vec2 crop{};
glm::vec2 size{};
glm::vec2 pivot{};
glm::vec2 position{};
glm::vec2 scale{100.0f, 100.0f};
glm::vec2 skew{};
Vec2 crop{};
Vec2 size{};
Vec2 pivot{};
Vec2 position{};
Vec2 scale{100.0f, 100.0f};
Vec2 skew{};
float rotation = 0;
glm::vec4 tint{COLOR_WHITE};
glm::vec4 colorOffset{};
Vec4 tint{COLOR_WHITE};
Vec4 colorOffset{};
int duration = 1;
bool isVisible = true;
Interpolation interpolation = Interpolation::NONE;
@@ -140,9 +140,9 @@ struct Region
std::uint64_t uid = uid_next();
int id = -1;
std::string name;
glm::vec2 crop{};
glm::vec2 size{};
glm::vec2 pivot{};
Vec2 crop{};
Vec2 size{};
Vec2 pivot{};
Origin origin = Origin::CUSTOM;
Extras extras = {};
@@ -416,7 +416,7 @@ std::set<int> spritesheets_vector_used_get(const Model&);
int track_frames_count_get(const Track&);
int track_length_get(const Track&);
int animation_length_get(const Animation&);
glm::ivec2 animation_play_range_get(const Animation&);
IVec2 animation_play_range_get(const Animation&);
const Track* animation_track_get(const Animation&, int, int, int = NONE, int = -1);
Track* animation_track_get(Animation&, int, int, int = NONE, int = -1);
TrackGroup* animation_track_group_get(Animation&, int, int);
+3 -3
View File
@@ -775,8 +775,8 @@ template <class Items> static void ids_repair(Items& items)
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);
return IVec2(region.crop) == IVec2(frame.crop) && IVec2(region.size) == IVec2(frame.size) &&
IVec2(region.pivot) == IVec2(frame.pivot);
}
// Loaded documents get unique content ids, frames lose dangling shader ids, and layer frames point at the region
@@ -1503,7 +1503,7 @@ IsaacIssues isaac_issues_get(const Model& model)
for (auto& frame : track.frames)
{
issues.easedFrames += track.type != ItemType::TRIGGER && is_special_interpolation(frame.interpolation);
issues.skewFrames += frame.skew != glm::vec2();
issues.skewFrames += frame.skew != Vec2();
issues.shaderFrames += frame.shaderId != -1;
issues.depthFrames += track.type == ItemType::LAYER && frame.depth != 0;
issues.alphaOffsetFrames += float_to_uint8(frame.colorOffset.a) != 0;
+8 -8
View File
@@ -70,7 +70,7 @@ static void free_rects_prune(std::vector<Rect>& freeRects)
}
}
static bool rect_insert(std::vector<Rect>& freeRects, glm::ivec2 size, Rect& result)
static bool rect_insert(std::vector<Rect>& freeRects, IVec2 size, Rect& result)
{
int bestShort = std::numeric_limits<int>::max();
int bestLong = std::numeric_limits<int>::max();
@@ -95,17 +95,17 @@ static bool rect_insert(std::vector<Rect>& freeRects, glm::ivec2 size, Rect& res
return true;
}
bool rects_pack(const std::vector<glm::ivec2>& sizes, glm::ivec2& packedSize, std::vector<glm::ivec2>& positions)
bool rects_pack(const std::vector<IVec2>& sizes, IVec2& packedSize, std::vector<IVec2>& positions)
{
if (sizes.empty())
return false;
glm::ivec2 maxSize{};
glm::ivec2 sumSize{};
IVec2 maxSize{};
IVec2 sumSize{};
std::int64_t totalArea = 0;
for (auto& size : sizes)
{
maxSize = glm::max(maxSize, size);
maxSize = vec_max(maxSize, size);
sumSize += size;
totalArea += (std::int64_t)size.x * size.y;
}
@@ -119,8 +119,8 @@ bool rects_pack(const std::vector<glm::ivec2>& sizes, glm::ivec2& packedSize, st
for (int width = maxSize.x; width <= endWidth; width += step)
{
std::vector<glm::ivec2> candidate(sizes.size());
glm::ivec2 used{};
std::vector<IVec2> candidate(sizes.size());
IVec2 used{};
bool isValid = false;
for (int height = std::max(maxSize.y, (int)std::ceil((double)totalArea / width));
height <= sumSize.y && !isValid; ++height)
@@ -133,7 +133,7 @@ bool rects_pack(const std::vector<glm::ivec2>& sizes, glm::ivec2& packedSize, st
Rect rect = {};
isValid = rect_insert(freeRects, sizes[i], rect);
candidate[i] = {rect.x, rect.y};
used = glm::max(used, glm::ivec2(rect.x + rect.w, rect.y + rect.h));
used = vec_max(used, IVec2(rect.x + rect.w, rect.y + rect.h));
}
}
if (!isValid)
+2 -2
View File
@@ -2,6 +2,6 @@
#include <vector>
#include <glm/glm.hpp>
#include "vec.h"
bool rects_pack(const std::vector<glm::ivec2>&, glm::ivec2&, std::vector<glm::ivec2>&);
bool rects_pack(const std::vector<IVec2>&, IVec2&, std::vector<IVec2>&);
+2 -2
View File
@@ -2,7 +2,7 @@
#include <cmath>
#include <glm/common.hpp>
#include "vec.h"
void Playback::toggle()
{
@@ -20,7 +20,7 @@ void Playback::timing_reset()
void Playback::clamp(int length)
{
time = glm::clamp(time, 0.0f, (float)length - 1.0f);
time = vec_clamp(time, 0.0f, (float)length - 1.0f);
}
// Plays the frames [start, end). A playhead outside them starts at start.
+42 -43
View File
@@ -178,7 +178,7 @@ bool animation_render(const std::filesystem::path& ffmpegPath, const std::filesy
}
constexpr int TEMP_DIRECTORY_ATTEMPTS = 1000;
constexpr glm::vec4 BOUNDS_DEFAULT = {-32.0f, -32.0f, 64.0f, 64.0f};
constexpr Vec4 BOUNDS_DEFAULT = {-32.0f, -32.0f, 64.0f, 64.0f};
constexpr int ALPHA_OPAQUE = 255;
constexpr float CHANNEL_MAX = 255.0f;
@@ -239,7 +239,7 @@ void pixels_unpremultiply(std::vector<uint8_t>& pixels)
pixels[index + channel] =
alpha == 0
? 0
: (uint8_t)glm::clamp(std::round(pixels[index + channel] * CHANNEL_MAX / alpha), 0.0f, CHANNEL_MAX);
: (uint8_t)vec_clamp(std::round(pixels[index + channel] * CHANNEL_MAX / alpha), 0.0f, CHANNEL_MAX);
}
}
@@ -278,23 +278,23 @@ bool HeadlessGL::is_valid() const
return context != nullptr;
}
glm::vec4 animation_bounds_get(const Document& document, const Animation& animation, bool isRootTransform)
Vec4 animation_bounds_get(const Document& document, const Animation& animation, bool isRootTransform)
{
auto bounds = animation_rect(document.model, animation, isRootTransform, document.library_resolver_get());
return bounds != glm::vec4(-1.0f) ? bounds : BOUNDS_DEFAULT;
return bounds != Vec4(-1.0f) ? bounds : BOUNDS_DEFAULT;
}
std::vector<uint8_t> animation_frame_render(Canvas& canvas, ShaderProgram& shader, Document& document,
const Animation& animation, float time, glm::vec4 bounds, float scale,
glm::vec4 background, bool isRootTransform)
const Animation& animation, float time, Vec4 bounds, float scale,
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))));
canvas.size_set(Vec2(vec_max(IVec2(vec_ceil(Vec2(bounds.z, bounds.w) * scale)), IVec2(1))));
float zoom = 0;
glm::vec2 pan{};
Vec2 pan{};
canvas.set_to_rect(zoom, pan, bounds);
canvas.bind();
canvas.viewport_set();
canvas.clear(glm::vec4(glm::vec3(background) * background.a, background.a));
canvas.clear(Vec4(Vec3(background) * background.a, background.a));
canvas.layers_render(
shader, document.model, animation,
{.time = time, .isRootTransform = isRootTransform, .library_get = document.library_resolver_get()},
@@ -334,7 +334,7 @@ bool Recorder::is_sound_frame() const
return (int)std::floor(time_get()) != soundTime;
}
bool Recorder::frame_capture(std::vector<uint8_t> pixels, glm::ivec2 size, std::vector<const AudioData*> frameSounds)
bool Recorder::frame_capture(std::vector<uint8_t> pixels, IVec2 size, std::vector<const AudioData*> frameSounds)
{
soundTime = (int)std::floor(time_get());
sounds.push_back(std::move(frameSounds));
@@ -365,11 +365,11 @@ void Recorder::finish()
else
{
Image sheet = {};
sheet.size = first.size * glm::ivec2(layout.columns, layout.rows);
sheet.size = first.size * IVec2(layout.columns, layout.rows);
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));
sheet.paste(frame, first.size * IVec2(i % layout.columns, i / layout.columns));
auto isSaved = sheet.write_png(options.path);
toast_log(isSaved ? Level::INFO : Level::ERROR,
isSaved ? TOAST_EXPORT_SPRITESHEET : TOAST_EXPORT_SPRITESHEET_FAILED, pathString);
@@ -399,8 +399,7 @@ void Recorder::cancel()
}
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)
const Animation& animation, Vec4 bounds, float scale, Vec4 background, bool isRootTransform)
{
auto options = recorderOptions;
options.isIsolated = options.isBounded = true;
@@ -411,7 +410,7 @@ bool animation_record(const RecorderOptions& recorderOptions, Canvas& canvas, Sh
{
auto pixels = animation_frame_render(canvas, shader, document, animation, recorder.time_get(), bounds, scale,
background, isRootTransform);
if (recorder.frame_capture(std::move(pixels), glm::ivec2(canvas.size)))
if (recorder.frame_capture(std::move(pixels), IVec2(canvas.size)))
continue;
recorder.cancel();
return false;
@@ -425,37 +424,37 @@ constexpr int BAKED_SIZE_MAX = 4096;
// 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`.
static std::optional<std::pair<Image, glm::vec2>> draw_bake(Canvas& canvas, ShaderProgram& shader, Document& document,
const Draw& draw, bool isColored)
static std::optional<std::pair<Image, Vec2>> draw_bake(Canvas& canvas, ShaderProgram& shader, Document& document,
const Draw& draw, bool isColored)
{
auto image = document.draw_image_get(draw, draw_scale_get(draw));
if (!image || !image->is_valid() || draw.frame.size == glm::vec2())
if (!image || !image->is_valid() || draw.frame.size == Vec2())
return {};
auto quad = draw.parent * draw_quad_model_get(draw);
glm::vec2 low{std::numeric_limits<float>::max()};
glm::vec2 high{std::numeric_limits<float>::lowest()};
for (auto corner : {glm::vec2(0.0f), glm::vec2(1.0f, 0.0f), glm::vec2(0.0f, 1.0f), glm::vec2(1.0f)})
Vec2 low{std::numeric_limits<float>::max()};
Vec2 high{std::numeric_limits<float>::lowest()};
for (auto corner : {Vec2(0.0f), Vec2(1.0f, 0.0f), Vec2(0.0f, 1.0f), Vec2(1.0f)})
{
auto point = glm::vec2(quad * glm::vec4(corner, 0.0f, 1.0f));
low = glm::min(low, point);
high = glm::max(high, point);
auto point = Vec2(quad * Vec4(corner, 0.0f, 1.0f));
low = vec_min(low, point);
high = vec_max(high, point);
}
auto reach = draw.frame.blur + BAKE_MARGIN;
low = glm::floor(low - reach);
high = glm::ceil(high + reach);
auto size = glm::ivec2(high - low);
low = vec_floor(low - reach);
high = vec_ceil(high + reach);
auto size = IVec2(high - low);
canvas.size_set(glm::vec2(size));
canvas.size_set(Vec2(size));
float zoom = 0;
glm::vec2 pan{};
canvas.set_to_rect(zoom, pan, glm::vec4(low, glm::vec2(size)));
Vec2 pan{};
canvas.set_to_rect(zoom, pan, Vec4(low, Vec2(size)));
canvas.bind();
canvas.viewport_set();
canvas.clear(glm::vec4(0.0f));
canvas.clear(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.transform_get(zoom, pan), draw, isColored ? draw.frame.tint : glm::vec4(1.0f),
isColored ? draw.frame.colorOffset : glm::vec4(0.0f));
canvas.transform_get(zoom, pan), draw, isColored ? draw.frame.tint : Vec4(1.0f),
isColored ? draw.frame.colorOffset : Vec4(0.0f));
auto pixels = canvas.pixels_get();
canvas.unbind();
pixels_unpremultiply(pixels);
@@ -471,10 +470,10 @@ void frames_bake(Document& document, Model& result, const std::filesystem::path&
{
auto game = result;
auto is_baked = [](const Frame& frame) {
return frame.skew != glm::vec2() || frame.blur > 0.0f || frame.shaderId != -1;
return frame.skew != Vec2() || frame.blur > 0.0f || frame.shaderId != -1;
};
auto is_skewed = [](const Track& root) {
return std::ranges::any_of(root.frames, [](const Frame& frame) { return frame.skew != glm::vec2(); });
return std::ranges::any_of(root.frames, [](const Frame& frame) { return frame.skew != Vec2(); });
};
std::vector<int> indices;
@@ -496,7 +495,7 @@ void frames_bake(Document& document, Model& result, const std::filesystem::path&
auto& textureInfo = SHADERS[SHADER_TEXTURE];
ShaderProgram shader(textureInfo.vertex, textureInfo.fragment);
Canvas canvas(glm::vec2(1.0f));
Canvas canvas(Vec2(1.0f));
auto& content = game.content;
auto spritesheetId = item_next_id_get(content.spritesheets);
@@ -557,7 +556,7 @@ void frames_bake(Document& document, Model& result, const std::filesystem::path&
for (int time = 0; time < length; ++time)
{
auto frame = frame_generate(track, (float)time);
std::optional<std::pair<Image, glm::vec2>> bakedImage{};
std::optional<std::pair<Image, Vec2>> bakedImage{};
Draw draw{.type = DrawType::LAYER,
.id = track.id,
.time = (float)time,
@@ -587,11 +586,11 @@ void frames_bake(Document& document, Model& result, const std::filesystem::path&
auto step = draw.frame;
if (step.shaderId != -1)
{
step.tint = glm::vec4(1.0f);
step.tint = Vec4(1.0f);
step.colorOffset = {};
}
step.crop = {};
step.size = glm::vec2(bakedImage->first.size);
step.size = Vec2(bakedImage->first.size);
step.pivot = {};
step.position = bakedImage->second;
step.scale = Frame{}.scale;
@@ -660,11 +659,11 @@ void frames_bake(Document& document, Model& result, const std::filesystem::path&
if (images.empty())
return;
std::vector<glm::ivec2> sizes{};
std::vector<IVec2> sizes{};
for (auto& image : images)
sizes.push_back(image.size);
glm::ivec2 packedSize{};
std::vector<glm::ivec2> positions{};
IVec2 packedSize{};
std::vector<IVec2> positions{};
rects_pack(sizes, packedSize, positions);
std::vector<ImagePart> parts;
for (int i = 0; i < (int)images.size(); ++i)
@@ -685,7 +684,7 @@ void frames_bake(Document& document, Model& result, const std::filesystem::path&
for (auto& frame : track.frames)
if (frame.regionId != -1)
{
frame.crop = glm::vec2(positions[frame.regionId]);
frame.crop = Vec2(positions[frame.regionId]);
frame.regionId = -1;
}
});
+7 -7
View File
@@ -7,7 +7,7 @@
#include "audio_data.h"
#include "audio.h"
#include <glm/glm.hpp>
#include "vec.h"
struct SDL_Window;
struct SDL_GLContextState;
@@ -132,10 +132,10 @@ public:
};
// 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 Animation&, bool);
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<uint8_t> animation_frame_render(Canvas&, ShaderProgram&, Document&, const Animation&, float, glm::vec4,
float, glm::vec4, bool);
std::vector<uint8_t> animation_frame_render(Canvas&, ShaderProgram&, Document&, const Animation&, float, Vec4, float,
Vec4, bool);
void pixels_unpremultiply(std::vector<uint8_t>&);
void frames_bake(Document&, Model&, const std::filesystem::path&);
@@ -169,7 +169,7 @@ public:
bool is_done() const;
float time_get() const;
bool is_sound_frame() const;
bool frame_capture(std::vector<uint8_t>, glm::ivec2, std::vector<const AudioData*> = {});
bool frame_capture(std::vector<uint8_t>, IVec2, std::vector<const AudioData*> = {});
void finish();
void cancel();
@@ -182,8 +182,8 @@ private:
// 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&, ShaderProgram&, Document&, const Animation&, glm::vec4, float,
glm::vec4, bool);
bool animation_record(const RecorderOptions&, Canvas&, ShaderProgram&, Document&, const Animation&, Vec4, float, Vec4,
bool);
std::filesystem::path ffmpeg_log_path();
bool animation_render(const std::filesystem::path&, const std::filesystem::path&,
+4 -12
View File
@@ -9,20 +9,12 @@
#include "math_util.h"
#include "path.h"
using namespace glm;
constexpr std::string_view SETTINGS_SHEAR = "Shear";
constexpr const char* COMPONENT_SUFFIXES_XY[] = {"X", "Y"};
constexpr const char* COMPONENT_SUFFIXES_WH[] = {"W", "H"};
constexpr const char* COMPONENT_SUFFIXES_RGBA[] = {"R", "G", "B", "A"};
template <class T>
concept GlmVector = requires(T value) {
T::length();
value[0];
};
static const char* const* component_suffixes_get(std::string_view type)
{
if (type.ends_with("_WH"))
@@ -237,10 +229,10 @@ Settings::Settings(const std::filesystem::path& path)
auto entry_load = [&](const std::string& key, std::istringstream& ss, const std::string& name, auto& value,
std::string_view type) {
using T = std::decay_t<decltype(value)>;
if constexpr (GlmVector<T>)
if constexpr (Vector<T>)
{
auto suffixes = component_suffixes_get(type);
for (int i = 0; i < T::length(); ++i)
for (int i = 0; i < T::SIZE; ++i)
if (key == name + suffixes[i])
{
stream_assign(value[i], ss);
@@ -356,10 +348,10 @@ void Settings::save(const std::filesystem::path& path, const std::string& imguiD
auto entry_save = [&](const std::string& name, const auto& value, const std::string_view type) {
using T = std::decay_t<decltype(value)>;
if constexpr (GlmVector<T>)
if constexpr (Vector<T>)
{
auto suffixes = component_suffixes_get(type);
for (int i = 0; i < T::length(); ++i)
for (int i = 0; i < T::SIZE; ++i)
value_save(name + suffixes[i], value[i]);
}
else
+8 -8
View File
@@ -3,7 +3,7 @@
#include <filesystem>
#include <string>
#include <glm/glm.hpp>
#include "vec.h"
#include "model/common.h"
#include "render.h"
@@ -38,12 +38,12 @@ constexpr auto RENDER_SCALE_STEP = 25.0f;
X(FLOAT, float) \
X(STRING, std::string) \
X(PATH, std::filesystem::path) \
X(IVEC2, glm::ivec2) \
X(IVEC2_WH, glm::ivec2) \
X(VEC2, glm::vec2) \
X(VEC2_WH, glm::vec2) \
X(VEC3, glm::vec3) \
X(VEC4, glm::vec4)
X(IVEC2, IVec2) \
X(IVEC2_WH, IVec2) \
X(VEC2, Vec2) \
X(VEC2_WH, Vec2) \
X(VEC3, Vec3) \
X(VEC4, Vec4)
#define X(name, type) using TYPE_##name = type;
SETTINGS_TYPES
@@ -52,7 +52,7 @@ SETTINGS_TYPES
#define SETTINGS_MEMBERS \
/* Symbol / Name / String / Type / Default */ \
X(WINDOW_SIZE, windowSize, STRING_UNDEFINED, IVEC2_WH, {1200, 720}) \
X(WINDOW_POSITION, windowPosition, STRING_UNDEFINED, IVEC2, glm::ivec2()) \
X(WINDOW_POSITION, windowPosition, STRING_UNDEFINED, IVEC2, IVec2()) \
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) \
+2 -2
View File
@@ -1,7 +1,7 @@
#pragma once
#include "gl.h"
#include <glm/glm.hpp>
#include "vec.h"
#include <array>
#include <string>
@@ -364,7 +364,7 @@ struct ShaderUniform
GLint size = 0;
UniformValueType valueType = UNIFORM_VALUE_UNKNOWN;
UniformBinding binding = UNIFORM_BINDING_IGNORE;
glm::vec4 value{};
Vec4 value{};
int intValue = 0;
std::array<Component, 4> components = {};
};
+2 -2
View File
@@ -33,7 +33,7 @@ GLuint texture_id_get(const Image& image)
gl.TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, filter);
gl.PixelStorei(GL_UNPACK_ALIGNMENT, 1);
gl.TexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.size.x, image.size.y, 0, GL_RGBA, GL_UNSIGNED_BYTE,
image.pixels.data());
image.pixels.data());
gl.BindTexture(GL_TEXTURE_2D, 0);
return entry.id;
}
@@ -48,7 +48,7 @@ void texture_garbage_collect()
});
}
Image texture_svg_load(const char* data, size_t length, glm::ivec2 size)
Image texture_svg_load(const char* data, size_t length, IVec2 size)
{
auto document = data ? lunasvg::Document::loadFromData(data, length) : nullptr;
if (!document)
+1 -1
View File
@@ -7,4 +7,4 @@
// GPU copies of Images, uploaded on first use and evicted when a frame passes without them being drawn.
GLuint texture_id_get(const Image&);
void texture_garbage_collect();
Image texture_svg_load(const char*, size_t, glm::ivec2);
Image texture_svg_load(const char*, size_t, IVec2);
+7 -9
View File
@@ -1,6 +1,6 @@
#pragma once
#include <glm/glm.hpp>
#include "vec.h"
enum ShortcutScope
{
@@ -45,14 +45,12 @@ enum EditState
EDIT_STATE_COMPLETE
};
using namespace glm;
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);
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);
enum class OnionskinMode
{
+7 -13
View File
@@ -19,8 +19,6 @@
#include "localization.h"
#include "ui/draw.h"
using namespace glm;
// The credits roll, after the original editor's About box: lengths are its pixels (for 14 px text), at its 30 Hz.
enum RollEffect
{
@@ -117,10 +115,6 @@ static constexpr About::Credit CREDITS[] = {
{"https://github.com/simdjson/simdjson"},
{"License: Apache-2.0 or MIT"},
{""},
{"glm"},
{"https://github.com/g-truc/glm"},
{"License: MIT"},
{""},
{"lunasvg"},
{"https://github.com/sammycage/lunasvg"},
{"License: MIT"},
@@ -171,13 +165,13 @@ static void friend_state_load(About::FriendState& state, const FriendInfo& info)
{
if (!state.canvas)
{
state.canvas = std::make_unique<Canvas>(vec2(1.0f, 1.0f));
state.canvas = std::make_unique<Canvas>(Vec2(1.0f, 1.0f));
state.canvas->filter = GL_NEAREST;
}
state.model = Model{};
state.textures.clear();
state.rect = vec4(-1.0f);
state.rect = Vec4(-1.0f);
state.time = 0.0f;
state.fps = 30.0f;
state.isLoaded = false;
@@ -203,7 +197,7 @@ static void friend_state_load(About::FriendState& state, const FriendInfo& info)
}
state.rect = animation_rect(state.model, *animation, true);
state.isLoaded = state.rect != vec4(-1.0f) && !state.textures.empty();
state.isLoaded = state.rect != Vec4(-1.0f) && !state.textures.empty();
}
static void friend_state_tick(About::FriendState& state, float delta)
@@ -229,7 +223,7 @@ static ImVec2 friend_size_get(const About::FriendState& state, float height)
}
// The animation's bounds with some room around them.
static 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);
@@ -243,10 +237,10 @@ static void friend_canvas_draw(About::FriendState& state, Resources& resources)
return;
auto rect = friend_rect_get(state);
state.canvas->size_set(glm::max(vec2(rect.z, rect.w), vec2(1.0f)));
state.canvas->size_set(vec_max(Vec2(rect.z, rect.w), Vec2(1.0f)));
state.canvas->bind();
state.canvas->viewport_set();
state.canvas->clear(vec4(0.0f));
state.canvas->clear(Vec4(0.0f));
auto animation = friend_animation_get(state);
if (!animation)
@@ -256,7 +250,7 @@ static void friend_canvas_draw(About::FriendState& state, Resources& resources)
}
float zoom = 100.0f;
vec2 pan{};
Vec2 pan{};
state.canvas->set_to_rect(zoom, pan, rect);
state.canvas->layers_render(resources.shaders[SHADER_TEXTURE], state.model, *animation,
+2 -2
View File
@@ -31,7 +31,7 @@ public:
float stretch = 1.0f;
int effect = 0;
int trailAlpha = 255;
glm::vec2 levels{};
Vec2 levels{};
float gradientHeight = 0;
ImU32 gradientColor = 0;
};
@@ -54,7 +54,7 @@ public:
Model model = {};
std::unique_ptr<Canvas> canvas;
std::unordered_map<int, Image> textures;
glm::vec4 rect{-1.0f};
Vec4 rect{-1.0f};
float time = 0;
float fps = 30.0f;
bool isLoaded = false;
+42 -44
View File
@@ -12,7 +12,7 @@
#include <system_error>
#include <vector>
#include <glm/gtc/type_ptr.hpp>
#include "vec.h"
#include "ui/actions.h"
#include "log.h"
@@ -30,13 +30,11 @@
#include "ui/shortcut.h"
#include "ui/timeline.h"
using namespace glm;
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);
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);
constexpr auto PARENT_DIM_ALPHA = 0.65f; // how much a stepped-into child's parent fades
constexpr auto POINT_SIZE = vec2(4, 4);
constexpr auto POINT_SIZE = Vec2(4, 4);
constexpr auto TRIGGER_TEXT_COLOR_DARK = ImVec4(1.0f, 1.0f, 1.0f, 0.5f);
constexpr auto TRIGGER_TEXT_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 0.5f);
struct OverlayAnimationOption
@@ -95,22 +93,22 @@ static Document* overlay_animation_document_get(Manager& manager, const Document
return nullptr;
}
static std::optional<vec4> animation_rects_merge(std::optional<vec4> rect, vec4 next)
static std::optional<Vec4> animation_rects_merge(std::optional<Vec4> rect, Vec4 next)
{
if (next == vec4(-1.0f))
if (next == Vec4(-1.0f))
return rect;
if (!rect)
return next;
auto minPoint = glm::min(vec2(rect->x, rect->y), vec2(next.x, next.y));
auto maxPoint = glm::max(vec2(rect->x + rect->z, rect->y + rect->w), vec2(next.x + next.z, next.y + next.w));
return vec4(minPoint, maxPoint - minPoint);
auto minPoint = vec_min(Vec2(rect->x, rect->y), Vec2(next.x, next.y));
auto maxPoint = vec_max(Vec2(rect->x + rect->z, rect->y + rect->w), Vec2(next.x + next.z, next.y + next.w));
return Vec4(minPoint, maxPoint - minPoint);
}
static std::optional<vec4> animation_render_rect_get(Manager& manager, Document& document, const Animation* animation,
static std::optional<Vec4> animation_render_rect_get(Manager& manager, Document& document, const Animation* animation,
bool isRootTransform)
{
std::optional<vec4> rect{};
std::optional<Vec4> rect{};
if (animation)
rect = animation_rects_merge(
@@ -223,7 +221,7 @@ void AnimationPreview::recording_start(Manager& manager, Settings& settings, Doc
recordPan = document.previewPan;
if (auto rect = animation_render_rect_get(manager, document, animation, settings.previewIsRootTransform))
{
recordSize = glm::vec2(rect->z, rect->w) * percent_to_unit(settings.renderScale);
recordSize = Vec2(rect->z, rect->w) * percent_to_unit(settings.renderScale);
auto previousSize = size;
size = recordSize;
set_to_rect(recordZoom, recordPan, *rect);
@@ -280,7 +278,7 @@ void AnimationPreview::update(Manager& manager, Settings& settings, Resources& r
auto& shaderTexture = resources.shaders[SHADER_TEXTURE];
auto& shaderDashed = resources.shaders[SHADER_DASHED];
auto center_view = [&]() {
pan = vec2();
pan = Vec2();
};
auto fit_view = [&]() {
@@ -310,7 +308,7 @@ void AnimationPreview::update(Manager& manager, Settings& settings, Resources& r
view_buttons_draw(manager, settings, center_view, fit_view);
auto readoutSize = ImVec2(row_widget_width_get(2), ImGui::GetTextLineHeightWithSpacing());
auto mousePosInt = ivec2(mousePos);
auto mousePosInt = IVec2(mousePos);
auto positionText =
std::vformat(localize.get(FORMAT_POSITION_SPACED), std::make_format_args(mousePosInt.x, mousePosInt.y));
if (ImGui::BeginChild("##Position Readout", readoutSize, false, ImGuiWindowFlags_NoScrollbar))
@@ -323,7 +321,7 @@ void AnimationPreview::update(Manager& manager, Settings& settings, Resources& r
ImGui::SameLine();
auto sizeInt = ivec2(size);
auto sizeInt = IVec2(size);
auto sizeText = std::vformat(localize.get(FORMAT_SIZE_SPACED), std::make_format_args(sizeInt.x, sizeInt.y));
if (ImGui::BeginChild("##Size Readout", readoutSize, false, ImGuiWindowFlags_NoScrollbar))
{
@@ -341,7 +339,7 @@ void AnimationPreview::update(Manager& manager, Settings& settings, Resources& r
{
ImGui::BeginDisabled(isTransparent);
{
ImGui::ColorEdit3(localize.get(LABEL_BACKGROUND_COLOR), value_ptr(backgroundColor),
ImGui::ColorEdit3(localize.get(LABEL_BACKGROUND_COLOR), values_get(backgroundColor),
ImGuiColorEditFlags_NoInputs);
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BACKGROUND_COLOR));
}
@@ -350,7 +348,7 @@ void AnimationPreview::update(Manager& manager, Settings& settings, Resources& r
ImGui::Checkbox(localize.get(LABEL_AXES), &isAxes);
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_AXES));
ImGui::SameLine();
ImGui::ColorEdit4(localize.get(BASIC_COLOR), value_ptr(axesColor), ImGuiColorEditFlags_NoInputs);
ImGui::ColorEdit4(localize.get(BASIC_COLOR), values_get(axesColor), ImGuiColorEditFlags_NoInputs);
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_AXES_COLOR));
auto overlayOptions = overlay_animation_options_get(manager);
@@ -371,8 +369,8 @@ void AnimationPreview::update(Manager& manager, Settings& settings, Resources& r
}
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_OVERLAY));
overlayDrawOrder = glm::clamp(overlayDrawOrder, (int)OVERLAY_OVER, (int)OVERLAY_UNDER);
overlayTransparency = glm::clamp(overlayTransparency, 0.0f, 100.0f);
overlayDrawOrder = vec_clamp(overlayDrawOrder, (int)OVERLAY_OVER, (int)OVERLAY_UNDER);
overlayTransparency = vec_clamp(overlayTransparency, 0.0f, 100.0f);
auto orderIconSize = icon_size_get();
auto orderButtonWidth = orderIconSize.x + ImGui::GetStyle().FramePadding.x * 2.0f;
auto alphaWidth = std::max(ImGui::GetContentRegionAvail().x - (orderButtonWidth * 2.0f) -
@@ -383,7 +381,7 @@ void AnimationPreview::update(Manager& manager, Settings& settings, Resources& r
ImGui::DragFloat("##Overlay Alpha", &overlayTransparency, DRAG_SPEED, 0, 100, "%.0f%%");
ImGui::PopItemWidth();
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_OVERLAY_ALPHA));
overlayTransparency = glm::clamp(overlayTransparency, 0.0f, 100.0f);
overlayTransparency = vec_clamp(overlayTransparency, 0.0f, 100.0f);
ImGui::SameLine();
radio_button_icon("##Overlay Over", &overlayDrawOrder, OVERLAY_OVER, resources.icon_id_get(ICON_OVER),
@@ -451,11 +449,11 @@ void AnimationPreview::update(Manager& manager, Settings& settings, Resources& r
else
{
auto nextSize = to_vec2(ImGui::GetContentRegionAvail());
bool isCanvasResized = ivec2(nextSize) != ivec2(size);
bool isCanvasResized = IVec2(nextSize) != IVec2(size);
size_set(nextSize);
if (isCanvasResized && ImGui::IsMouseDragging(ImGuiMouseButton_Left))
{
auto resizeSizeInt = ivec2(size);
auto resizeSizeInt = IVec2(size);
auto resizeSizeText = std::vformat(localize.get(FORMAT_SIZE_SPACED),
std::make_format_args(resizeSizeInt.x, resizeSizeInt.y));
ImGui::SetTooltip("%s", resizeSizeText.c_str());
@@ -505,14 +503,14 @@ void AnimationPreview::update(Manager& manager, Settings& settings, Resources& r
auto isDuring = isToolDown || input.isArrowDown;
auto isEnd = isToolReleased || input.isArrowEnd;
auto arrow = input.arrow * input.step;
auto isArrow = arrow != vec2();
auto isArrow = arrow != Vec2();
// Changes apply to every selected frame. Absolute values are applied as the difference from the edited
// frame.
auto frames_change = [&](FrameChange change, ChangeType type = ChangeType::ADD) {
frames_change_push(manager, selectedFrameReferences, change, type);
};
auto null_rect_set = [&](vec2 minPoint, vec2 maxPoint) {
auto null_rect_set = [&](Vec2 minPoint, Vec2 maxPoint) {
auto rectSize = maxPoint - minPoint;
frames_change({.positionX = minPoint.x + rectSize.x * 0.5f - frame->position.x,
.positionY = minPoint.y + rectSize.y * 0.5f - frame->position.y,
@@ -535,13 +533,13 @@ void AnimationPreview::update(Manager& manager, Settings& settings, Resources& r
if (isToolClicked)
{
auto origin = isSelectedNullRect ? null_rect_top_left(*frame) : frame->position;
moveOffset = settings.inputIsMoveToolSnapToMouse ? vec2() : mousePos - origin;
moveOffset = settings.inputIsMoveToolSnapToMouse ? Vec2() : mousePos - origin;
isMoveDragging = true;
}
if (isToolDown && isMoveDragging)
{
auto position =
vec2(ivec2(mousePos - moveOffset + (isSelectedNullRect ? frame->scale * 0.5f : vec2())));
Vec2(IVec2(mousePos - moveOffset + (isSelectedNullRect ? frame->scale * 0.5f : Vec2())));
frames_change(
{.positionX = position.x - frame->position.x, .positionY = position.y - frame->position.y});
}
@@ -600,7 +598,7 @@ void AnimationPreview::update(Manager& manager, Settings& settings, Resources& r
edit_begin_push(manager, EDIT_FRAME_ROTATION);
if (isToolDown)
frames_change({.rotation = input.mouseDelta.x});
if (auto turn = glm::sign(input.arrow.x - input.arrow.y); turn != 0.0f)
if (auto turn = vec_sign(input.arrow.x - input.arrow.y); turn != 0.0f)
frames_change({.rotation = turn * input.step});
if (isDuring)
tooltip_lines_draw({localize_format(FORMAT_ROTATION, frame->rotation)});
@@ -628,13 +626,13 @@ void AnimationPreview::update(Manager& manager, Settings& settings, Resources& r
}
if (input.wheel != 0 || input.isZoomIn || input.isZoomOut)
zoom_step(zoom, pan, vec2(mousePos),
zoom_step(zoom, pan, Vec2(mousePos),
(input.wheel > 0 || input.isZoomIn) ? ZOOM_LEVEL_STEP : -ZOOM_LEVEL_STEP);
}
bind();
viewport_set();
clear(isViewTransparent ? vec4(0) : vec4(backgroundColor, 1.0f));
clear(isViewTransparent ? Vec4(0) : Vec4(backgroundColor, 1.0f));
if (isAxes && !isIsolated)
axes_render(shaderAxes, viewZoom, viewPan, axesColor);
@@ -647,9 +645,9 @@ void AnimationPreview::update(Manager& manager, Settings& settings, Resources& r
DrawOptions drawOptions{.time = frameTime,
.isRootTransform = isRootTransform,
.isIndexSampled = settings.onionskinMode == (int)OnionskinMode::INDEX};
std::vector<vec3> sampleColors{};
std::vector<Vec3> sampleColors{};
std::vector<float> sampleAlphas;
auto samples_add = [&](int count, int direction, vec3 color) {
auto samples_add = [&](int count, int direction, Vec3 color) {
for (int i = 1; i <= count; ++i)
{
drawOptions.samples.push_back({.timeOffset = (float)(direction * i), .indexOffset = direction * i});
@@ -694,7 +692,7 @@ void AnimationPreview::update(Manager& manager, Settings& settings, Resources& r
// 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 Animation& sampleAnimation, float alphaOffset,
const DrawOptions& options, const mat4& scene = mat4(1.0f), int skipLayerId = -1) {
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;
@@ -708,12 +706,12 @@ void AnimationPreview::update(Manager& manager, Settings& settings, Resources& r
auto isOnion = draw.sample != -1;
if (isOnion && isOnlySelected && !(isActiveDocument && is_draw_selected(draw)))
continue;
auto sampleColor = isOnion ? sampleColors[draw.sample] : vec3();
auto sampleColor = isOnion ? sampleColors[draw.sample] : Vec3();
auto sampleAlpha = isOnion ? sampleAlphas[draw.sample] : 0.0f;
auto onionColor = vec4(sampleColor, 1.0f - sampleAlpha);
auto onionColor = Vec4(sampleColor, 1.0f - sampleAlpha);
auto& frame = draw.frame;
auto transform = baseTransform * scene * draw.parent;
auto marker_model_get = [&](vec2 markerSize) {
auto marker_model_get = [&](Vec2 markerSize) {
return quad_model_get(markerSize, frame.position, markerSize * 0.5f, percent_to_unit(frame.scale),
frame.rotation, percent_to_unit(frame.skew));
};
@@ -725,7 +723,7 @@ void AnimationPreview::update(Manager& manager, Settings& settings, Resources& r
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)
auto color = isOnion ? Vec4(sampleColor, sampleAlpha)
: draw.type == DrawType::ROOT ? COLOR_GREEN
: isSelected ? COLOR_RED
: ROOT_COLOR;
@@ -748,7 +746,7 @@ void AnimationPreview::update(Manager& manager, Settings& settings, Resources& r
auto customShader = sampleDocument.shader_get(frame.shaderId);
layer_render(customShader ? *customShader : shaderTexture, texture_id_get(*layerTexture),
textureSize, baseTransform * scene, draw, tint,
frame.colorOffset + vec4(sampleColor, 0.0f));
frame.colorOffset + Vec4(sampleColor, 0.0f));
if (isParent)
continue;
@@ -772,7 +770,7 @@ void AnimationPreview::update(Manager& manager, Settings& settings, Resources& r
transform * marker_model_get(markerSize), color);
if (!isShowRect)
continue;
auto rectModel = quad_model_get(frame.scale, frame.position, frame.scale * 0.5f, vec2(1.0f),
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);
}
@@ -800,9 +798,9 @@ void AnimationPreview::update(Manager& manager, Settings& settings, Resources& r
auto placement = parentAnimation ? layer_child_transform_get(*parentAnimation, step.layer.itemID,
step.frameTime, isRootTransform)
: std::nullopt;
if (placement && glm::determinant(*placement) != 0.0f)
if (placement && mat4_determinant(*placement) != 0.0f)
render(*parentDocument, *parentAnimation, PARENT_DIM_ALPHA,
{.time = step.frameTime, .isRootTransform = isRootTransform}, glm::inverse(*placement),
{.time = step.frameTime, .isRootTransform = isRootTransform}, mat4_inverse(*placement),
step.layer.itemID);
}
@@ -832,7 +830,7 @@ void AnimationPreview::update(Manager& manager, Settings& settings, Resources& r
});
if (path == pivotPaths.end())
path = pivotPaths.insert(pivotPaths.end(), {.item = draw});
path->points.push_back(vec2(draw.parent * vec4(draw.frame.position, 0.0f, 1.0f)));
path->points.push_back(Vec2(draw.parent * Vec4(draw.frame.position, 0.0f, 1.0f)));
}
}
+5 -5
View File
@@ -15,18 +15,18 @@ class AnimationPreview : public CanvasView
bool wasPlaybackPlaying = false;
int soundFrame = -1;
bool isMoveDragging = false;
glm::vec2 moveOffset{};
glm::vec2 nullRectScaleAnchor{};
Vec2 moveOffset{};
Vec2 nullRectScaleAnchor{};
Recorder recorder = {};
glm::vec2 recordSize{};
glm::vec2 recordPan{};
Vec2 recordSize{};
Vec2 recordPan{};
float recordZoom = 0;
// Where each item's pivot is at every frame of the animation, kept until the document or view changes.
struct PivotPath
{
Draw item = {};
std::vector<glm::vec2> points{};
std::vector<Vec2> points{};
};
std::vector<PivotPath> pivotPaths;
std::tuple<std::uint64_t, std::uint64_t, int, bool> pivotPathsKey;
+15 -17
View File
@@ -1,6 +1,6 @@
#include "ui/canvas_view.h"
#include <glm/gtc/type_ptr.hpp>
#include "vec.h"
#include "ui/actions.h"
#include "edit/edit.h"
@@ -8,8 +8,6 @@
#include "ui/layout.h"
#include "ui/shortcut.h"
using namespace glm;
CanvasInput canvas_input_get(Manager& manager, bool isFocused)
{
auto key_axis_get = [](ImGuiKey negative, ImGuiKey positive) {
@@ -23,7 +21,7 @@ CanvasInput canvas_input_get(Manager& manager, bool isFocused)
auto isMod = ImGui::IsKeyDown(ImGuiMod_Shift);
return {.arrow = {key_axis_get(ImGuiKey_LeftArrow, ImGuiKey_RightArrow),
key_axis_get(ImGuiKey_UpArrow, ImGuiKey_DownArrow)},
.mouseDelta = vec2(ivec2(to_vec2(io.MouseDelta))),
.mouseDelta = Vec2(IVec2(to_vec2(io.MouseDelta))),
.wheel = io.MouseWheel,
.step = (float)(isMod ? STEP_FAST : STEP),
.isArrowBegin = is_any([](ImGuiKey key) { return ImGui::IsKeyPressed(key, false); }),
@@ -65,10 +63,10 @@ void frames_change_push(Manager& manager, const std::set<Reference>& frames, Fra
}
// The rectangle spanned by two corners, grown outward to the grid when snapping, in whole pixels.
std::pair<vec2, vec2> rect_snap(vec2 corner, vec2 otherCorner, bool isSnap, ivec2 gridSize, ivec2 gridOffset)
std::pair<Vec2, Vec2> rect_snap(Vec2 corner, Vec2 otherCorner, bool isSnap, IVec2 gridSize, IVec2 gridOffset)
{
auto minPoint = glm::min(corner, otherCorner);
auto maxPoint = glm::max(corner, otherCorner);
auto minPoint = vec_min(corner, otherCorner);
auto maxPoint = vec_max(corner, otherCorner);
for (int axis = 0; axis < 2 && isSnap; ++axis)
{
if (gridSize[axis] == 0)
@@ -78,7 +76,7 @@ std::pair<vec2, vec2> rect_snap(vec2 corner, vec2 otherCorner, bool isSnap, ivec
minPoint[axis] = std::floor((minPoint[axis] - offset) / size) * size + offset;
maxPoint[axis] = std::ceil((maxPoint[axis] - offset) / size) * size + offset;
}
return {vec2(ivec2(minPoint)), vec2(ivec2(maxPoint))};
return {Vec2(IVec2(minPoint)), Vec2(IVec2(maxPoint))};
}
void tooltip_lines_draw(std::initializer_list<std::string> lines)
@@ -111,7 +109,7 @@ void tool_cursor_update(Tool type, ToolArea area, bool isFrameAvailable, bool is
tooltip_lines_draw({localize.get(hint)});
}
CanvasView::CanvasView() : Canvas(vec2())
CanvasView::CanvasView() : Canvas(Vec2())
{}
bool CanvasView::is_focused_get() const
@@ -119,7 +117,7 @@ bool CanvasView::is_focused_get() const
return isFocused;
}
void CanvasView::checker_pan_reset(float zoom, vec2 pan)
void CanvasView::checker_pan_reset(float zoom, Vec2 pan)
{
checkerPan = pan;
checkerSyncPan = pan;
@@ -128,7 +126,7 @@ void CanvasView::checker_pan_reset(float zoom, vec2 pan)
hasPendingZoomPanAdjust = false;
}
void CanvasView::checker_pan_sync(float zoom, vec2 pan)
void CanvasView::checker_pan_sync(float zoom, Vec2 pan)
{
if (!isCheckerPanInitialized)
return checker_pan_reset(zoom, pan);
@@ -144,7 +142,7 @@ void CanvasView::checker_pan_sync(float zoom, vec2 pan)
hasPendingZoomPanAdjust = false;
}
void CanvasView::zoom_step(float& zoom, vec2& pan, vec2 focus, int levelDelta)
void CanvasView::zoom_step(float& zoom, Vec2& pan, Vec2 focus, int levelDelta)
{
auto previousZoom = zoom;
zoom_level_adjust(zoom, pan, focus, levelDelta);
@@ -152,7 +150,7 @@ void CanvasView::zoom_step(float& zoom, vec2& pan, vec2 focus, int levelDelta)
hasPendingZoomPanAdjust = true;
}
void CanvasView::grid_child_draw(ImVec2 childSize, bool& isGrid, vec4& gridColor, ivec2& gridSize, ivec2& gridOffset,
void CanvasView::grid_child_draw(ImVec2 childSize, bool& isGrid, Vec4& gridColor, IVec2& gridSize, IVec2& gridOffset,
bool* isGridSnap)
{
if (ImGui::BeginChild("##Grid Child", childSize, true, ImGuiWindowFlags_HorizontalScrollbar))
@@ -166,12 +164,12 @@ void CanvasView::grid_child_draw(ImVec2 childSize, bool& isGrid, vec4& gridColor
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_GRID_SNAP));
}
ImGui::SameLine();
ImGui::ColorEdit4(localize.get(BASIC_COLOR), value_ptr(gridColor), ImGuiColorEditFlags_NoInputs);
ImGui::ColorEdit4(localize.get(BASIC_COLOR), values_get(gridColor), ImGuiColorEditFlags_NoInputs);
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_GRID_COLOR));
input_int2_range(localize.get(BASIC_SIZE), gridSize, ivec2(GRID_SIZE_MIN), ivec2(GRID_SIZE_MAX));
input_int2_range(localize.get(BASIC_SIZE), gridSize, IVec2(GRID_SIZE_MIN), IVec2(GRID_SIZE_MAX));
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_GRID_SIZE));
input_int2_range(localize.get(BASIC_OFFSET), gridOffset, ivec2(GRID_OFFSET_MIN), ivec2(GRID_OFFSET_MAX));
input_int2_range(localize.get(BASIC_OFFSET), gridOffset, IVec2(GRID_OFFSET_MIN), IVec2(GRID_OFFSET_MAX));
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_GRID_OFFSET));
}
ImGui::EndChild();
@@ -193,7 +191,7 @@ void CanvasView::view_buttons_draw(Manager& manager, Settings& settings, const s
}
void CanvasView::view_context_menu_draw(const char* label, Manager& manager, Settings& settings, Document& document,
float& zoom, vec2& pan, const std::function<void()>& center,
float& zoom, Vec2& pan, const std::function<void()>& center,
const std::function<void()>& fit, bool isFitEnabled)
{
auto zoom_center_step = [&](int levelDelta) {
+11 -11
View File
@@ -16,8 +16,8 @@
// One frame of canvas input. `arrow` is the arrow keys pressed this frame (with key repeat), x right and y down.
struct CanvasInput
{
glm::vec2 arrow{};
glm::vec2 mouseDelta{};
Vec2 arrow{};
Vec2 mouseDelta{};
float wheel = 0;
float step = 0;
bool isArrowBegin = false;
@@ -40,27 +40,27 @@ bool is_canvas_hovered(ImVec2, ImVec2);
void edit_begin_push(Manager&, StringType);
void document_change_push(Manager&);
void frames_change_push(Manager&, const std::set<Reference>&, FrameChange, ChangeType = ChangeType::ADJUST);
std::pair<glm::vec2, glm::vec2> rect_snap(glm::vec2, glm::vec2, bool, glm::ivec2, glm::ivec2);
std::pair<Vec2, Vec2> rect_snap(Vec2, Vec2, bool, IVec2, IVec2);
void tooltip_lines_draw(std::initializer_list<std::string>);
void tool_cursor_update(Tool, ToolArea, bool, bool, bool, StringType);
class CanvasView : public Canvas
{
protected:
glm::vec2 mousePos{};
glm::vec2 checkerPan{};
glm::vec2 checkerSyncPan{};
Vec2 mousePos{};
Vec2 checkerPan{};
Vec2 checkerSyncPan{};
float checkerSyncZoom = 0;
bool isCheckerPanInitialized = false;
bool hasPendingZoomPanAdjust = false;
bool isFocused = false;
void checker_pan_reset(float, glm::vec2);
void checker_pan_sync(float, glm::vec2);
void zoom_step(float&, glm::vec2&, glm::vec2, int);
void grid_child_draw(ImVec2, bool&, glm::vec4&, glm::ivec2&, glm::ivec2&, bool* = nullptr);
void checker_pan_reset(float, Vec2);
void checker_pan_sync(float, Vec2);
void zoom_step(float&, Vec2&, Vec2, int);
void grid_child_draw(ImVec2, bool&, Vec4&, IVec2&, IVec2&, bool* = nullptr);
void view_buttons_draw(Manager&, Settings&, const std::function<void()>&, const std::function<void()>&);
void view_context_menu_draw(const char*, Manager&, Settings&, Document&, float&, glm::vec2&,
void view_context_menu_draw(const char*, Manager&, Settings&, Document&, float&, Vec2&,
const std::function<void()>&, const std::function<void()>&, bool);
public:
+10 -12
View File
@@ -2,7 +2,7 @@
#include <format>
#include <glm/gtc/type_ptr.hpp>
#include "vec.h"
#include <algorithm>
#include <ranges>
@@ -14,8 +14,6 @@
#include "ui/input.h"
#include "ui/layout.h"
using namespace glm;
constexpr int CHANGE_TYPE_COUNT = 5;
constexpr const char* COLOR_COMPONENT_FORMATS[] = {"R:%d", "G:%d", "B:%d", "A:%d"};
@@ -91,7 +89,7 @@ static void components_draw(const ComponentRow& row, bool isColor)
ImVec4 buttonColor = {0.0f, 0.0f, 0.0f, 1.0f};
for (int i = 0; i < count; ++i)
if (*row.isEnabled[i])
(&buttonColor.x)[i] = glm::clamp(row.values[i], 0.0f, 1.0f);
(&buttonColor.x)[i] = vec_clamp(row.values[i], 0.0f, 1.0f);
ImGui::SameLine();
ImGui::ColorButton(label, buttonColor);
ImGui::SameLine();
@@ -162,26 +160,26 @@ void ChangeAllFrameProperties::update(Manager& manager, Document& document, Sett
child_layer_add(&layer);
ComponentRow componentRows[] = {
{BASIC_CROP, {&settings.changeIsCropX, &settings.changeIsCropY}, value_ptr(settings.changeCrop), true},
{BASIC_SIZE, {&settings.changeIsSizeX, &settings.changeIsSizeY}, value_ptr(settings.changeSize), true},
{BASIC_CROP, {&settings.changeIsCropX, &settings.changeIsCropY}, values_get(settings.changeCrop), true},
{BASIC_SIZE, {&settings.changeIsSizeX, &settings.changeIsSizeY}, values_get(settings.changeSize), true},
{BASIC_POSITION,
{&settings.changeIsPositionX, &settings.changeIsPositionY},
value_ptr(settings.changePosition),
values_get(settings.changePosition),
false},
{BASIC_PIVOT, {&settings.changeIsPivotX, &settings.changeIsPivotY}, value_ptr(settings.changePivot), true},
{BASIC_SCALE, {&settings.changeIsScaleX, &settings.changeIsScaleY}, value_ptr(settings.changeScale), false},
{BASIC_SKEW, {&settings.changeIsSkewX, &settings.changeIsSkewY}, value_ptr(settings.changeSkew), false},
{BASIC_PIVOT, {&settings.changeIsPivotX, &settings.changeIsPivotY}, values_get(settings.changePivot), true},
{BASIC_SCALE, {&settings.changeIsScaleX, &settings.changeIsScaleY}, values_get(settings.changeScale), false},
{BASIC_SKEW, {&settings.changeIsSkewX, &settings.changeIsSkewY}, values_get(settings.changeSkew), false},
{BASIC_ROTATION, {&settings.changeIsRotation}, &settings.changeRotation, false},
{BASIC_BLUR, {&settings.changeIsBlur}, &settings.changeBlur, true}};
ComponentRow colorRows[] = {
{BASIC_TINT,
{&settings.changeIsTintR, &settings.changeIsTintG, &settings.changeIsTintB, &settings.changeIsTintA},
value_ptr(settings.changeTint),
values_get(settings.changeTint),
false},
{BASIC_COLOR_OFFSET,
{&settings.changeIsColorOffsetR, &settings.changeIsColorOffsetG, &settings.changeIsColorOffsetB,
&settings.changeIsColorOffsetA},
value_ptr(settings.changeColorOffset),
values_get(settings.changeColorOffset),
false}};
auto rows_draw = [&](std::span<ComponentRow> rows, bool isColor) {
+5 -5
View File
@@ -66,7 +66,7 @@ void image_premultiplied_draw(ImDrawList* drawList, ImTextureID texture, ImVec2
drawList->AddCallback(ImDrawCallback_ResetRenderState, nullptr);
}
void render_checker_background(ImDrawList* drawList, ImVec2 min, ImVec2 max, glm::vec2 offset, float step)
void render_checker_background(ImDrawList* drawList, ImVec2 min, ImVec2 max, Vec2 offset, float step)
{
if (!drawList || step <= 0.0f)
return;
@@ -77,16 +77,16 @@ void render_checker_background(ImDrawList* drawList, ImVec2 min, ImVec2 max, glm
auto [startY, rowIndex] = checker_start(min.y, offset.y, step);
for (float y = startY; y < max.y; y += step, ++rowIndex)
{
float y1 = glm::max(y, min.y);
float y2 = glm::min(y + step, max.y);
float y1 = vec_max(y, min.y);
float y2 = vec_min(y + step, max.y);
if (y2 <= y1)
continue;
auto [startX, columnIndex] = checker_start(min.x, offset.x, step);
for (float x = startX; x < max.x; x += step, ++columnIndex)
{
float x1 = glm::max(x, min.x);
float x2 = glm::min(x + step, max.x);
float x1 = vec_max(x, min.x);
float x2 = vec_min(x + step, max.x);
if (x2 <= x1)
continue;
+2 -2
View File
@@ -1,6 +1,6 @@
#pragma once
#include <glm/glm.hpp>
#include "vec.h"
#include <imgui/imgui.h>
bool is_drop_after(ImVec2, ImVec2);
@@ -8,4 +8,4 @@ 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);
void render_checker_background(ImDrawList*, ImVec2, ImVec2, Vec2, float);
+7 -9
View File
@@ -12,8 +12,6 @@
#include "ui/input.h"
#include "ui/layout.h"
using namespace glm;
constexpr int TRIGGER_EVENTS_ROWS = 3;
struct Vec2Field
@@ -21,7 +19,7 @@ struct Vec2Field
StringType label;
StringType tooltip;
StringType edit;
vec2 Frame::* member;
Vec2 Frame::* member;
bool isRegionField;
};
@@ -209,13 +207,13 @@ void frame_properties_update(Manager& manager, Settings& settings, FrameProperti
for (auto& field : VEC2_FIELDS)
{
auto& source = field.isRegionField ? displayFrame : useFrame;
auto value = frame ? source.*field.member : vec2();
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 != &Frame::pivot)));
auto state = drag_float2_persistent(localize.get(field.label),
frame ? &value : &dummy_value<vec2>(), DRAG_SPEED, 0.0f,
frame ? &value : &dummy_value<Vec2>(), DRAG_SPEED, 0.0f,
0.0f, frame ? vec2_format_get(source.*field.member) : "");
frame_edit(state, field.edit,
[value, member = field.member](Document&, Frame& frame, Track*, const Reference&) {
@@ -262,7 +260,7 @@ void frame_properties_update(Manager& manager, Settings& settings, FrameProperti
ImGui::EndDisabled();
auto tintEdit =
color_edit4_persistent(localize.get(BASIC_TINT), frame ? &useFrame.tint : &dummy_value<vec4>());
color_edit4_persistent(localize.get(BASIC_TINT), frame ? &useFrame.tint : &dummy_value<Vec4>());
frame_edit(tintEdit, EDIT_FRAME_TINT,
[tint = useFrame.tint](Document&, Frame& frame, Track*, const Reference&) {
frame.tint = tint;
@@ -270,7 +268,7 @@ void frame_properties_update(Manager& manager, Settings& settings, FrameProperti
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_TINT));
auto colorOffsetEdit = color_edit4_persistent(localize.get(BASIC_COLOR_OFFSET),
frame ? &useFrame.colorOffset : &dummy_value<vec4>());
frame ? &useFrame.colorOffset : &dummy_value<Vec4>());
frame_edit(colorOffsetEdit, EDIT_FRAME_COLOR_OFFSET,
[colorOffset = useFrame.colorOffset](Document&, Frame& frame, Track*, const Reference&) {
frame.colorOffset = colorOffset;
@@ -419,6 +417,6 @@ void frame_properties_update(Manager& manager, Settings& settings, FrameProperti
dummy_value<float>() = 0;
dummy_value<int>() = 0;
dummy_value<bool>() = 0;
dummy_value<vec2>() = vec2();
dummy_value<vec4>() = vec4();
dummy_value<Vec2>() = Vec2();
dummy_value<Vec4>() = Vec4();
}
+8 -10
View File
@@ -1,6 +1,6 @@
#include "ui/generate_animation_from_grid.h"
#include <glm/gtc/type_ptr.hpp>
#include "vec.h"
#include "math_util.h"
#include "model/frames.h"
@@ -11,9 +11,7 @@
#include <algorithm>
#include <format>
using namespace glm;
GenerateAnimationFromGrid::GenerateAnimationFromGrid() : Canvas(vec2())
GenerateAnimationFromGrid::GenerateAnimationFromGrid() : Canvas(Vec2())
{}
void GenerateAnimationFromGrid::update(Manager& manager, Document& document, Resources& resources, Settings& settings)
@@ -43,9 +41,9 @@ void GenerateAnimationFromGrid::update(Manager& manager, Document& document, Res
if (ImGui::BeginChild("##Options Child", childSize, ImGuiChildFlags_Borders))
{
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), vec2_format_get(pivot));
ImGui::InputInt2(localize.get(LABEL_GENERATE_START_POSITION), values_get(startPosition));
ImGui::InputInt2(localize.get(LABEL_GENERATE_FRAME_SIZE), values_get(size));
ImGui::InputFloat2(localize.get(BASIC_PIVOT), values_get(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);
@@ -82,7 +80,7 @@ void GenerateAnimationFromGrid::update(Manager& manager, Document& document, Res
size_set(to_vec2(previewSize));
bind();
viewport_set();
clear(isTransparent ? vec4(0) : vec4(backgroundColor, 1.0f));
clear(isTransparent ? Vec4(0) : Vec4(backgroundColor, 1.0f));
if (!layerReferences.empty())
{
@@ -96,13 +94,13 @@ void GenerateAnimationFromGrid::update(Manager& manager, Document& document, Res
auto length = std::max(track_length_get(previewTrack), FRAME_DURATION_MIN);
auto sampleTime = std::min(time * (float)length, (float)length - 0.001f);
auto frame = frame_generate(previewTrack, sampleTime);
auto textureSize = vec2(sourceTexture->size);
auto textureSize = Vec2(sourceTexture->size);
if (textureSize.x > 0.0f && textureSize.y > 0.0f && frame.size.x > 0.0f && frame.size.y > 0.0f)
{
auto uvMin = frame.crop / textureSize;
auto uvMax = (frame.crop + frame.size) / textureSize;
mat4 transform = transform_get(zoom) * quad_model_get(frame.size, frame.position, frame.pivot,
Mat4 transform = 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);
+16 -18
View File
@@ -5,12 +5,10 @@
#include <cmath>
#include <numeric>
#include <glm/gtc/type_ptr.hpp>
#include "vec.h"
#include "path.h"
using namespace glm;
int input_text_callback(ImGuiInputTextCallbackData* data)
{
if (data->EventFlag == ImGuiInputTextFlags_CallbackResize)
@@ -115,14 +113,14 @@ EditState drag_float_persistent(const char* label, float* value, float speed, fl
return EDIT_STATE_NONE;
}
EditState drag_float2_persistent(const char* label, vec2* value, float speed, float min, float max, const char* format,
EditState drag_float2_persistent(const char* label, Vec2* value, float speed, float min, float max, const char* format,
ImGuiSliderFlags flags)
{
static bool isEditing = false;
static vec2 start{NAN};
auto persistent = value ? *value : vec2();
static Vec2 start{NAN};
auto persistent = value ? *value : Vec2();
ImGui::DragFloat2(label, value_ptr(persistent), speed, min, max, format, flags);
ImGui::DragFloat2(label, values_get(persistent), speed, min, max, format, flags);
if (!value)
return EDIT_STATE_NONE;
if (ImGui::IsItemActivated() && persistent != start)
@@ -135,7 +133,7 @@ EditState drag_float2_persistent(const char* label, vec2* value, float speed, fl
{
isEditing = false;
*value = persistent;
start = vec2{NAN};
start = Vec2{NAN};
return EDIT_STATE_END;
}
else if (isEditing)
@@ -147,13 +145,13 @@ EditState drag_float2_persistent(const char* label, vec2* value, float speed, fl
return EDIT_STATE_NONE;
}
EditState color_edit4_persistent(const char* label, vec4* value, ImGuiColorEditFlags flags)
EditState color_edit4_persistent(const char* label, Vec4* value, ImGuiColorEditFlags flags)
{
static bool isEditing = false;
static vec4 start{NAN};
auto persistent = value ? *value : vec4();
static Vec4 start{NAN};
auto persistent = value ? *value : Vec4();
ImGui::ColorEdit4(label, value_ptr(persistent), flags);
ImGui::ColorEdit4(label, values_get(persistent), flags);
if (!value)
return EDIT_STATE_NONE;
if (ImGui::IsItemActivated() && persistent != start)
@@ -166,7 +164,7 @@ EditState color_edit4_persistent(const char* label, vec4* value, ImGuiColorEditF
{
isEditing = false;
*value = persistent;
start = vec4{NAN};
start = Vec4{NAN};
return EDIT_STATE_END;
}
else if (isEditing)
@@ -196,14 +194,14 @@ bool radio_button_icon(const char* label, int* value, int buttonValue, ImTexture
bool input_int_range(const char* label, int& value, int min, int max, int step, int stepFast, ImGuiInputTextFlags flags)
{
auto isActivated = ImGui::InputInt(label, &value, step, stepFast, flags);
value = glm::clamp(value, min, max);
value = vec_clamp(value, min, max);
return isActivated;
}
bool input_int2_range(const char* label, ivec2& value, ivec2 min, ivec2 max, ImGuiInputTextFlags flags)
bool input_int2_range(const char* label, IVec2& value, IVec2 min, IVec2 max, ImGuiInputTextFlags flags)
{
auto isActivated = ImGui::InputInt2(label, value_ptr(value), flags);
value = glm::clamp(value, min, max);
auto isActivated = ImGui::InputInt2(label, values_get(value), flags);
value = vec_clamp(value, min, max);
return isActivated;
}
@@ -211,6 +209,6 @@ bool input_float_range(const char* label, float& value, float min, float max, fl
const char* format, ImGuiInputTextFlags flags)
{
auto isActivated = ImGui::InputFloat(label, &value, step, stepFast, format, flags);
value = glm::clamp(value, min, max);
value = vec_clamp(value, min, max);
return isActivated;
}
+5 -5
View File
@@ -4,7 +4,7 @@
#include <string>
#include <vector>
#include <glm/glm.hpp>
#include "vec.h"
#include <imgui/imgui.h>
#include "types.h"
@@ -18,14 +18,14 @@ int input_text_callback(ImGuiInputTextCallbackData*);
bool input_text_string(const char*, std::string*, ImGuiInputTextFlags = 0);
bool input_text_path(const char*, std::filesystem::path*, ImGuiInputTextFlags = 0);
bool input_int_range(const char*, int&, int, int, int = STEP, int = STEP_FAST, ImGuiInputTextFlags = 0);
bool input_int2_range(const char*, glm::ivec2&, glm::ivec2, glm::ivec2, ImGuiInputTextFlags = 0);
bool input_int2_range(const char*, IVec2&, IVec2, IVec2, ImGuiInputTextFlags = 0);
bool input_float_range(const char*, float&, float, float, float = STEP, float = STEP_FAST, const char* = "%.3f",
ImGuiInputTextFlags = 0);
EditState drag_float_persistent(const char*, float*, float = DRAG_SPEED, float = {}, float = {}, const char* = "%.3f",
ImGuiSliderFlags = 0);
EditState drag_float2_persistent(const char*, glm::vec2*, float = DRAG_SPEED, float = {}, float = {},
const char* = "%.3f", ImGuiSliderFlags = 0);
EditState color_edit4_persistent(const char*, glm::vec4*, ImGuiColorEditFlags = 0);
EditState drag_float2_persistent(const char*, Vec2*, float = DRAG_SPEED, float = {}, float = {}, const char* = "%.3f",
ImGuiSliderFlags = 0);
EditState color_edit4_persistent(const char*, 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<int>&, const std::vector<std::string>&);
bool combo_string_mapped(const std::string&, std::string*, const std::vector<std::string>&,
+7 -7
View File
@@ -2,30 +2,30 @@
#include <string>
#include <glm/glm.hpp>
#include "vec.h"
#include <imgui/imgui.h>
constexpr ImVec2 to_imvec2(const glm::vec2& v) noexcept
constexpr ImVec2 to_imvec2(const Vec2& v) noexcept
{
return {v.x, v.y};
}
constexpr glm::vec2 to_vec2(const ImVec2& v) noexcept
constexpr Vec2 to_vec2(const ImVec2& v) noexcept
{
return {v.x, v.y};
}
constexpr glm::ivec2 to_ivec2(const ImVec2& v) noexcept
constexpr IVec2 to_ivec2(const ImVec2& v) noexcept
{
return {v.x, v.y};
return Vec2(v.x, v.y);
}
constexpr ImVec4 to_imvec4(const glm::vec4& v) noexcept
constexpr ImVec4 to_imvec4(const Vec4& v) noexcept
{
return {v.x, v.y, v.z, v.w};
}
constexpr glm::vec4 to_vec4(const ImVec4& v) noexcept
constexpr Vec4 to_vec4(const ImVec4& v) noexcept
{
return {v.x, v.y, v.z, v.w};
}
+37 -38
View File
@@ -65,44 +65,43 @@ void libraries_update(Panel& panel)
items_clipboard_actions_add<Library>(actions, panel, SelectionKind::LIBRARIES, EDIT_PASTE_LIBRARIES,
TOAST_DESERIALIZE_LIBRARIES_FAILED, libraries_get);
ListRows rows{
.label_get =
[&](int id) {
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(item_get(libraries, id)->path));
ImGui::Text("%s: %d", localize.get(BASIC_ID), id);
if (loaded && loaded->model.isValid)
{
auto animations = loaded->model.animations_get();
auto count = animations.size();
ImGui::SeparatorText(
std::vformat(localize.get(FORMAT_LIBRARY_ANIMATIONS), std::make_format_args(count))
.c_str());
for (auto [index, animation] : animations)
ImGui::BulletText("%s", animation->name.c_str());
ImGui::Separator();
ImGui::TextUnformatted(localize.get(TOOLTIP_LIBRARY_OPEN));
}
else
{
ImGui::Spacing();
ImGui::TextWrapped("%s", localize.get(TOOLTIP_LIBRARY_INVALID));
}
},
.image_get =
[&](int id) {
auto loaded = loaded_get(id);
auto isValid = loaded && loaded->model.isValid;
auto& texture = resources.icons[isValid ? ICON_ANIMATION : ICON_NONE];
return CardImage{.texture = &texture, .size = glm::vec2(texture.size), .isValid = isValid};
},
.activate = open,
.cardLines = LIBRARY_CARD_LINES};
ListRows rows{.label_get =
[&](int id) {
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(item_get(libraries, id)->path));
ImGui::Text("%s: %d", localize.get(BASIC_ID), id);
if (loaded && loaded->model.isValid)
{
auto animations = loaded->model.animations_get();
auto count = animations.size();
ImGui::SeparatorText(std::vformat(localize.get(FORMAT_LIBRARY_ANIMATIONS),
std::make_format_args(count))
.c_str());
for (auto [index, animation] : animations)
ImGui::BulletText("%s", animation->name.c_str());
ImGui::Separator();
ImGui::TextUnformatted(localize.get(TOOLTIP_LIBRARY_OPEN));
}
else
{
ImGui::Spacing();
ImGui::TextWrapped("%s", localize.get(TOOLTIP_LIBRARY_INVALID));
}
},
.image_get =
[&](int id) {
auto loaded = loaded_get(id);
auto isValid = loaded && loaded->model.isValid;
auto& texture = resources.icons[isValid ? ICON_ANIMATION : ICON_NONE];
return CardImage{.texture = &texture, .size = Vec2(texture.size), .isValid = isValid};
},
.activate = open,
.cardLines = LIBRARY_CARD_LINES};
list_panel_draw(
panel, actions, {{ACTION_ADD, ACTION_REMOVE, ACTION_RELOAD, ACTION_OPEN}},
[&]() { content_list_draw(panel, SelectionKind::LIBRARIES, item_ids_get(libraries), rows); }, true);
+3 -5
View File
@@ -1,14 +1,12 @@
#include "ui/panel.h"
#include <glm/gtc/type_ptr.hpp>
#include "vec.h"
#include "localization.h"
#include "ui/input.h"
#include "ui/layout.h"
#include "ui/shortcut.h"
using namespace glm;
constexpr auto FRAMES_MAX = 100;
void onionskin_update(Manager& manager, Settings& settings)
@@ -22,12 +20,12 @@ void onionskin_update(Manager& manager, Settings& settings)
if (ImGui::Begin(localize.get(LABEL_ONIONSKIN_WINDOW), &settings.windowIsOnionskin))
{
auto configure_widgets = [&](const char* separator, int& frames, vec3& color) {
auto configure_widgets = [&](const char* separator, int& frames, Vec3& color) {
ImGui::PushID(separator);
ImGui::SeparatorText(separator);
input_int_range(localize.get(BASIC_FRAMES), frames, 0, FRAMES_MAX);
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ONIONSKIN_FRAMES));
ImGui::ColorEdit3(localize.get(BASIC_COLOR), value_ptr(color));
ImGui::ColorEdit3(localize.get(BASIC_COLOR), values_get(color));
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_ONIONSKIN_COLOR));
ImGui::PopID();
};
+2 -4
View File
@@ -9,8 +9,6 @@
#include "ui/layout.h"
#include "ui/shortcut.h"
using namespace glm;
constexpr float SCROLL_CENTER = 0.5f;
constexpr std::size_t REMOVE_LINES_MAX = 10;
constexpr float TOOLTIP_PADDING_MULTIPLIER = 4.0f;
@@ -484,8 +482,8 @@ void tooltip_name_draw(Resources& resources, const std::string& name)
void tooltip_image_draw(const CardImage& image, const std::function<void()>& info_draw)
{
auto maxPreviewSize = to_vec2(ImGui::GetMainViewport()->Size) * PREVIEW_VIEWPORT_FRACTION;
auto previewSize = glm::max(image.size, vec2(1.0f));
previewSize *= glm::min(1.0f, glm::min(maxPreviewSize.x / previewSize.x, maxPreviewSize.y / previewSize.y));
auto previewSize = vec_max(image.size, Vec2(1.0f));
previewSize *= vec_min(1.0f, vec_min(maxPreviewSize.x / previewSize.x, maxPreviewSize.y / previewSize.y));
auto childFlags = ImGuiChildFlags_Borders | ImGuiChildFlags_AutoResizeX | ImGuiChildFlags_AutoResizeY;
auto noScrollFlags = ImGuiWindowFlags_NoScrollbar | ImGuiWindowFlags_NoScrollWithMouse;
+3 -3
View File
@@ -29,9 +29,9 @@ using Footer = std::vector<std::vector<ActionType>>;
struct CardImage
{
const Image* texture = nullptr;
glm::vec2 size{};
glm::vec2 uvMin{};
glm::vec2 uvMax{1.0f};
Vec2 size{};
Vec2 uvMin{};
Vec2 uvMax{1.0f};
bool isValid = false;
};
+1 -1
View File
@@ -68,7 +68,7 @@ void PopupHelper::trigger()
switch (position)
{
case POPUP_CENTER:
ImGui::SetNextWindowPos(viewport->GetCenter(), ImGuiCond_None, to_imvec2(glm::vec2(0.5f)));
ImGui::SetNextWindowPos(viewport->GetCenter(), ImGuiCond_None, to_imvec2(Vec2(0.5f)));
if (POPUP_IS_HEIGHT_SET[type])
ImGui::SetNextWindowSize(to_imvec2(to_vec2(viewport->Size) * POPUP_MULTIPLIERS[type]));
else
+9 -11
View File
@@ -3,7 +3,7 @@
#include <algorithm>
#include <format>
#include <glm/gtc/type_ptr.hpp>
#include "vec.h"
#include "math_util.h"
#include "path.h"
@@ -13,8 +13,6 @@
#include "vector.h"
#include "working_directory.h"
using namespace glm;
constexpr int REGION_CARD_LINES = 2;
constexpr int REGION_POPUP_ROWS = 5;
constexpr const char* REGION_DRAG_DROP = "Region Drag Drop";
@@ -82,8 +80,8 @@ static CardImage region_image_get(Document& document, Resources& resources, cons
return {.texture = &resources.icons[ICON_NONE], .size = region.size};
return {.texture = texture,
.size = region.size,
.uvMin = region.crop / vec2(texture->size),
.uvMax = (region.crop + region.size) / vec2(texture->size),
.uvMin = region.crop / Vec2(texture->size),
.uvMax = (region.crop + region.size) / Vec2(texture->size),
.isValid = true};
}
@@ -99,8 +97,8 @@ static bool region_export(Document& document, const RegionExportOptions& options
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();
auto minPoint = region ? IVec2(vec_min(region->crop, region->crop + region->size)) : IVec2();
auto exportSize = region ? IVec2(vec_max(region->crop, region->crop + region->size)) - minPoint : IVec2();
if (!region || !texture || !texture->is_valid() || exportSize.x <= 0 || exportSize.y <= 0)
{
toast_log(Level::ERROR, TOAST_EXPORT_REGION_FAILED, region ? region->name : std::string(), pathString);
@@ -144,7 +142,7 @@ static bool region_export(Document& document, const RegionExportOptions& options
exportedRegion.uid = uid_next();
exportedRegion.id = 0;
exportedRegion.crop = {};
exportedRegion.size = vec2(exportSize);
exportedRegion.size = Vec2(exportSize);
region_pivot_apply(exportedRegion);
exported.regions.push_back(exportedRegion);
spritesheets.push_back(exported);
@@ -268,12 +266,12 @@ static void region_properties_popup_update(Panel& panel, RegionsPanel& regions)
ImGui::SetKeyboardFocusHere();
input_text_string(localize.get(BASIC_NAME), &region.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,
ImGui::DragFloat2(localize.get(BASIC_CROP), values_get(region.crop), DRAG_SPEED, 0.0f, 0.0f,
vec2_format_get(region.crop));
ImGui::DragFloat2(localize.get(BASIC_SIZE), value_ptr(region.size), DRAG_SPEED, 0.0f, 0.0f,
ImGui::DragFloat2(localize.get(BASIC_SIZE), values_get(region.size), DRAG_SPEED, 0.0f, 0.0f,
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,
ImGui::DragFloat2(localize.get(BASIC_PIVOT), values_get(region.pivot), DRAG_SPEED, 0.0f, 0.0f,
vec2_format_get(region.pivot));
ImGui::EndDisabled();
+1 -1
View File
@@ -347,7 +347,7 @@ void shaders_update(Panel& panel, ShadersPanel& shaders)
auto image_get = [&](int id) {
auto isValid = document.shader_get(id) != nullptr;
auto& image = resources.icons[isValid ? ICON_SHADER : ICON_NONE];
return CardImage{.texture = &image, .size = glm::vec2(image.size), .isValid = isValid};
return CardImage{.texture = &image, .size = Vec2(image.size), .isValid = isValid};
};
ListRows rows{.label_get =
[&](int id) {
+1 -2
View File
@@ -103,8 +103,7 @@ void sounds_update(Panel& panel)
auto audio = document.sound_get(id);
auto isValid = audio && audio->is_valid();
auto& texture = resources.icons[isValid ? ICON_SOUND : ICON_NONE];
return CardImage{
.texture = &texture, .size = glm::vec2(texture.size), .isValid = isValid};
return CardImage{.texture = &texture, .size = Vec2(texture.size), .isValid = isValid};
},
.select =
[&](int id) {
+28 -31
View File
@@ -5,7 +5,7 @@
#include <set>
#include <utility>
#include <glm/gtc/type_ptr.hpp>
#include "vec.h"
#include "ui/actions.h"
#include "imgui_internal.h"
@@ -19,8 +19,6 @@
#include "ui/layout.h"
#include "ui/shortcut.h"
using namespace glm;
void SpritesheetEditor::update(Manager& manager, Settings& settings, Resources& resources)
{
isFocused = false;
@@ -83,7 +81,7 @@ void SpritesheetEditor::update(Manager& manager, Settings& settings, Resources&
view_buttons_draw(manager, settings, center_view, fit_view);
auto mousePosInt = ivec2(mousePos);
auto mousePosInt = IVec2(mousePos);
ImGui::TextUnformatted(
std::vformat(localize.get(FORMAT_POSITION_SPACED), std::make_format_args(mousePosInt.x, mousePosInt.y))
.c_str());
@@ -100,7 +98,7 @@ void SpritesheetEditor::update(Manager& manager, Settings& settings, Resources&
{
ImGui::BeginDisabled(isTransparent);
{
ImGui::ColorEdit3(localize.get(LABEL_BACKGROUND_COLOR), value_ptr(backgroundColor),
ImGui::ColorEdit3(localize.get(LABEL_BACKGROUND_COLOR), values_get(backgroundColor),
ImGuiColorEditFlags_NoInputs);
ImGui::SetItemTooltip("%s", localize.get(TOOLTIP_BACKGROUND_COLOR));
}
@@ -140,8 +138,8 @@ void SpritesheetEditor::update(Manager& manager, Settings& settings, Resources&
auto isDuring = isMouseDown || input.isArrowDown;
auto isEnd = input.isLeftReleased || input.isRightReleased || input.isArrowEnd;
auto arrow = input.arrow * input.step;
auto gridArrow = isGridSnap ? arrow * vec2(gridSize) : arrow;
auto isArrow = arrow != vec2();
auto gridArrow = isGridSnap ? arrow * Vec2(gridSize) : arrow;
auto isArrow = arrow != Vec2();
auto selectedFrameReferences = document.frame_references_get();
std::erase_if(selectedFrameReferences,
@@ -158,8 +156,8 @@ void SpritesheetEditor::update(Manager& manager, Settings& settings, Resources&
previousMousePos = mousePos;
mousePos = position_translate(zoom, pan, to_ivec2(ImGui::GetMousePos()) - to_ivec2(cursorScreenPos));
auto pivot_snap = [&](vec2 value, vec2 current) {
return isGridSnap ? vec2(ivec2(value)) : glm::floor(value) + (current - glm::floor(current));
auto pivot_snap = [&](Vec2 value, Vec2 current) {
return isGridSnap ? Vec2(IVec2(value)) : vec_floor(value) + (current - vec_floor(current));
};
// Region edits apply to the given regions of the edited spritesheet when the command runs.
auto regions_update = [&](std::set<int> ids, std::function<void(Region&)> update) {
@@ -171,7 +169,7 @@ void SpritesheetEditor::update(Manager& manager, Settings& settings, Resources&
update(*region);
}});
};
auto region_pivot_update = [&](std::function<vec2(vec2)> pivot_get) {
auto region_pivot_update = [&](std::function<Vec2(Vec2)> pivot_get) {
regions_update({regionReference}, [=](Region& region) {
region.origin = Origin::CUSTOM;
region.pivot = pivot_get(region.pivot);
@@ -193,10 +191,9 @@ void SpritesheetEditor::update(Manager& manager, Settings& settings, Resources&
if (useTool == TOOL_PAN && spritesheet && texture && texture->is_valid())
for (auto& region : spritesheet->regions)
{
auto minPoint = glm::min(region.crop, region.crop + region.size);
auto maxPoint = glm::max(region.crop, region.crop + region.size);
if (glm::all(glm::greaterThanEqual(mousePos, minPoint)) &&
glm::all(glm::lessThanEqual(mousePos, maxPoint)))
auto minPoint = vec_min(region.crop, region.crop + region.size);
auto maxPoint = vec_max(region.crop, region.crop + region.size);
if (is_all_less_equal(minPoint, mousePos) && is_all_less_equal(mousePos, maxPoint))
{
hoveredRegionId = region.id;
break;
@@ -256,10 +253,10 @@ void SpritesheetEditor::update(Manager& manager, Settings& settings, Resources&
edit_begin_push(manager, EDIT_REGION_MOVE);
if (isMouseDown)
region_pivot_update(
[pivot = pivot_snap(mousePos - region->crop, region->pivot)](vec2) { return pivot; });
[pivot = pivot_snap(mousePos - region->crop, region->pivot)](Vec2) { return pivot; });
if (isArrow)
region_pivot_update(
[=, this](vec2 pivot) { return isGridSnap ? vec2(ivec2(pivot + arrow)) : pivot + arrow; });
[=, this](Vec2 pivot) { return isGridSnap ? Vec2(IVec2(pivot + arrow)) : pivot + arrow; });
if (isDuring)
tooltip_lines_draw({localize_format(FORMAT_PIVOT, region->pivot.x, region->pivot.y)});
if (isEnd)
@@ -287,7 +284,7 @@ void SpritesheetEditor::update(Manager& manager, Settings& settings, Resources&
{
if (isBegin)
edit_begin_push(manager, isRegionCrop ? EDIT_REGION_CROP : EDIT_FRAME_CROP);
auto rect_set = [&](vec2 crop, vec2 cropSize) {
auto rect_set = [&](Vec2 crop, Vec2 cropSize) {
if (isRegionCrop)
regions_update(regionSelection, [=](Region& region) {
region.crop = crop;
@@ -303,9 +300,9 @@ void SpritesheetEditor::update(Manager& manager, Settings& settings, Resources&
if (isMouseClicked)
{
cropAnchor = mousePos;
auto crop = vec2(ivec2(cropAnchor));
auto crop = Vec2(IVec2(cropAnchor));
if (isRegionCrop)
rect_set(crop, vec2());
rect_set(crop, Vec2());
else
frames_change({.regionId = -1, .cropX = crop.x, .cropY = crop.y});
}
@@ -316,8 +313,8 @@ void SpritesheetEditor::update(Manager& manager, Settings& settings, Resources&
}
if (isArrow && isRegionCrop)
regions_update(regionSelection, [=](Region& region) {
region.crop = vec2(ivec2(region.crop + gridArrow));
region.size = vec2(ivec2(region.size));
region.crop = Vec2(IVec2(region.crop + gridArrow));
region.size = Vec2(IVec2(region.size));
});
else if (isArrow)
frames_change({.regionId = -1, .cropX = gridArrow.x, .cropY = gridArrow.y}, ChangeType::ADD);
@@ -348,8 +345,8 @@ void SpritesheetEditor::update(Manager& manager, Settings& settings, Resources&
}});
auto shown = isRegionCrop ? region_get(*regionSelection.begin()) : nullptr;
auto crop = shown ? shown->crop : frame ? frame->crop : vec2();
auto cropSize = shown ? shown->size : frame ? frame->size : vec2();
auto crop = shown ? shown->crop : frame ? frame->crop : Vec2();
auto cropSize = shown ? shown->size : frame ? frame->size : Vec2();
if (isDuring && (shown || !isRegionCrop))
tooltip_lines_draw({localize_format(FORMAT_CROP, crop.x, crop.y),
localize_format(FORMAT_SIZE, cropSize.x, cropSize.y)});
@@ -370,8 +367,8 @@ void SpritesheetEditor::update(Manager& manager, Settings& settings, Resources&
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(),
{manager.selected, [start = IVec2(previousMousePos), end = IVec2(mousePos),
color = useTool == TOOL_DRAW ? toolColor : Vec4(),
spritesheetId = referenceSpritesheet](Manager&, Document& document) {
if (auto texture = document.texture_edit(spritesheetId))
texture->pixel_line(start, end, color);
@@ -390,7 +387,7 @@ void SpritesheetEditor::update(Manager& manager, Settings& settings, Resources&
{
ImGui::ColorButton("##Color Picker Button", to_imvec4(toolColor));
ImGui::SameLine();
auto rgba8 = glm::clamp(ivec4(toolColor * 255.0f + 0.5f), ivec4(0), ivec4(255));
auto rgba8 = vec_clamp(IVec4(toolColor * 255.0f + 0.5f), IVec4(0), IVec4(255));
ImGui::TextUnformatted(
std::format("#{:02X}{:02X}{:02X}{:02X}", rgba8.r, rgba8.g, rgba8.b, rgba8.a).c_str());
ImGui::SameLine();
@@ -419,14 +416,14 @@ void SpritesheetEditor::update(Manager& manager, Settings& settings, Resources&
if (input.wheel != 0 || input.isZoomIn || input.isZoomOut)
{
auto focus = input.wheel != 0 ? vec2(mousePos) : texture ? vec2(texture->size) / 2.0f : vec2();
auto focus = input.wheel != 0 ? Vec2(mousePos) : texture ? Vec2(texture->size) / 2.0f : Vec2();
zoom_step(zoom, pan, focus, (input.wheel > 0 || input.isZoomIn) ? ZOOM_LEVEL_STEP : -ZOOM_LEVEL_STEP);
}
}
bind();
viewport_set();
clear(isTransparent ? vec4(0) : vec4(backgroundColor, 1.0f));
clear(isTransparent ? Vec4(0) : Vec4(backgroundColor, 1.0f));
auto frame = model.frame_get(reference);
@@ -457,7 +454,7 @@ void SpritesheetEditor::update(Manager& manager, Settings& settings, Resources&
{
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));
rect_fill_render(shaderLine, cropTransform, cropModel, Vec4(1.0f, 1.0f, 1.0f, 0.5f));
}
}
@@ -480,7 +477,7 @@ void SpritesheetEditor::update(Manager& manager, Settings& settings, Resources&
highlightedRegionId = regionReference;
}
auto draw_region_rect = [&](const Region& region, vec4 regionColor) {
auto draw_region_rect = [&](const Region& region, Vec4 regionColor) {
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,
@@ -530,7 +527,7 @@ void SpritesheetEditor::update(Manager& manager, Settings& settings, Resources&
if (isTransparent)
render_checker_background(drawList, min, max, -size * 0.5f - checkerPan, CHECKER_SIZE);
else
drawList->AddRectFilled(min, max, ImGui::GetColorU32(to_imvec4(vec4(backgroundColor, 1.0f))));
drawList->AddRectFilled(min, max, ImGui::GetColorU32(to_imvec4(Vec4(backgroundColor, 1.0f))));
image_premultiplied_draw(this->texture, to_imvec2(size));
}
+2 -2
View File
@@ -7,8 +7,8 @@
class SpritesheetEditor : public CanvasView
{
glm::vec2 previousMousePos{};
glm::vec2 cropAnchor{};
Vec2 previousMousePos{};
Vec2 cropAnchor{};
int hoveredRegionId = -1;
public:
+2 -2
View File
@@ -122,7 +122,7 @@ static void spritesheets_merge_popup_update(Panel& panel, SpritesheetsPanel& spr
return popup.end();
settings.mergeSpritesheetsRegionOrigin =
glm::clamp(settings.mergeSpritesheetsRegionOrigin, 0, (int)std::size(MERGE_REGION_ORIGINS) - 1);
vec_clamp(settings.mergeSpritesheetsRegionOrigin, 0, (int)std::size(MERGE_REGION_ORIGINS) - 1);
if (ImGui::BeginChild("##Merge Spritesheets Options", child_size_get(MERGE_OPTIONS_ROWS), ImGuiChildFlags_Borders))
{
ImGui::SeparatorText(localize.get(LABEL_REGION_PROPERTIES_ORIGIN));
@@ -300,7 +300,7 @@ void spritesheets_update(Panel& panel, SpritesheetsPanel& spritesheets)
auto texture = document.texture_get(id);
auto isValid = texture && texture->is_valid();
auto& image = isValid ? *texture : resources.icons[ICON_NONE];
return CardImage{.texture = &image, .size = glm::vec2(image.size), .isValid = isValid};
return CardImage{.texture = &image, .size = Vec2(image.size), .isValid = isValid};
};
ListRows rows{
.label_get =
-2
View File
@@ -18,8 +18,6 @@
#include "ui/layout.h"
#include "ui/shortcut.h"
using namespace glm;
constexpr auto GENERATE_REGIONS_TARGET_SELECTION = 0;
constexpr auto GENERATE_REGIONS_TARGET_ALL = 1;
+2 -2
View File
@@ -248,8 +248,8 @@ void TimelineContext::shortcuts_update()
if (auto item = selected_item_get(); item && !item->frames.empty())
{
auto frameReference = reference;
frameReference.frameIndex = glm::clamp(reference.frameIndex + (int)isNextFrame - (int)isPreviousFrame, 0,
(int)item->frames.size() - 1);
frameReference.frameIndex = vec_clamp(reference.frameIndex + (int)isNextFrame - (int)isPreviousFrame, 0,
(int)item->frames.size() - 1);
reference_set(frameReference);
document.frame_focus_select();
document.frameTime = frame_time_from_index_get(*item, reference.frameIndex);
+17 -17
View File
@@ -15,24 +15,24 @@
#include "localization.h"
#include "ui/popup.h"
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);
inline const Vec4 ROOT_COLOR = Vec4(0.140f, 0.310f, 0.560f, 1.000f);
inline const Vec4 ROOT_COLOR_ACTIVE = Vec4(0.240f, 0.520f, 0.880f, 1.000f);
inline const Vec4 ROOT_COLOR_HOVERED = Vec4(0.320f, 0.640f, 1.000f, 1.000f);
inline const glm::vec4 LAYER_COLOR = glm::vec4(0.640f, 0.320f, 0.110f, 1.000f);
inline const glm::vec4 LAYER_COLOR_ACTIVE = glm::vec4(0.840f, 0.450f, 0.170f, 1.000f);
inline const glm::vec4 LAYER_COLOR_HOVERED = glm::vec4(0.960f, 0.560f, 0.240f, 1.000f);
inline const Vec4 LAYER_COLOR = Vec4(0.640f, 0.320f, 0.110f, 1.000f);
inline const Vec4 LAYER_COLOR_ACTIVE = Vec4(0.840f, 0.450f, 0.170f, 1.000f);
inline const Vec4 LAYER_COLOR_HOVERED = Vec4(0.960f, 0.560f, 0.240f, 1.000f);
inline const glm::vec4 NULL_COLOR = glm::vec4(0.140f, 0.430f, 0.200f, 1.000f);
inline const glm::vec4 NULL_COLOR_ACTIVE = glm::vec4(0.250f, 0.650f, 0.350f, 1.000f);
inline const glm::vec4 NULL_COLOR_HOVERED = glm::vec4(0.350f, 0.800f, 0.480f, 1.000f);
inline const Vec4 NULL_COLOR = Vec4(0.140f, 0.430f, 0.200f, 1.000f);
inline const Vec4 NULL_COLOR_ACTIVE = Vec4(0.250f, 0.650f, 0.350f, 1.000f);
inline const Vec4 NULL_COLOR_HOVERED = Vec4(0.350f, 0.800f, 0.480f, 1.000f);
inline const glm::vec4 TRIGGER_COLOR = glm::vec4(0.620f, 0.150f, 0.260f, 1.000f);
inline const glm::vec4 TRIGGER_COLOR_ACTIVE = glm::vec4(0.820f, 0.250f, 0.380f, 1.000f);
inline const glm::vec4 TRIGGER_COLOR_HOVERED = glm::vec4(0.950f, 0.330f, 0.490f, 1.000f);
inline const Vec4 TRIGGER_COLOR = Vec4(0.620f, 0.150f, 0.260f, 1.000f);
inline const Vec4 TRIGGER_COLOR_ACTIVE = Vec4(0.820f, 0.250f, 0.380f, 1.000f);
inline const Vec4 TRIGGER_COLOR_HOVERED = Vec4(0.950f, 0.330f, 0.490f, 1.000f);
#define ANM2_ITEM_TYPES \
X(NONE, STRING_UNDEFINED, ICON_NONE, glm::vec4(), glm::vec4(), glm::vec4()) \
X(NONE, STRING_UNDEFINED, ICON_NONE, Vec4(), Vec4(), 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) \
@@ -50,19 +50,19 @@ constexpr Icon TYPE_ICONS[] = {
#undef X
};
inline const glm::vec4 TYPE_COLOR[] = {
inline const Vec4 TYPE_COLOR[] = {
#define X(symbol, string, icon, color, colorActive, colorHovered) color,
ANM2_ITEM_TYPES
#undef X
};
inline const glm::vec4 TYPE_COLOR_ACTIVE[] = {
inline const Vec4 TYPE_COLOR_ACTIVE[] = {
#define X(symbol, string, icon, color, colorActive, colorHovered) colorActive,
ANM2_ITEM_TYPES
#undef X
};
inline const glm::vec4 TYPE_COLOR_HOVERED[] = {
inline const Vec4 TYPE_COLOR_HOVERED[] = {
#define X(symbol, string, icon, color, colorActive, colorHovered) colorHovered,
ANM2_ITEM_TYPES
#undef X
@@ -162,7 +162,7 @@ struct TimelineState
int animationLengthEditIndex = -1;
std::vector<TimelineRow> rowDragReferences;
std::set<std::uint64_t> expandedLayerTracks; // animation layer tracks (by uid) showing their child's tracks
glm::vec2 scroll{};
Vec2 scroll{};
ImGuiStyle style = {};
};
+34 -36
View File
@@ -26,11 +26,9 @@
#include "vector.h"
#include "ui/panel.h"
using namespace glm;
constexpr auto WIDTH_MULTIPLIER = 1.25f;
constexpr auto COLOR_HIDDEN_MULTIPLIER = vec4(0.5f, 0.5f, 0.5f, 1.000f);
constexpr auto COLOR_HIDDEN_MULTIPLIER = Vec4(0.5f, 0.5f, 0.5f, 1.000f);
constexpr auto FRAME_BORDER_COLOR_DARK = ImVec4(1.0f, 1.0f, 1.0f, 0.15f);
constexpr auto FRAME_BORDER_COLOR_LIGHT = ImVec4(0.0f, 0.0f, 0.0f, 0.25f);
constexpr auto FRAME_BORDER_COLOR_REFERENCED_DARK = ImVec4(1.0f, 1.0f, 1.0f, 0.50f);
@@ -64,36 +62,36 @@ enum class DropZone
AFTER
};
constexpr glm::vec4 FRAME_COLOR_LIGHT_BASE[] = {{0.80f, 0.80f, 0.80f, 1.0f},
{0.5216f, 0.7333f, 1.0f, 1.0f},
{1.0f, 0.9961f, 0.5882f, 1.0f},
{0.6157f, 1.0f, 0.5882f, 1.0f},
{1.0f, 0.5882f, 0.8314f, 1.0f}};
constexpr glm::vec4 FRAME_COLOR_LIGHT_ACTIVE[] = {{0.74f, 0.74f, 0.74f, 1.0f},
{0.0980f, 0.3765f, 0.6431f, 1.0f},
{1.0f, 0.5255f, 0.3333f, 1.0f},
{0.3686f, 0.5765f, 0.2353f, 1.0f},
{0.6118f, 0.2039f, 0.2745f, 1.0f}};
constexpr glm::vec4 FRAME_COLOR_LIGHT_HOVERED[] = {{0.84f, 0.84f, 0.84f, 1.0f},
{0.0752f, 0.2887f, 0.4931f, 1.0f},
{0.85f, 0.4467f, 0.2833f, 1.0f},
{0.2727f, 0.4265f, 0.1741f, 1.0f},
{0.4618f, 0.1539f, 0.2072f, 1.0f}};
constexpr glm::vec4 ITEM_COLOR_LIGHT_BASE[] = {{0.3059f, 0.3255f, 0.5412f, 1.0f},
{0.3333f, 0.5725f, 0.8392f, 1.0f},
{1.0f, 0.5412f, 0.3412f, 1.0f},
{0.5255f, 0.8471f, 0.4588f, 1.0f},
{0.7961f, 0.3882f, 0.5412f, 1.0f}};
constexpr glm::vec4 ITEM_COLOR_LIGHT_ACTIVE[] = {{0.3459f, 0.3655f, 0.5812f, 1.0f},
{0.3733f, 0.6125f, 0.8792f, 1.0f},
{0.9106f, 0.4949f, 0.2753f, 1.0f},
{0.5655f, 0.8871f, 0.4988f, 1.0f},
{0.8361f, 0.4282f, 0.5812f, 1.0f}};
constexpr glm::vec4 ITEM_COLOR_LIGHT_SELECTED[] = {{0.74f, 0.74f, 0.74f, 1.0f},
{0.2039f, 0.4549f, 0.7176f, 1.0f},
{0.8745f, 0.4392f, 0.2275f, 1.0f},
{0.3765f, 0.6784f, 0.2980f, 1.0f},
{0.6353f, 0.2235f, 0.3647f, 1.0f}};
constexpr Vec4 FRAME_COLOR_LIGHT_BASE[] = {{0.80f, 0.80f, 0.80f, 1.0f},
{0.5216f, 0.7333f, 1.0f, 1.0f},
{1.0f, 0.9961f, 0.5882f, 1.0f},
{0.6157f, 1.0f, 0.5882f, 1.0f},
{1.0f, 0.5882f, 0.8314f, 1.0f}};
constexpr Vec4 FRAME_COLOR_LIGHT_ACTIVE[] = {{0.74f, 0.74f, 0.74f, 1.0f},
{0.0980f, 0.3765f, 0.6431f, 1.0f},
{1.0f, 0.5255f, 0.3333f, 1.0f},
{0.3686f, 0.5765f, 0.2353f, 1.0f},
{0.6118f, 0.2039f, 0.2745f, 1.0f}};
constexpr Vec4 FRAME_COLOR_LIGHT_HOVERED[] = {{0.84f, 0.84f, 0.84f, 1.0f},
{0.0752f, 0.2887f, 0.4931f, 1.0f},
{0.85f, 0.4467f, 0.2833f, 1.0f},
{0.2727f, 0.4265f, 0.1741f, 1.0f},
{0.4618f, 0.1539f, 0.2072f, 1.0f}};
constexpr Vec4 ITEM_COLOR_LIGHT_BASE[] = {{0.3059f, 0.3255f, 0.5412f, 1.0f},
{0.3333f, 0.5725f, 0.8392f, 1.0f},
{1.0f, 0.5412f, 0.3412f, 1.0f},
{0.5255f, 0.8471f, 0.4588f, 1.0f},
{0.7961f, 0.3882f, 0.5412f, 1.0f}};
constexpr Vec4 ITEM_COLOR_LIGHT_ACTIVE[] = {{0.3459f, 0.3655f, 0.5812f, 1.0f},
{0.3733f, 0.6125f, 0.8792f, 1.0f},
{0.9106f, 0.4949f, 0.2753f, 1.0f},
{0.5655f, 0.8871f, 0.4988f, 1.0f},
{0.8361f, 0.4282f, 0.5812f, 1.0f}};
constexpr Vec4 ITEM_COLOR_LIGHT_SELECTED[] = {{0.74f, 0.74f, 0.74f, 1.0f},
{0.2039f, 0.4549f, 0.7176f, 1.0f},
{0.8745f, 0.4392f, 0.2275f, 1.0f},
{0.3765f, 0.6784f, 0.2980f, 1.0f},
{0.6353f, 0.2235f, 0.3647f, 1.0f}};
constexpr auto MARKER_ALPHA = 0.5f;
constexpr auto MARKER_OUTSIDE_COLOR = IM_COL32(0, 0, 0, 96);
@@ -114,8 +112,8 @@ enum TimelineColor
struct TimelineColorSet
{
const glm::vec4* light;
const glm::vec4* dark;
const Vec4* light;
const Vec4* dark;
};
inline const TimelineColorSet TIMELINE_COLORS[] = {{FRAME_COLOR_LIGHT_BASE, TYPE_COLOR},
@@ -187,7 +185,7 @@ struct TimelineContext : TimelineState
const TrackGroup* track_group_get(int type, int groupId);
bool is_track_group_visible(int type, int groupId);
const TrackGroup* row_group_get(const TimelineRow& row);
glm::vec4 color_get(TimelineColor, int);
Vec4 color_get(TimelineColor, int);
std::set<Reference> drag_frame_references_get(const Reference&);
// Queues an edit on the document. Its result is selected (frames by default).
template <class Operation>
+7 -7
View File
@@ -130,9 +130,9 @@ void TimelineContext::frame_child(const TimelineRow& row, int& index, float widt
if (frameSize.x > 0.0f && ImGui::IsWindowHovered(ImGuiHoveredFlags_AllowWhenBlockedByActiveItem))
{
auto mouseX = ImGui::GetIO().MousePos.x - cursorScreenPos.x;
frameSplitTimeAtCursor = glm::max(0, (int)std::floor(mouseX / frameSize.x));
frameSplitTimeAtCursor = vec_max(0, (int)std::floor(mouseX / frameSize.x));
}
auto border = glm::max(0.5f, ImGui::GetStyle().FrameBorderSize * 0.5f);
auto border = vec_max(0.5f, ImGui::GetStyle().FrameBorderSize * 0.5f);
auto borderLineLength = frameSize.y / 5;
auto frameMin = std::max(0, (int)std::floor(scroll.x / frameSize.x) - 1);
auto frameMax = std::min(FRAME_NUM_MAX, (int)std::ceil((scroll.x + clipMax.x) / frameSize.x) + 1);
@@ -340,7 +340,7 @@ void TimelineContext::frame_child(const TimelineRow& row, int& index, float widt
if (mousePos.x >= rowMin.x && mousePos.x < rowMax.x && mousePos.y >= rowMin.y && mousePos.y < rowMax.y)
{
auto mouseX = mousePos.x - cursorScreenPos.x;
auto targetTime = glm::max(0.0f, mouseX / frameSize.x);
auto targetTime = vec_max(0.0f, mouseX / frameSize.x);
int dropIndex = (int)item->frames.size();
float dropFrameTime = 0;
float frameTime = 0;
@@ -376,7 +376,7 @@ void TimelineContext::frame_child(const TimelineRow& row, int& index, float widt
Reference{reference.animationIndex, type, id, dropIndex, row.groupType, row.groupId};
auto dropX = cursorScreenPos.x + dropFrameTime * frameSize.x;
auto previewWidth = glm::max(frameSize.x, (float)frameMoveDrag.duration * frameSize.x);
auto previewWidth = vec_max(frameSize.x, (float)frameMoveDrag.duration * frameSize.x);
frameMovePreviewMin = ImVec2(dropX, cursorScreenPos.y);
frameMovePreviewMax = ImVec2(dropX + previewWidth, cursorScreenPos.y + frameSize.y);
isFrameMovePreview = true;
@@ -398,7 +398,7 @@ void TimelineContext::frame_child(const TimelineRow& row, int& index, float widt
frameTime = frame.atFrame;
auto buttonSize =
type == TRIGGER ? frameSize : to_imvec2(vec2(frameSize.x * frame.duration, frameSize.y));
type == TRIGGER ? frameSize : to_imvec2(Vec2(frameSize.x * frame.duration, frameSize.y));
auto frameStart = type == TRIGGER ? frame.atFrame : frameTime;
auto frameEnd = type == TRIGGER ? frameStart + 1.0f : frameStart + frame.duration;
if (frameEnd <= (float)frameMin || frameStart >= (float)frameMax)
@@ -507,7 +507,7 @@ void TimelineContext::frame_child(const TimelineRow& row, int& index, float widt
for (auto selectedReference : selectedReferences)
if (auto selectedFrame = document.model.frame_get(selectedReference))
dragDuration += selectedFrame->duration;
dragDuration = glm::max(1, dragDuration);
dragDuration = vec_max(1, dragDuration);
frameMoveDrag = {.animationIndex = reference.animationIndex,
.duration = dragDuration,
@@ -595,7 +595,7 @@ void TimelineContext::frame_drag_update()
auto targetReference = draggedFrameReference;
if (draggedFrameType == TRIGGER)
{
auto atFrame = glm::clamp(
auto atFrame = vec_clamp(
hoveredTime, 0, settings.playbackIsClamp && animation ? animation->frameNum - 1 : FRAME_NUM_MAX - 1);
command_push(
[=](Manager&, Document& document) { trigger_at_frame_set(document.model, targetReference, atFrame); });
+1 -1
View File
@@ -33,7 +33,7 @@ const Track* TimelineContext::selected_item_get()
return document.model.track_get(reference);
}
glm::vec4 TimelineContext::color_get(TimelineColor color, int type)
Vec4 TimelineContext::color_get(TimelineColor color, int type)
{
auto& colors = TIMELINE_COLORS[color];
return isLightTheme ? colors.light[std::clamp(type, 0, TRIGGER)] : colors.dark[type];
+3 -5
View File
@@ -1,7 +1,7 @@
#include "ui/panel.h"
#include <glm/gtc/type_ptr.hpp>
#include "vec.h"
#include "localization.h"
#include "tool.h"
@@ -9,8 +9,6 @@
#include "ui/layout.h"
#include "ui/shortcut.h"
using namespace glm;
void tools_update(Manager& manager, Settings& settings, Resources& resources, PopupHelper& colorEditPopup)
{
auto& document = *manager.get();
@@ -20,7 +18,7 @@ void tools_update(Manager& manager, Settings& settings, Resources& resources, Po
ImGui::PushStyleVar(ImGuiStyleVar_ItemSpacing, ImVec2(2, 2));
auto availableWidth = ImGui::GetContentRegionAvail().x;
auto size = vec2(ImGui::GetTextLineHeightWithSpacing() * 1.5f);
auto size = Vec2(ImGui::GetTextLineHeightWithSpacing() * 1.5f);
auto usedWidth = ImGui::GetStyle().WindowPadding.x;
auto tool_use = [&](Tool type) {
@@ -98,7 +96,7 @@ void tools_update(Manager& manager, Settings& settings, Resources& resources, Po
if (ImGui::BeginPopup(colorEditPopup.label()))
{
ImGui::ColorPicker4(colorEditPopup.label(), value_ptr(settings.toolColor));
ImGui::ColorPicker4(colorEditPopup.label(), values_get(settings.toolColor));
ImGui::EndPopup();
}
}
+494
View File
@@ -0,0 +1,494 @@
#pragma once
#include <cmath>
#include <type_traits>
// Vectors and 4x4 matrices for 2D drawing, shaped like GLSL's: components x, y, z, w (r, g, b, a for colors), and
// matrices column-major, so m[column][row]. Formulas follow glm's, which the editor used before.
template <class T> struct TVec4;
template <class T> struct TVec2
{
using Value = T;
static constexpr int SIZE = 2;
T x = 0;
T y = 0;
constexpr TVec2() = default;
constexpr TVec2(T x, T y) : x(x), y(y)
{}
explicit constexpr TVec2(T value) : x(value), y(value)
{}
template <class U> constexpr TVec2(TVec2<U> v) : x((T)v.x), y((T)v.y)
{}
template <class V>
requires(V::SIZE > 2)
constexpr TVec2(V v) : x((T)v.x), y((T)v.y)
{}
constexpr T& operator[](int i)
{
return i == 0 ? x : y;
}
constexpr T operator[](int i) const
{
return i == 0 ? x : y;
}
};
template <class T> struct TVec3
{
using Value = T;
static constexpr int SIZE = 3;
union
{
T x = 0;
T r;
};
union
{
T y = 0;
T g;
};
union
{
T z = 0;
T b;
};
constexpr TVec3() = default;
constexpr TVec3(T x, T y, T z) : x(x), y(y), z(z)
{}
explicit constexpr TVec3(T value) : x(value), y(value), z(value)
{}
constexpr TVec3(TVec2<T> xy, T z) : x(xy.x), y(xy.y), z(z)
{}
template <class U> constexpr TVec3(TVec3<U> v) : x((T)v.x), y((T)v.y), z((T)v.z)
{}
template <class U> constexpr TVec3(TVec4<U> v) : x((T)v.x), y((T)v.y), z((T)v.z)
{}
constexpr T& operator[](int i)
{
return i == 0 ? x : i == 1 ? y : z;
}
constexpr T operator[](int i) const
{
return i == 0 ? x : i == 1 ? y : z;
}
};
template <class T> struct TVec4
{
using Value = T;
static constexpr int SIZE = 4;
union
{
T x = 0;
T r;
};
union
{
T y = 0;
T g;
};
union
{
T z = 0;
T b;
};
union
{
T w = 0;
T a;
};
constexpr TVec4() = default;
constexpr TVec4(T x, T y, T z, T w) : x(x), y(y), z(z), w(w)
{}
explicit constexpr TVec4(T value) : x(value), y(value), z(value), w(value)
{}
constexpr TVec4(TVec2<T> xy, TVec2<T> zw) : x(xy.x), y(xy.y), z(zw.x), w(zw.y)
{}
constexpr TVec4(TVec2<T> xy, T z, T w) : x(xy.x), y(xy.y), z(z), w(w)
{}
constexpr TVec4(TVec3<T> xyz, T w) : x(xyz.x), y(xyz.y), z(xyz.z), w(w)
{}
template <class U> constexpr TVec4(TVec4<U> v) : x((T)v.x), y((T)v.y), z((T)v.z), w((T)v.w)
{}
constexpr T& operator[](int i)
{
return i == 0 ? x : i == 1 ? y : i == 2 ? z : w;
}
constexpr T operator[](int i) const
{
return i == 0 ? x : i == 1 ? y : i == 2 ? z : w;
}
};
using Vec2 = TVec2<float>;
using Vec3 = TVec3<float>;
using Vec4 = TVec4<float>;
using IVec2 = TVec2<int>;
using IVec4 = TVec4<int>;
template <class V>
concept Vector = requires {
V::SIZE;
typename V::Value;
};
#define VEC_OPERATOR(op, assign) \
template <Vector V, Vector W> \
requires(V::SIZE == W::SIZE) \
constexpr V& operator assign(V& a, W b) \
{ \
for (int i = 0; i < V::SIZE; ++i) \
a[i] assign b[i]; \
return a; \
} \
template <Vector V> constexpr V& operator assign(V& a, typename V::Value value) \
{ \
for (int i = 0; i < V::SIZE; ++i) \
a[i] assign value; \
return a; \
} \
template <Vector V> constexpr V operator op(V a, V b) \
{ \
return a assign b; \
} \
template <Vector V> constexpr V operator op(V a, typename V::Value value) \
{ \
return a assign value; \
} \
template <Vector V> constexpr V operator op(typename V::Value value, V a) \
{ \
auto result = V(value); \
return result assign a; \
}
VEC_OPERATOR(+, +=)
VEC_OPERATOR(-, -=)
VEC_OPERATOR(*, *=)
VEC_OPERATOR(/, /=)
#undef VEC_OPERATOR
template <Vector V> constexpr V operator-(V v)
{
for (int i = 0; i < V::SIZE; ++i)
v[i] = -v[i];
return v;
}
template <Vector V> constexpr bool operator==(V a, V b)
{
for (int i = 0; i < V::SIZE; ++i)
if (a[i] != b[i])
return false;
return true;
}
// Applies `function` to each component of a vector, or to a plain number.
template <class T, class F> constexpr T components_map(T a, F function)
{
if constexpr (Vector<T>)
{
for (int i = 0; i < T::SIZE; ++i)
a[i] = function(a[i]);
return a;
}
else
return function(a);
}
template <class T, class F> constexpr T components_map(T a, T b, F function)
{
if constexpr (Vector<T>)
{
for (int i = 0; i < T::SIZE; ++i)
a[i] = function(a[i], b[i]);
return a;
}
else
return function(a, b);
}
template <class T> struct VectorValue
{
using Type = T;
};
template <Vector V> struct VectorValue<V>
{
using Type = typename V::Value;
};
// A vector, or a number for every component.
template <class T> using Bound = std::type_identity_t<T>;
template <class T> constexpr T vec_min(T a, Bound<T> b)
{
return components_map(a, b, [](auto x, auto y) { return y < x ? y : x; });
}
template <class T> constexpr T vec_max(T a, Bound<T> b)
{
return components_map(a, b, [](auto x, auto y) { return x < y ? y : x; });
}
template <Vector V> constexpr V vec_min(V a, typename V::Value b)
{
return vec_min(a, V(b));
}
template <Vector V> constexpr V vec_max(V a, typename V::Value b)
{
return vec_max(a, V(b));
}
template <class T, class B> constexpr T vec_clamp(T value, B low, B high)
{
return vec_min(vec_max(value, low), high);
}
template <class T> constexpr T vec_mix(T a, T b, typename VectorValue<T>::Type amount)
{
return a * (1 - amount) + b * amount;
}
template <Vector V> constexpr V vec_mix(V a, V b, V amount)
{
return a * (V(1) - amount) + b * amount;
}
template <class T> T vec_floor(T v)
{
return components_map(v, [](auto x) { return std::floor(x); });
}
template <class T> T vec_ceil(T v)
{
return components_map(v, [](auto x) { return std::ceil(x); });
}
template <class T> T vec_round(T v)
{
return components_map(v, [](auto x) { return std::round(x); });
}
template <class T> T vec_abs(T v)
{
return components_map(v, [](auto x) { return std::abs(x); });
}
template <class T> constexpr T vec_sign(T v)
{
return components_map(v, [](auto x) { return (decltype(x))((0 < x) - (x < 0)); });
}
template <Vector V> constexpr typename V::Value vec_dot(V a, V b)
{
typename V::Value sum = 0;
for (int i = 0; i < V::SIZE; ++i)
sum += a[i] * b[i];
return sum;
}
template <Vector V> typename V::Value vec_length(V v)
{
return std::sqrt(vec_dot(v, v));
}
template <Vector V> typename V::Value vec_distance(V a, V b)
{
return vec_length(b - a);
}
template <Vector V> V vec_normalize(V v)
{
return v * (1 / std::sqrt(vec_dot(v, v)));
}
// Whether `point` lies in [low, high), each axis.
template <Vector V> constexpr bool is_within(V point, V low, V high)
{
for (int i = 0; i < V::SIZE; ++i)
if (point[i] < low[i] || !(point[i] < high[i]))
return false;
return true;
}
// Whether every component of `a` is at most the one of `b`.
template <Vector V> constexpr bool is_all_less_equal(V a, V b)
{
for (int i = 0; i < V::SIZE; ++i)
if (b[i] < a[i])
return false;
return true;
}
// Whether any component of `a` is at most the one of `b`.
template <Vector V> constexpr bool is_any_less_equal(V a, V b)
{
for (int i = 0; i < V::SIZE; ++i)
if (!(b[i] < a[i]))
return true;
return false;
}
constexpr float radians(float degrees)
{
return degrees * 0.01745329251994329576923690768489f;
}
constexpr float degrees(float radians)
{
return radians * 57.295779513082320876798154814105f;
}
struct Mat4
{
Vec4 columns[4];
constexpr Mat4() = default;
constexpr Mat4(Vec4 c0, Vec4 c1, Vec4 c2, Vec4 c3) : columns{c0, c1, c2, c3}
{}
explicit constexpr Mat4(float diagonal)
: columns{{diagonal, 0, 0, 0}, {0, diagonal, 0, 0}, {0, 0, diagonal, 0}, {0, 0, 0, diagonal}}
{}
constexpr Vec4& operator[](int i)
{
return columns[i];
}
constexpr Vec4 operator[](int i) const
{
return columns[i];
}
};
constexpr Vec4 operator*(const Mat4& m, Vec4 v)
{
return m[0] * v.x + m[1] * v.y + m[2] * v.z + m[3] * v.w;
}
constexpr Mat4 operator*(const Mat4& a, const Mat4& b)
{
Mat4 result;
for (int i = 0; i < 4; ++i)
result[i] = a * b[i];
return result;
}
constexpr Mat4& operator*=(Mat4& a, const Mat4& b)
{
return a = a * b;
}
constexpr bool operator==(const Mat4& a, const Mat4& b)
{
for (int i = 0; i < 4; ++i)
if (a[i] != b[i])
return false;
return true;
}
constexpr Mat4 mat4_translate(Mat4 m, Vec3 v)
{
m[3] = m[0] * v.x + m[1] * v.y + m[2] * v.z + m[3];
return m;
}
constexpr Mat4 mat4_scale(Mat4 m, Vec3 v)
{
m[0] *= v.x;
m[1] *= v.y;
m[2] *= v.z;
return m;
}
// Turns `m` by `angle` radians around the z axis.
inline Mat4 mat4_rotate(Mat4 m, float angle)
{
auto cosine = std::cos(angle);
auto sine = std::sin(angle);
auto column0 = m[0] * cosine + m[1] * sine;
m[1] = m[0] * -sine + m[1] * cosine;
m[0] = column0;
return m;
}
constexpr Mat4 mat4_ortho(float left, float right, float bottom, float top, float near, float far)
{
Mat4 result(1.0f);
result[0][0] = 2 / (right - left);
result[1][1] = 2 / (top - bottom);
result[2][2] = -2 / (far - near);
result[3][0] = -(right + left) / (right - left);
result[3][1] = -(top + bottom) / (top - bottom);
result[3][2] = -(far + near) / (far - near);
return result;
}
// The 2x2 minors of the bottom two rows, shared by the determinant and the inverse.
struct Mat4Minors
{
float s[6];
float c[6];
};
constexpr Mat4Minors mat4_minors_get(const Mat4& m)
{
return {{m[0][0] * m[1][1] - m[1][0] * m[0][1], m[0][0] * m[1][2] - m[1][0] * m[0][2],
m[0][0] * m[1][3] - m[1][0] * m[0][3], m[0][1] * m[1][2] - m[1][1] * m[0][2],
m[0][1] * m[1][3] - m[1][1] * m[0][3], m[0][2] * m[1][3] - m[1][2] * m[0][3]},
{m[2][2] * m[3][3] - m[3][2] * m[2][3], m[2][1] * m[3][3] - m[3][1] * m[2][3],
m[2][1] * m[3][2] - m[3][1] * m[2][2], m[2][0] * m[3][3] - m[3][0] * m[2][3],
m[2][0] * m[3][2] - m[3][0] * m[2][2], m[2][0] * m[3][1] - m[3][0] * m[2][1]}};
}
constexpr float mat4_determinant(const Mat4& m)
{
auto [s, c] = mat4_minors_get(m);
return s[0] * c[0] - s[1] * c[1] + s[2] * c[2] + s[3] * c[3] - s[4] * c[4] + s[5] * c[5];
}
constexpr Mat4 mat4_inverse(const Mat4& m)
{
auto [s, c] = mat4_minors_get(m);
auto inverse = 1 / (s[0] * c[0] - s[1] * c[1] + s[2] * c[2] + s[3] * c[3] - s[4] * c[4] + s[5] * c[5]);
Mat4 result;
result[0] =
Vec4(m[1][1] * c[0] - m[1][2] * c[1] + m[1][3] * c[2], -m[0][1] * c[0] + m[0][2] * c[1] - m[0][3] * c[2],
m[3][1] * s[5] - m[3][2] * s[4] + m[3][3] * s[3], -m[2][1] * s[5] + m[2][2] * s[4] - m[2][3] * s[3]);
result[1] =
Vec4(-m[1][0] * c[0] + m[1][2] * c[3] - m[1][3] * c[4], m[0][0] * c[0] - m[0][2] * c[3] + m[0][3] * c[4],
-m[3][0] * s[5] + m[3][2] * s[2] - m[3][3] * s[1], m[2][0] * s[5] - m[2][2] * s[2] + m[2][3] * s[1]);
result[2] =
Vec4(m[1][0] * c[1] - m[1][1] * c[3] + m[1][3] * c[5], -m[0][0] * c[1] + m[0][1] * c[3] - m[0][3] * c[5],
m[3][0] * s[4] - m[3][1] * s[2] + m[3][3] * s[0], -m[2][0] * s[4] + m[2][1] * s[2] - m[2][3] * s[0]);
result[3] =
Vec4(-m[1][0] * c[2] + m[1][1] * c[4] - m[1][2] * c[5], m[0][0] * c[2] - m[0][1] * c[4] + m[0][2] * c[5],
-m[3][0] * s[3] + m[3][1] * s[1] - m[3][2] * s[0], m[2][0] * s[3] - m[2][1] * s[1] + m[2][2] * s[0]);
for (auto& column : result.columns)
column *= inverse;
return result;
}
// The floats behind a vector or matrix, for OpenGL and ImGui.
template <Vector V> constexpr typename V::Value* values_get(V& v)
{
return &v.x;
}
template <Vector V> constexpr const typename V::Value* values_get(const V& v)
{
return &v.x;
}
constexpr float* values_get(Mat4& m)
{
return &m.columns[0].x;
}
constexpr const float* values_get(const Mat4& m)
{
return &m.columns[0].x;
}
+6 -6
View File
@@ -26,11 +26,11 @@ TEST_CASE("Image png round trip and uid tracking")
CHECK(copy.uid == image.uid);
copy.pixel_set({1, 1}, {1.0f, 1.0f, 1.0f, 1.0f});
CHECK(copy.uid != image.uid);
CHECK(copy.pixel_read({1, 1}) == glm::vec4(1.0f));
CHECK(copy.pixel_read({1, 1}) == Vec4(1.0f));
auto merged = Image::compose({{&image, {}, image.size, {}}, {&loaded, {}, loaded.size, {image.size.x, 0}}},
{image.size.x * 2, image.size.y}, false);
CHECK(merged.size == glm::ivec2(4, 2));
CHECK(merged.size == IVec2(4, 2));
CHECK(merged.pixel_read({2, 0}) == image.pixel_read({0, 0}));
}
@@ -66,13 +66,13 @@ TEST_CASE("an SVG spritesheet loads in SVG units and draws again at any scale")
Image image(TEST_DIR / "render" / "vector.svg");
REQUIRE(image.is_valid());
CHECK(image.is_vector());
CHECK(image.size == glm::ivec2(32, 16));
CHECK(image.size == IVec2(32, 16));
auto red = image.pixel_read({8.0f, 8.0f});
CHECK(red.r > 0.8f);
CHECK(red.b < 0.2f);
auto large = image.vector_render(4.0f);
CHECK(large.size == glm::ivec2(128, 64));
CHECK(large.size == IVec2(128, 64));
CHECK(large.unit_size_get() == image.unit_size_get());
CHECK(large.uid != image.uid);
}
@@ -88,7 +88,7 @@ TEST_CASE("SVG spritesheets compose into SVGs that draw the same")
REQUIRE(swapped.is_vector());
CHECK(swapped.size == vector.size);
CHECK(swapped.pixel_read({24.0f, 8.0f}) == vector.pixel_read({8.0f, 8.0f}));
CHECK(swapped.pixel_read({1.0f, 1.0f}) == glm::vec4());
CHECK(swapped.pixel_read({1.0f, 1.0f}) == Vec4());
// A PNG part is embedded as an image, pixel for pixel. Composing the result again still works.
const std::vector<uint8_t> pixels = {255, 0, 0, 255, 0, 255, 0, 255, 0, 0, 255, 255, 255, 255, 255, 255};
@@ -115,7 +115,7 @@ TEST_CASE("an SVG's shapes meet without a seam")
REQUIRE(image.is_vector());
auto seam = image.pixel_read({10.0f, 2.0f});
CHECK(seam.a == 1.0f);
CHECK(glm::distance(glm::vec3(seam), glm::vec3(image.pixel_read({5.0f, 2.0f}))) < 2.0f / 255.0f);
CHECK(vec_distance(Vec3(seam), Vec3(image.pixel_read({5.0f, 2.0f}))) < 2.0f / 255.0f);
CHECK(image.pixel_read({20.0f, 2.0f}).a < 1.0f);
}
+13 -14
View File
@@ -19,7 +19,7 @@ TEST_CASE("draw lists put the root first and each item's onion samples before it
auto layerDraws = std::ranges::count_if(
draws, [](const Draw& draw) { return draw.type == DrawType::LAYER && draw.sample == -1; });
CHECK(layerDraws > 0);
CHECK(animation_rect(anm2, animation, true) != glm::vec4(-1.0f));
CHECK(animation_rect(anm2, animation, true) != Vec4(-1.0f));
}
TEST_CASE("root transforms fold into layer draws")
@@ -82,27 +82,27 @@ TEST_CASE("an animation layer draws its child animation, from this file or a lib
auto spin = model_load(file_load(TEST_DIR / "render" / "spin.anm2"));
DrawOptions options = {.library_get = [&](const Model&, int id) { return id == 0 ? &spin : nullptr; }};
auto red_position_get = [&](int layerId) {
std::optional<glm::vec2> position{};
std::optional<Vec2> position{};
for (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));
if (draw.type == DrawType::LAYER && draw.id == layerId && draw.frame.crop == Vec2())
position = Vec2(draw.parent * Vec4(draw.frame.position, 0.0f, 1.0f));
return position;
};
// The library's red square, half size at (40, 0), starts on its fifth frame (at x 16).
CHECK(red_position_get(0) == glm::vec2(48.0f, 0.0f));
CHECK(red_position_get(0) == Vec2(48.0f, 0.0f));
// This file's Inner holds its first frame however far the parent plays.
options.time = 1.0f;
CHECK(red_position_get(1) == glm::vec2(-40.0f, 0.0f));
CHECK(red_position_get(1) == Vec2(-40.0f, 0.0f));
// An animation never draws inside itself.
CHECK_FALSE(red_position_get(3));
// Once stops on the child's last frame. Loop wraps around it.
options.time = 6.0f;
anm2.frame_edit({0, LAYER, 1, 0})->childMode = ChildMode::ONCE;
CHECK(red_position_get(1) == glm::vec2(-40.0f, 10.0f));
CHECK(red_position_get(1) == Vec2(-40.0f, 10.0f));
anm2.frame_edit({0, LAYER, 1, 0})->childMode = ChildMode::LOOP;
CHECK(red_position_get(1) == glm::vec2(-40.0f, 0.0f));
CHECK(red_position_get(1) == Vec2(-40.0f, 0.0f));
// Without the library loaded, its layer draws nothing.
options.library_get = {};
@@ -172,12 +172,11 @@ TEST_CASE("flattening animation layers bakes their children into plain layers th
// Every frame, the plain layers draw where the animation layers' children did.
auto points_get = [&](const Model& model, const LibraryGet& get, float time) {
std::vector<glm::vec2> points{};
std::vector<Vec2> points{};
for (auto& draw : 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); });
points.push_back(vec_round(Vec2(draw.parent * draw_quad_model_get(draw) * Vec4(1, 1, 0, 1))));
std::ranges::sort(points, [](Vec2 a, 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)
@@ -205,7 +204,7 @@ 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 = 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(Vec2(*placement * Vec4(16.0f, 0.0f, 0.0f, 1.0f)) == Vec2(48.0f, 0.0f));
CHECK_FALSE(layer_child_transform_get(*anm2.animation_get(0), 99, 0.0f, true));
}
@@ -223,7 +222,7 @@ TEST_CASE("the game's copy stands in for depth and alpha offsets")
// Every frame, the same crops draw in the same order and places, with no depth left.
auto draws_get = [](const Model& model, float time) {
std::vector<std::pair<glm::vec2, glm::vec2>> draws{};
std::vector<std::pair<Vec2, Vec2>> draws{};
for (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);
+23 -23
View File
@@ -109,27 +109,27 @@ TEST_CASE("frame_bake and frame_mix")
to.rotation = 90.0f;
to.tint = {0.0f, 1.0f, 1.0f, 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.position == Vec2(5.0f, -10.0f));
CHECK(from.skew == Vec2(15.0f, 0.0f));
CHECK(from.rotation == doctest::Approx(45.0f));
CHECK(from.tint.a == doctest::Approx(0.75f));
}
TEST_CASE("rects_pack fits every rect without overlap")
{
std::vector<glm::ivec2> sizes{{16, 16}, {32, 8}, {8, 32}, {5, 7}, {64, 1}, {1, 1}};
glm::ivec2 size{};
std::vector<glm::ivec2> positions{};
std::vector<IVec2> sizes{{16, 16}, {32, 8}, {8, 32}, {5, 7}, {64, 1}, {1, 1}};
IVec2 size{};
std::vector<IVec2> positions{};
REQUIRE(rects_pack(sizes, size, positions));
REQUIRE(positions.size() == sizes.size());
for (std::size_t i = 0; i < sizes.size(); ++i)
{
CHECK(glm::all(glm::greaterThanEqual(positions[i], glm::ivec2(0))));
CHECK(glm::all(glm::lessThanEqual(positions[i] + sizes[i], size)));
CHECK(is_all_less_equal(IVec2(0), positions[i]));
CHECK(is_all_less_equal(positions[i] + sizes[i], size));
for (std::size_t j = i + 1; j < sizes.size(); ++j)
{
auto isSeparate = glm::any(glm::lessThanEqual(positions[i] + sizes[i], positions[j])) ||
glm::any(glm::lessThanEqual(positions[j] + sizes[j], positions[i]));
auto isSeparate = is_any_less_equal(positions[i] + sizes[i], positions[j]) ||
is_any_less_equal(positions[j] + sizes[j], positions[i]);
CHECK(isSeparate);
}
}
@@ -234,7 +234,7 @@ TEST_CASE("edit layer operations")
TEST_CASE("spritesheet pixel edits")
{
auto image_make = [](glm::ivec2 size, std::vector<glm::ivec2> opaque = {}) {
auto image_make = [](IVec2 size, std::vector<IVec2> opaque = {}) {
std::vector<uint8_t> 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) * IMAGE_CHANNELS, IMAGE_CHANNELS,
@@ -249,9 +249,9 @@ TEST_CASE("spritesheet pixel edits")
auto model = fixture_load("05_regions.anm2");
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));
CHECK(region->crop == Vec2(4, 6));
CHECK(region->size == Vec2(1, 1));
CHECK(region->pivot == Vec2(-1, -1));
}
SUBCASE("spritesheet_pack returns an image holding every region")
@@ -261,7 +261,7 @@ TEST_CASE("spritesheet pixel edits")
REQUIRE(packed);
CHECK(packed->is_valid());
for (auto& region : model.content.spritesheets[0].regions)
CHECK(glm::all(glm::lessThanEqual(glm::ivec2(region.crop + region.size), packed->size)));
CHECK(is_all_less_equal(IVec2(region.crop + region.size), packed->size));
}
SUBCASE("spritesheets_merge appends images and moves layers onto the base sheet")
@@ -272,7 +272,7 @@ TEST_CASE("spritesheet pixel edits")
};
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(merged->size == IVec2(80, 64));
CHECK(model.content.spritesheets.size() == 1);
CHECK(item_get(model.content.layers, 1)->spritesheetId == 0);
operation_check("spritesheets_merge", model);
@@ -287,7 +287,7 @@ TEST_CASE("markers stay in the editor's copy and bound playback")
animation->frameNum = 10;
animation->startMarker = 2;
animation->endMarker = 5;
CHECK(animation_play_range_get(*animation) == glm::ivec2(2, 6));
CHECK(animation_play_range_get(*animation) == IVec2(2, 6));
auto text = model_to_string(model);
CHECK(game_document_get(text).find("Marker") == std::string::npos);
@@ -325,11 +325,11 @@ TEST_CASE("frames_property_set copies one property to the frames that have it")
auto nullCrop = model.frame_get(null)->crop;
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));
CHECK(model.frame_get(layer)->position == Vec2(3, 4));
CHECK(model.frame_get(null)->position == Vec2(3, 4));
frames_property_set(model, {layer, null}, FrameProperty::CROP, source);
CHECK(model.frame_get(layer)->crop == glm::vec2(7, 8));
CHECK(model.frame_get(layer)->crop == Vec2(7, 8));
CHECK(model.frame_get(null)->crop == nullCrop);
CHECK_FALSE(is_frame_property_valid(FrameProperty::EVENT, ItemType::LAYER));
@@ -418,7 +418,7 @@ TEST_CASE("skew reads from the old Shear attributes too")
{
auto frames = frames_from_string(R"(<Frame ShearX="5" ShearY="6"/><Frame SkewX="7" ShearX="9"/>)", ItemType::NULL_);
REQUIRE(frames.size() == 2);
CHECK(frames[0].skew == glm::vec2(5, 6));
CHECK(frames[0].skew == Vec2(5, 6));
CHECK(frames[1].skew.x == 7);
CHECK(frames[0].extras.attributes.empty());
}
@@ -445,10 +445,10 @@ TEST_CASE("SVG spritesheets pack and merge into SVGs")
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)}})
for (auto [id, original] : {std::pair{0, Vec2(8, 8)}, std::pair{1, Vec2(24, 8)}})
{
auto region = item_get(model.content.spritesheets.front().regions, id);
CHECK(packed->pixel_read(region->crop + glm::vec2(8, 8)) == vector.pixel_read(original));
CHECK(packed->pixel_read(region->crop + 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.
@@ -463,7 +463,7 @@ TEST_CASE("SVG spritesheets pack and merge into SVGs")
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));
CHECK(merged->size == IVec2(36, 16));
CHECK(merged->pixel_read({33, 1}) == raster.pixel_read({1, 1}));
CHECK(mixed.content.spritesheets.front().path == "vector.svg");
+19 -21
View File
@@ -23,7 +23,7 @@ const std::filesystem::path OUTPUT_DIR = ANM2ED_RENDER_DIR;
constexpr int CHANNEL_TOLERANCE = 8;
constexpr double MISMATCH_RATIO_MAX = 0.01;
constexpr float SCALE = 3.0f;
constexpr glm::vec4 BACKGROUND = {0.2f, 0.2f, 0.2f, 1.0f};
constexpr Vec4 BACKGROUND = {0.2f, 0.2f, 0.2f, 1.0f};
// Different OpenGL implementations round a little differently: a few pixels may differ, each only slightly.
static void golden_image_check(const std::string& name)
@@ -53,7 +53,7 @@ struct RenderFixture
std::optional<ShaderProgram> shader;
std::optional<Canvas> canvas;
const Animation* animation = nullptr;
glm::vec4 bounds{};
Vec4 bounds{};
explicit RenderFixture(const char* file)
{
@@ -63,7 +63,7 @@ struct RenderFixture
document.emplace(RENDER_TEST_DIR / file, false);
auto& info = SHADERS[SHADER_TEXTURE];
shader.emplace(info.vertex, info.fragment);
canvas.emplace(glm::vec2(1.0f));
canvas.emplace(Vec2(1.0f));
animation = document->model.animation_get(0);
bounds = animation_bounds_get(*document, *animation, true);
}
@@ -76,9 +76,9 @@ struct RenderFixture
return pixels;
}
glm::u8vec4 pixel_get(const std::vector<uint8_t>& pixels, glm::vec2 point)
TVec4<uint8_t> pixel_get(const std::vector<uint8_t>& pixels, Vec2 point)
{
auto position = glm::ivec2((point - glm::vec2(bounds.x, bounds.y)) * SCALE);
auto position = IVec2((point - Vec2(bounds.x, bounds.y)) * SCALE);
auto index = ((std::size_t)position.y * (std::size_t)canvas->size.x + (std::size_t)position.x) * 4;
return {pixels[index], pixels[index + 1], pixels[index + 2], pixels[index + 3]};
}
@@ -106,7 +106,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(Image::write_pixels_png(framePath, glm::ivec2(fixture.canvas->size), pixels.data()));
REQUIRE(Image::write_pixels_png(framePath, IVec2(fixture.canvas->size), pixels.data()));
golden_image_check("spin_frame_0.png");
}
@@ -129,7 +129,7 @@ TEST_CASE("a recorded spritesheet holds every frame")
fixture.bounds, SCALE, BACKGROUND, true));
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));
CHECK(sheet.size == IVec2(fixture.canvas->size) * IVec2(layout.columns, layout.rows));
golden_image_check("spin_sheet.png");
}
@@ -146,15 +146,14 @@ TEST_CASE("animation layers draw their child animations")
// The library's red square at half size starts on its fifth frame, centered at (48, 0). This file's Inner holds its
// red square at (-40, 0).
auto pixels = fixture.frame_get(0.0f);
for (auto point : {glm::vec2(48.0f, 0.0f), glm::vec2(-40.0f, 0.0f)})
for (auto point : {Vec2(48.0f, 0.0f), Vec2(-40.0f, 0.0f)})
{
auto red = fixture.pixel_get(pixels, point);
CHECK(red.r > 200);
CHECK(red.g < 80);
}
REQUIRE(
Image::write_pixels_png(OUTPUT_DIR / "nested_frame_0.png", glm::ivec2(fixture.canvas->size), pixels.data()));
REQUIRE(Image::write_pixels_png(OUTPUT_DIR / "nested_frame_0.png", IVec2(fixture.canvas->size), pixels.data()));
golden_image_check("nested_frame_0.png");
}
@@ -170,7 +169,7 @@ TEST_CASE("a blurred layer spreads past its crop like Flash's blur filter")
// The red square (16 x 16 at (-16, 0)) sharp leaves the canvas clear 2 above its top edge and solid 1 inside it. An
// 8 pixel box spreads a third of it out and takes as much from inside.
constexpr glm::vec2 OUTSIDE{-20.0f, -10.0f}, INSIDE{-20.0f, -7.0f};
constexpr Vec2 OUTSIDE{-20.0f, -10.0f}, INSIDE{-20.0f, -7.0f};
auto sharp = fixture.frame_get(0.0f);
fixture.document->model.frame_edit({0, LAYER, 0, 0})->blur = 8.0f;
fixture.animation = fixture.document->model.animation_get(0);
@@ -178,8 +177,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(Image::write_pixels_png(OUTPUT_DIR / "spin_blur_frame_0.png", glm::ivec2(fixture.canvas->size),
blurred.data()));
REQUIRE(Image::write_pixels_png(OUTPUT_DIR / "spin_blur_frame_0.png", IVec2(fixture.canvas->size), blurred.data()));
}
TEST_CASE("SVG spritesheets draw sharp at any scale")
@@ -200,8 +198,7 @@ TEST_CASE("SVG spritesheets draw sharp at any scale")
CHECK(inside.r > 200);
CHECK(outside.r < 80);
REQUIRE(
Image::write_pixels_png(OUTPUT_DIR / "vector_frame_0.png", glm::ivec2(fixture.canvas->size), pixels.data()));
REQUIRE(Image::write_pixels_png(OUTPUT_DIR / "vector_frame_0.png", IVec2(fixture.canvas->size), pixels.data()));
golden_image_check("vector_frame_0.png");
}
@@ -299,7 +296,7 @@ TEST_CASE("the game's copy bakes skew and blur into a spritesheet that draws the
auto& info = SHADERS[SHADER_TEXTURE];
ShaderProgram shader(info.vertex, info.fragment);
Canvas canvas(glm::vec2(1.0f));
Canvas canvas(Vec2(1.0f));
for (int index = 0; index < document.model.animations_count_get(); ++index)
{
auto& animation = *document.model.animation_get(index);
@@ -307,14 +304,14 @@ TEST_CASE("the game's copy bakes skew and blur into a spritesheet that draws the
INFO("animation: ", animation.name);
// On whole pixels, so the baked images land on the pixels they were drawn on.
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);
bounds = Vec4(vec_floor(Vec2(bounds)) - 8.0f, vec_ceil(Vec2(bounds.z, bounds.w)) + 16.0f);
for (int time = 0; time < animation.frameNum; ++time)
{
INFO("time: ", time);
auto expected = animation_frame_render(canvas, shader, document, animation, (float)time, bounds, 1.0f,
glm::vec4(0.0f), true);
Vec4(0.0f), true);
auto actual = animation_frame_render(canvas, shader, gameDocument, gameAnimation, (float)time, bounds, 1.0f,
glm::vec4(0.0f), true);
Vec4(0.0f), true);
REQUIRE(actual.size() == expected.size());
CHECK(std::ranges::any_of(expected, [](uint8_t channel) { return channel != 0; }));
int mismatches = 0;
@@ -344,8 +341,9 @@ TEST_CASE("audio decodes and mixes")
constexpr int FREQUENCY = 22050;
constexpr int FRAMES = 100;
std::vector<unsigned char> wav = {'R', 'I', 'F', 'F', 0, 0, 0, 0, 'W', 'A', 'V', 'E', 'f', 'm', 't', ' ', 16, 0, 0, 0,
1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 16, 0, 'd', 'a', 't', 'a', 0, 0, 0, 0};
std::vector<unsigned char> wav = {'R', 'I', 'F', 'F', 0, 0, 0, 0, 'W', 'A', 'V', 'E', 'f', 'm', 't',
' ', 16, 0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0,
0, 0, 2, 0, 16, 0, 'd', 'a', 't', 'a', 0, 0, 0, 0};
auto put = [&](int offset, std::uint32_t value, int size) {
for (int i = 0; i < size; ++i)
wav[offset + i] = (unsigned char)(value >> (i * 8));