Add ruby bindings for internal structures, allow better controlled localization

This commit is contained in:
2026-05-06 22:01:48 +01:00
parent 3894b90398
commit 65109cc3c4
8 changed files with 1047 additions and 114 deletions
+33 -12
View File
@@ -16,6 +16,7 @@ struct Element {
Vec2<float> position = {0, 0}; Vec2<float> position = {0, 0};
float rotation = 0; float rotation = 0;
Vec2<float> scale = {1, 1}; Vec2<float> scale = {1, 1};
float alpha = 1.0f;
float z = 0; float z = 0;
bool click_through = false; bool click_through = false;
Ruby::Block on_click; Ruby::Block on_click;
@@ -56,28 +57,38 @@ struct EImage : Element {
return; return;
int frame_index = (int)((abs_time * animation.frame_rate) / 1000) % animation.frames.size(); int frame_index = (int)((abs_time * animation.frame_rate) / 1000) % animation.frames.size();
window.draw(animation.frames[frame_index], position, z, rotation, scale); window.draw(animation.frames[frame_index], position, z, rotation, scale, alpha);
} }
}; };
struct EText : Element { struct EText : Element {
Localization::Key key; Localization::Key key;
uint64_t font_id = UINT64_MAX; uint64_t font_id = UINT64_MAX;
Color color = {255, 255, 255};
mrb_value params = mrb_nil_value();
~EText() { ~EText() {
if (text_id != UINT64_MAX) if (text_id != UINT64_MAX)
text_pool.release(text_id); text_pool.release(text_id);
if (font_id != UINT64_MAX) if (font_id != UINT64_MAX)
font_pool.release(font_id); font_pool.release(font_id);
if (!mrb_nil_p(params))
mrb_gc_unregister(Ruby::mrb, params);
} }
Color color = {255, 255, 255, 255}; EText(Localization::Key key, uint64_t font_id, Color color, mrb_value params)
: Element(Type::TEXT), key(key), font_id(font_id), color(color), params(params) {
EText(Localization::Key key, uint64_t font_id, Color color) if (!mrb_nil_p(params))
: Element(Type::TEXT), key(key), font_id(font_id), color(color) { mrb_gc_protect(Ruby::mrb, params);
font_pool.use(font_id); font_pool.use(font_id);
} }
void reload_params() {
// Force re-render by resetting last_key (without affecting this frame)
// this can be changed to use a dirty flag or version counter if needed
last_key = UINT16_MAX;
}
Vec2<float> size(Window *window) override { Vec2<float> size(Window *window) override {
if (text_id == UINT64_MAX) if (text_id == UINT64_MAX)
return {0, 0}; return {0, 0};
@@ -85,26 +96,32 @@ struct EText : Element {
}; };
void render(Window &window, uint64_t) override { void render(Window &window, uint64_t) override {
if (last_language != Localization::current_language || last_key != key || text_id == UINT64_MAX) { if (
std::string localized_str = Localization::get(key); last_language != Localization::current_language
|| last_key != key || text_id == UINT64_MAX
|| last_color != color
) {
std::string localized_str = Localization::get(Ruby::mrb, key, params);
if (text_id != UINT64_MAX) if (text_id != UINT64_MAX)
text_pool.release(text_id); text_pool.release(text_id);
text_id = window.create_text(font_id, localized_str.c_str(), localized_str.size(), color); text_id = window.create_text(font_id, localized_str.c_str(), localized_str.size(), color);
last_language = Localization::current_language; last_language = Localization::current_language;
last_key = key; last_key = key;
last_color = color;
} }
window.write(text_id, position, z, rotation, scale); window.write(text_id, position, z, rotation, scale, alpha);
} }
private: private:
uint64_t text_id = UINT64_MAX; uint64_t text_id = UINT64_MAX;
Localization::LanguageCode last_language = UINT_MAX; Color last_color = color;
Localization::Key last_key = UINT_MAX; Localization::LanguageCode last_language = UINT32_MAX;
Localization::Key last_key = UINT16_MAX;
}; };
struct ERect : Element { struct ERect : Element {
Vec2<float> shape = {0, 0}; Vec2<float> shape = {0, 0};
Color color = {255, 255, 255, 255}; Color color = {255, 255, 255};
Vec2<float> size(Window *) override { Vec2<float> size(Window *) override {
return shape; return shape;
}; };
@@ -112,7 +129,7 @@ struct ERect : Element {
ERect(Vec2<float> shape, Color color) : Element(Type::RECT), shape(shape), color(color) {} ERect(Vec2<float> shape, Color color) : Element(Type::RECT), shape(shape), color(color) {}
void render(Window &window, uint64_t) override { void render(Window &window, uint64_t) override {
window.draw_rect(Rect::from_size(position, shape), color, z, rotation); window.draw_rect(Rect::from_size(position, shape), color, z, rotation, scale, alpha);
} }
}; };
@@ -195,6 +212,10 @@ struct App {
bool running = true; bool running = true;
Vec2<float> mouse_position = {-1, -1}; Vec2<float> mouse_position = {-1, -1};
void exit() {
running = false;
}
void switch_to_scene(uint64_t scene_id) { void switch_to_scene(uint64_t scene_id) {
scene_pool.release(current_scene_id); scene_pool.release(current_scene_id);
scene_pool.use(scene_id); scene_pool.use(scene_id);
File diff suppressed because it is too large Load Diff
+2
View File
@@ -94,6 +94,8 @@ DEF_SYM(bold)
DEF_SYM(italic) DEF_SYM(italic)
DEF_SYM(underline) DEF_SYM(underline)
DEF_SYM(position) DEF_SYM(position)
DEF_SYM(rotation)
DEF_SYM(scale)
DEF_SYM(alpha) DEF_SYM(alpha)
DEF_SYM(fps) DEF_SYM(fps)
DEF_SYM(click_through) DEF_SYM(click_through)
+82 -8
View File
@@ -17,20 +17,87 @@ inline JoinedKey join_keys(LanguageCode lang_code, Key loc_key) {
return (static_cast<JoinedKey>(lang_code) << 16) | loc_key; return (static_cast<JoinedKey>(lang_code) << 16) | loc_key;
} }
inline std::unordered_map<JoinedKey, std::string> localized_strings; struct Segment {
bool is_var;
std::string text;
};
inline std::string get(Key key) { inline std::unordered_map<JoinedKey, std::vector<Segment>> localized_strings;
auto it = localized_strings.find(join_keys(current_language, key)); inline std::unordered_map<std::string, mrb_sym> var_sym_cache;
if (it != localized_strings.end())
inline mrb_sym get_var_sym(mrb_state *mrb, const std::string &name) {
auto it = var_sym_cache.find(name);
if (it != var_sym_cache.end())
return it->second; return it->second;
for (const auto &[joined, value] : localized_strings) { mrb_sym sym = mrb_intern_cstr(mrb, name.c_str());
Key k = (Key)(joined & 0xFFFF); var_sym_cache[name] = sym;
if (k == key) return sym;
return value; }
inline std::vector<Segment> parse_localized(const std::string &input) {
std::vector<Segment> out;
size_t i = 0;
while (i < input.size()) {
size_t start = input.find("%{", i);
if (start == std::string::npos) {
out.push_back({false, input.substr(i)});
break;
} }
if (start > i) {
out.push_back({false, input.substr(i, start - i)});
}
size_t end = input.find("}", start);
if (end == std::string::npos) {
// malformed fallback
out.push_back({false, input.substr(start)});
break;
}
std::string var = input.substr(start + 2, end - (start + 2));
out.push_back({true, var});
i = end + 1;
}
return out;
}
inline void set(LanguageCode lang_code, Key key, const std::string &text) {
localized_strings[join_keys(lang_code, key)] = parse_localized(text);
}
inline std::string get(mrb_state *mrb, Key key, mrb_value hash) {
auto it = localized_strings.find(join_keys(current_language, key));
if (it == localized_strings.end())
return "Localization not set!"; return "Localization not set!";
const auto &entry = it->second;
std::string result;
result.reserve(10);
for (const auto &seg : entry) {
if (!seg.is_var) {
result += seg.text;
} else {
mrb_sym sym = get_var_sym(mrb, seg.text);
if (mrb_nil_p(hash) || mrb_nil_p(mrb_hash_get(mrb, hash, mrb_symbol_value(sym)))) {
result += "%{" + seg.text + "}";
continue;
}
mrb_value val = mrb_hash_get(mrb, hash, mrb_symbol_value(sym));
if (mrb_nil_p(val))
continue;
result += mrb_str_to_cstr(mrb, val);
}
}
return result;
} }
inline LanguageCode lang_from_sym(mrb_state *mrb, mrb_sym sym) { inline LanguageCode lang_from_sym(mrb_state *mrb, mrb_sym sym) {
@@ -49,6 +116,13 @@ inline LanguageCode lang_from_sym(mrb_state *mrb, mrb_sym sym) {
return code; return code;
} }
inline mrb_sym lang_to_sym(mrb_state *mrb, LanguageCode code) {
char s[5] = {0};
for (int i = 0; i < 4; ++i)
s[i] = (code >> (8 * (3 - i))) & 0xFF;
return mrb_intern_cstr(mrb, s);
}
inline Key key_from_sym(mrb_state *mrb, mrb_sym sym) { inline Key key_from_sym(mrb_state *mrb, mrb_sym sym) {
const char *key_name = mrb_sym2name(mrb, sym); const char *key_name = mrb_sym2name(mrb, sym);
+5 -1
View File
@@ -9,7 +9,11 @@
#define UNUSED(x) (void)(x) #define UNUSED(x) (void)(x)
struct Color { struct Color {
uint8_t r, g, b = 0, a = 255; uint8_t r, g, b = 0;
bool operator!=(const Color &other) const {
return r != other.r || g != other.g || b != other.b;
}
}; };
template <typename T> template <typename T>
+6 -7
View File
@@ -83,8 +83,6 @@ struct Event {
struct Animation { struct Animation {
std::vector<uint64_t> frames; std::vector<uint64_t> frames;
float frame_rate; float frame_rate;
bool loop;
int reference_count = 0;
~Animation() { ~Animation() {
for (uint64_t frame_id : frames) for (uint64_t frame_id : frames)
@@ -104,20 +102,20 @@ public:
~Window(); ~Window();
// Rendering functions // Rendering functions
uint64_t load_image(const char *path, float alpha = 1.0f, bool pixel_art = false); uint64_t load_image(const char *path, bool pixel_art);
Vec2<float> get_image_size(uint64_t image_id); Vec2<float> get_image_size(uint64_t image_id);
uint64_t load_font(const char *path, int font_size, bool bold = false, bool italic = false, bool underline = false, bool pixel_art = false); uint64_t load_font(const char *path, int font_size, bool bold, bool italic, bool underline, bool pixel_art);
// text is copied internally, so it can be free'd by the caller after the text is created. // text is copied internally, so it can be free'd by the caller after the text is created.
uint64_t create_text(uint64_t font_id, const char *text, uint32_t length, Color color); uint64_t create_text(uint64_t font_id, const char *text, uint32_t length, Color color);
Vec2<float> get_text_size(uint64_t text_id); Vec2<float> get_text_size(uint64_t text_id);
bool write(uint64_t text_id, Vec2<float> position, float z, float angle = 0.0f, Vec2<float> scale = {1.0f, 1.0f}); bool write(uint64_t text_id, Vec2<float> position, float z, float angle, Vec2<float> scale, float alpha);
bool draw(uint64_t image_id, Vec2<float> position, float z, float angle = 0.0f, Vec2<float> scale = {1.0f, 1.0f}); bool draw(uint64_t image_id, Vec2<float> position, float z, float angle, Vec2<float> scale, float alpha);
bool draw_rect(Rect rect, Color color, float z, float angle = 0.0f); bool draw_rect(Rect rect, Color color, float z, float angle, Vec2<float> scale, float alpha);
void render(); // the rest of the calls only build the instruction list, this actually renders everything added to the screen (following z order) void render(); // the rest of the calls only build the instruction list, this actually renders everything added to the screen (following z order)
@@ -170,6 +168,7 @@ private:
float z; float z;
float angle; float angle;
Vec2<float> scale; Vec2<float> scale;
float alpha;
union { union {
struct { struct {
+17 -22
View File
@@ -4,33 +4,35 @@ main_scene = Scene.new
default_font = Font.new "assets/fonts/charybdis.ttf", 24, pixel_art: true default_font = Font.new "assets/fonts/charybdis.ttf", 24, pixel_art: true
bg_image1 = Image.new "assets/images/menu_bg.png", alpha: 0.7, pixel_art: true bg_image1 = Image.new "assets/images/menu_bg.png", pixel_art: true
bg_image2 = Image.new "assets/images/game_over_dead_bg.png", alpha: 1, pixel_art: true bg_image2 = Image.new "assets/images/game_over_dead_bg.png", pixel_art: true
bg_animation = Animation.new [bg_image1, bg_image2], fps: 5 bg_animation = Animation.new [bg_image1, bg_image2], fps: 5
App.language = :en App.language = :en
App.localize(:en, :btn_text, "Click me!") App.localize(:en, :btn_text, "Click %{name}!")
text = ElementText.new :btn_text, default_font, position: {x: 50, y: 50}, z: 1, click_through: true text = ElementText.new :btn_text, default_font, 0xFFFFFF, {name: "Me"}, position: {x: 50, y: 50}, z: 1, click_through: true, alpha: 1
rect = ElementRect.new({x: 50, y: 50, w: 100, h: 25}, 0xFF0000FF, z: 0) rect = ElementRect.new 100, 25, 0xFF0000, position: {x: 50, y: 50}, z: 0, rotation: 60, scale: { x: 1.5, y: 1 }, alpha: 0.4
image_element = ElementImage.new bg_animation, position: {x: 0, y: 0}, z: -1, click_through: true image_element = ElementImage.new bg_animation, position: {x: 0, y: 0}, z: -1, click_through: true, alpha: 1
rect.on_click do rect.on_click do
rect.color = rect.color == 0xFF0000FF ? rect.color = rect.color == 0xFF0000 ?
0x00FF00FF 0x00FF00 :
: 0xFF0000
0xFF0000FF text.params[:name] = text.params[:name] == "Me" ?
"You" :
"Me"
text.params!
end end
=begin =begin
input handling: input handling:
on_click - exists to simplify on elements, not the standard way.
App.map_key(:space, :jump) # maps the space key to a :jump action (multiple keys can be mapped to the same action) App.map_key(:space, :jump) # maps the space key to a :jump action (multiple keys can be mapped to the same action)
# all events here are in english ones, (so need to find which english key corresponds to the key in the current language of the keyboard) # all events here are in english ones, (so need to find which english key corresponds to the key in the current language of the keyboard)
key can be one of [:a..:z, :0..:9, :space, :enter, :shift, :ctrl, :alt, :tab, :backspace, :escape, :up, :down, :left, :right, :middle] key can be one of [:a..:z, :0..:9, :space, :enter, :shift, :ctrl, :alt, :tab, :backspace, :escape, :up, :down, :left, :right, :middle]
@@ -58,16 +60,9 @@ App.text_input # returns the text typed this frame as a string (useful for text
App.stop_text_input! App.stop_text_input!
####
also in a scene you can use (with click_though semantics):
main_scene.elements_at(x, y)
=end =end
main_scene.on_update do |delta_time| main_scene.on_update do |delta_time|
# puts "Delta time: #{delta_time}ms" # puts "Delta time: #{delta_time}ms"
# commented out to avoid spamming the console, but you can uncomment to see the delta time being printed every frame # commented out to avoid spamming the console, but you can uncomment to see the delta time being printed every frame
@@ -76,11 +71,11 @@ main_scene.on_update do |delta_time|
el = main_scene.elements_at(App.mouse_position) el = main_scene.elements_at(App.mouse_position)
for elem in el for elem in el
if elem == image_element if elem == image_element
puts "Hovering over image element" #puts "Hovering over image element"
elsif elem == rect elsif elem == rect
puts "Hovering over rect element" #puts "Hovering over rect element"
elsif elem == text elsif elem == text
puts "Hovering over text element" #puts "Hovering over text element"
end end
end end
+16 -11
View File
@@ -56,7 +56,7 @@ Window::~Window() {
SDL_Quit(); SDL_Quit();
} }
uint64_t Window::load_image(const char *path, float alpha, bool pixel_art) { uint64_t Window::load_image(const char *path, bool pixel_art) {
SDL_Texture *texture = IMG_LoadTexture(renderer, path); SDL_Texture *texture = IMG_LoadTexture(renderer, path);
if (pixel_art) { if (pixel_art) {
@@ -68,8 +68,6 @@ uint64_t Window::load_image(const char *path, float alpha, bool pixel_art) {
return UINT64_MAX; return UINT64_MAX;
} }
SDL_SetTextureAlphaMod(texture, (uint8_t)(alpha * 255));
float w, h; float w, h;
SDL_GetTextureSize(texture, &w, &h); SDL_GetTextureSize(texture, &w, &h);
@@ -119,7 +117,7 @@ uint64_t Window::create_text(uint64_t font_id, const char *text, uint32_t length
return UINT64_MAX; return UINT64_MAX;
} }
SDL_Color sdl_color = {color.r, color.g, color.b, color.a}; SDL_Color sdl_color = {color.r, color.g, color.b, 255};
SDL_Surface *surface = TTF_RenderText_Solid(font_pool[font_id]->font, text, length, sdl_color); SDL_Surface *surface = TTF_RenderText_Solid(font_pool[font_id]->font, text, length, sdl_color);
if (surface == nullptr) { if (surface == nullptr) {
@@ -157,7 +155,7 @@ Vec2<float> Window::get_text_size(uint64_t text_id) {
return text_pool[text_id]->size; return text_pool[text_id]->size;
} }
bool Window::write(uint64_t text_id, Vec2<float> position, float z, float angle, Vec2<float> scale) { bool Window::write(uint64_t text_id, Vec2<float> position, float z, float angle, Vec2<float> scale, float alpha) {
if (!text_pool.is_valid(text_id)) { if (!text_pool.is_valid(text_id)) {
fprintf(stderr, "(Write) Invalid text ID: %llu\n", (unsigned long long)text_id); fprintf(stderr, "(Write) Invalid text ID: %llu\n", (unsigned long long)text_id);
return false; return false;
@@ -168,6 +166,7 @@ bool Window::write(uint64_t text_id, Vec2<float> position, float z, float angle,
.z = z, .z = z,
.angle = angle, .angle = angle,
.scale = scale, .scale = scale,
.alpha = alpha,
.draw_text = { .draw_text = {
.text_id = text_id, .text_id = text_id,
.position = position, .position = position,
@@ -177,7 +176,7 @@ bool Window::write(uint64_t text_id, Vec2<float> position, float z, float angle,
return true; return true;
}; };
bool Window::draw(uint64_t image_id, Vec2<float> position, float z, float angle, Vec2<float> scale) { bool Window::draw(uint64_t image_id, Vec2<float> position, float z, float angle, Vec2<float> scale, float alpha) {
if (!image_pool.is_valid(image_id)) { if (!image_pool.is_valid(image_id)) {
fprintf(stderr, "Invalid image ID: %llu\n", (unsigned long long)image_id); fprintf(stderr, "Invalid image ID: %llu\n", (unsigned long long)image_id);
return false; return false;
@@ -188,6 +187,7 @@ bool Window::draw(uint64_t image_id, Vec2<float> position, float z, float angle,
.z = z, .z = z,
.angle = angle, .angle = angle,
.scale = scale, .scale = scale,
.alpha = alpha,
.draw_image = { .draw_image = {
.image_id = image_id, .image_id = image_id,
.position = position, .position = position,
@@ -197,12 +197,13 @@ bool Window::draw(uint64_t image_id, Vec2<float> position, float z, float angle,
return true; return true;
}; };
bool Window::draw_rect(Rect rect, Color color, float z, float angle) { bool Window::draw_rect(Rect rect, Color color, float z, float angle, Vec2<float> scale, float alpha) {
render_instructions.push_back( render_instructions.push_back(
{.type = RenderInstruction::DRAW_RECT, {.type = RenderInstruction::DRAW_RECT,
.z = z, .z = z,
.angle = angle, .angle = angle,
.scale = {1.0f, 1.0f}, .scale = scale,
.alpha = alpha,
.draw_rect = { .draw_rect = {
.rect = rect, .rect = rect,
.color = color, .color = color,
@@ -276,6 +277,8 @@ void Window::render() {
dst_rect.w = scale_x * text->size.x; dst_rect.w = scale_x * text->size.x;
dst_rect.h = scale_y * text->size.y; dst_rect.h = scale_y * text->size.y;
SDL_SetTextureAlphaModFloat(texture, instruction.alpha);
SDL_RenderTextureRotated( SDL_RenderTextureRotated(
renderer, renderer,
texture, texture,
@@ -306,6 +309,8 @@ void Window::render() {
dst_rect.w = scale_x * image->size.x; dst_rect.w = scale_x * image->size.x;
dst_rect.h = scale_y * image->size.y; dst_rect.h = scale_y * image->size.y;
SDL_SetTextureAlphaModFloat(image->texture, instruction.alpha);
SDL_RenderTextureRotated( SDL_RenderTextureRotated(
renderer, renderer,
image->texture, image->texture,
@@ -321,8 +326,8 @@ void Window::render() {
SDL_FRect dst_rect; SDL_FRect dst_rect;
dst_rect.x = instruction.draw_rect.rect.x() * scale + offset.x; dst_rect.x = instruction.draw_rect.rect.x() * scale + offset.x;
dst_rect.y = instruction.draw_rect.rect.y() * scale + offset.y; dst_rect.y = instruction.draw_rect.rect.y() * scale + offset.y;
dst_rect.w = instruction.draw_rect.rect.w() * scale; dst_rect.w = instruction.draw_rect.rect.w() * scale * instruction.scale.x;
dst_rect.h = instruction.draw_rect.rect.h() * scale; dst_rect.h = instruction.draw_rect.rect.h() * scale * instruction.scale.y;
SDL_SetTextureColorMod( SDL_SetTextureColorMod(
white_tex, white_tex,
@@ -331,7 +336,7 @@ void Window::render() {
instruction.draw_rect.color.b instruction.draw_rect.color.b
); );
SDL_SetTextureAlphaMod(white_tex, instruction.draw_rect.color.a); SDL_SetTextureAlphaModFloat(white_tex, instruction.alpha);
SDL_RenderTextureRotated( SDL_RenderTextureRotated(
renderer, renderer,