Estado atual do TinyBlocks: editor estilo Scratch + graphics como interface

Snapshot do projeto antes de implementar o diálogo "Criar um Bloco":
- runtime C block-based (src/, include/)
- libraries: graphics (interface), sdl2 (backend), editor (estilo Scratch),
  python, mcp
- exemplos (hello, sdl2, editor, vector, json, customappearance, python, mcp)
- Makefile com alvo help e build do editor

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
mguinhosandClaude committed 2026-10-20 19:10:43 -03:00
commit 4950ad6006
49 files changed
+10596

No files matched your search

+9
View File
@@ -0,0 +1,9 @@
# Artefatos de build
/build/
build.tar.xz
*.o
*.a
*.so
# Configuração local do Claude Code
.claude/settings.local.json
+244
View File
@@ -0,0 +1,244 @@
CC := gcc
CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \
-D_POSIX_C_SOURCE=200809L -Iinclude
CFLAGS_DBG := $(CFLAGS) -g -DDEBUG -fsanitize=address,undefined
CFLAGS_REL := $(CFLAGS) -O2 -DNDEBUG
BUILD := build
LIB_A := $(BUILD)/libtinyblocks.a
LIB_SO := $(BUILD)/libtinyblocks.so
EXAMPLE := $(BUILD)/hello
GFX_INC := libraries/tinyblocks-graphics/include
GFX_HDR := $(GFX_INC)/tb_graphics.h
SRCS := src/tinyblocks.c \
src/tb_value.c \
src/tb_block.c \
src/tb_type_block.c \
src/tb_library_block.c \
src/tb_text_block.c \
src/tb_integer_block.c \
src/tb_real_block.c \
src/tb_vector_block.c \
src/tb_renderable_block.c \
src/tb_json_block.c
OBJS := $(patsubst src/%.c,$(BUILD)/%.o,$(SRCS))
OBJS_DBG := $(patsubst src/%.c,$(BUILD)/%-dbg.o,$(SRCS))
.PHONY: all help debug release static shared example sdl2 clean run python-lib mcp-lib json \
editor run-editor run-sdl2 mylib vector customappearance graphics sdl2-backend
all: static example ## Compila a biblioteca estática e o exemplo hello (padrão)
help: ## Lista os alvos disponíveis
@echo "TinyBlocks — alvos do make:"
@echo
@awk 'BEGIN {FS = ":.*## "} /^[a-zA-Z0-9_-]+:.*## / { printf " \033[36m%-18s\033[0m %s\n", $$1, $$2 }' $(MAKEFILE_LIST)
@echo
@echo "Exemplo: make run-editor (libraries extras: ./build/editor build/mylib.so)"
# ── Biblioteca ────────────────────────────────────────────────────────────
static: $(LIB_A) ## Compila build/libtinyblocks.a
shared: $(LIB_SO) ## Compila build/libtinyblocks.so
HDRS := $(wildcard include/tinyblocks/*.h)
$(BUILD)/%.o: src/%.c $(HDRS)
@mkdir -p $(BUILD)
$(CC) $(CFLAGS_REL) -fPIC -c $< -o $@
$(BUILD)/%-dbg.o: src/%.c $(HDRS)
@mkdir -p $(BUILD)
$(CC) $(CFLAGS_DBG) -fPIC -c $< -o $@
$(LIB_A): $(OBJS)
ar rcs $@ $^
$(LIB_SO): $(OBJS)
$(CC) -shared -o $@ $^
# ── Exemplo hello ─────────────────────────────────────────────────────────
$(EXAMPLE): examples/hello/main.c $(LIB_A)
$(CC) $(CFLAGS_REL) $< -o $@ -L$(BUILD) -ltinyblocks
example: $(EXAMPLE) ## Compila o exemplo hello
run: example ## Compila e roda o exemplo hello
./$(EXAMPLE)
# ── Build de debug com ASan/UBSan ────────────────────────────────────────
$(BUILD)/libtinyblocks-dbg.a: $(OBJS_DBG)
ar rcs $@ $^
$(BUILD)/hello-dbg: examples/hello/main.c $(BUILD)/libtinyblocks-dbg.a
$(CC) $(CFLAGS_DBG) $< -o $@ -L$(BUILD) -ltinyblocks-dbg
debug: $(BUILD)/hello-dbg ## Compila e roda o hello com ASan/UBSan
./$(BUILD)/hello-dbg
# ── Library SDL2 ──────────────────────────────────────────────────────────
SDL2_CFLAGS := $(shell sdl2-config --cflags)
SDL2_LIBS := $(shell sdl2-config --libs)
$(BUILD)/sdl2-example: examples/sdl2/main.c $(LIB_A) $(BUILD)/libtinyblocks-sdl2.a
$(CC) $(CFLAGS_REL) $(SDL2_CFLAGS) $(SDL2TTF_CFLAGS) \
-Ilibraries/tinyblocks-sdl2/include \
$< -o $@ \
-L$(BUILD) -ltinyblocks-sdl2 -ltinyblocks $(SDL2_LIBS) $(SDL2TTF_LIBS) -lm
sdl2: static $(BUILD)/libtinyblocks-sdl2.a $(BUILD)/sdl2-example ## Compila a library SDL2 e seu exemplo
@echo "Build SDL2 OK: $(BUILD)/sdl2-example"
$(BUILD)/libtinyblocks-sdl2.a: $(BUILD)/tb_sdl2.o
ar rcs $@ $^
$(BUILD)/tb_sdl2.o: libraries/tinyblocks-sdl2/src/tb_sdl2.c $(GFX_HDR) $(HDRS)
@mkdir -p $(BUILD)
$(CC) $(CFLAGS_REL) $(SDL2_CFLAGS) $(SDL2TTF_CFLAGS) \
-Ilibraries/tinyblocks-sdl2/include -I$(GFX_INC) -Iinclude -fPIC -c $< -o $@
# Backend SDL2 como .so, para trocar em tempo de execução (--backend)
$(BUILD)/libtinyblocks-sdl2.so: libraries/tinyblocks-sdl2/src/tb_sdl2.c $(GFX_HDR) $(LIB_A)
$(CC) $(CFLAGS_REL) $(SDL2_CFLAGS) $(SDL2TTF_CFLAGS) \
-Ilibraries/tinyblocks-sdl2/include -I$(GFX_INC) -Iinclude -fPIC -shared \
$< -o $@ -L$(BUILD) -ltinyblocks $(SDL2_LIBS) $(SDL2TTF_LIBS) -lm
sdl2-backend: static $(BUILD)/libtinyblocks-sdl2.so ## Backend SDL2 como .so (./build/editor --backend build/libtinyblocks-sdl2.so)
@echo "Build backend OK: $(BUILD)/libtinyblocks-sdl2.so"
# ── Library Graphics (interface; backend padrão: SDL2) ───────────────────
$(BUILD)/tb_graphics.o: libraries/tinyblocks-graphics/src/tb_graphics.c $(GFX_HDR) $(HDRS)
@mkdir -p $(BUILD)
$(CC) $(CFLAGS_REL) -DTB_GRAPHICS_DEFAULT_SDL2 \
-I$(GFX_INC) -Ilibraries/tinyblocks-sdl2/include -fPIC -c $< -o $@
$(BUILD)/libtinyblocks-graphics.a: $(BUILD)/tb_graphics.o
ar rcs $@ $^
graphics: static $(BUILD)/libtinyblocks-graphics.a $(BUILD)/libtinyblocks-sdl2.a ## Interface gráfica (com backend SDL2)
@echo "Build graphics OK: $(BUILD)/libtinyblocks-graphics.a"
run-sdl2: sdl2 ## Compila e roda o exemplo SDL2
LD_LIBRARY_PATH=$(BUILD) ./$(BUILD)/sdl2-example
# ── Library Editor ────────────────────────────────────────────────────────
SDL2TTF_CFLAGS := $(shell pkg-config --cflags SDL2_ttf 2>/dev/null)
SDL2TTF_LIBS := $(shell pkg-config --libs SDL2_ttf 2>/dev/null)
EDITOR_SRC := libraries/tinyblocks-editor/src
EDITOR_HDRS := $(EDITOR_SRC)/tb_stage.h libraries/tinyblocks-editor/include/tb_editor.h $(GFX_HDR) $(HDRS)
$(BUILD)/tb_editor.o: $(EDITOR_SRC)/tb_editor.c $(EDITOR_HDRS)
$(CC) $(CFLAGS_REL) -Ilibraries/tinyblocks-editor/include -I$(GFX_INC) -fPIC -c $< -o $@
$(BUILD)/tb_stage.o: $(EDITOR_SRC)/tb_stage.c $(EDITOR_HDRS)
$(CC) $(CFLAGS_REL) -I$(GFX_INC) -fPIC -c $< -o $@
$(BUILD)/libtinyblocks-editor.a: $(BUILD)/tb_editor.o $(BUILD)/tb_stage.o
ar rcs $@ $^
$(BUILD)/editor: examples/editor/main.c $(LIB_A) $(BUILD)/libtinyblocks-editor.a \
$(BUILD)/libtinyblocks-graphics.a $(BUILD)/libtinyblocks-sdl2.a
$(CC) $(CFLAGS_REL) -Ilibraries/tinyblocks-editor/include -I$(GFX_INC) \
$< -o $@ \
-L$(BUILD) -ltinyblocks-editor -ltinyblocks-graphics -ltinyblocks-sdl2 -ltinyblocks \
$(SDL2_LIBS) $(SDL2TTF_LIBS) -ldl -lm \
'-Wl,-rpath,$$ORIGIN'
editor: static graphics $(BUILD)/libtinyblocks-editor.a $(BUILD)/editor ## Compila o editor visual (estilo Scratch)
@echo "Build editor OK: $(BUILD)/editor"
run-editor: editor ## Compila e abre o editor visual
./$(BUILD)/editor
# ── Exemplo de library externa (hot reload) ──────────────────────────────
$(BUILD)/mylib.so: examples/mylib/mylib.c $(LIB_A)
$(CC) $(CFLAGS_REL) -Iinclude -fPIC -shared \
$< -o $@ -L$(BUILD) -ltinyblocks '-Wl,-rpath,$$ORIGIN'
mylib: static $(BUILD)/mylib.so ## Library de exemplo (hot reload) → build/mylib.so
@echo "Build mylib OK: $(BUILD)/mylib.so → Carregue no editor com Ctrl+O"
# ── Library de vetor 2D ───────────────────────────────────────────────────
$(BUILD)/vector.so: examples/vector/vector.c $(LIB_A)
$(CC) $(CFLAGS_REL) -Iinclude -fPIC -shared \
$< -o $@ -L$(BUILD) -ltinyblocks '-Wl,-rpath,$$ORIGIN'
vector: static $(BUILD)/vector.so ## Library de vetor 2D → build/vector.so
@echo "Build vector OK: $(BUILD)/vector.so → Carregue no editor com Ctrl+O"
# ── Library de JSON ────────────────────────────────────────────────────────
$(BUILD)/json.so: examples/json/json.c $(LIB_A)
$(CC) $(CFLAGS_REL) -Iinclude -fPIC -shared \
$< -o $@ -L$(BUILD) -ltinyblocks '-Wl,-rpath,$$ORIGIN'
json: static $(BUILD)/json.so ## Library de JSON → build/json.so
@echo "Build json OK: $(BUILD)/json.so → Carregue no editor com Ctrl+O"
# ── Library de aparência personalizada (on_render demo) ───────────────────
$(BUILD)/customappearance.so: examples/customappearance/customappearance.c $(LIB_A)
$(CC) $(CFLAGS_REL) -Iinclude -fPIC -shared \
$< -o $@ -L$(BUILD) -ltinyblocks -lm '-Wl,-rpath,$$ORIGIN'
customappearance: static $(BUILD)/customappearance.so ## Library de demo do on_draw → build/customappearance.so
@echo "Build customappearance OK: $(BUILD)/customappearance.so"
# ── Library Python (embedding CPython) ───────────────────────────────────
PYTHON_CFLAGS := $(shell python3-config --cflags --embed 2>/dev/null || python3-config --cflags)
PYTHON_LIBS := $(shell python3-config --ldflags --embed 2>/dev/null || python3-config --ldflags)
$(BUILD)/tb_python_lib.o: libraries/tinyblocks-python/src/tb_python.c
@mkdir -p $(BUILD)
$(CC) $(CFLAGS_REL) $(PYTHON_CFLAGS) \
-Ilibraries/tinyblocks-python/include -fPIC -c $< -o $@
# Shared lib — garante um único interpretador Python no processo
$(BUILD)/libtinyblocks-python.so: $(BUILD)/tb_python_lib.o
$(CC) -shared -Wl,-soname,libtinyblocks-python.so -o $@ $^ $(PYTHON_LIBS)
$(BUILD)/python.so: examples/python/python.c $(LIB_A) $(BUILD)/libtinyblocks-python.so
$(CC) $(CFLAGS_REL) $(PYTHON_CFLAGS) \
-Ilibraries/tinyblocks-python/include -Iinclude -fPIC -shared \
$< -o $@ -L$(BUILD) -ltinyblocks -ltinyblocks-python \
'-Wl,-rpath,$$ORIGIN'
python-lib: static $(BUILD)/libtinyblocks-python.so $(BUILD)/python.so ## Library Python (CPython embutido) → build/python.so
@echo "Build python OK: $(BUILD)/python.so"
# ── Library MCP (usa tinyblocks-python) ──────────────────────────────────
# Gera header com o código Python embutido (unsigned char tb_mcp_py[])
libraries/tinyblocks-mcp/src/tb_mcp_py.h: libraries/tinyblocks-mcp/src/tb_mcp.py
xxd -i -n tb_mcp_py $< $@
$(BUILD)/tb_mcp_lib.o: libraries/tinyblocks-mcp/src/tb_mcp.c \
libraries/tinyblocks-mcp/src/tb_mcp_py.h \
libraries/tinyblocks-python/include/tinyblocks-python/tb_python.h
@mkdir -p $(BUILD)
$(CC) $(CFLAGS_REL) $(PYTHON_CFLAGS) \
-Ilibraries/tinyblocks-mcp/include \
-Ilibraries/tinyblocks-python/include \
-Ilibraries/tinyblocks-mcp/src \
-fPIC -c $< -o $@
$(BUILD)/libtinyblocks-mcp.so: $(BUILD)/tb_mcp_lib.o $(BUILD)/libtinyblocks-python.so
$(CC) -shared -Wl,-soname,libtinyblocks-mcp.so -o $@ $(BUILD)/tb_mcp_lib.o \
-L$(BUILD) -ltinyblocks-python $(PYTHON_LIBS) \
'-Wl,-rpath,$$ORIGIN'
$(BUILD)/mcp.so: examples/mcp/mcp.c $(LIB_A) \
$(BUILD)/libtinyblocks-mcp.so $(BUILD)/libtinyblocks-python.so
$(CC) $(CFLAGS_REL) \
-Ilibraries/tinyblocks-mcp/include \
-Ilibraries/tinyblocks-python/include \
-Iinclude -fPIC -shared \
$< -o $@ -L$(BUILD) -ltinyblocks -ltinyblocks-mcp -ltinyblocks-python \
'-Wl,-rpath,$$ORIGIN'
mcp-lib: static $(BUILD)/libtinyblocks-python.so $(BUILD)/libtinyblocks-mcp.so $(BUILD)/mcp.so ## Library cliente MCP → build/mcp.so
@echo "Build mcp OK: $(BUILD)/mcp.so"
# ── Limpeza ───────────────────────────────────────────────────────────────
clean: ## Remove o diretório build/
$(RM) -r $(BUILD)
$(MAKE) -C libraries/tinyblocks-sdl2 clean 2>/dev/null || true
@@ -0,0 +1,283 @@
/*
* customappearance.c — Demonstração de on_draw (aparência personalizada de bloco).
*
* Blocos:
* Viz.ColorSwatch — inputs: r, g, b, a (0..1) → mostra quadrado colorido
* Viz.Gauge — inputs: value (0..1), r, g, b → barra de progresso
* Viz.Star — inputs: r, g, b, a → estrela de 5 pontas (contorno)
* Viz.BarChart — inputs: a, b, c, d (reais) → mini gráfico de barras
*
* make customappearance → build/customappearance.so
*/
#define _POSIX_C_SOURCE 200809L
#include <math.h>
#include <string.h>
#include <tinyblocks/tinyblocks.h>
#include <tinyblocks/tb_renderable_block.h>
/* ── Helpers ─────────────────────────────────────────────────────────────── */
static float gf(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) {
TinyBlocks_Value v = tb_block_get_input(self, rt, idx);
if (v.kind == TB_VALUE_REAL) return (float)v.as.real;
if (v.kind == TB_VALUE_INTEGER) return (float)v.as.integer;
return 0.0f;
}
static float out_f(TinyBlocks_Block* self, uint32_t idx) {
if (!self || idx >= self->output_count) return 0.0f;
TinyBlocks_Value* v = &self->outputs[idx];
if (v->kind == TB_VALUE_REAL) return (float)v->as.real;
if (v->kind == TB_VALUE_INTEGER) return (float)v->as.integer;
return 0.0f;
}
/* ══════════════════════════════════════════════════════════════════════════
* Viz.ColorSwatch
* ══════════════════════════════════════════════════════════════════════════ */
static void eval_color_swatch(TinyBlocks_Block* self, TinyBlocks* rt) {
for (uint32_t i = 0; i < 4 && i < self->output_count; i++)
tb_block_set_output(self, i, tb_value_real((double)gf(self, rt, i)));
self->dirty = false;
}
static bool draw_color_swatch(TinyBlocks_Block* self, TinyBlocks* rt,
TinyBlocks_RenderableBlock** dst) {
(void)rt;
TinyBlocks_RenderableBlock* rb = tb_renderable_acquire();
if (!rb) return false;
float r = out_f(self, 0), g = out_f(self, 1);
float b = out_f(self, 2), a = out_f(self, 3);
/* Área de conteúdo: coordenadas locais ao bloco (0,0 = topo-esq) */
float bw = 168.f, bh = 60.f;
float pad = 6.f;
float w = bw - 2*pad, h = bh - 2*pad;
/* Xadrez de fundo */
float cell = 8.f;
for (float cy = 0; cy < h; cy += cell) {
for (float cx = 0; cx < w; cx += cell) {
float dark = ((int)(cx/cell)+(int)(cy/cell)) % 2 == 0 ? 0.6f : 0.9f;
float cw2 = (cx+cell > w) ? w-cx : cell;
float ch2 = (cy+cell > h) ? h-cy : cell;
tb_draw_fill_rect(rb, pad+cx, pad+cy, cw2, ch2, dark, dark, dark, 1.f);
}
}
/* Swatch com alpha real */
tb_draw_fill_rect(rb, pad, pad, w, h, r, g, b, a);
/* Borda */
tb_draw_stroke_rect(rb, pad, pad, w, h, 1.f, 0.9f, 0.9f, 0.9f, 0.6f);
*dst = rb;
return true;
}
/* ══════════════════════════════════════════════════════════════════════════
* Viz.Gauge
* ══════════════════════════════════════════════════════════════════════════ */
static void eval_gauge(TinyBlocks_Block* self, TinyBlocks* rt) {
for (uint32_t i = 0; i < 4 && i < self->output_count; i++)
tb_block_set_output(self, i, tb_value_real((double)gf(self, rt, i)));
self->dirty = false;
}
static bool draw_gauge(TinyBlocks_Block* self, TinyBlocks* rt,
TinyBlocks_RenderableBlock** dst) {
(void)rt;
TinyBlocks_RenderableBlock* rb = tb_renderable_acquire();
if (!rb) return false;
float value = out_f(self, 0);
float r = out_f(self, 1), g = out_f(self, 2), b = out_f(self, 3);
if (value < 0.f) value = 0.f;
if (value > 1.f) value = 1.f;
float bw = 168.f, bh = 60.f;
float pad = 8.f;
float barh = 14.f;
float bary = (bh - barh) * 0.5f;
float barw = bw - 2*pad;
/* Fundo escuro */
tb_draw_fill_rect(rb, pad, bary, barw, barh, 0.15f, 0.15f, 0.2f, 1.f);
/* Preenchimento proporcional */
if (value > 0.001f)
tb_draw_fill_rect(rb, pad, bary, barw * value, barh, r, g, b, 1.f);
/* Borda */
tb_draw_stroke_rect(rb, pad, bary, barw, barh, 1.f, 0.6f, 0.6f, 0.7f, 0.8f);
*dst = rb;
return true;
}
/* ══════════════════════════════════════════════════════════════════════════
* Viz.Star
* ══════════════════════════════════════════════════════════════════════════ */
static void eval_star(TinyBlocks_Block* self, TinyBlocks* rt) {
for (uint32_t i = 0; i < 4 && i < self->output_count; i++)
tb_block_set_output(self, i, tb_value_real((double)gf(self, rt, i)));
self->dirty = false;
}
static bool draw_star(TinyBlocks_Block* self, TinyBlocks* rt,
TinyBlocks_RenderableBlock** dst) {
(void)rt;
TinyBlocks_RenderableBlock* rb = tb_renderable_acquire();
if (!rb) return false;
float r = out_f(self, 0), g = out_f(self, 1);
float b = out_f(self, 2), a = out_f(self, 3);
float bw = 168.f, bh = 60.f;
float cx = bw * 0.5f, cy = bh * 0.5f;
float ro = (bw < bh ? bw : bh) * 0.42f;
float ri = ro * 0.42f;
#ifndef M_PI
#define M_PI 3.14159265358979323846
#endif
/* Desenha 5 linhas da estrela (conecta pontos alternados) */
float px[10], py[10];
for (int i = 0; i < 10; i++) {
float angle = (float)i * (float)M_PI / 5.f - (float)M_PI / 2.f;
float rad = (i % 2 == 0) ? ro : ri;
px[i] = cx + rad * cosf(angle);
py[i] = cy + rad * sinf(angle);
}
/* Contorno */
for (int i = 0; i < 10; i++) {
int j = (i + 1) % 10;
tb_draw_stroke_line(rb, px[i], py[i], px[j], py[j], 1.5f, r, g, b, a);
}
/* Diagonais internas (estrela de 5 pontas típica) */
for (int i = 0; i < 5; i++) {
int j = (i + 2) % 10 * 2 % 10;
tb_draw_stroke_line(rb, px[i*2], py[i*2], px[j], py[j], 1.f, r*0.6f, g*0.6f, b*0.6f, a);
}
*dst = rb;
return true;
}
/* ══════════════════════════════════════════════════════════════════════════
* Viz.BarChart
* ══════════════════════════════════════════════════════════════════════════ */
static void eval_barchart(TinyBlocks_Block* self, TinyBlocks* rt) {
for (uint32_t i = 0; i < 4 && i < self->output_count; i++)
tb_block_set_output(self, i, tb_value_real((double)gf(self, rt, i)));
self->dirty = false;
}
static bool draw_barchart(TinyBlocks_Block* self, TinyBlocks* rt,
TinyBlocks_RenderableBlock** dst) {
(void)rt;
TinyBlocks_RenderableBlock* rb = tb_renderable_acquire();
if (!rb) return false;
float vals[4];
for (int i = 0; i < 4; i++) vals[i] = out_f(self, i);
float maxv = 0.001f;
for (int i = 0; i < 4; i++) if (vals[i] > maxv) maxv = vals[i];
static const float colors[4][3] = {
{0.36f, 0.70f, 1.00f},
{0.40f, 0.86f, 0.56f},
{1.00f, 0.75f, 0.30f},
{0.86f, 0.40f, 0.50f},
};
float bw = 168.f, bh = 60.f;
float pad = 6.f;
float gap = 4.f;
float tw = bw - 2*pad;
float th = bh - 2*pad - 4.f;
float barw = (tw - gap*3.f) / 4.f;
/* Linha de base */
tb_draw_fill_rect(rb, pad, pad+th, tw, 1.f, 0.3f, 0.3f, 0.35f, 1.f);
for (int i = 0; i < 4; i++) {
float norm = vals[i] / maxv;
float bh2 = norm * th;
float bx = pad + i * (barw + gap);
float by = pad + th - bh2;
if (bh2 < 1.f) bh2 = 1.f;
tb_draw_fill_rect(rb, bx, by, barw, bh2,
colors[i][0], colors[i][1], colors[i][2], 0.9f);
}
*dst = rb;
return true;
}
/* ══════════════════════════════════════════════════════════════════════════
* Descritores de slots
* ══════════════════════════════════════════════════════════════════════════ */
static const TinyBlocks_SlotDesc rgba_in[] = {
{"r", TB_VALUE_REAL}, {"g", TB_VALUE_REAL},
{"b", TB_VALUE_REAL}, {"a", TB_VALUE_REAL}
};
static const TinyBlocks_SlotDesc rgba_out[] = {
{"r", TB_VALUE_REAL}, {"g", TB_VALUE_REAL},
{"b", TB_VALUE_REAL}, {"a", TB_VALUE_REAL}
};
static const TinyBlocks_SlotDesc gauge_in[] = {
{"value", TB_VALUE_REAL},
{"r", TB_VALUE_REAL}, {"g", TB_VALUE_REAL}, {"b", TB_VALUE_REAL}
};
static const TinyBlocks_SlotDesc gauge_out[] = {
{"value", TB_VALUE_REAL},
{"r", TB_VALUE_REAL}, {"g", TB_VALUE_REAL}, {"b", TB_VALUE_REAL}
};
static const TinyBlocks_SlotDesc chart_in[] = {
{"a", TB_VALUE_REAL}, {"b", TB_VALUE_REAL},
{"c", TB_VALUE_REAL}, {"d", TB_VALUE_REAL}
};
static const TinyBlocks_SlotDesc chart_out[] = {
{"a", TB_VALUE_REAL}, {"b", TB_VALUE_REAL},
{"c", TB_VALUE_REAL}, {"d", TB_VALUE_REAL}
};
/* ══════════════════════════════════════════════════════════════════════════
* Registro
* ══════════════════════════════════════════════════════════════════════════ */
static bool ca_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
TinyBlocks_TypeBlock* t;
#define REG_VIZ(name, ins, ni, outs, no, eval_fn, draw_fn) \
t = tb_type_block_create(rt, name, ins, ni, outs, no, eval_fn); \
if (t) { t->on_draw = draw_fn; tb_library_add(lib, &t->base); }
REG_VIZ("Viz.ColorSwatch", rgba_in, 4, rgba_out, 4,
eval_color_swatch, draw_color_swatch);
REG_VIZ("Viz.Gauge", gauge_in, 4, gauge_out, 4,
eval_gauge, draw_gauge);
REG_VIZ("Viz.Star", rgba_in, 4, rgba_out, 4,
eval_star, draw_star);
REG_VIZ("Viz.BarChart", chart_in, 4, chart_out, 4,
eval_barchart, draw_barchart);
#undef REG_VIZ
return true;
}
static void ca_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
(void)rt; (void)lib;
}
TINYBLOCKS_DEFINE_LIBRARY(customappearance,
"customappearance",
"1.0.0",
ca_init,
ca_deinit)
+185
View File
@@ -0,0 +1,185 @@
/*
* TinyBlocks — exemplo editor
*
* Abre o editor visual com os blocos Math.* e IO.Print pré-registrados.
* A janela vem da interface tinyblocks-graphics; o backend padrão é SDL2 e
* pode ser trocado por outro .so:
*
* ./editor [--backend libbackend.so] [library.so ...]
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tinyblocks/tinyblocks.h>
#include <tb_editor.h>
#include <tb_graphics.h>
/* ── TypeBlocks de demonstração ─────────────────────────────────────────── */
static void eval_math_add(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Value a = tb_block_get_input(self, rt, 0);
TinyBlocks_Value b = tb_block_get_input(self, rt, 1);
int64_t va = a.kind==TB_VALUE_INTEGER ? a.as.integer : 0;
int64_t vb = b.kind==TB_VALUE_INTEGER ? b.as.integer : 0;
tb_block_set_output(self, 0, tb_value_integer(va + vb));
}
static void eval_math_sub(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Value a = tb_block_get_input(self, rt, 0);
TinyBlocks_Value b = tb_block_get_input(self, rt, 1);
int64_t va = a.kind==TB_VALUE_INTEGER ? a.as.integer : 0;
int64_t vb = b.kind==TB_VALUE_INTEGER ? b.as.integer : 0;
tb_block_set_output(self, 0, tb_value_integer(va - vb));
}
static void eval_math_mul(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Value a = tb_block_get_input(self, rt, 0);
TinyBlocks_Value b = tb_block_get_input(self, rt, 1);
int64_t va = a.kind==TB_VALUE_INTEGER ? a.as.integer : 0;
int64_t vb = b.kind==TB_VALUE_INTEGER ? b.as.integer : 0;
tb_block_set_output(self, 0, tb_value_integer(va * vb));
}
static void eval_math_div(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Value a = tb_block_get_input(self, rt, 0);
TinyBlocks_Value b = tb_block_get_input(self, rt, 1);
int64_t va = a.kind==TB_VALUE_INTEGER ? a.as.integer : 0;
int64_t vb = b.kind==TB_VALUE_INTEGER ? b.as.integer : 1;
tb_block_set_output(self, 0, tb_value_integer(vb ? va/vb : 0));
}
static void eval_math_mod(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Value a = tb_block_get_input(self, rt, 0);
TinyBlocks_Value b = tb_block_get_input(self, rt, 1);
int64_t va = a.kind==TB_VALUE_INTEGER ? a.as.integer : 0;
int64_t vb = b.kind==TB_VALUE_INTEGER ? b.as.integer : 1;
tb_block_set_output(self, 0, tb_value_integer(vb ? va%vb : 0));
}
static void eval_math_abs(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Value a = tb_block_get_input(self, rt, 0);
int64_t v = a.kind==TB_VALUE_INTEGER ? a.as.integer : 0;
tb_block_set_output(self, 0, tb_value_integer(v<0 ? -v : v));
}
static void eval_math_max(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Value a = tb_block_get_input(self, rt, 0);
TinyBlocks_Value b = tb_block_get_input(self, rt, 1);
int64_t va = a.kind==TB_VALUE_INTEGER ? a.as.integer : 0;
int64_t vb = b.kind==TB_VALUE_INTEGER ? b.as.integer : 0;
tb_block_set_output(self, 0, tb_value_integer(va>vb ? va : vb));
}
static void eval_math_min(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Value a = tb_block_get_input(self, rt, 0);
TinyBlocks_Value b = tb_block_get_input(self, rt, 1);
int64_t va = a.kind==TB_VALUE_INTEGER ? a.as.integer : 0;
int64_t vb = b.kind==TB_VALUE_INTEGER ? b.as.integer : 0;
tb_block_set_output(self, 0, tb_value_integer(va<vb ? va : vb));
}
static void eval_io_print(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Value label = tb_block_get_input(self, rt, 0);
TinyBlocks_Value value = tb_block_get_input(self, rt, 1);
const char* lbl = label.kind==TB_VALUE_TEXT ? label.as.text : "resultado";
if (value.kind==TB_VALUE_INTEGER)
printf("%s = %lld\n", lbl, (long long)value.as.integer);
else if (value.kind==TB_VALUE_REAL)
printf("%s = %g\n", lbl, value.as.real);
else if (value.kind==TB_VALUE_TEXT)
printf("%s = %s\n", lbl, value.as.text ? value.as.text : "");
else printf("%s\n", lbl);
}
static void eval_io_print_int(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Value v = tb_block_get_input(self, rt, 0);
int64_t n = v.kind==TB_VALUE_INTEGER ? v.as.integer : 0;
printf("%lld\n", (long long)n);
}
static void eval_text_concat(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Value a = tb_block_get_input(self, rt, 0);
TinyBlocks_Value b = tb_block_get_input(self, rt, 1);
const char* sa = a.kind==TB_VALUE_TEXT ? a.as.text : "";
const char* sb = b.kind==TB_VALUE_TEXT ? b.as.text : "";
size_t n = strlen(sa)+strlen(sb)+1;
char* buf = (char*)malloc(n);
if (!buf) return;
memcpy(buf, sa, strlen(sa));
memcpy(buf+strlen(sa), sb, strlen(sb)+1);
TinyBlocks_Value v; v.kind=TB_VALUE_TEXT; v.as.text=buf;
tb_block_set_output(self, 0, v);
}
static void eval_text_len(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Value a = tb_block_get_input(self, rt, 0);
int64_t n = a.kind==TB_VALUE_TEXT && a.as.text ? (int64_t)strlen(a.as.text) : 0;
tb_block_set_output(self, 0, tb_value_integer(n));
}
int main(int argc, char** argv) {
TinyBlocks* rt = NULL;
if (!tinyblocks_init(&rt, NULL)) return 1;
/* --backend troca o backend gráfico; os demais .so são pré-carregados */
for (int i = 1; i < argc; i++) {
if (strcmp(argv[i], "--backend") == 0 && i + 1 < argc) {
if (!tb_graphics_load_backend(argv[++i])) return 1;
} else {
tb_editor_preload(argv[i]);
}
}
/* Slots reutilizáveis */
static const TinyBlocks_SlotDesc two_int[] = {
{"a", TB_VALUE_INTEGER}, {"b", TB_VALUE_INTEGER} };
static const TinyBlocks_SlotDesc one_int[] = {
{"n", TB_VALUE_INTEGER} };
static const TinyBlocks_SlotDesc int_out[] = { {"result", TB_VALUE_INTEGER} };
static const TinyBlocks_SlotDesc print_in[] = {
{"label", TB_VALUE_TEXT}, {"value", TB_VALUE_NONE} };
static const TinyBlocks_SlotDesc two_text[] = {
{"a", TB_VALUE_TEXT}, {"b", TB_VALUE_TEXT} };
static const TinyBlocks_SlotDesc text_out[] = { {"result", TB_VALUE_TEXT} };
static const TinyBlocks_SlotDesc text_in[] = { {"text", TB_VALUE_TEXT} };
/* Math */
tb_type_block_create(rt,"Math.Add", two_int,2, int_out,1, eval_math_add);
tb_type_block_create(rt,"Math.Sub", two_int,2, int_out,1, eval_math_sub);
tb_type_block_create(rt,"Math.Mul", two_int,2, int_out,1, eval_math_mul);
tb_type_block_create(rt,"Math.Div", two_int,2, int_out,1, eval_math_div);
tb_type_block_create(rt,"Math.Mod", two_int,2, int_out,1, eval_math_mod);
tb_type_block_create(rt,"Math.Abs", one_int,1, int_out,1, eval_math_abs);
tb_type_block_create(rt,"Math.Max", two_int,2, int_out,1, eval_math_max);
tb_type_block_create(rt,"Math.Min", two_int,2, int_out,1, eval_math_min);
/* IO */
tb_type_block_create(rt,"IO.Print", print_in,2, NULL,0, eval_io_print);
tb_type_block_create(rt,"IO.PrintInt", one_int,1, NULL,0, eval_io_print_int);
/* Text */
tb_type_block_create(rt,"Text.Concat", two_text,2, text_out,1, eval_text_concat);
tb_type_block_create(rt,"Text.Length", text_in, 1, int_out, 1, eval_text_len);
/* Interface gráfica primeiro: o editor mede texto e cria o palco ao nascer */
tb_library_register(rt, tb_graphics_get_library());
tb_library_register(rt, tb_editor_get_library());
/* Graphics.Input → Editor.Scene → Graphics.Window */
TinyBlocks_TypeBlock* t_input = tb_type_block_find(rt, "Graphics.Input");
TinyBlocks_TypeBlock* t_scene = tb_type_block_find(rt, "Editor.Scene");
TinyBlocks_TypeBlock* t_win = tb_type_block_find(rt, "Graphics.Window");
if (!t_input || !t_scene || !t_win) {
fprintf(stderr, "blocos Graphics.Input / Editor.Scene / Graphics.Window não encontrados\n");
return 1;
}
TinyBlocks_Block* input = tb_block_create(rt, t_input);
TinyBlocks_Block* scene = tb_block_create(rt, t_scene);
TinyBlocks_Block* win = tb_block_create(rt, t_win);
tb_block_set_default(scene, 0, tb_value_block(input));
TinyBlocks_Value title = tb_value_text("TinyBlocks Editor");
tb_block_set_default(win, 0, title); /* set_default clona */
tb_value_free(&title);
tb_block_set_default(win, 1, tb_value_integer(1280));
tb_block_set_default(win, 2, tb_value_integer(800));
tb_block_set_default(win, 3, tb_value_block(scene));
tb_block_set_default(win, 4, tb_value_block(input));
tb_block_eval(win, rt); /* abre a janela */
printf("Backend gráfico: %s\n", tb_graphics_backend()->name);
tb_graphics_run(rt); /* loop até a janela principal fechar */
tinyblocks_deinit(&rt);
return 0;
}
+235
View File
@@ -0,0 +1,235 @@
/*
* TinyBlocks — exemplo hello
*
* Demonstra:
* 1. Inicializar o runtime
* 2. Criar TypeBlocks (Math.Add, Math.Mul, IO.Print)
* 3. Criar blocos literais (IntegerBlock, TextBlock)
* 4. Conectar blocos e avaliar
* 5. Usar LibraryBlock como namespace
*/
#include <stdio.h>
#include <tinyblocks/tinyblocks.h>
/* ── TypeBlock: Math.Add ─────────────────────────────────────────────────── */
/* inputs: a(int), b(int)
* outputs: result(int) */
static void eval_math_add(TinyBlocks_Block* self, TinyBlocks* rt)
{
TinyBlocks_Value va = tb_block_get_input(self, rt, 0);
TinyBlocks_Value vb = tb_block_get_input(self, rt, 1);
int64_t a = va.kind == TB_VALUE_INTEGER ? va.as.integer : 0;
int64_t b = vb.kind == TB_VALUE_INTEGER ? vb.as.integer : 0;
tb_block_set_output(self, 0, tb_value_integer(a + b));
}
/* ── TypeBlock: Math.Mul ─────────────────────────────────────────────────── */
static void eval_math_mul(TinyBlocks_Block* self, TinyBlocks* rt)
{
TinyBlocks_Value va = tb_block_get_input(self, rt, 0);
TinyBlocks_Value vb = tb_block_get_input(self, rt, 1);
int64_t a = va.kind == TB_VALUE_INTEGER ? va.as.integer : 0;
int64_t b = vb.kind == TB_VALUE_INTEGER ? vb.as.integer : 0;
tb_block_set_output(self, 0, tb_value_integer(a * b));
}
/* ── TypeBlock: IO.Print ─────────────────────────────────────────────────── */
/* inputs: label(text), value(int)
* outputs: (nenhum) */
static void eval_io_print(TinyBlocks_Block* self, TinyBlocks* rt)
{
TinyBlocks_Value vlabel = tb_block_get_input(self, rt, 0);
TinyBlocks_Value vvalue = tb_block_get_input(self, rt, 1);
const char* label = vlabel.kind == TB_VALUE_TEXT ? vlabel.as.text : "(sem rótulo)";
char valstr[64] = "?";
if (vvalue.kind == TB_VALUE_INTEGER)
snprintf(valstr, sizeof(valstr), "%lld", (long long)vvalue.as.integer);
else if (vvalue.kind == TB_VALUE_REAL)
snprintf(valstr, sizeof(valstr), "%g", vvalue.as.real);
else if (vvalue.kind == TB_VALUE_TEXT)
snprintf(valstr, sizeof(valstr), "%s", vvalue.as.text);
printf("[IO.Print] %s = %s\n", label, valstr);
}
/* ── TypeBlock: Math.Factorial (demonstra userdata por instância) ─────────── */
/* inputs: n(int)
* outputs: result(int) */
typedef struct { int64_t memo; } FactorialData;
static void eval_math_factorial(TinyBlocks_Block* self, TinyBlocks* rt)
{
TinyBlocks_Value vn = tb_block_get_input(self, rt, 0);
int64_t n = vn.kind == TB_VALUE_INTEGER ? vn.as.integer : 0;
int64_t result = 1;
for (int64_t i = 2; i <= n; ++i) result *= i;
FactorialData* d = (FactorialData*)self->userdata;
if (d) d->memo = result; /* guarda no userdata por instância */
tb_block_set_output(self, 0, tb_value_integer(result));
}
/* ═══════════════════════════════════════════════════════════════════════════
* main
* ═══════════════════════════════════════════════════════════════════════════ */
int main(void)
{
printf("=== TinyBlocks — exemplo hello ===\n\n");
/* 1. Inicializar runtime */
TinyBlocks* rt = NULL;
if (!tinyblocks_init(&rt, NULL)) {
fprintf(stderr, "Falha ao inicializar TinyBlocks\n");
return 1;
}
printf("[runtime] inicializado id_counter=%llu\n\n",
(unsigned long long)rt->next_id);
/* 2. Criar library "Math" */
TinyBlocks_LibraryBlock* lib_math = tb_library_block_create(rt, "Math");
TinyBlocks_LibraryBlock* lib_io = tb_library_block_create(rt, "IO");
/* 3. Definir slots e TypeBlocks */
static const TinyBlocks_SlotDesc two_int_ins[] = {
{ "a", TB_VALUE_INTEGER }, { "b", TB_VALUE_INTEGER } };
static const TinyBlocks_SlotDesc int_out[] = {
{ "result", TB_VALUE_INTEGER } };
static const TinyBlocks_SlotDesc one_int_in[] = {
{ "n", TB_VALUE_INTEGER } };
static const TinyBlocks_SlotDesc print_ins[] = {
{ "label", TB_VALUE_TEXT }, { "value", TB_VALUE_NONE } };
TinyBlocks_TypeBlock* t_add = tb_type_block_create(rt, "Math.Add",
two_int_ins, 2, int_out, 1, eval_math_add);
TinyBlocks_TypeBlock* t_mul = tb_type_block_create(rt, "Math.Mul",
two_int_ins, 2, int_out, 1, eval_math_mul);
TinyBlocks_TypeBlock* t_fact = tb_type_block_create(rt, "Math.Factorial",
one_int_in, 1, int_out, 1, eval_math_factorial);
TinyBlocks_TypeBlock* t_print = tb_type_block_create(rt, "IO.Print",
print_ins, 2, NULL, 0, eval_io_print);
/* Factorial usa userdata por instância */
tb_type_block_set_instance_hooks(t_fact, sizeof(FactorialData), NULL, NULL);
/* Adiciona às libraries */
tb_library_add(lib_math, &t_add->base);
tb_library_add(lib_math, &t_mul->base);
tb_library_add(lib_math, &t_fact->base);
tb_library_add(lib_io, &t_print->base);
printf("[types] Math.Add, Math.Mul, Math.Factorial, IO.Print registrados\n");
printf("[libs] Math=%u blocos, IO=%u bloco(s)\n\n",
lib_math->block_count, lib_io->block_count);
/* ── Exemplo 1: 3 + 4 ───────────────────────────────────────────────── */
printf("--- Exemplo 1: 3 + 4 ---\n");
{
TinyBlocks_IntegerBlock* lit3 = tb_integer_block_create(rt, 3);
TinyBlocks_IntegerBlock* lit4 = tb_integer_block_create(rt, 4);
TinyBlocks_TextBlock* label = tb_text_block_create(rt, "3 + 4");
TinyBlocks_Block* add = tb_block_create(rt, t_add);
TinyBlocks_Block* print = tb_block_create(rt, t_print);
/* Conecta: add.in[0] ← lit3.out[0]
add.in[1] ← lit4.out[0] */
tb_block_connect(add, 0, &lit3->base, 0);
tb_block_connect(add, 1, &lit4->base, 0);
/* print.in[0] ← label.out[0]
print.in[1] ← add.out[0] */
tb_block_connect(print, 0, &label->base, 0);
tb_block_connect(print, 1, add, 0);
/* Avalia a cadeia inteira (lazy: avalia dependências primeiro) */
tb_block_eval(print, rt);
}
/* ── Exemplo 2: (2 + 3) * 5 ────────────────────────────────────────── */
printf("\n--- Exemplo 2: (2 + 3) * 5 ---\n");
{
TinyBlocks_IntegerBlock* lit2 = tb_integer_block_create(rt, 2);
TinyBlocks_IntegerBlock* lit3 = tb_integer_block_create(rt, 3);
TinyBlocks_IntegerBlock* lit5 = tb_integer_block_create(rt, 5);
TinyBlocks_TextBlock* label = tb_text_block_create(rt, "(2+3)*5");
TinyBlocks_Block* add = tb_block_create(rt, t_add);
TinyBlocks_Block* mul = tb_block_create(rt, t_mul);
TinyBlocks_Block* print = tb_block_create(rt, t_print);
tb_block_connect(add, 0, &lit2->base, 0);
tb_block_connect(add, 1, &lit3->base, 0);
tb_block_connect(mul, 0, add, 0);
tb_block_connect(mul, 1, &lit5->base, 0);
tb_block_connect(print, 0, &label->base, 0);
tb_block_connect(print, 1, mul, 0);
tb_block_eval(print, rt);
}
/* ── Exemplo 3: 7! (fatorial com userdata por instância) ────────────── */
printf("\n--- Exemplo 3: 7! ---\n");
{
TinyBlocks_IntegerBlock* lit7 = tb_integer_block_create(rt, 7);
TinyBlocks_TextBlock* label = tb_text_block_create(rt, "7!");
TinyBlocks_Block* fact = tb_block_create(rt, t_fact);
TinyBlocks_Block* print = tb_block_create(rt, t_print);
tb_block_connect(fact, 0, &lit7->base, 0);
tb_block_connect(print, 0, &label->base, 0);
tb_block_connect(print, 1, fact, 0);
tb_block_eval(print, rt);
/* Lê o valor memoizado do userdata */
FactorialData* d = (FactorialData*)fact->userdata;
printf(" userdata.memo = %lld\n", (long long)d->memo);
}
/* ── Exemplo 4: busca de tipo por nome ──────────────────────────────── */
printf("\n--- Exemplo 4: busca de tipo por nome ---\n");
{
TinyBlocks_TypeBlock* found = tb_type_block_find(rt, "Math.Add");
printf("tb_type_block_find(\"Math.Add\") = %s\n",
found ? found->type_name : "NULL");
/* Busca dentro da library */
TinyBlocks_Block* b = tb_library_find(lib_math, "Math.Mul");
printf("tb_library_find(lib_math, \"Math.Mul\") kind=%d name=%s\n",
b ? (int)b->kind : -1,
b && b->kind == TB_KIND_TYPE
? ((TinyBlocks_TypeBlock*)b)->type_name : "?");
}
/* ── Exemplo 5: to_string ────────────────────────────────────────────── */
printf("\n--- Exemplo 5: representação textual ---\n");
{
TinyBlocks_IntegerBlock* ib = tb_integer_block_create(rt, 42);
TinyBlocks_RealBlock* rb = tb_real_block_create(rt, 3.14);
TinyBlocks_TextBlock* tb2 = tb_text_block_create(rt, "olá");
char buf[256];
tb_block_eval(&ib->base, rt);
tb_block_eval(&rb->base, rt);
tb_block_eval(&tb2->base, rt);
tb_block_to_string(&ib->base, rt, buf, sizeof(buf));
printf("IntegerBlock: %s\n", buf);
tb_block_to_string(&rb->base, rt, buf, sizeof(buf));
printf("RealBlock: %s\n", buf);
tb_block_to_string(&tb2->base, rt, buf, sizeof(buf));
printf("TextBlock: %s\n", buf);
}
/* ── Resumo do runtime ───────────────────────────────────────────────── */
printf("\n--- Estado do runtime ---\n");
printf("blocks vivos: %u\n", rt->block_count);
printf("types: %u\n", rt->type_count);
printf("libraries: %u\n", rt->library_count);
/* 4. Desinicializar (libera tudo) */
tinyblocks_deinit(&rt);
printf("\n[runtime] deinicializado. rt = %p\n", (void*)rt);
return 0;
}
+260
View File
@@ -0,0 +1,260 @@
/*
* json.c — Library de JSON para o TinyBlocks Editor.
*
* Blocos incluídos:
* Json.Parse — texto -> json (null em caso de erro de sintaxe)
* Json.Stringify — json -> texto
* Json.Null — constrói json null
* Json.Bool — inteiro (0/1) -> json bool
* Json.Number — real -> json number
* Json.String — texto -> json string
* Json.Array — constrói array vazio
* Json.Object — constrói objeto vazio
* Json.Push — (array, valor) -> novo array com valor anexado
* Json.Set — (objeto, chave, valor) -> novo objeto com campo definido
* Json.Get — (objeto, chave) -> valor do campo, ou Json.Null
* Json.Index — (array, índice) -> valor na posição, ou Json.Null
* Json.Length — (json) -> nº de elementos (array/objeto) ou 0
* Json.TypeOf — (json) -> "null"|"bool"|"number"|"string"|"array"|"object"
* Json.ToNumber — (json, default) -> número (ou default se não for number/bool)
* Json.ToText — (json) -> string contida, ou "" se não for string
* Json.ToBool — (json, default) -> 0/1 (ou default se não for bool/number)
*
* Json.Push/Json.Set não mutam o valor recebido: clonam e devolvem uma nova
* árvore, mantendo o fluxo de dados imutável como o resto do TinyBlocks.
*
* Para compilar:
* make json
*
* Para carregar no editor:
* Ctrl+O → build/json.so ou arraste build/json.so para a janela
*/
#define _POSIX_C_SOURCE 200809L
#include <stdlib.h>
#include <string.h>
#include <tinyblocks/tinyblocks.h>
/* ── Helpers de leitura de inputs ────────────────────────────────────────── */
static const char* gt(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) {
TinyBlocks_Value v = tb_block_get_input(self, rt, idx);
return v.kind == TB_VALUE_TEXT ? v.as.text : "";
}
static double gn(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) {
TinyBlocks_Value v = tb_block_get_input(self, rt, idx);
if (v.kind == TB_VALUE_REAL) return v.as.real;
if (v.kind == TB_VALUE_INTEGER) return (double)v.as.integer;
return 0.0;
}
static int64_t gi(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) {
TinyBlocks_Value v = tb_block_get_input(self, rt, idx);
if (v.kind == TB_VALUE_INTEGER) return v.as.integer;
if (v.kind == TB_VALUE_REAL) return (int64_t)v.as.real;
return 0;
}
static TinyBlocks_JsonValue* gj(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) {
TinyBlocks_Value v = tb_block_get_input(self, rt, idx);
return tb_value_as_json(v);
}
/* Macro: produz output json/texto/integer/real e libera self->dirty */
#define EMIT_JSON(self, j) do { \
tb_block_set_output((self), 0, tb_value_json(j)); \
tb_json_release(j); \
(self)->dirty = false; \
} while (0)
/* ══════════════════════════════════════════════════════════════════════════
* Implementações dos blocos
* ══════════════════════════════════════════════════════════════════════════ */
static void eval_parse(TinyBlocks_Block* self, TinyBlocks* rt) {
char err[128] = {0};
TinyBlocks_JsonValue* j = tb_json_parse(gt(self, rt, 0), err, sizeof(err));
if (!j) j = tb_json_null();
EMIT_JSON(self, j);
}
static void eval_stringify(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_JsonValue* j = gj(self, rt, 0);
char* s = tb_json_stringify(j);
tb_block_set_output(self, 0, tb_value_text(s ? s : "null"));
free(s);
self->dirty = false;
}
static void eval_null(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)rt;
EMIT_JSON(self, tb_json_null());
}
static void eval_bool(TinyBlocks_Block* self, TinyBlocks* rt) {
EMIT_JSON(self, tb_json_bool(gi(self, rt, 0) != 0));
}
static void eval_number(TinyBlocks_Block* self, TinyBlocks* rt) {
EMIT_JSON(self, tb_json_number(gn(self, rt, 0)));
}
static void eval_string(TinyBlocks_Block* self, TinyBlocks* rt) {
EMIT_JSON(self, tb_json_string(gt(self, rt, 0)));
}
static void eval_array(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)rt;
EMIT_JSON(self, tb_json_array());
}
static void eval_object(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)rt;
EMIT_JSON(self, tb_json_object());
}
static void eval_push(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_JsonValue* arr = tb_json_clone(gj(self, rt, 0));
if (!arr || tb_json_kind(arr) != TB_JSON_ARRAY) {
tb_json_release(arr);
arr = tb_json_array();
}
TinyBlocks_JsonValue* item = gj(self, rt, 1);
tb_json_array_push(arr, item ? item : tb_json_null());
EMIT_JSON(self, arr);
}
static void eval_set(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_JsonValue* obj = tb_json_clone(gj(self, rt, 0));
if (!obj || tb_json_kind(obj) != TB_JSON_OBJECT) {
tb_json_release(obj);
obj = tb_json_object();
}
TinyBlocks_JsonValue* val = gj(self, rt, 2);
tb_json_object_set(obj, gt(self, rt, 1), val ? val : tb_json_null());
EMIT_JSON(self, obj);
}
static void eval_get(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_JsonValue* obj = gj(self, rt, 0);
TinyBlocks_JsonValue* val = tb_json_object_get(obj, gt(self, rt, 1));
if (!val) val = tb_json_null();
EMIT_JSON(self, val);
}
static void eval_index(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_JsonValue* arr = gj(self, rt, 0);
int64_t idx = gi(self, rt, 1);
TinyBlocks_JsonValue* val = (idx >= 0) ? tb_json_array_get(arr, (uint32_t)idx) : NULL;
if (!val) val = tb_json_null();
EMIT_JSON(self, val);
}
static void eval_length(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_JsonValue* j = gj(self, rt, 0);
uint32_t n = 0;
switch (tb_json_kind(j)) {
case TB_JSON_ARRAY: n = tb_json_array_length(j); break;
case TB_JSON_OBJECT: n = tb_json_object_length(j); break;
case TB_JSON_STRING: n = (uint32_t)strlen(tb_json_as_string(j)); break;
default: break;
}
tb_block_set_output(self, 0, tb_value_integer(n));
self->dirty = false;
}
static void eval_typeof(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_JsonValue* j = gj(self, rt, 0);
tb_block_set_output(self, 0, tb_value_text(tb_json_kind_name(j)));
self->dirty = false;
}
static void eval_to_number(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_JsonValue* j = gj(self, rt, 0);
double def = gn(self, rt, 1);
tb_block_set_output(self, 0, tb_value_real(tb_json_as_number(j, def)));
self->dirty = false;
}
static void eval_to_text(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_JsonValue* j = gj(self, rt, 0);
const char* s = tb_json_as_string(j);
tb_block_set_output(self, 0, tb_value_text(s ? s : ""));
self->dirty = false;
}
static void eval_to_bool(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_JsonValue* j = gj(self, rt, 0);
bool def = gi(self, rt, 1) != 0;
tb_block_set_output(self, 0, tb_value_integer(tb_json_as_bool(j, def) ? 1 : 0));
self->dirty = false;
}
/* ══════════════════════════════════════════════════════════════════════════
* Descritores de slots
* ══════════════════════════════════════════════════════════════════════════ */
static const TinyBlocks_SlotDesc out_json[] = {{"json", TB_VALUE_JSON}};
static const TinyBlocks_SlotDesc out_text[] = {{"text", TB_VALUE_TEXT}};
static const TinyBlocks_SlotDesc out_integer[] = {{"n", TB_VALUE_INTEGER}};
static const TinyBlocks_SlotDesc out_real[] = {{"n", TB_VALUE_REAL}};
static const TinyBlocks_SlotDesc in_text[] = {{"text", TB_VALUE_TEXT}};
static const TinyBlocks_SlotDesc in_json[] = {{"json", TB_VALUE_JSON}};
static const TinyBlocks_SlotDesc in_integer[] = {{"n", TB_VALUE_INTEGER}};
static const TinyBlocks_SlotDesc in_real[] = {{"n", TB_VALUE_REAL}};
static const TinyBlocks_SlotDesc in_json_json[] = {{"a", TB_VALUE_JSON},
{"b", TB_VALUE_JSON}};
static const TinyBlocks_SlotDesc in_json_text_json[] = {{"obj", TB_VALUE_JSON},
{"key", TB_VALUE_TEXT},
{"val", TB_VALUE_JSON}};
static const TinyBlocks_SlotDesc in_json_text[] = {{"obj", TB_VALUE_JSON},
{"key", TB_VALUE_TEXT}};
static const TinyBlocks_SlotDesc in_json_int[] = {{"arr", TB_VALUE_JSON},
{"idx", TB_VALUE_INTEGER}};
static const TinyBlocks_SlotDesc in_json_real[] = {{"json", TB_VALUE_JSON},
{"def", TB_VALUE_REAL}};
static const TinyBlocks_SlotDesc in_json_int_def[] = {{"json", TB_VALUE_JSON},
{"def", TB_VALUE_INTEGER}};
/* ══════════════════════════════════════════════════════════════════════════
* Registro da library
* ══════════════════════════════════════════════════════════════════════════ */
static bool json_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
TinyBlocks_TypeBlock* t;
#define REG(name, ins, ni, outs, no, fn) \
t = tb_type_block_create(rt, name, ins, ni, outs, no, fn); \
if (t) tb_library_add(lib, &t->base)
REG("Json.Parse", in_text, 1, out_json, 1, eval_parse);
REG("Json.Stringify", in_json, 1, out_text, 1, eval_stringify);
REG("Json.Null", NULL, 0, out_json, 1, eval_null);
REG("Json.Bool", in_integer, 1, out_json, 1, eval_bool);
REG("Json.Number", in_real, 1, out_json, 1, eval_number);
REG("Json.String", in_text, 1, out_json, 1, eval_string);
REG("Json.Array", NULL, 0, out_json, 1, eval_array);
REG("Json.Object", NULL, 0, out_json, 1, eval_object);
REG("Json.Push", in_json_json, 2, out_json, 1, eval_push);
REG("Json.Set", in_json_text_json, 3, out_json, 1, eval_set);
REG("Json.Get", in_json_text, 2, out_json, 1, eval_get);
REG("Json.Index", in_json_int, 2, out_json, 1, eval_index);
REG("Json.Length", in_json, 1, out_integer, 1, eval_length);
REG("Json.TypeOf", in_json, 1, out_text, 1, eval_typeof);
REG("Json.ToNumber", in_json_real, 2, out_real, 1, eval_to_number);
REG("Json.ToText", in_json, 1, out_text, 1, eval_to_text);
REG("Json.ToBool", in_json_int_def, 2, out_integer, 1, eval_to_bool);
#undef REG
return true;
}
static void json_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
(void)rt; (void)lib;
}
TINYBLOCKS_DEFINE_LIBRARY(json,
"tinyblocks-json",
"1.0.0",
json_init,
json_deinit)
+109
View File
@@ -0,0 +1,109 @@
/*
* mcp.c — Plugin TinyBlocks com blocos MCP (Model Context Protocol).
*
* Blocos:
* MCP.Server — literal: armazena a URL do servidor MCP
* HTTP: "http://localhost:3000/mcp"
* stdio: "stdio://npx @modelcontextprotocol/server-filesystem /tmp"
*
* MCP.Ping — input: url (text) → output: status (text)
* Verifica se o servidor responde.
*
* MCP.ListTools — input: url (text) → output: tools (text)
* Lista ferramentas disponíveis no servidor.
*
* MCP.Call — inputs: url, tool, args (text) → output: result (text)
* Chama uma ferramenta com argumentos JSON.
*
* Compilar:
* make mcp-lib
*
* Carregar no editor:
* ./build/editor build/mcp.so ou Ctrl+O → build/mcp.so
*
* Exemplo de uso no editor:
* [Literal.Text "stdio://npx @modelcontextprotocol/server-filesystem /tmp"]
* → [MCP.ListTools] → [IO.Print "tools"]
*/
#define _POSIX_C_SOURCE 200809L
#include <stdlib.h>
#include <string.h>
#include <tinyblocks/tinyblocks.h>
#include <tinyblocks-mcp/tb_mcp.h>
/* ── Helper: lê texto de slot ────────────────────────────────────────────── */
static const char* gs(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) {
TinyBlocks_Value v = tb_block_get_input(self, rt, idx);
return (v.kind == TB_VALUE_TEXT && v.as.text) ? v.as.text : "";
}
/* ── MCP.Ping ────────────────────────────────────────────────────────────── */
static void eval_mcp_ping(TinyBlocks_Block* self, TinyBlocks* rt) {
const char* url = gs(self, rt, 0);
char* result = tb_mcp_ping(url);
tb_block_set_output(self, 0, tb_value_text(result ? result : "erro"));
free(result);
self->dirty = false;
}
/* ── MCP.ListTools ───────────────────────────────────────────────────────── */
static void eval_mcp_list_tools(TinyBlocks_Block* self, TinyBlocks* rt) {
const char* url = gs(self, rt, 0);
char* result = tb_mcp_list_tools(url);
tb_block_set_output(self, 0, tb_value_text(result ? result : "erro"));
free(result);
self->dirty = false;
}
/* ── MCP.Call ────────────────────────────────────────────────────────────── */
static void eval_mcp_call(TinyBlocks_Block* self, TinyBlocks* rt) {
const char* url = gs(self, rt, 0);
const char* tool = gs(self, rt, 1);
const char* args = gs(self, rt, 2);
char* result = tb_mcp_call_tool(url, tool, args);
tb_block_set_output(self, 0, tb_value_text(result ? result : "erro"));
free(result);
self->dirty = false;
}
/* ── Slots ───────────────────────────────────────────────────────────────── */
static const TinyBlocks_SlotDesc url_in[] = {{"url", TB_VALUE_TEXT}};
static const TinyBlocks_SlotDesc call_in[] = {{"url", TB_VALUE_TEXT},
{"tool", TB_VALUE_TEXT},
{"args", TB_VALUE_TEXT}};
static const TinyBlocks_SlotDesc status_out[] = {{"status", TB_VALUE_TEXT}};
static const TinyBlocks_SlotDesc tools_out[] = {{"tools", TB_VALUE_TEXT}};
static const TinyBlocks_SlotDesc result_out[] = {{"result", TB_VALUE_TEXT}};
/* ── Registro ────────────────────────────────────────────────────────────── */
static bool mcp_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
if (!tb_mcp_init()) return false;
TinyBlocks_TypeBlock* t;
t = tb_type_block_create(rt, "MCP.Ping",
url_in, 1, status_out, 1, eval_mcp_ping);
if (t) tb_library_add(lib, &t->base);
t = tb_type_block_create(rt, "MCP.ListTools",
url_in, 1, tools_out, 1, eval_mcp_list_tools);
if (t) tb_library_add(lib, &t->base);
t = tb_type_block_create(rt, "MCP.Call",
call_in, 3, result_out, 1, eval_mcp_call);
if (t) tb_library_add(lib, &t->base);
return true;
}
static void mcp_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
(void)rt; (void)lib;
tb_mcp_deinit();
}
TINYBLOCKS_DEFINE_LIBRARY(mcp,
"tinyblocks-mcp",
"1.0.0",
mcp_init,
mcp_deinit)
+125
View File
@@ -0,0 +1,125 @@
/*
* mylib.c — Library de exemplo para testar hot reload no TinyBlocks Editor.
*
* Blocos incluídos:
* Extra.Square — n² de um inteiro
* Extra.Cube — n³ de um inteiro
* Extra.Clamp — limita valor entre min e max
* Extra.Fibonacci — n-ésimo número de Fibonacci
* Extra.IsEven — 1 se par, 0 se ímpar
* Extra.IntToText — converte inteiro em texto
* Extra.Pow — base elevado a exp (inteiros)
*
* Para compilar:
* make mylib
*
* Para carregar no editor:
* Ctrl+O → build/mylib.so ou arraste build/mylib.so para a janela
*/
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tinyblocks/tinyblocks.h>
/* ── Slots reutilizáveis ─────────────────────────────────────────────────── */
static const TinyBlocks_SlotDesc in_n[] = {{"n", TB_VALUE_INTEGER}};
static const TinyBlocks_SlotDesc in_ab[] = {{"a", TB_VALUE_INTEGER},
{"b", TB_VALUE_INTEGER}};
static const TinyBlocks_SlotDesc in_clamp[]= {{"val", TB_VALUE_INTEGER},
{"min", TB_VALUE_INTEGER},
{"max", TB_VALUE_INTEGER}};
static const TinyBlocks_SlotDesc out_int[] = {{"out", TB_VALUE_INTEGER}};
static const TinyBlocks_SlotDesc out_txt[] = {{"out", TB_VALUE_TEXT}};
/* ── Implementações ──────────────────────────────────────────────────────── */
static void eval_square(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Value v = tb_block_get_input(self, rt, 0);
int64_t n = v.kind==TB_VALUE_INTEGER ? v.as.integer : 0;
tb_block_set_output(self, 0, tb_value_integer(n * n));
}
static void eval_cube(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Value v = tb_block_get_input(self, rt, 0);
int64_t n = v.kind==TB_VALUE_INTEGER ? v.as.integer : 0;
tb_block_set_output(self, 0, tb_value_integer(n * n * n));
}
static void eval_pow(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Value a = tb_block_get_input(self, rt, 0);
TinyBlocks_Value b = tb_block_get_input(self, rt, 1);
int64_t base = a.kind==TB_VALUE_INTEGER ? a.as.integer : 0;
int64_t exp = b.kind==TB_VALUE_INTEGER ? b.as.integer : 0;
if (exp < 0) { tb_block_set_output(self, 0, tb_value_integer(0)); return; }
int64_t result = 1;
for (int64_t i = 0; i < exp; i++) result *= base;
tb_block_set_output(self, 0, tb_value_integer(result));
}
static void eval_clamp(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Value val = tb_block_get_input(self, rt, 0);
TinyBlocks_Value mn = tb_block_get_input(self, rt, 1);
TinyBlocks_Value mx = tb_block_get_input(self, rt, 2);
int64_t v = val.kind==TB_VALUE_INTEGER ? val.as.integer : 0;
int64_t lo = mn.kind ==TB_VALUE_INTEGER ? mn.as.integer : 0;
int64_t hi = mx.kind ==TB_VALUE_INTEGER ? mx.as.integer : 100;
if (v < lo) v = lo;
if (v > hi) v = hi;
tb_block_set_output(self, 0, tb_value_integer(v));
}
static void eval_fibonacci(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Value v = tb_block_get_input(self, rt, 0);
int64_t n = v.kind==TB_VALUE_INTEGER ? v.as.integer : 0;
if (n <= 0) { tb_block_set_output(self, 0, tb_value_integer(0)); return; }
if (n == 1) { tb_block_set_output(self, 0, tb_value_integer(1)); return; }
int64_t a=0, b=1;
for (int64_t i=2; i<=n && i<94; i++) { int64_t c=a+b; a=b; b=c; }
tb_block_set_output(self, 0, tb_value_integer(b));
}
static void eval_iseven(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Value v = tb_block_get_input(self, rt, 0);
int64_t n = v.kind==TB_VALUE_INTEGER ? v.as.integer : 0;
tb_block_set_output(self, 0, tb_value_integer((n % 2 == 0) ? 1 : 0));
}
static void eval_int_to_text(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Value v = tb_block_get_input(self, rt, 0);
int64_t n = v.kind==TB_VALUE_INTEGER ? v.as.integer : 0;
char buf[32];
snprintf(buf, sizeof(buf), "%lld", (long long)n);
tb_block_set_output(self, 0, tb_value_text(buf));
}
/* ── Registro da library ─────────────────────────────────────────────────── */
static bool mylib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
TinyBlocks_TypeBlock* t;
#define REG(name, ins, ni, outs, no, fn) \
t = tb_type_block_create(rt, name, ins, ni, outs, no, fn); \
if (t) tb_library_add(lib, &t->base)
REG("Extra.Square", in_n, 1, out_int, 1, eval_square);
REG("Extra.Cube", in_n, 1, out_int, 1, eval_cube);
REG("Extra.Pow", in_ab, 2, out_int, 1, eval_pow);
REG("Extra.Clamp", in_clamp, 3, out_int, 1, eval_clamp);
REG("Extra.Fibonacci", in_n, 1, out_int, 1, eval_fibonacci);
REG("Extra.IsEven", in_n, 1, out_int, 1, eval_iseven);
REG("Extra.IntToText", in_n, 1, out_txt, 1, eval_int_to_text);
#undef REG
return true;
}
static void mylib_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
(void)rt; (void)lib;
}
TINYBLOCKS_DEFINE_LIBRARY(mylib,
"mylib",
"1.0.0",
mylib_init,
mylib_deinit)
+111
View File
@@ -0,0 +1,111 @@
/*
* python.c — Plugin TinyBlocks com blocos Python.*.
*
* Blocos:
* Python.Eval — avalia expressão Python com variáveis x0..x3
* Python.Run — executa script Python com variáveis x0..x3, captura stdout
*
* Compilar:
* make python-lib
*
* Carregar no editor:
* ./build/editor build/python.so ou Ctrl+O → build/python.so
*
* Exemplos de expressões:
* x0 ** 2 + x1 ** 2
* __import__('math').sqrt(x0)
* [x*x for x in range(int(x0))]
*/
#define _POSIX_C_SOURCE 200809L
#include <stdlib.h>
#include <string.h>
#include <tinyblocks/tinyblocks.h>
#include <tinyblocks-python/tb_python.h>
/* ── Helper: lê float de slot numérico ──────────────────────────────────── */
static double gd(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) {
TinyBlocks_Value v = tb_block_get_input(self, rt, idx);
if (v.kind == TB_VALUE_REAL) return v.as.real;
if (v.kind == TB_VALUE_INTEGER) return (double)v.as.integer;
return 0.0;
}
static const char* gs(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) {
TinyBlocks_Value v = tb_block_get_input(self, rt, idx);
return (v.kind == TB_VALUE_TEXT && v.as.text) ? v.as.text : "";
}
/* ── Python.Eval ─────────────────────────────────────────────────────────── */
/*
* Inputs: expr (text), x0..x3 (real)
* Output: result (text)
*/
static void eval_python_eval(TinyBlocks_Block* self, TinyBlocks* rt) {
const char* expr = gs(self, rt, 0);
double vals[4] = { gd(self,rt,1), gd(self,rt,2), gd(self,rt,3), gd(self,rt,4) };
static const char* names[] = {"x0","x1","x2","x3"};
char* result = tb_python_eval(expr, names, vals, 4);
tb_block_set_output(self, 0, tb_value_text(result ? result : ""));
free(result);
self->dirty = false;
}
/* ── Python.Run ──────────────────────────────────────────────────────────── */
/*
* Inputs: code (text), x0..x3 (real)
* Output: stdout (text)
*/
static void eval_python_run(TinyBlocks_Block* self, TinyBlocks* rt) {
const char* code = gs(self, rt, 0);
double vals[4] = { gd(self,rt,1), gd(self,rt,2), gd(self,rt,3), gd(self,rt,4) };
static const char* names[] = {"x0","x1","x2","x3"};
char* out = tb_python_run_with_vars(code, names, vals, 4);
tb_block_set_output(self, 0, tb_value_text(out ? out : ""));
free(out);
self->dirty = false;
}
/* ── Slots ───────────────────────────────────────────────────────────────── */
static const TinyBlocks_SlotDesc eval_in[] = {
{"expr", TB_VALUE_TEXT},
{"x0", TB_VALUE_REAL}, {"x1", TB_VALUE_REAL},
{"x2", TB_VALUE_REAL}, {"x3", TB_VALUE_REAL},
};
static const TinyBlocks_SlotDesc run_in[] = {
{"code", TB_VALUE_TEXT},
{"x0", TB_VALUE_REAL}, {"x1", TB_VALUE_REAL},
{"x2", TB_VALUE_REAL}, {"x3", TB_VALUE_REAL},
};
static const TinyBlocks_SlotDesc text_out[] = {{"result", TB_VALUE_TEXT}};
static const TinyBlocks_SlotDesc stdout_out[]= {{"stdout", TB_VALUE_TEXT}};
/* ── Registro ────────────────────────────────────────────────────────────── */
static bool py_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
if (!tb_python_init()) return false;
TinyBlocks_TypeBlock* t;
t = tb_type_block_create(rt, "Python.Eval",
eval_in, 5, text_out, 1, eval_python_eval);
if (t) tb_library_add(lib, &t->base);
t = tb_type_block_create(rt, "Python.Run",
run_in, 5, stdout_out, 1, eval_python_run);
if (t) tb_library_add(lib, &t->base);
return true;
}
static void py_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
(void)rt; (void)lib;
tb_python_deinit();
}
TINYBLOCKS_DEFINE_LIBRARY(python,
"tinyblocks-python",
"1.0.0",
py_init,
py_deinit)
+162
View File
@@ -0,0 +1,162 @@
/*
* TinyBlocks — exemplo SDL2
*
* Demonstra o uso da library tinyblocks-sdl2 registrada estaticamente.
* Abre uma janela 640x480, desenha um retângulo pulsante e fecha ao pressionar
* Escape ou fechar a janela. Toda a lógica gráfica é expressa como blocos.
*/
#include <stdio.h>
#include <tinyblocks/tinyblocks.h>
#include <tb_sdl2.h>
int main(void)
{
/* ── Runtime ──────────────────────────────────────────────────────────── */
TinyBlocks* rt = NULL;
if (!tinyblocks_init(&rt, NULL)) { fprintf(stderr, "init falhou\n"); return 1; }
/* ── Registra a library SDL2 estaticamente ────────────────────────────── */
TinyBlocks_LibraryBlock* sdl2 = tb_library_register(rt, tb_sdl2_get_library());
if (!sdl2) {
fprintf(stderr, "Falha ao registrar SDL2: %s\n", tinyblocks_last_error(rt));
tinyblocks_deinit(&rt);
return 1;
}
printf("Library '%s' carregada com %u blocos\n",
sdl2->base.name, sdl2->block_count);
/* ── Busca os TypeBlocks que vamos usar ───────────────────────────────── */
TinyBlocks_TypeBlock* T_Init = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.Init");
TinyBlocks_TypeBlock* T_Quit = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.Quit");
TinyBlocks_TypeBlock* T_Window = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.Window");
TinyBlocks_TypeBlock* T_Renderer = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.Renderer");
TinyBlocks_TypeBlock* T_SetColor = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.SetDrawColor");
TinyBlocks_TypeBlock* T_Clear = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.Clear");
TinyBlocks_TypeBlock* T_FillRect = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.FillRect");
TinyBlocks_TypeBlock* T_Present = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.Present");
TinyBlocks_TypeBlock* T_PollEvent = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.PollEvent");
TinyBlocks_TypeBlock* T_DestroyWin = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.DestroyWindow");
TinyBlocks_TypeBlock* T_DestroyRend = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.DestroyRenderer");
TinyBlocks_TypeBlock* T_Delay = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.Delay");
/* ── SDL2.Init ────────────────────────────────────────────────────────── */
TinyBlocks_Block* b_init = tb_block_create(rt, T_Init);
tb_block_eval(b_init, rt);
/* ── SDL2.Window ─────────────────────────────────────────────────────── */
TinyBlocks_TextBlock* lit_title = tb_text_block_create(rt, "TinyBlocks SDL2");
TinyBlocks_IntegerBlock* lit_cx = tb_integer_block_create(rt, -1); /* centered */
TinyBlocks_IntegerBlock* lit_cy = tb_integer_block_create(rt, -1);
TinyBlocks_IntegerBlock* lit_w = tb_integer_block_create(rt, 640);
TinyBlocks_IntegerBlock* lit_h = tb_integer_block_create(rt, 480);
TinyBlocks_Block* b_window = tb_block_create(rt, T_Window);
tb_block_connect(b_window, 0, &lit_title->base, 0);
tb_block_connect(b_window, 1, &lit_cx->base, 0);
tb_block_connect(b_window, 2, &lit_cy->base, 0);
tb_block_connect(b_window, 3, &lit_w->base, 0);
tb_block_connect(b_window, 4, &lit_h->base, 0);
tb_block_eval(b_window, rt);
/* ── SDL2.Renderer ───────────────────────────────────────────────────── */
TinyBlocks_Block* b_renderer = tb_block_create(rt, T_Renderer);
tb_block_connect(b_renderer, 0, b_window, 0);
tb_block_eval(b_renderer, rt);
/* ── Blocos reutilizáveis por frame ──────────────────────────────────── */
TinyBlocks_Block* b_poll = tb_block_create(rt, T_PollEvent);
TinyBlocks_Block* b_bg_color = tb_block_create(rt, T_SetColor);
TinyBlocks_Block* b_clear = tb_block_create(rt, T_Clear);
TinyBlocks_Block* b_rect_color= tb_block_create(rt, T_SetColor);
TinyBlocks_Block* b_rect = tb_block_create(rt, T_FillRect);
TinyBlocks_Block* b_present = tb_block_create(rt, T_Present);
TinyBlocks_Block* b_delay = tb_block_create(rt, T_Delay);
/* Cor de fundo: preto */
TinyBlocks_IntegerBlock* lit_0 = tb_integer_block_create(rt, 0);
TinyBlocks_IntegerBlock* lit_255 = tb_integer_block_create(rt, 255);
tb_block_connect(b_bg_color, 0, b_renderer, 0);
tb_block_connect(b_bg_color, 1, &lit_0->base, 0);
tb_block_connect(b_bg_color, 2, &lit_0->base, 0);
tb_block_connect(b_bg_color, 3, &lit_0->base, 0);
tb_block_connect(b_bg_color, 4, &lit_255->base, 0);
tb_block_connect(b_clear, 0, b_renderer, 0);
/* Cor do retângulo: vermelho */
TinyBlocks_IntegerBlock* lit_r = tb_integer_block_create(rt, 220);
TinyBlocks_IntegerBlock* lit_g = tb_integer_block_create(rt, 50);
TinyBlocks_IntegerBlock* lit_b2= tb_integer_block_create(rt, 50);
tb_block_connect(b_rect_color, 0, b_renderer, 0);
tb_block_connect(b_rect_color, 1, &lit_r->base, 0);
tb_block_connect(b_rect_color, 2, &lit_g->base, 0);
tb_block_connect(b_rect_color, 3, &lit_b2->base, 0);
tb_block_connect(b_rect_color, 4, &lit_255->base, 0);
/* Retângulo dinâmico — usaremos IntegerBlocks mutáveis para posição */
TinyBlocks_IntegerBlock* lit_rx = tb_integer_block_create(rt, 100);
TinyBlocks_IntegerBlock* lit_ry = tb_integer_block_create(rt, 100);
TinyBlocks_IntegerBlock* lit_rw = tb_integer_block_create(rt, 200);
TinyBlocks_IntegerBlock* lit_rh = tb_integer_block_create(rt, 120);
tb_block_connect(b_rect, 0, b_renderer, 0);
tb_block_connect(b_rect, 1, &lit_rx->base, 0);
tb_block_connect(b_rect, 2, &lit_ry->base, 0);
tb_block_connect(b_rect, 3, &lit_rw->base, 0);
tb_block_connect(b_rect, 4, &lit_rh->base, 0);
tb_block_connect(b_present, 0, b_renderer, 0);
TinyBlocks_IntegerBlock* lit_delay = tb_integer_block_create(rt, 16); /* ~60fps */
tb_block_connect(b_delay, 0, &lit_delay->base, 0);
/* ── Loop principal ──────────────────────────────────────────────────── */
printf("Janela aberta. Pressione Escape ou feche a janela para sair.\n");
int running = 1;
int frame = 0;
while (running) {
/* Eventos */
b_poll->dirty = true;
tb_block_eval(b_poll, rt);
TinyBlocks_Value vquit = b_poll->outputs[1];
TinyBlocks_Value vtype = b_poll->outputs[0];
if (vquit.as.integer) running = 0;
if (vtype.as.integer == 768 /* SDL_KEYDOWN */) {
/* sacancode 41 = Escape */
if (b_poll->outputs[2].as.integer == 41) running = 0;
}
/* Animação simples: retângulo oscila horizontalmente */
frame++;
int offset = (int)(80.0 * (0.5 + 0.5 * ((frame % 120) < 60
? (frame % 60) / 60.0
: 1.0 - (frame % 60) / 60.0)));
tb_integer_block_set(lit_rx, 80 + offset);
/* Renderização — cada bloco é avaliado na ordem correta */
b_bg_color->dirty = true; tb_block_eval(b_bg_color, rt);
b_clear->dirty = true; tb_block_eval(b_clear, rt);
b_rect_color->dirty = true; tb_block_eval(b_rect_color, rt);
b_rect->dirty = true; tb_block_eval(b_rect, rt);
b_present->dirty = true; tb_block_eval(b_present, rt);
b_delay->dirty = true; tb_block_eval(b_delay, rt);
}
/* ── Limpeza SDL2 via blocos ──────────────────────────────────────────── */
TinyBlocks_Block* b_drend = tb_block_create(rt, T_DestroyRend);
TinyBlocks_Block* b_dwin = tb_block_create(rt, T_DestroyWin);
TinyBlocks_Block* b_quit = tb_block_create(rt, T_Quit);
tb_block_connect(b_drend, 0, b_renderer, 0);
tb_block_connect(b_dwin, 0, b_window, 0);
tb_block_eval(b_drend, rt);
tb_block_eval(b_dwin, rt);
tb_block_eval(b_quit, rt);
tinyblocks_deinit(&rt);
printf("Encerrado.\n");
return 0;
}
+210
View File
@@ -0,0 +1,210 @@
/*
* vector.c — Library de vetor 2D para o TinyBlocks Editor.
*
* Blocos incluídos:
* Vector.BeginPath — inicia um novo path (sem inputs)
* Vector.MoveTo — move caneta para (x, y)
* Vector.LineTo — linha até (x, y)
* Vector.ClosePath — fecha sub-path atual
* Vector.Stroke — aplica traçado com cor/espessura RGBA
* Vector.Fill — aplica preenchimento RGBA ao path
* Vector.Rect — retângulo preenchido (usa Fill por cima)
* Vector.Circle — círculo preenchido
* Vector.Render — recebe vector e desenha no corpo do bloco (on_draw)
*
* Todos os blocos encadeiam: cada um recebe o vetor do anterior e devolve
* um novo com o comando acrescentado. Combine-os com Vector.Render no final.
*
* Para compilar:
* make vector
*
* Para carregar no editor:
* Ctrl+O → build/vector.so ou arraste build/vector.so para a janela
*/
#define _POSIX_C_SOURCE 200809L
#include <stdlib.h>
#include <string.h>
#include <tinyblocks/tinyblocks.h>
#include <tinyblocks/tb_renderable_block.h>
/* ── Helper: lê float de qualquer slot numérico ──────────────────────────── */
static float gf(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) {
TinyBlocks_Value v = tb_block_get_input(self, rt, idx);
if (v.kind == TB_VALUE_REAL) return (float)v.as.real;
if (v.kind == TB_VALUE_INTEGER) return (float)v.as.integer;
return 0.0f;
}
/* Helper: obtém VectorData do slot 0 e clona (ou cria novo se não conectado) */
static TinyBlocks_VectorData* clone_vec(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Value v = tb_block_get_input(self, rt, 0);
TinyBlocks_VectorData* src = tb_value_as_vector(v);
return src ? tb_vector_data_clone(src) : tb_vector_data_create();
}
/* Macro: produz output vector e libera a ref local */
#define EMIT_VEC(self, v) do { \
tb_block_set_output((self), 0, tb_value_vector(v)); \
tb_vector_data_release(v); \
(self)->dirty = false; \
} while(0)
/* ══════════════════════════════════════════════════════════════════════════
* Implementações dos blocos
* ══════════════════════════════════════════════════════════════════════════ */
static void eval_begin_path(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)rt;
TinyBlocks_VectorData* v = tb_vector_data_create();
if (!v) return;
tb_vector_begin_path(v);
EMIT_VEC(self, v);
}
static void eval_move_to(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_VectorData* v = clone_vec(self, rt);
if (!v) return;
tb_vector_move_to(v, gf(self, rt, 1), gf(self, rt, 2));
EMIT_VEC(self, v);
}
static void eval_line_to(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_VectorData* v = clone_vec(self, rt);
if (!v) return;
tb_vector_line_to(v, gf(self, rt, 1), gf(self, rt, 2));
EMIT_VEC(self, v);
}
static void eval_close_path(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_VectorData* v = clone_vec(self, rt);
if (!v) return;
tb_vector_close_path(v);
EMIT_VEC(self, v);
}
static void eval_stroke(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_VectorData* v = clone_vec(self, rt);
if (!v) return;
tb_vector_stroke(v, gf(self,rt,1), gf(self,rt,2),
gf(self,rt,3), gf(self,rt,4), gf(self,rt,5));
EMIT_VEC(self, v);
}
static void eval_fill(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_VectorData* v = clone_vec(self, rt);
if (!v) return;
tb_vector_fill(v, gf(self,rt,1), gf(self,rt,2),
gf(self,rt,3), gf(self,rt,4));
EMIT_VEC(self, v);
}
static void eval_rect(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_VectorData* v = clone_vec(self, rt);
if (!v) return;
tb_vector_rect(v, gf(self,rt,1), gf(self,rt,2),
gf(self,rt,3), gf(self,rt,4));
EMIT_VEC(self, v);
}
static void eval_circle(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_VectorData* v = clone_vec(self, rt);
if (!v) return;
tb_vector_circle(v, gf(self,rt,1), gf(self,rt,2), gf(self,rt,3));
EMIT_VEC(self, v);
}
/* Vector.Render — passa o vetor adiante e tem on_render para preview */
static void eval_render(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Value v = tb_block_get_input(self, rt, 0);
/* Clona para manter o vector vivo no output (get_input é não-owning) */
if (v.kind == TB_VALUE_VECTOR && v.as.vector) {
tb_vector_data_retain(v.as.vector);
tb_block_set_output(self, 0, v); /* set_output toma ownership */
}
self->dirty = false;
}
static bool on_draw_vector(TinyBlocks_Block* self, TinyBlocks* rt,
TinyBlocks_RenderableBlock** dst) {
(void)rt;
if (!self) return false;
TinyBlocks_RenderableBlock* rb = tb_renderable_acquire();
if (!rb) return false;
TinyBlocks_VectorData* vd = tb_value_as_vector(self->outputs[0]);
if (vd) tb_draw_ctx_play(rb, vd);
*dst = rb;
return true;
}
/* ══════════════════════════════════════════════════════════════════════════
* Descritores de slots
* ══════════════════════════════════════════════════════════════════════════ */
static const TinyBlocks_SlotDesc out_vec[] = {{"vec", TB_VALUE_VECTOR}};
static const TinyBlocks_SlotDesc in_vec[] = {{"vec", TB_VALUE_VECTOR}};
static const TinyBlocks_SlotDesc in_vec_xy[] = {{"vec", TB_VALUE_VECTOR},
{"x", TB_VALUE_REAL},
{"y", TB_VALUE_REAL}};
static const TinyBlocks_SlotDesc in_vec_rgba[] = {{"vec", TB_VALUE_VECTOR},
{"r", TB_VALUE_REAL},
{"g", TB_VALUE_REAL},
{"b", TB_VALUE_REAL},
{"a", TB_VALUE_REAL}};
static const TinyBlocks_SlotDesc in_vec_rgbaw[] = {{"vec", TB_VALUE_VECTOR},
{"r", TB_VALUE_REAL},
{"g", TB_VALUE_REAL},
{"b", TB_VALUE_REAL},
{"a", TB_VALUE_REAL},
{"w", TB_VALUE_REAL}};
static const TinyBlocks_SlotDesc in_vec_xywh[] = {{"vec", TB_VALUE_VECTOR},
{"x", TB_VALUE_REAL},
{"y", TB_VALUE_REAL},
{"w", TB_VALUE_REAL},
{"h", TB_VALUE_REAL}};
static const TinyBlocks_SlotDesc in_vec_cyr[] = {{"vec", TB_VALUE_VECTOR},
{"cx", TB_VALUE_REAL},
{"cy", TB_VALUE_REAL},
{"r", TB_VALUE_REAL}};
/* ══════════════════════════════════════════════════════════════════════════
* Registro da library
* ══════════════════════════════════════════════════════════════════════════ */
static bool vector_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
TinyBlocks_TypeBlock* t;
#define REG(name, ins, ni, fn) \
t = tb_type_block_create(rt, name, ins, ni, out_vec, 1, fn); \
if (t) tb_library_add(lib, &t->base)
REG("Vector.BeginPath", NULL, 0, eval_begin_path);
REG("Vector.MoveTo", in_vec_xy, 3, eval_move_to);
REG("Vector.LineTo", in_vec_xy, 3, eval_line_to);
REG("Vector.ClosePath", in_vec, 1, eval_close_path);
REG("Vector.Stroke", in_vec_rgbaw, 6, eval_stroke);
REG("Vector.Fill", in_vec_rgba, 5, eval_fill);
REG("Vector.Rect", in_vec_xywh, 5, eval_rect);
REG("Vector.Circle", in_vec_cyr, 4, eval_circle);
#undef REG
/* Vector.Render tem on_draw — preview gráfico no corpo do bloco */
t = tb_type_block_create(rt, "Vector.Render",
in_vec, 1, out_vec, 1, eval_render);
if (t) {
t->on_draw = on_draw_vector;
tb_library_add(lib, &t->base);
}
return true;
}
static void vector_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
(void)rt; (void)lib;
}
TINYBLOCKS_DEFINE_LIBRARY(vector,
"tinyblocks-vector",
"1.0.0",
vector_init,
vector_deinit)
+95
View File
@@ -0,0 +1,95 @@
/*
* TinyBlocks — tb_block.h
* Estrutura base de todo bloco e operações polimórficas via vtable.
*
* Todos os tipos concretos (TypeBlock, LibraryBlock, TextBlock…) começam com
* um campo `TinyBlocks_Block base` — herança em C via primeiro membro.
*/
#ifndef TINYBLOCKS_BLOCK_H
#define TINYBLOCKS_BLOCK_H
#include "tb_defs.h"
/* ── Vtable de bloco ─────────────────────────────────────────────────────── */
typedef struct TinyBlocks_BlockVTable {
/* Avalia o bloco: lê inputs, processa, escreve outputs */
void (*eval) (TinyBlocks_Block* self, TinyBlocks* rt);
/* Libera recursos internos (NÃO libera o ponteiro do bloco em si) */
void (*destroy) (TinyBlocks_Block* self, TinyBlocks* rt);
/* Representação textual; escreve em buf[0..buf_size-1], retorna len */
size_t (*to_string)(TinyBlocks_Block* self, TinyBlocks* rt,
char* buf, size_t buf_size);
/* Clona recursivamente o bloco (o runtime registra o clone) */
TinyBlocks_Block* (*clone) (const TinyBlocks_Block* self, TinyBlocks* rt);
} TinyBlocks_BlockVTable;
/* ── Estrutura base de todo bloco ────────────────────────────────────────── */
struct TinyBlocks_Block {
TinyBlocks_BlockKind kind;
const TinyBlocks_BlockVTable* vtable;
uint64_t id; /* ID único gerado pelo runtime */
char* name; /* rótulo opcional (heap-owned) */
TinyBlocks_TypeBlock* type; /* tipo/classe deste bloco; NULL *
* para blocos primitivos built-in */
/* Slots de entrada: connections[i] descreve de onde vem o input i */
TinyBlocks_Connection* inputs;
uint32_t input_count;
/* Slots de saída: valores computados pelo último eval */
TinyBlocks_Value* outputs;
uint32_t output_count;
TinyBlocks_Block* parent; /* bloco pai (se aninhado) */
void* userdata; /* dados extra por instância */
bool dirty; /* marcado quando inputs mudam */
bool in_eval; /* guard anti-ciclo */
};
/* ── Ciclo de vida ───────────────────────────────────────────────────────── */
/* Cria um bloco a partir de um TypeBlock; registra no runtime */
TB_API TinyBlocks_Block* tb_block_create (TinyBlocks* rt, TinyBlocks_TypeBlock* type);
/* Destrói e libera; remove do registro do runtime */
TB_API void tb_block_destroy(TinyBlocks_Block* block, TinyBlocks* rt);
/* Avalia o bloco (e seus inputs recursivamente se dirty) */
TB_API void tb_block_eval (TinyBlocks_Block* block, TinyBlocks* rt);
/* Clona o bloco e o registra no runtime */
TB_API TinyBlocks_Block* tb_block_clone (const TinyBlocks_Block* block, TinyBlocks* rt);
/* Representação textual */
TB_API size_t tb_block_to_string(TinyBlocks_Block* block, TinyBlocks* rt,
char* buf, size_t buf_size);
/* ── Conexões ────────────────────────────────────────────────────────────── */
TB_API bool tb_block_connect (TinyBlocks_Block* target, uint32_t input_idx,
TinyBlocks_Block* source, uint32_t output_idx);
TB_API void tb_block_disconnect(TinyBlocks_Block* target, uint32_t input_idx);
TB_API bool tb_block_set_default(TinyBlocks_Block* target, uint32_t input_idx,
TinyBlocks_Value default_value);
/* ── Acesso a valores (para uso dentro de eval_fn) ───────────────────────── */
/* Retorna o valor do input[idx]; resolve a conexão se necessário */
TB_API TinyBlocks_Value tb_block_get_input (TinyBlocks_Block* self, TinyBlocks* rt,
uint32_t input_idx);
/* Escreve no output[idx] */
TB_API void tb_block_set_output(TinyBlocks_Block* self,
uint32_t output_idx, TinyBlocks_Value v);
/* ── Downcasting seguro ──────────────────────────────────────────────────── */
TB_API TinyBlocks_TypeBlock* tb_block_as_type (TinyBlocks_Block* b);
TB_API TinyBlocks_LibraryBlock* tb_block_as_library(TinyBlocks_Block* b);
TB_API TinyBlocks_TextBlock* tb_block_as_text (TinyBlocks_Block* b);
TB_API TinyBlocks_IntegerBlock* tb_block_as_integer(TinyBlocks_Block* b);
TB_API TinyBlocks_RealBlock* tb_block_as_real (TinyBlocks_Block* b);
/* ── Helpers internos (usados por implementações de built-ins) ───────────── */
TB_API TinyBlocks_Block* tb_block_alloc_base(TinyBlocks* rt,
TinyBlocks_BlockKind kind,
size_t struct_size,
uint32_t input_count,
uint32_t output_count,
const TinyBlocks_BlockVTable* vtable);
#endif /* TINYBLOCKS_BLOCK_H */
+116
View File
@@ -0,0 +1,116 @@
/*
* TinyBlocks — tb_defs.h
* Forward declarations, enums e tipos primitivos compartilhados por todo o runtime.
*/
#ifndef TINYBLOCKS_DEFS_H
#define TINYBLOCKS_DEFS_H
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
/* ── Visibilidade de API ─────────────────────────────────────────────────── */
#ifdef _WIN32
# define TB_API __declspec(dllexport)
#else
# define TB_API __attribute__((visibility("default")))
#endif
/* ── Forward declarations ────────────────────────────────────────────────── */
typedef struct TinyBlocks TinyBlocks;
typedef struct TinyBlocks_Block TinyBlocks_Block;
typedef struct TinyBlocks_TypeBlock TinyBlocks_TypeBlock;
typedef struct TinyBlocks_LibraryBlock TinyBlocks_LibraryBlock;
typedef struct TinyBlocks_TextBlock TinyBlocks_TextBlock;
typedef struct TinyBlocks_IntegerBlock TinyBlocks_IntegerBlock;
typedef struct TinyBlocks_RealBlock TinyBlocks_RealBlock;
typedef struct TinyBlocks_VectorBlock TinyBlocks_VectorBlock;
typedef struct TinyBlocks_VectorData TinyBlocks_VectorData;
typedef struct TinyBlocks_RenderableBlock TinyBlocks_RenderableBlock;
typedef struct TinyBlocks_JsonValue TinyBlocks_JsonValue;
/* ── Kinds de bloco ──────────────────────────────────────────────────────── */
typedef enum TinyBlocks_BlockKind {
TB_KIND_BLOCK = 0, /* bloco genérico / definido pelo usuário */
TB_KIND_TYPE = 1, /* TinyBlocks_TypeBlock */
TB_KIND_LIBRARY = 2, /* TinyBlocks_LibraryBlock */
TB_KIND_TEXT = 3, /* TinyBlocks_TextBlock */
TB_KIND_INTEGER = 4, /* TinyBlocks_IntegerBlock */
TB_KIND_REAL = 5, /* TinyBlocks_RealBlock */
TB_KIND_VECTOR = 6, /* TinyBlocks_VectorBlock */
} TinyBlocks_BlockKind;
/* ── Kinds de valor (para slots) ─────────────────────────────────────────── */
typedef enum TinyBlocks_ValueKind {
TB_VALUE_NONE = 0,
TB_VALUE_INTEGER = 1,
TB_VALUE_REAL = 2,
TB_VALUE_TEXT = 3,
TB_VALUE_BLOCK = 4, /* referência a qualquer bloco (handle opaco) */
TB_VALUE_VECTOR = 5, /* dados de vetor 2D (ref-counted) */
TB_VALUE_JSON = 6, /* valor JSON (ref-counted) */
} TinyBlocks_ValueKind;
/* ── Valor com tag (flui entre slots) ────────────────────────────────────── */
typedef struct TinyBlocks_Value {
TinyBlocks_ValueKind kind;
union {
int64_t integer;
double real;
char* text; /* heap-owned (tb_value_free) */
TinyBlocks_Block* block; /* ponteiro não-owning */
TinyBlocks_VectorData* vector; /* ref-counted (retain/release) */
TinyBlocks_JsonValue* json; /* ref-counted (retain/release) */
} as;
} TinyBlocks_Value;
/* ══════════════════════════════════════════════════════════════════════════
* Dados de vetor 2D (fluxo de comandos de desenho, ref-counted)
* ══════════════════════════════════════════════════════════════════════════ */
typedef enum TinyBlocks_VCmdKind {
TB_VCMD_BEGIN_PATH = 0, /* nenhum arg */
TB_VCMD_MOVE_TO, /* args[0]=x, args[1]=y */
TB_VCMD_LINE_TO, /* args[0]=x, args[1]=y */
TB_VCMD_CLOSE_PATH, /* nenhum arg */
TB_VCMD_STROKE, /* args[0..3]=r,g,b,a args[4]=width */
TB_VCMD_FILL, /* args[0..3]=r,g,b,a */
TB_VCMD_RECT, /* args[0..3]=x,y,w,h */
TB_VCMD_CIRCLE, /* args[0..2]=cx,cy,raio */
} TinyBlocks_VCmdKind;
typedef struct { TinyBlocks_VCmdKind kind; float args[5]; } TinyBlocks_VCmd;
struct TinyBlocks_VectorData {
TinyBlocks_VCmd* cmds;
uint32_t count, capacity;
int32_t ref;
};
/* ── Descritor de slot (em TypeBlock — descreve a forma dos inputs/outputs) ─ */
typedef struct TinyBlocks_SlotDesc {
const char* name;
TinyBlocks_ValueKind expected_kind; /* TB_VALUE_NONE = aceita qualquer tipo */
} TinyBlocks_SlotDesc;
/* ── Conexão de entrada (de qual bloco/slot este input lê) ───────────────── */
typedef struct TinyBlocks_Connection {
TinyBlocks_Block* source; /* bloco de origem (NULL se não conectado) */
uint32_t output_idx; /* qual output slot da origem */
TinyBlocks_Value default_value; /* valor quando não há conexão */
} TinyBlocks_Connection;
/* ── Alocador customizável ───────────────────────────────────────────────── */
typedef void* (*TinyBlocks_AllocFn)(size_t size, void* userdata);
typedef void (*TinyBlocks_FreeFn) (void* ptr, void* userdata);
/* ── Helpers para TinyBlocks_Value ──────────────────────────────────────── */
TB_API TinyBlocks_Value tb_value_none(void);
TB_API TinyBlocks_Value tb_value_integer(int64_t v);
TB_API TinyBlocks_Value tb_value_real(double v);
TB_API TinyBlocks_Value tb_value_text(const char* v); /* copia a string */
TB_API TinyBlocks_Value tb_value_block(TinyBlocks_Block* v);
TB_API TinyBlocks_Value tb_value_clone(TinyBlocks_Value v); /* deep copy */
TB_API void tb_value_free(TinyBlocks_Value* v); /* libera text */
#endif /* TINYBLOCKS_DEFS_H */
+26
View File
@@ -0,0 +1,26 @@
/*
* TinyBlocks — tb_integer_block.h
* TinyBlocks_IntegerBlock: bloco primitivo que contém um inteiro de 64 bits.
*
* IntegerBlocks são literais: têm 0 inputs e 1 output (TB_VALUE_INTEGER).
*/
#ifndef TINYBLOCKS_INTEGER_BLOCK_H
#define TINYBLOCKS_INTEGER_BLOCK_H
#include "tb_block.h"
struct TinyBlocks_IntegerBlock {
TinyBlocks_Block base; /* DEVE ser o primeiro campo */
int64_t value;
};
/* ── Ciclo de vida ───────────────────────────────────────────────────────── */
TB_API TinyBlocks_IntegerBlock* tb_integer_block_create (TinyBlocks* rt, int64_t value);
TB_API void tb_integer_block_destroy(TinyBlocks_IntegerBlock* ib,
TinyBlocks* rt);
/* ── Acesso ao valor ─────────────────────────────────────────────────────── */
TB_API int64_t tb_integer_block_get(const TinyBlocks_IntegerBlock* ib);
TB_API void tb_integer_block_set(TinyBlocks_IntegerBlock* ib, int64_t value);
#endif /* TINYBLOCKS_INTEGER_BLOCK_H */
+72
View File
@@ -0,0 +1,72 @@
/*
* TinyBlocks — tb_json_block.h
* TinyBlocks_JsonValue: árvore JSON imutável e ref-counted que flui como valor
* entre blocos (TB_VALUE_JSON).
*
* Fluxo típico de uso:
* TinyBlocks_JsonValue* root = tb_json_parse(text, NULL, 0);
* TinyBlocks_JsonValue* name = tb_json_object_get(root, "name"); // ref nova
* const char* s = tb_json_as_string(name);
* tb_json_release(name);
* tb_json_release(root);
*
* Mutações (array_push/object_set) são feitas em árvores recém-criadas (não
* compartilhadas); para "modificar" um valor já em uso, clone primeiro com
* tb_json_clone.
*/
#ifndef TINYBLOCKS_JSON_BLOCK_H
#define TINYBLOCKS_JSON_BLOCK_H
#include "tb_block.h"
typedef enum TinyBlocks_JsonKind {
TB_JSON_NULL = 0,
TB_JSON_BOOL = 1,
TB_JSON_NUMBER = 2,
TB_JSON_STRING = 3,
TB_JSON_ARRAY = 4,
TB_JSON_OBJECT = 5,
} TinyBlocks_JsonKind;
/* ── Ciclo de vida ───────────────────────────────────────────────────────── */
TB_API TinyBlocks_JsonValue* tb_json_null (void);
TB_API TinyBlocks_JsonValue* tb_json_bool (bool b);
TB_API TinyBlocks_JsonValue* tb_json_number(double d);
TB_API TinyBlocks_JsonValue* tb_json_string(const char* s); /* copia a string */
TB_API TinyBlocks_JsonValue* tb_json_array (void); /* array vazio */
TB_API TinyBlocks_JsonValue* tb_json_object(void); /* objeto vazio */
TB_API void tb_json_retain (TinyBlocks_JsonValue* j);
TB_API void tb_json_release(TinyBlocks_JsonValue* j);
TB_API TinyBlocks_JsonValue* tb_json_clone (const TinyBlocks_JsonValue* j); /* deep copy */
/* ── Inspeção ────────────────────────────────────────────────────────────── */
TB_API TinyBlocks_JsonKind tb_json_kind (const TinyBlocks_JsonValue* j);
TB_API const char* tb_json_kind_name(const TinyBlocks_JsonValue* j);
TB_API bool tb_json_as_bool (const TinyBlocks_JsonValue* j, bool def);
TB_API double tb_json_as_number(const TinyBlocks_JsonValue* j, double def);
TB_API const char* tb_json_as_string(const TinyBlocks_JsonValue* j); /* NULL se não for string */
/* ── Arrays (mutação in-place; use em árvores não compartilhadas) ───────── */
TB_API bool tb_json_array_push (TinyBlocks_JsonValue* arr, TinyBlocks_JsonValue* item);
TB_API uint32_t tb_json_array_length(const TinyBlocks_JsonValue* arr);
TB_API TinyBlocks_JsonValue* tb_json_array_get(const TinyBlocks_JsonValue* arr, uint32_t idx); /* ref nova, ou NULL */
/* ── Objetos (mutação in-place; use em árvores não compartilhadas) ──────── */
TB_API bool tb_json_object_set (TinyBlocks_JsonValue* obj, const char* key, TinyBlocks_JsonValue* val);
TB_API uint32_t tb_json_object_length (const TinyBlocks_JsonValue* obj);
TB_API const char* tb_json_object_key_at (const TinyBlocks_JsonValue* obj, uint32_t idx);
TB_API TinyBlocks_JsonValue* tb_json_object_get(const TinyBlocks_JsonValue* obj, const char* key); /* ref nova, ou NULL */
/* ── Parsing / serialização ──────────────────────────────────────────────── */
/* Retorna NULL em erro de sintaxe; se errbuf não for NULL, escreve a mensagem. */
TB_API TinyBlocks_JsonValue* tb_json_parse(const char* text, char* errbuf, size_t errbuf_size);
/* Serializa para texto; retorna buffer heap-alocado (free() do chamador). */
TB_API char* tb_json_stringify(const TinyBlocks_JsonValue* j);
/* ── Helpers para TinyBlocks_Value ──────────────────────────────────────── */
TB_API TinyBlocks_Value tb_value_json (TinyBlocks_JsonValue* j); /* retém ref */
TB_API TinyBlocks_JsonValue* tb_value_as_json(TinyBlocks_Value v);
#endif /* TINYBLOCKS_JSON_BLOCK_H */
+82
View File
@@ -0,0 +1,82 @@
/*
* TinyBlocks — tb_library_block.h
* TinyBlocks_LibraryBlock: contêiner que agrupa um conjunto de blocos.
*
* Libraries são o mecanismo de modularidade da linguagem. Uma library contém
* TypeBlocks (tipos/operações) e pode ser carregada dinamicamente via dlopen.
*
* Estrutura de uma library em C:
* 1. Exporte `const TinyBlocks_LibraryDescriptor* tinyblocks_get_library(void)`
* 2. Implemente `init` para criar TypeBlocks e adicioná-los com tb_library_add
* 3. Implemente `deinit` para limpeza
*/
#ifndef TINYBLOCKS_LIBRARY_BLOCK_H
#define TINYBLOCKS_LIBRARY_BLOCK_H
#include "tb_block.h"
struct TinyBlocks_LibraryBlock {
TinyBlocks_Block base; /* DEVE ser o primeiro campo */
TinyBlocks_Block** blocks; /* blocos contidos (TypeBlocks, etc.) */
uint32_t block_count;
uint32_t block_capacity;
/* Hooks chamados pelo runtime ao carregar/descarregar (podem ser NULL) */
bool (*on_load )(TinyBlocks_LibraryBlock* self, TinyBlocks* rt);
void (*on_unload)(TinyBlocks_LibraryBlock* self, TinyBlocks* rt);
void* lib_userdata; /* dados privados da library */
};
/* ── Descritor exportado por cada library .so/.dll ───────────────────────── */
typedef struct TinyBlocks_LibraryDescriptor {
const char* name;
const char* version;
bool (*init )(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib);
void (*deinit)(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib);
} TinyBlocks_LibraryDescriptor;
/* Símbolo que cada library deve exportar */
#define TINYBLOCKS_LIBRARY_SYMBOL "tinyblocks_get_library"
/* Macro de conveniência para implementações de library */
#define TINYBLOCKS_DEFINE_LIBRARY(sym, name_, version_, init_, deinit_) \
static const TinyBlocks_LibraryDescriptor _tb_lib_desc_##sym = { \
.name = (name_), \
.version = (version_), \
.init = (init_), \
.deinit = (deinit_), \
}; \
TB_API __attribute__((weak)) \
const TinyBlocks_LibraryDescriptor* tinyblocks_get_library(void) { \
return &_tb_lib_desc_##sym; \
}
/* ── Operações em LibraryBlock ───────────────────────────────────────────── */
TB_API TinyBlocks_LibraryBlock* tb_library_block_create(TinyBlocks* rt,
const char* name);
TB_API void tb_library_block_destroy(TinyBlocks_LibraryBlock* lib, TinyBlocks* rt);
/* Adiciona um bloco à library (a library não toma ownership do bloco) */
TB_API bool tb_library_add(TinyBlocks_LibraryBlock* lib, TinyBlocks_Block* block);
/* Remove um bloco da library pelo índice */
TB_API bool tb_library_remove_at(TinyBlocks_LibraryBlock* lib, uint32_t index);
/* Busca um bloco pelo nome dentro da library */
TB_API TinyBlocks_Block* tb_library_find(TinyBlocks_LibraryBlock* lib,
const char* name);
/* ── Carregamento dinâmico de libraries ──────────────────────────────────── */
/* Carrega uma library a partir de um .so/.dll; retorna NULL em erro */
TB_API TinyBlocks_LibraryBlock* tb_library_load(TinyBlocks* rt, const char* path);
/* Descarrega uma library previamente carregada com tb_library_load */
TB_API void tb_library_unload(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib);
/* Registra um LibraryDescriptor estático (para libraries embutidas) */
TB_API TinyBlocks_LibraryBlock* tb_library_register(
TinyBlocks* rt, const TinyBlocks_LibraryDescriptor* desc);
#endif /* TINYBLOCKS_LIBRARY_BLOCK_H */
+26
View File
@@ -0,0 +1,26 @@
/*
* TinyBlocks — tb_real_block.h
* TinyBlocks_RealBlock: bloco primitivo que contém um número real (double).
*
* RealBlocks são literais: têm 0 inputs e 1 output (TB_VALUE_REAL).
*/
#ifndef TINYBLOCKS_REAL_BLOCK_H
#define TINYBLOCKS_REAL_BLOCK_H
#include "tb_block.h"
struct TinyBlocks_RealBlock {
TinyBlocks_Block base; /* DEVE ser o primeiro campo */
double value;
};
/* ── Ciclo de vida ───────────────────────────────────────────────────────── */
TB_API TinyBlocks_RealBlock* tb_real_block_create (TinyBlocks* rt, double value);
TB_API void tb_real_block_destroy(TinyBlocks_RealBlock* rb,
TinyBlocks* rt);
/* ── Acesso ao valor ─────────────────────────────────────────────────────── */
TB_API double tb_real_block_get(const TinyBlocks_RealBlock* rb);
TB_API void tb_real_block_set(TinyBlocks_RealBlock* rb, double value);
#endif /* TINYBLOCKS_REAL_BLOCK_H */
+116
View File
@@ -0,0 +1,116 @@
/*
* TinyBlocks — tb_renderable_block.h
*
* TinyBlocks_RenderableBlock: lista de comandos de desenho produzida por on_draw.
* O backend (ex: SDL2.App) interpreta os comandos para renderizar na tela.
*
* Uso típico:
* bool my_on_draw(TinyBlocks_Block* self, TinyBlocks* rt,
* TinyBlocks_RenderableBlock** dst) {
* TinyBlocks_RenderableBlock* rb = tb_renderable_acquire();
* if (!rb) return false;
* tb_draw_clear(rb, 0.1f, 0.1f, 0.18f, 1.f);
* tb_draw_fill_rect(rb, 10, 10, 200, 100, 0.5f, 0.3f, 0.9f, 1.f);
* tb_draw_text(rb, 20, 50, "Olá", 13.f, 1,1,1,1);
* *dst = rb;
* return true;
* }
* // Após renderizar: tb_renderable_release_all();
*/
#ifndef TINYBLOCKS_RENDERABLE_BLOCK_H
#define TINYBLOCKS_RENDERABLE_BLOCK_H
#include "tb_defs.h"
/* ── Tipos de comando ──────────────────────────────────────────────────────── */
typedef enum {
TB_DRAW_CLEAR, /* limpa toda a área com uma cor */
TB_DRAW_FILL_RECT, /* retângulo preenchido */
TB_DRAW_FILL_RRECT, /* retângulo com cantos arredondados (param=radius) */
TB_DRAW_FILL_CIRCLE, /* círculo preenchido (x=cx, y=cy, param=radius) */
TB_DRAW_STROKE_LINE, /* linha (x,y → w,h como x2,y2; param=espessura) */
TB_DRAW_STROKE_RECT, /* contorno de retângulo (param=espessura) */
TB_DRAW_STROKE_CIRCLE, /* contorno de círculo (x=cx,y=cy,param=r,w=espessura)*/
TB_DRAW_SET_CLIP, /* define rect de clip (coordenadas tela) */
TB_DRAW_CLEAR_CLIP, /* remove clip */
TB_DRAW_TEXT, /* texto (x,y=baseline-left; font_size em px) */
} TinyBlocks_DrawCmdKind;
typedef struct {
TinyBlocks_DrawCmdKind kind;
float x, y, w, h; /* geometria (significado varia por kind) */
float r, g, b, a; /* cor RGBA [0..1] */
float param; /* radius (rrect/circle), espessura (linha/stroke) */
float font_size; /* tamanho da fonte em pixels (TB_DRAW_TEXT) */
char text[128]; /* conteúdo do texto (TB_DRAW_TEXT) */
} TinyBlocks_DrawCmd;
/* ── RenderableBlock ───────────────────────────────────────────────────────── */
#define TB_DRAW_CMD_CAP 8192
struct TinyBlocks_RenderableBlock {
TinyBlocks_DrawCmd cmds[TB_DRAW_CMD_CAP];
uint32_t count;
};
/* ── Pool de renderables (reset por frame, sem malloc durante o loop) ──────── */
/* Adquire um renderable limpo do pool. Retorna NULL se esgotado. */
TB_API TinyBlocks_RenderableBlock* tb_renderable_acquire(void);
/* Libera um renderable individual de volta ao pool (uso após merge). */
TB_API void tb_renderable_release(TinyBlocks_RenderableBlock* rb);
/* Libera todos os renderables de volta ao pool (chamar uma vez por frame,
depois que o backend terminar de renderizar). */
TB_API void tb_renderable_release_all(void);
/* ── Helpers para acrescentar comandos ────────────────────────────────────── */
TB_API void tb_draw_clear (TinyBlocks_RenderableBlock* rb,
float r, float g, float b, float a);
TB_API void tb_draw_fill_rect (TinyBlocks_RenderableBlock* rb,
float x, float y, float w, float h,
float r, float g, float b, float a);
TB_API void tb_draw_fill_rrect (TinyBlocks_RenderableBlock* rb,
float x, float y, float w, float h, float radius,
float r, float g, float b, float a);
TB_API void tb_draw_fill_circle(TinyBlocks_RenderableBlock* rb,
float cx, float cy, float radius,
float r, float g, float b, float a);
TB_API void tb_draw_stroke_line(TinyBlocks_RenderableBlock* rb,
float x1, float y1, float x2, float y2, float w,
float r, float g, float b, float a);
TB_API void tb_draw_stroke_rect (TinyBlocks_RenderableBlock* rb,
float x, float y, float w, float h, float stroke_w,
float r, float g, float b, float a);
TB_API void tb_draw_stroke_circle(TinyBlocks_RenderableBlock* rb,
float cx, float cy, float radius, float stroke_w,
float r, float g, float b, float a);
TB_API void tb_draw_set_clip (TinyBlocks_RenderableBlock* rb,
float x, float y, float w, float h);
TB_API void tb_draw_clear_clip (TinyBlocks_RenderableBlock* rb);
TB_API void tb_draw_text (TinyBlocks_RenderableBlock* rb,
float x, float y, const char* text, float font_size,
float r, float g, float b, float a);
/* Mescla src em dst deslocando todas as coordenadas por (dx, dy).
Usado pelo editor para incorporar sub-renderables de blocos com on_draw. */
TB_API void tb_draw_merge_offset(TinyBlocks_RenderableBlock* dst,
const TinyBlocks_RenderableBlock* src,
float dx, float dy);
/* Estimativa de largura de texto (independente de fonte real).
Precisa ser substituída por medição real pelo backend quando disponível. */
TB_API float tb_measure_text(const char* text, float font_size);
#endif /* TINYBLOCKS_RENDERABLE_BLOCK_H */
+30
View File
@@ -0,0 +1,30 @@
/*
* TinyBlocks — tb_text_block.h
* TinyBlocks_TextBlock: bloco primitivo que contém um valor textual.
*
* TextBlocks são literais: têm 0 inputs e 1 output (TB_VALUE_TEXT).
* A string interna é heap-owned e gerenciada pelo bloco.
*/
#ifndef TINYBLOCKS_TEXT_BLOCK_H
#define TINYBLOCKS_TEXT_BLOCK_H
#include "tb_block.h"
struct TinyBlocks_TextBlock {
TinyBlocks_Block base; /* DEVE ser o primeiro campo */
char* value; /* string heap-owned */
};
/* ── Ciclo de vida ───────────────────────────────────────────────────────── */
TB_API TinyBlocks_TextBlock* tb_text_block_create (TinyBlocks* rt, const char* value);
TB_API void tb_text_block_destroy(TinyBlocks_TextBlock* tb,
TinyBlocks* rt);
/* ── Acesso ao valor ─────────────────────────────────────────────────────── */
TB_API const char* tb_text_block_get(const TinyBlocks_TextBlock* tb);
TB_API void tb_text_block_set(TinyBlocks_TextBlock* tb, const char* value);
/* Concatena value ao final da string atual */
TB_API void tb_text_block_append(TinyBlocks_TextBlock* tb, const char* suffix);
#endif /* TINYBLOCKS_TEXT_BLOCK_H */
+72
View File
@@ -0,0 +1,72 @@
/*
* TinyBlocks — tb_type_block.h
* TinyBlocks_TypeBlock: representa a "classe" de um bloco.
*
* Um TypeBlock define:
* • O nome do tipo
* • Os descritores de slots (inputs e outputs)
* • A função de avaliação para instâncias
* • Hooks de init/deinit por instância
* • Tamanho extra de userdata para instâncias
*
* TypeBlocks são eles mesmos blocos (base.kind == TB_KIND_TYPE).
*/
#ifndef TINYBLOCKS_TYPE_BLOCK_H
#define TINYBLOCKS_TYPE_BLOCK_H
#include "tb_block.h"
struct TinyBlocks_TypeBlock {
TinyBlocks_Block base; /* DEVE ser o primeiro campo */
char* type_name; /* nome do tipo, e.g. "SDL2.Window" */
/* Descritores de slots */
TinyBlocks_SlotDesc* input_descs;
uint32_t input_desc_count;
TinyBlocks_SlotDesc* output_descs;
uint32_t output_desc_count;
/* Função de avaliação chamada para todas as instâncias deste tipo */
void (*eval_fn)(TinyBlocks_Block* self, TinyBlocks* rt);
/* Tamanho do bloco de userdata alocado em cada instância (pode ser 0) */
size_t instance_userdata_size;
/* Hooks de ciclo de vida por instância (podem ser NULL) */
bool (*instance_init )(TinyBlocks_Block* self, TinyBlocks* rt);
void (*instance_deinit)(TinyBlocks_Block* self, TinyBlocks* rt);
/* Renderização personalizada (opcional, NULL = aparência padrão do editor).
* Produz comandos de desenho em *dst (adquirido do pool ou passado pelo caller).
* Para blocos widget: coordenadas relativas à área de conteúdo (0,0=top-left).
* Para blocos de cena (ex: Editor.Scene): coordenadas absolutas de tela. */
bool (*on_draw)(TinyBlocks_Block* self, TinyBlocks* rt,
TinyBlocks_RenderableBlock** dst);
};
/* ── Criação de TypeBlock ────────────────────────────────────────────────── */
/* Cria e registra um TypeBlock no runtime */
TB_API TinyBlocks_TypeBlock* tb_type_block_create(
TinyBlocks* rt,
const char* type_name,
const TinyBlocks_SlotDesc* input_descs, uint32_t input_count,
const TinyBlocks_SlotDesc* output_descs, uint32_t output_count,
void (*eval_fn)(TinyBlocks_Block* self, TinyBlocks* rt)
);
TB_API void tb_type_block_destroy(TinyBlocks_TypeBlock* tb, TinyBlocks* rt);
/* Configura hooks de ciclo de vida e tamanho de userdata de instância */
TB_API void tb_type_block_set_instance_hooks(
TinyBlocks_TypeBlock* tb,
size_t instance_userdata_size,
bool (*init )(TinyBlocks_Block* self, TinyBlocks* rt),
void (*deinit)(TinyBlocks_Block* self, TinyBlocks* rt)
);
/* Localiza um TypeBlock por nome no runtime */
TB_API TinyBlocks_TypeBlock* tb_type_block_find(TinyBlocks* rt, const char* type_name);
#endif /* TINYBLOCKS_TYPE_BLOCK_H */
+65
View File
@@ -0,0 +1,65 @@
/*
* TinyBlocks — tb_vector_block.h
* TinyBlocks_VectorBlock: bloco que armazena dados de vetor 2D.
* TinyBlocks_VectorData: comandos de desenho ref-counted que fluem como valores.
*
* Fluxo típico de uso:
* v = tb_vector_data_create();
* tb_vector_begin_path(v);
* tb_vector_move_to(v, 0, 0);
* tb_vector_line_to(v, 100, 50);
* tb_vector_stroke(v, 1,0,0,1, 2.0f);
* TinyBlocks_Value val = tb_value_vector(v); // retém ref
* tb_vector_data_release(v); // libera ref local
* tb_block_set_output(self, 0, val); // set_output toma ownership
*
* Reprodução em RenderableBlock:
* tb_draw_ctx_play(rb, val.as.vector);
*/
#ifndef TINYBLOCKS_VECTOR_BLOCK_H
#define TINYBLOCKS_VECTOR_BLOCK_H
#include "tb_block.h"
#include "tb_renderable_block.h"
/* ── TinyBlocks_VectorBlock — bloco que contém VectorData ───────────────── */
struct TinyBlocks_VectorBlock {
TinyBlocks_Block base; /* DEVE ser o primeiro campo */
TinyBlocks_VectorData* data;
};
/* ── Ciclo de vida de VectorData ────────────────────────────────────────── */
TB_API TinyBlocks_VectorData* tb_vector_data_create (void);
TB_API void tb_vector_data_retain (TinyBlocks_VectorData* v);
TB_API void tb_vector_data_release(TinyBlocks_VectorData* v);
TB_API TinyBlocks_VectorData* tb_vector_data_clone (const TinyBlocks_VectorData* v);
TB_API bool tb_vector_data_push (TinyBlocks_VectorData* v,
TinyBlocks_VCmd cmd);
/* ── Construtores de comandos ────────────────────────────────────────────── */
TB_API bool tb_vector_begin_path(TinyBlocks_VectorData* v);
TB_API bool tb_vector_move_to (TinyBlocks_VectorData* v, float x, float y);
TB_API bool tb_vector_line_to (TinyBlocks_VectorData* v, float x, float y);
TB_API bool tb_vector_close_path(TinyBlocks_VectorData* v);
TB_API bool tb_vector_stroke (TinyBlocks_VectorData* v,
float r, float g, float b, float a, float width);
TB_API bool tb_vector_fill (TinyBlocks_VectorData* v,
float r, float g, float b, float a);
TB_API bool tb_vector_rect (TinyBlocks_VectorData* v,
float x, float y, float w, float h);
TB_API bool tb_vector_circle (TinyBlocks_VectorData* v,
float cx, float cy, float radius);
/* ── Helpers para TinyBlocks_Value ──────────────────────────────────────── */
TB_API TinyBlocks_Value tb_value_vector (TinyBlocks_VectorData* v);
TB_API TinyBlocks_VectorData* tb_value_as_vector(TinyBlocks_Value v);
/* ── VectorBlock (bloco no grafo) ────────────────────────────────────────── */
TB_API TinyBlocks_VectorBlock* tb_vector_block_create (TinyBlocks* rt);
TB_API void tb_vector_block_set_data (TinyBlocks_VectorBlock* b,
TinyBlocks_VectorData* v);
/* ── Reprodução de VectorData via RenderableBlock ───────────────────────── */
TB_API void tb_draw_ctx_play(TinyBlocks_RenderableBlock* rb, TinyBlocks_VectorData* v);
#endif /* TINYBLOCKS_VECTOR_BLOCK_H */
+113
View File
@@ -0,0 +1,113 @@
/*
* TinyBlocks — tinyblocks.h
* Cabeçalho principal do runtime. Inclua apenas este arquivo.
*
* O struct TinyBlocks é o runtime da linguagem. Ele é completamente separado
* de qualquer interface gráfica — GUIs são implementadas como LibraryBlocks.
*
* Fluxo de uso mínimo:
*
* TinyBlocks* rt = NULL;
* tinyblocks_init(&rt, NULL); // inicializa com alocador padrão
*
* // carrega uma library (estática ou dinâmica)
* tb_library_register(rt, my_library_descriptor());
*
* // cria blocos, conecta-os, avalia
* TinyBlocks_TypeBlock* t = tb_type_block_find(rt, "Math.Add");
* TinyBlocks_Block* b = tb_block_create(rt, t);
* tb_block_connect(b, 0, lit_a, 0);
* tb_block_connect(b, 1, lit_b, 0);
* tb_block_eval(b, rt);
* TinyBlocks_Value result = b->outputs[0];
*
* tinyblocks_deinit(&rt);
*/
#ifndef TINYBLOCKS_H
#define TINYBLOCKS_H
#include "tb_defs.h"
#include "tb_block.h"
#include "tb_type_block.h"
#include "tb_library_block.h"
#include "tb_text_block.h"
#include "tb_integer_block.h"
#include "tb_real_block.h"
#include "tb_vector_block.h"
#include "tb_json_block.h"
/* ── Runtime ─────────────────────────────────────────────────────────────── */
struct TinyBlocks {
/* Alocador (padrão: malloc/free) */
TinyBlocks_AllocFn alloc;
TinyBlocks_FreeFn free;
void* alloc_userdata;
/* Registro global de blocos vivos */
TinyBlocks_Block** blocks;
uint32_t block_count;
uint32_t block_capacity;
/* Registro de tipos */
TinyBlocks_TypeBlock** types;
uint32_t type_count;
uint32_t type_capacity;
/* Registro de libraries */
TinyBlocks_LibraryBlock** libraries;
uint32_t library_count;
uint32_t library_capacity;
/* Handles de bibliotecas carregadas dinamicamente (dlopen) */
void** dl_handles;
uint32_t dl_handle_count;
uint32_t dl_handle_capacity;
/* Gerador de IDs únicos */
uint64_t next_id;
/* Último erro em texto legível */
char error[512];
};
/* ── Opções de inicialização ─────────────────────────────────────────────── */
typedef struct TinyBlocks_InitOptions {
TinyBlocks_AllocFn alloc; /* NULL = malloc padrão */
TinyBlocks_FreeFn free_fn; /* NULL = free padrão */
void* alloc_userdata;
uint32_t initial_block_cap; /* 0 = 64 */
uint32_t initial_type_cap; /* 0 = 32 */
uint32_t initial_library_cap; /* 0 = 16 */
} TinyBlocks_InitOptions;
/* ── Ciclo de vida do runtime ────────────────────────────────────────────── */
TB_API bool tinyblocks_init (TinyBlocks** out_rt, const TinyBlocks_InitOptions* opts);
TB_API void tinyblocks_deinit(TinyBlocks** rt);
/* ── Registro interno (usado pelas implementações de bloco) ─────────────── */
TB_API bool tb_rt_register_block (TinyBlocks* rt, TinyBlocks_Block* block);
TB_API void tb_rt_unregister_block(TinyBlocks* rt, TinyBlocks_Block* block);
TB_API bool tb_rt_register_type (TinyBlocks* rt, TinyBlocks_TypeBlock* type);
TB_API void tb_rt_unregister_type (TinyBlocks* rt, TinyBlocks_TypeBlock* type);
TB_API bool tb_rt_register_library(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib);
TB_API void tb_rt_unregister_library(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib);
/* ── Alocação com o alocador do runtime ─────────────────────────────────── */
TB_API void* tb_alloc(TinyBlocks* rt, size_t size);
TB_API void tb_free (TinyBlocks* rt, void* ptr);
TB_API char* tb_strdup(TinyBlocks* rt, const char* str);
/* ── Diagnósticos ────────────────────────────────────────────────────────── */
TB_API const char* tinyblocks_last_error(TinyBlocks* rt);
TB_API void tinyblocks_set_error (TinyBlocks* rt, const char* fmt, ...);
TB_API void tinyblocks_clear_error(TinyBlocks* rt);
/* ── Busca no registro ───────────────────────────────────────────────────── */
TB_API TinyBlocks_Block* tb_rt_find_block (TinyBlocks* rt, uint64_t id);
TB_API TinyBlocks_TypeBlock* tb_rt_find_type (TinyBlocks* rt, const char* name);
TB_API TinyBlocks_LibraryBlock* tb_rt_find_library(TinyBlocks* rt, const char* name);
/* ── Geração de ID ───────────────────────────────────────────────────────── */
TB_API uint64_t tb_rt_next_id(TinyBlocks* rt);
#endif /* TINYBLOCKS_H */
+43
View File
@@ -0,0 +1,43 @@
CC := gcc
BUILD := ../../build
SDL2_CFLAGS := $(shell sdl2-config --cflags)
SDL2_LIBS := $(shell sdl2-config --libs)
SDL2TTF_CFLAGS:= $(shell pkg-config --cflags SDL2_ttf 2>/dev/null)
SDL2TTF_LIBS := $(shell pkg-config --libs SDL2_ttf 2>/dev/null)
ifeq ($(SDL2TTF_LIBS),)
$(error SDL2_ttf não encontrado. Instale: sudo apt install libsdl2-ttf-dev)
endif
CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \
-D_POSIX_C_SOURCE=200809L \
-I../../include \
-Iinclude \
$(SDL2_CFLAGS) $(SDL2TTF_CFLAGS)
LDFLAGS := $(SDL2_LIBS) $(SDL2TTF_LIBS) -lm
OBJ := $(BUILD)/tb_editor.o
LIB_A := $(BUILD)/libtinyblocks-editor.a
LIB_SO := $(BUILD)/libtinyblocks-editor.so
.PHONY: all static shared clean
all: static shared
static: $(LIB_A)
shared: $(LIB_SO)
$(OBJ): src/tb_editor.c include/tb_editor.h
@mkdir -p $(BUILD)
$(CC) $(CFLAGS) -fPIC -c $< -o $@
$(LIB_A): $(OBJ)
ar rcs $@ $^
$(LIB_SO): $(OBJ)
$(CC) -shared -o $@ $^ $(LDFLAGS)
clean:
$(RM) $(OBJ) $(LIB_A) $(LIB_SO)
@@ -0,0 +1,37 @@
/*
* TinyBlocks — tb_editor.h
* Editor visual block-based (estilo Scratch) implementado como LibraryBlock.
*
* O editor é o próprio bloco "Editor.Scene": não abre janela nem processa
* eventos SDL2 diretamente. Em vez disso:
* - implementa on_draw, produzindo um TinyBlocks_RenderableBlock
* - lê o estado de input/mouse/teclado a partir de um bloco SDL2.Events
* conectado ao seu input "events"
* - deve ser conectado ao input "scene" de um bloco SDL2.App, que é quem
* de fato cria a janela, roda o loop e interpreta o RenderableBlock.
*
* Uso:
* tb_library_register(rt, tb_editor_get_library());
* tb_library_register(rt, tb_sdl2_get_library());
*
* TinyBlocks_Block* events = tb_block_create(rt, tb_type_block_find(rt,"SDL2.Events"));
* TinyBlocks_Block* scene = tb_block_create(rt, tb_type_block_find(rt,"Editor.Scene"));
* tb_block_set_default(scene, 0, tb_value_block(events));
*
* TinyBlocks_Block* app = tb_block_create(rt, tb_type_block_find(rt,"SDL2.App"));
* tb_block_set_default(app, 3, tb_value_block(scene));
* tb_block_set_default(app, 4, tb_value_block(events));
* tb_block_eval(app, rt); // roda o loop principal — bloqueia até fechar
*/
#ifndef TINYBLOCKS_EDITOR_H
#define TINYBLOCKS_EDITOR_H
#include <tinyblocks/tinyblocks.h>
TB_API const TinyBlocks_LibraryDescriptor* tb_editor_get_library(void);
TB_API const TinyBlocks_LibraryDescriptor* tinyblocks_get_library(void);
/* Enfileira um .so para ser carregado automaticamente ao abrir o editor */
TB_API void tb_editor_preload(const char* path);
#endif /* TINYBLOCKS_EDITOR_H */
File diff suppressed because it is too large. Load diff
+259
View File
@@ -0,0 +1,259 @@
/*
* TinyBlocks — tb_stage.c
* O Palco do editor: uma tela lógica de 480x360 (origem no centro, y para
* cima, como no Scratch) onde os blocos Stage.* desenham. É um componente de
* UI: o editor o embute no painel direito (chamando seu on_draw) ou o entrega
* como cena de um Graphics.Window próprio ("destacar palco").
*
* Os desenhos ficam numa lista retida e são re-emitidos a cada on_draw,
* escalados para o tamanho da área (letterbox mantendo 4:3).
*/
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tb_graphics.h>
#include "tb_stage.h"
#define STAGE_W 480.f
#define STAGE_H 360.f
#define STAGE_MAX_CMDS 4000
#define STAGE_TEXT_FS 14.f
typedef enum { SC_RECT, SC_CIRCLE, SC_LINE, SC_TEXT } StageCmdKind;
typedef struct {
StageCmdKind kind;
float a, b, c, d; /* geometria em coordenadas do palco */
float size; /* espessura da caneta */
float col[3];
char text[96];
} StageCmd;
typedef struct {
StageCmd* cmds;
int n, cap;
float bg[3];
float pen[3];
float pen_size;
float view_w, view_h;
bool full_warned;
} Stage;
static TinyBlocks_Block* s_current = NULL;
static Stage* stage_of(TinyBlocks_Block* b) { return b ? *(Stage**)b->userdata : NULL; }
TinyBlocks_Block* tb_stage_current(void) { return s_current; }
void tb_stage_set_view(TinyBlocks_Block* stage, float w, float h) {
Stage* s = stage_of(stage);
if (s && w > 0 && h > 0) { s->view_w = w; s->view_h = h; }
}
/* ══════════════════════════════════════════════════════════════════════════
* Editor.Stage
* ══════════════════════════════════════════════════════════════════════════ */
static bool stage_instance_init(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)rt;
Stage* s = (Stage*)calloc(1, sizeof(Stage));
if (!s) return false;
s->bg[0] = s->bg[1] = s->bg[2] = 1.f;
s->pen[0] = 76/255.f; s->pen[1] = 151/255.f; s->pen[2] = 1.f;
s->pen_size = 2.f;
s->view_w = STAGE_W; s->view_h = STAGE_H;
*(Stage**)self->userdata = s;
s_current = self;
return true;
}
static void stage_instance_deinit(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)rt;
Stage* s = stage_of(self);
if (s) { free(s->cmds); free(s); }
*(Stage**)self->userdata = NULL;
if (s_current == self) s_current = NULL;
}
/* input 0 (opcional): Graphics.Input da janela que mostra o palco — dá o tamanho da vista */
static void eval_stage(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
TinyBlocks_Value v = tb_block_get_input(self, rt, 0);
TinyBlocks_Block* in = v.kind == TB_VALUE_BLOCK ? v.as.block : NULL;
if (!in || in->output_count < GFX_IN_COUNT) return;
TinyBlocks_Value w = in->outputs[GFX_IN_WIN_W], h = in->outputs[GFX_IN_WIN_H];
if (w.kind == TB_VALUE_INTEGER && h.kind == TB_VALUE_INTEGER)
tb_stage_set_view(self, (float)w.as.integer, (float)h.as.integer);
}
static bool stage_on_draw(TinyBlocks_Block* self, TinyBlocks* rt, TinyBlocks_RenderableBlock** dst) {
(void)rt;
Stage* s = stage_of(self);
if (!s) return false;
TinyBlocks_RenderableBlock* rb = tb_renderable_acquire();
if (!rb) return false;
float sc = s->view_w / STAGE_W < s->view_h / STAGE_H ? s->view_w / STAGE_W : s->view_h / STAGE_H;
float ox = (s->view_w - STAGE_W*sc) * 0.5f, oy = (s->view_h - STAGE_H*sc) * 0.5f;
#define SX(x) (ox + ((x) + STAGE_W*0.5f) * sc)
#define SY(y) (oy + (STAGE_H*0.5f - (y)) * sc)
if (ox > 0.5f || oy > 0.5f) tb_draw_fill_rect(rb, 0, 0, s->view_w, s->view_h, 0.12f, 0.12f, 0.14f, 1.f);
tb_draw_fill_rect(rb, ox, oy, STAGE_W*sc, STAGE_H*sc, s->bg[0], s->bg[1], s->bg[2], 1.f);
tb_draw_set_clip(rb, ox, oy, STAGE_W*sc, STAGE_H*sc);
for (int i = 0; i < s->n && rb->count < TB_DRAW_CMD_CAP - 2; i++) {
const StageCmd* c = &s->cmds[i];
float r = c->col[0], g = c->col[1], b = c->col[2];
switch (c->kind) {
case SC_RECT:
tb_draw_fill_rect(rb, SX(c->a - c->c*0.5f), SY(c->b + c->d*0.5f), c->c*sc, c->d*sc, r, g, b, 1.f);
break;
case SC_CIRCLE:
tb_draw_fill_circle(rb, SX(c->a), SY(c->b), c->c*sc, r, g, b, 1.f);
break;
case SC_LINE:
tb_draw_stroke_line(rb, SX(c->a), SY(c->b), SX(c->c), SY(c->d), c->size*sc, r, g, b, 1.f);
break;
case SC_TEXT: {
float fs = STAGE_TEXT_FS * sc;
tb_draw_text(rb, SX(c->a), SY(c->b) + fs*0.36f, c->text, fs, r, g, b, 1.f);
break;
}
}
}
tb_draw_clear_clip(rb);
#undef SX
#undef SY
*dst = rb;
return true;
}
/* ══════════════════════════════════════════════════════════════════════════
* Blocos Stage.* — desenham no palco atual
* ══════════════════════════════════════════════════════════════════════════ */
static float num(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) {
TinyBlocks_Value v = tb_block_get_input(self, rt, i);
if (v.kind == TB_VALUE_REAL) return (float)v.as.real;
if (v.kind == TB_VALUE_INTEGER) return (float)v.as.integer;
if (v.kind == TB_VALUE_TEXT && v.as.text) return (float)strtod(v.as.text, NULL);
return 0.f;
}
static float chan(float v) { return v < 0 ? 0.f : v > 255 ? 1.f : v / 255.f; }
static StageCmd* push(TinyBlocks* rt, StageCmdKind kind) {
Stage* s = stage_of(s_current);
if (!s) { tinyblocks_set_error(rt, "nenhum palco (Editor.Stage) criado"); return NULL; }
if (s->n >= STAGE_MAX_CMDS) {
if (!s->full_warned) tinyblocks_set_error(rt, "palco cheio (%d desenhos) — use \"apague tudo\"", STAGE_MAX_CMDS);
s->full_warned = true;
return NULL;
}
if (s->n >= s->cap) {
int nc = s->cap ? s->cap * 2 : 64;
StageCmd* p = (StageCmd*)realloc(s->cmds, (size_t)nc * sizeof(StageCmd));
if (!p) return NULL;
s->cmds = p; s->cap = nc;
}
StageCmd* c = &s->cmds[s->n++];
memset(c, 0, sizeof(*c));
c->kind = kind;
memcpy(c->col, s->pen, sizeof(c->col));
c->size = s->pen_size;
return c;
}
static void eval_clear(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)rt;
Stage* s = stage_of(s_current);
if (s) { s->n = 0; s->full_warned = false; }
self->dirty = false;
}
static void eval_background(TinyBlocks_Block* self, TinyBlocks* rt) {
Stage* s = stage_of(s_current);
if (s) { s->bg[0] = chan(num(self, rt, 0)); s->bg[1] = chan(num(self, rt, 1)); s->bg[2] = chan(num(self, rt, 2)); }
self->dirty = false;
}
static void eval_pen_color(TinyBlocks_Block* self, TinyBlocks* rt) {
Stage* s = stage_of(s_current);
if (s) { s->pen[0] = chan(num(self, rt, 0)); s->pen[1] = chan(num(self, rt, 1)); s->pen[2] = chan(num(self, rt, 2)); }
self->dirty = false;
}
static void eval_pen_size(TinyBlocks_Block* self, TinyBlocks* rt) {
Stage* s = stage_of(s_current);
float v = num(self, rt, 0);
if (s) s->pen_size = v < 1.f ? 1.f : v;
self->dirty = false;
}
static void eval_line(TinyBlocks_Block* self, TinyBlocks* rt) {
StageCmd* c = push(rt, SC_LINE);
if (c) { c->a = num(self, rt, 0); c->b = num(self, rt, 1); c->c = num(self, rt, 2); c->d = num(self, rt, 3); }
self->dirty = false;
}
static void eval_rect(TinyBlocks_Block* self, TinyBlocks* rt) {
StageCmd* c = push(rt, SC_RECT);
if (c) { c->a = num(self, rt, 0); c->b = num(self, rt, 1); c->c = num(self, rt, 2); c->d = num(self, rt, 3); }
self->dirty = false;
}
static void eval_circle(TinyBlocks_Block* self, TinyBlocks* rt) {
StageCmd* c = push(rt, SC_CIRCLE);
if (c) { c->a = num(self, rt, 0); c->b = num(self, rt, 1); c->c = num(self, rt, 2); }
self->dirty = false;
}
static void eval_text(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Value v = tb_block_get_input(self, rt, 0);
char buf[96] = "";
if (v.kind == TB_VALUE_TEXT && v.as.text) snprintf(buf, sizeof(buf), "%s", v.as.text);
else if (v.kind == TB_VALUE_INTEGER) snprintf(buf, sizeof(buf), "%lld", (long long)v.as.integer);
else if (v.kind == TB_VALUE_REAL) snprintf(buf, sizeof(buf), "%g", v.as.real);
StageCmd* c = push(rt, SC_TEXT);
if (c) { memcpy(c->text, buf, sizeof(c->text)); c->a = num(self, rt, 1); c->b = num(self, rt, 2); }
self->dirty = false;
}
/* ══════════════════════════════════════════════════════════════════════════
* Registro
* ══════════════════════════════════════════════════════════════════════════ */
static bool reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name,
const TinyBlocks_SlotDesc* in, uint32_t ni,
void (*fn)(TinyBlocks_Block*, TinyBlocks*)) {
TinyBlocks_TypeBlock* t = tb_type_block_create(rt, name, in, ni, NULL, 0, fn);
if (!t) return false;
tb_library_add(lib, &t->base);
return true;
}
bool tb_stage_register(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
static const TinyBlocks_SlotDesc stage_in[] = {{"entrada", TB_VALUE_BLOCK}};
TinyBlocks_TypeBlock* t = tb_type_block_create(rt, "Editor.Stage", stage_in, 1, NULL, 0, eval_stage);
if (!t) return false;
tb_type_block_set_instance_hooks(t, sizeof(Stage*), stage_instance_init, stage_instance_deinit);
t->on_draw = stage_on_draw;
tb_library_add(lib, &t->base);
static const TinyBlocks_SlotDesc rgb[] = {{"r", TB_VALUE_REAL}, {"g", TB_VALUE_REAL}, {"b", TB_VALUE_REAL}};
static const TinyBlocks_SlotDesc size[] = {{"tamanho", TB_VALUE_REAL}};
static const TinyBlocks_SlotDesc line[] = {{"x1", TB_VALUE_REAL}, {"y1", TB_VALUE_REAL},
{"x2", TB_VALUE_REAL}, {"y2", TB_VALUE_REAL}};
static const TinyBlocks_SlotDesc rect[] = {{"x", TB_VALUE_REAL}, {"y", TB_VALUE_REAL},
{"largura", TB_VALUE_REAL}, {"altura", TB_VALUE_REAL}};
static const TinyBlocks_SlotDesc circ[] = {{"x", TB_VALUE_REAL}, {"y", TB_VALUE_REAL}, {"raio", TB_VALUE_REAL}};
static const TinyBlocks_SlotDesc text[] = {{"texto", TB_VALUE_TEXT}, {"x", TB_VALUE_REAL}, {"y", TB_VALUE_REAL}};
return reg(rt, lib, "Stage.Clear", NULL, 0, eval_clear)
&& reg(rt, lib, "Stage.Background", rgb, 3, eval_background)
&& reg(rt, lib, "Stage.PenColor", rgb, 3, eval_pen_color)
&& reg(rt, lib, "Stage.PenSize", size, 1, eval_pen_size)
&& reg(rt, lib, "Stage.Line", line, 4, eval_line)
&& reg(rt, lib, "Stage.Rect", rect, 4, eval_rect)
&& reg(rt, lib, "Stage.Circle", circ, 3, eval_circle)
&& reg(rt, lib, "Stage.Text", text, 3, eval_text);
}
@@ -0,0 +1,19 @@
/*
* TinyBlocks — tb_stage.h
* Palco do editor (Editor.Stage) e blocos de desenho Stage.*.
*/
#ifndef TINYBLOCKS_EDITOR_STAGE_H
#define TINYBLOCKS_EDITOR_STAGE_H
#include <tinyblocks/tinyblocks.h>
/* Registra Editor.Stage e os blocos Stage.* na library do editor */
bool tb_stage_register(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib);
/* Tamanho da área onde o palco será desenhado (on_draw usa 0..w × 0..h) */
void tb_stage_set_view(TinyBlocks_Block* stage, float w, float h);
/* Palco onde os blocos Stage.* desenham (o último criado) */
TinyBlocks_Block* tb_stage_current(void);
#endif /* TINYBLOCKS_EDITOR_STAGE_H */
@@ -0,0 +1,126 @@
/*
* TinyBlocks — tb_graphics.h
* Interface gráfica do TinyBlocks: janelas, entrada, desenho e texto.
*
* Tudo o que é gráfico passa por aqui antes de chegar a um backend concreto.
* O backend (ex: tinyblocks-sdl2) implementa TinyBlocks_GraphicsBackend e
* pode ser trocado livremente:
* - estaticamente: tb_graphics_set_backend(tb_sdl2_graphics_backend());
* - dinamicamente: tb_graphics_load_backend("build/libtinyblocks-sdl2.so");
* (o .so exporta TINYBLOCKS_GRAPHICS_BACKEND_SYMBOL)
* Sem escolha explícita usa o backend padrão de compilação (SDL2) ou, na
* falta dele, o backend nulo (headless — útil para testes).
*
* TypeBlocks registrados por tb_graphics_get_library():
* Graphics.Input — estado de entrada de uma janela no frame (outputs GFX_IN_*)
* Graphics.Window — uma janela do SO que mostra uma cena (qualquer bloco com on_draw)
* in: título, largura, altura, cena(block), entrada(block), principal(int)
* Graphics.Run — roda o loop até a janela principal fechar
*
* Esta library não conhece nenhum consumidor (editor, palco…): só define o
* contrato e despacha para o backend. Cenas são quaisquer blocos com on_draw.
*
* Uso típico (host):
* tb_library_register(rt, tb_graphics_get_library());
* TinyBlocks_Block* in = tb_block_create(rt, tb_type_block_find(rt, "Graphics.Input"));
* TinyBlocks_Block* win = tb_block_create(rt, tb_type_block_find(rt, "Graphics.Window"));
* tb_block_set_default(win, 3, tb_value_block(cena));
* tb_block_set_default(win, 4, tb_value_block(in));
* tb_block_eval(win, rt); // abre a janela
* tb_graphics_run(rt); // loop até a janela principal fechar
*/
#ifndef TINYBLOCKS_GRAPHICS_H
#define TINYBLOCKS_GRAPHICS_H
#include <tinyblocks/tinyblocks.h>
#include <tinyblocks/tb_renderable_block.h>
/* ── Teclas (neutras; o backend traduz as suas) ──────────────────────────── */
enum {
TB_KEY_NONE = 0,
TB_KEY_ESCAPE, TB_KEY_RETURN, TB_KEY_BACKSPACE, TB_KEY_DELETE, TB_KEY_TAB,
TB_KEY_SPACE, TB_KEY_LEFT, TB_KEY_RIGHT, TB_KEY_UP, TB_KEY_DOWN,
TB_KEY_HOME, TB_KEY_END,
TB_KEY_F1, TB_KEY_F2, TB_KEY_F3, TB_KEY_F4, TB_KEY_F5, TB_KEY_F6,
TB_KEY_F7, TB_KEY_F8, TB_KEY_F9, TB_KEY_F10, TB_KEY_F11, TB_KEY_F12,
TB_KEY_A = 64, /* TB_KEY_A + n = letra 'a'+n */
TB_KEY_0 = TB_KEY_A + 26, /* TB_KEY_0 + n = dígito n */
TB_KEY_OTHER = 127
};
/* ── Modificadores (bitmask) ─────────────────────────────────────────────── */
#define TB_MOD_SHIFT 0x1
#define TB_MOD_CTRL 0x2
#define TB_MOD_ALT 0x4
/* ── Índices de output do bloco Graphics.Input ───────────────────────────── */
#define GFX_IN_MOUSE_X 0 /* real: posição X do mouse na janela */
#define GFX_IN_MOUSE_Y 1 /* real: posição Y do mouse na janela */
#define GFX_IN_MOUSE_L_HELD 2 /* int: botão esquerdo pressionado (estado) */
#define GFX_IN_MOUSE_R_HELD 3 /* int: botão direito pressionado (estado) */
#define GFX_IN_MOUSE_L_DOWN 4 /* int: 1 se pressionado neste frame */
#define GFX_IN_MOUSE_L_UP 5 /* int: 1 se solto neste frame */
#define GFX_IN_MOUSE_R_DOWN 6 /* int: 1 se pressionado neste frame */
#define GFX_IN_MOUSE_R_UP 7 /* int: 1 se solto neste frame */
#define GFX_IN_SCROLL_DX 8 /* real: scroll horizontal deste frame */
#define GFX_IN_SCROLL_DY 9 /* real: scroll vertical deste frame */
#define GFX_IN_KEY 10 /* int: TB_KEY_* pressionada neste frame */
#define GFX_IN_KEY_MOD 11 /* int: TB_MOD_* no momento da tecla */
#define GFX_IN_KEY_REPEAT 12 /* int: 1 se é repetição de tecla segurada */
#define GFX_IN_TEXT 13 /* text: texto digitado neste frame */
#define GFX_IN_CLOSE 14 /* int: 1 se o usuário pediu para fechar */
#define GFX_IN_WIN_W 15 /* int: largura atual da janela */
#define GFX_IN_WIN_H 16 /* int: altura atual da janela */
#define GFX_IN_DROP_FILE 17 /* text: caminho de arquivo solto na janela */
#define GFX_IN_MOD_STATE 18 /* int: TB_MOD_* segurados agora */
#define GFX_IN_COUNT 19
/* Estado de entrada de uma janela em um frame (preenchido pelo backend) */
typedef struct TinyBlocks_GfxInput {
float mouse_x, mouse_y;
int l_held, r_held;
int l_down, l_up, r_down, r_up;
float scroll_dx, scroll_dy;
int key, key_mod, key_repeat;
char text[64];
int close;
int win_w, win_h;
char drop_file[512];
int mod_state;
} TinyBlocks_GfxInput;
/* ── Contrato de um backend gráfico ──────────────────────────────────────── */
typedef struct TinyBlocks_GraphicsBackend {
const char* name;
bool (*init)(void); /* idempotente */
void (*shutdown)(void);
void* (*window_open)(const char* title, int w, int h); /* handle opaco ou NULL */
void (*window_close)(void* win);
void (*poll)(void); /* coleta eventos do SO */
void (*window_input)(void* win, TinyBlocks_GfxInput* out);
void (*window_present)(void* win, const TinyBlocks_RenderableBlock* rb);
float (*measure_text)(const char* text, float font_size); /* NULL = estimativa */
void (*frame_wait)(void); /* NULL = ~16 ms */
} TinyBlocks_GraphicsBackend;
/* Símbolo exportado por um backend carregado como .so */
#define TINYBLOCKS_GRAPHICS_BACKEND_SYMBOL "tinyblocks_get_graphics_backend"
typedef const TinyBlocks_GraphicsBackend* (*TinyBlocks_GetGraphicsBackendFn)(void);
/* ── API ─────────────────────────────────────────────────────────────────── */
TB_API const TinyBlocks_LibraryDescriptor* tb_graphics_get_library(void);
/* Escolhe o backend (antes de abrir a primeira janela) */
TB_API bool tb_graphics_set_backend(const TinyBlocks_GraphicsBackend* backend);
TB_API bool tb_graphics_load_backend(const char* so_path);
TB_API const TinyBlocks_GraphicsBackend* tb_graphics_backend(void);
TB_API const TinyBlocks_GraphicsBackend* tb_graphics_null_backend(void);
/* Largura de um texto na fonte do backend */
TB_API float tb_graphics_measure_text(const char* text, float font_size);
/* Loop principal: roda todas as janelas abertas até a principal fechar */
TB_API void tb_graphics_run(TinyBlocks* rt);
TB_API bool tb_graphics_window_is_open(TinyBlocks_Block* window);
#endif /* TINYBLOCKS_GRAPHICS_H */
@@ -0,0 +1,383 @@
/*
* TinyBlocks — tb_graphics.c
* Interface gráfica: escolha de backend, janelas, entrada e loop principal.
*/
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <dlfcn.h>
#include "../include/tb_graphics.h"
#ifdef TB_GRAPHICS_DEFAULT_SDL2
#include <tb_sdl2.h>
#endif
/* ══════════════════════════════════════════════════════════════════════════
* Backend nulo (headless): janelas sem tela, entrada vazia, texto estimado
* ══════════════════════════════════════════════════════════════════════════ */
typedef struct { int w, h; } NullWin;
static bool null_init(void) { return true; }
static void null_shutdown(void) { }
static void* null_open(const char* title, int w, int h) {
(void)title;
NullWin* n = (NullWin*)calloc(1, sizeof(*n));
if (n) { n->w = w; n->h = h; }
return n;
}
static void null_close(void* win) { free(win); }
static void null_poll(void) { }
static void null_input(void* win, TinyBlocks_GfxInput* out) {
memset(out, 0, sizeof(*out));
const NullWin* n = (const NullWin*)win;
if (n) { out->win_w = n->w; out->win_h = n->h; }
}
static void null_present(void* win, const TinyBlocks_RenderableBlock* rb) { (void)win; (void)rb; }
static const TinyBlocks_GraphicsBackend s_null_backend = {
.name = "null",
.init = null_init,
.shutdown = null_shutdown,
.window_open = null_open,
.window_close = null_close,
.poll = null_poll,
.window_input = null_input,
.window_present = null_present,
.measure_text = NULL,
.frame_wait = NULL,
};
const TinyBlocks_GraphicsBackend* tb_graphics_null_backend(void) { return &s_null_backend; }
/* ══════════════════════════════════════════════════════════════════════════
* Escolha do backend
* ══════════════════════════════════════════════════════════════════════════ */
static const TinyBlocks_GraphicsBackend* s_backend = NULL;
static bool s_backend_ready = false;
static void* s_backend_dl = NULL;
#define MAX_WINDOWS 16
typedef struct { TinyBlocks_Block* block; uint64_t id; } WinEntry;
static WinEntry s_wins[MAX_WINDOWS];
static int s_win_n = 0;
static uint64_t s_next_id = 1;
const TinyBlocks_GraphicsBackend* tb_graphics_backend(void) {
if (!s_backend) {
#ifdef TB_GRAPHICS_DEFAULT_SDL2
s_backend = (const TinyBlocks_GraphicsBackend*)tb_sdl2_graphics_backend();
#endif
if (!s_backend) s_backend = &s_null_backend;
}
return s_backend;
}
/* Backend inicializado; se o init falhar, cai para o nulo */
static const TinyBlocks_GraphicsBackend* backend_ready(void) {
const TinyBlocks_GraphicsBackend* b = tb_graphics_backend();
if (s_backend_ready) return b;
if (b->init && !b->init()) {
fprintf(stderr, "tinyblocks-graphics: backend '%s' falhou ao iniciar; usando 'null'\n", b->name);
s_backend = b = &s_null_backend;
}
s_backend_ready = true;
return b;
}
bool tb_graphics_set_backend(const TinyBlocks_GraphicsBackend* backend) {
if (!backend || !backend->window_open || !backend->window_present) return false;
if (backend == s_backend) return true;
if (s_win_n > 0) {
fprintf(stderr, "tinyblocks-graphics: feche as janelas antes de trocar o backend\n");
return false;
}
if (s_backend_ready && s_backend->shutdown) s_backend->shutdown();
s_backend_ready = false;
s_backend = backend;
return true;
}
bool tb_graphics_load_backend(const char* so_path) {
void* dl = dlopen(so_path, RTLD_NOW | RTLD_LOCAL);
if (!dl) {
fprintf(stderr, "tinyblocks-graphics: dlopen: %s\n", dlerror());
return false;
}
TinyBlocks_GetGraphicsBackendFn get =
(TinyBlocks_GetGraphicsBackendFn)(uintptr_t)dlsym(dl, TINYBLOCKS_GRAPHICS_BACKEND_SYMBOL);
const TinyBlocks_GraphicsBackend* b = get ? get() : NULL;
if (!b || !tb_graphics_set_backend(b)) {
fprintf(stderr, "tinyblocks-graphics: '%s' não exporta um backend válido (%s)\n",
so_path, TINYBLOCKS_GRAPHICS_BACKEND_SYMBOL);
dlclose(dl);
return false;
}
if (s_backend_dl) dlclose(s_backend_dl);
s_backend_dl = dl;
return true;
}
/* ══════════════════════════════════════════════════════════════════════════
* Medição de texto
* ══════════════════════════════════════════════════════════════════════════ */
/* Larguras de avanço da DejaVu Sans, em em, para ASCII 32..126 — estimativa
* usada quando o backend não sabe medir (ex: backend nulo). */
static const float s_adv[95] = {
.318f,.401f,.460f,.838f,.636f,.950f,.780f,.275f,.390f,.390f,.500f,.838f,.318f,.361f,.318f,.337f,
.636f,.636f,.636f,.636f,.636f,.636f,.636f,.636f,.636f,.636f,.337f,.337f,.838f,.838f,.838f,.531f,
1.0f, .684f,.686f,.698f,.770f,.632f,.575f,.775f,.752f,.295f,.295f,.656f,.557f,.863f,.748f,.787f,
.603f,.787f,.695f,.635f,.611f,.732f,.684f,.989f,.685f,.611f,.685f,.390f,.337f,.390f,.838f,.500f,
.500f,.613f,.635f,.550f,.635f,.615f,.352f,.635f,.634f,.278f,.278f,.579f,.278f,.974f,.634f,.612f,
.635f,.635f,.411f,.521f,.392f,.634f,.592f,.818f,.592f,.592f,.525f,.636f,.337f,.636f,.838f
};
static float estimate_text(const char* s, float fs) {
float w = 0.f;
for (const unsigned char* p = (const unsigned char*)s; *p; p++) {
if (*p >= 32 && *p < 127) w += s_adv[*p - 32];
else if ((*p & 0xC0) == 0xC0) w += (*p >= 0xE0) ? 0.9f : 0.62f; /* início de UTF-8 */
}
return w * fs;
}
float tb_graphics_measure_text(const char* text, float font_size) {
if (!text || !text[0]) return 0.f;
const TinyBlocks_GraphicsBackend* b = backend_ready();
return b->measure_text ? b->measure_text(text, font_size) : estimate_text(text, font_size);
}
/* ══════════════════════════════════════════════════════════════════════════
* Graphics.Input — estado de entrada de uma janela no frame
* ══════════════════════════════════════════════════════════════════════════ */
static const TinyBlocks_SlotDesc s_input_outs[GFX_IN_COUNT] = {
{"mouse_x", TB_VALUE_REAL}, {"mouse_y", TB_VALUE_REAL},
{"l_held", TB_VALUE_INTEGER}, {"r_held", TB_VALUE_INTEGER},
{"l_down", TB_VALUE_INTEGER}, {"l_up", TB_VALUE_INTEGER},
{"r_down", TB_VALUE_INTEGER}, {"r_up", TB_VALUE_INTEGER},
{"scroll_dx", TB_VALUE_REAL}, {"scroll_dy", TB_VALUE_REAL},
{"key", TB_VALUE_INTEGER}, {"key_mod", TB_VALUE_INTEGER},
{"key_repeat", TB_VALUE_INTEGER}, {"text", TB_VALUE_TEXT},
{"close", TB_VALUE_INTEGER}, {"win_w", TB_VALUE_INTEGER},
{"win_h", TB_VALUE_INTEGER}, {"drop_file", TB_VALUE_TEXT},
{"mod_state", TB_VALUE_INTEGER},
};
static void eval_input(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)rt;
/* Os outputs são preenchidos pelo loop; aqui só garante valores neutros */
for (uint32_t i = 0; i < self->output_count && i < GFX_IN_COUNT; i++) {
if (self->outputs[i].kind != TB_VALUE_NONE) continue;
switch (s_input_outs[i].expected_kind) {
case TB_VALUE_REAL: self->outputs[i] = tb_value_real(0.0); break;
case TB_VALUE_TEXT: self->outputs[i] = tb_value_text(""); break;
default: self->outputs[i] = tb_value_integer(0); break;
}
}
self->dirty = false;
}
static void input_push(TinyBlocks_Block* b, const TinyBlocks_GfxInput* in) {
if (!b || b->output_count < GFX_IN_COUNT) return;
#define SET(idx, v) tb_block_set_output(b, idx, v)
SET(GFX_IN_MOUSE_X, tb_value_real(in->mouse_x));
SET(GFX_IN_MOUSE_Y, tb_value_real(in->mouse_y));
SET(GFX_IN_MOUSE_L_HELD, tb_value_integer(in->l_held));
SET(GFX_IN_MOUSE_R_HELD, tb_value_integer(in->r_held));
SET(GFX_IN_MOUSE_L_DOWN, tb_value_integer(in->l_down));
SET(GFX_IN_MOUSE_L_UP, tb_value_integer(in->l_up));
SET(GFX_IN_MOUSE_R_DOWN, tb_value_integer(in->r_down));
SET(GFX_IN_MOUSE_R_UP, tb_value_integer(in->r_up));
SET(GFX_IN_SCROLL_DX, tb_value_real(in->scroll_dx));
SET(GFX_IN_SCROLL_DY, tb_value_real(in->scroll_dy));
SET(GFX_IN_KEY, tb_value_integer(in->key));
SET(GFX_IN_KEY_MOD, tb_value_integer(in->key_mod));
SET(GFX_IN_KEY_REPEAT, tb_value_integer(in->key_repeat));
SET(GFX_IN_TEXT, tb_value_text(in->text));
SET(GFX_IN_CLOSE, tb_value_integer(in->close));
SET(GFX_IN_WIN_W, tb_value_integer(in->win_w));
SET(GFX_IN_WIN_H, tb_value_integer(in->win_h));
SET(GFX_IN_DROP_FILE, tb_value_text(in->drop_file));
SET(GFX_IN_MOD_STATE, tb_value_integer(in->mod_state));
#undef SET
b->dirty = false;
}
/* ══════════════════════════════════════════════════════════════════════════
* Graphics.Window — uma janela do SO mostrando uma cena
* inputs: 0 título, 1 largura, 2 altura, 3 cena(block), 4 entrada(block),
* 5 principal(int: fechar esta janela encerra o loop; padrão 1)
* output: 0 aberta(int)
* ══════════════════════════════════════════════════════════════════════════ */
typedef struct { void* handle; uint64_t id; bool open; } WinState;
static int win_find(uint64_t id) {
for (int i = 0; i < s_win_n; i++) if (s_wins[i].id == id) return i;
return -1;
}
static void win_close(TinyBlocks_Block* self) {
WinState* ws = (WinState*)self->userdata;
if (!ws->open) return;
int i = win_find(ws->id);
if (i >= 0) { s_wins[i] = s_wins[s_win_n - 1]; s_win_n--; }
if (ws->handle && s_backend_ready) s_backend->window_close(ws->handle);
ws->handle = NULL;
ws->open = false;
tb_block_set_output(self, 0, tb_value_integer(0));
}
static bool win_instance_init(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)rt;
memset(self->userdata, 0, sizeof(WinState));
return true;
}
static void win_instance_deinit(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)rt;
win_close(self);
}
static void eval_window(TinyBlocks_Block* self, TinyBlocks* rt) {
WinState* ws = (WinState*)self->userdata;
self->dirty = false;
if (ws->open) return;
if (s_win_n >= MAX_WINDOWS) {
tinyblocks_set_error(rt, "Graphics.Window: limite de %d janelas", MAX_WINDOWS);
return;
}
TinyBlocks_Value vt = tb_block_get_input(self, rt, 0);
TinyBlocks_Value vw = tb_block_get_input(self, rt, 1);
TinyBlocks_Value vh = tb_block_get_input(self, rt, 2);
const char* title = (vt.kind == TB_VALUE_TEXT && vt.as.text) ? vt.as.text : "TinyBlocks";
int w = vw.kind == TB_VALUE_INTEGER && vw.as.integer > 0 ? (int)vw.as.integer : 640;
int h = vh.kind == TB_VALUE_INTEGER && vh.as.integer > 0 ? (int)vh.as.integer : 480;
const TinyBlocks_GraphicsBackend* b = backend_ready();
void* handle = b->window_open(title, w, h);
if (!handle) {
tinyblocks_set_error(rt, "Graphics.Window: o backend '%s' não abriu a janela", b->name);
return;
}
ws->handle = handle;
ws->id = s_next_id++;
ws->open = true;
s_wins[s_win_n++] = (WinEntry){ self, ws->id };
tb_block_set_output(self, 0, tb_value_integer(1));
}
bool tb_graphics_window_is_open(TinyBlocks_Block* window) {
if (!window || !window->type || !window->type->type_name ||
strcmp(window->type->type_name, "Graphics.Window") != 0) return false;
return ((WinState*)window->userdata)->open;
}
/* ══════════════════════════════════════════════════════════════════════════
* Loop principal
* ══════════════════════════════════════════════════════════════════════════ */
static void default_wait(void) {
struct timespec ts = { 0, 16 * 1000000L };
nanosleep(&ts, NULL);
}
void tb_graphics_run(TinyBlocks* rt) {
const TinyBlocks_GraphicsBackend* b = backend_ready();
bool running = s_win_n > 0;
while (running) {
if (b->poll) b->poll();
/* As cenas podem abrir/fechar janelas: itera sobre uma cópia dos ids */
uint64_t ids[MAX_WINDOWS];
int n = s_win_n;
for (int i = 0; i < n; i++) ids[i] = s_wins[i].id;
for (int k = 0; k < n; k++) {
int i = win_find(ids[k]);
if (i < 0) continue;
TinyBlocks_Block* wb = s_wins[i].block;
WinState* ws = (WinState*)wb->userdata;
TinyBlocks_GfxInput in;
b->window_input(ws->handle, &in);
TinyBlocks_Value vin = tb_block_get_input(wb, rt, 4);
if (vin.kind == TB_VALUE_BLOCK) input_push(vin.as.block, &in);
if (in.close) {
TinyBlocks_Value vp = tb_block_get_input(wb, rt, 5);
if (vp.kind != TB_VALUE_INTEGER || vp.as.integer) running = false;
win_close(wb);
continue;
}
TinyBlocks_RenderableBlock* rb = NULL;
TinyBlocks_Value vs = tb_block_get_input(wb, rt, 3);
TinyBlocks_Block* scene = vs.kind == TB_VALUE_BLOCK ? vs.as.block : NULL;
if (scene) {
scene->dirty = true;
tb_block_eval(scene, rt);
if (win_find(ids[k]) < 0) continue; /* a cena fechou esta janela */
if (scene->type && scene->type->on_draw) scene->type->on_draw(scene, rt, &rb);
}
b->window_present(ws->handle, rb);
if (rb) tb_renderable_release(rb);
}
tb_renderable_release_all();
if (s_win_n == 0) running = false;
if (running) { if (b->frame_wait) b->frame_wait(); else default_wait(); }
}
while (s_win_n > 0) win_close(s_wins[s_win_n - 1].block);
if (b->shutdown) b->shutdown();
s_backend_ready = false;
}
static void eval_run(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
tb_graphics_run(rt);
}
/* ══════════════════════════════════════════════════════════════════════════
* Registro da library
* ══════════════════════════════════════════════════════════════════════════ */
static bool graphics_lib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
TinyBlocks_TypeBlock* t;
t = tb_type_block_create(rt, "Graphics.Input", NULL, 0, s_input_outs, GFX_IN_COUNT, eval_input);
if (!t) return false;
tb_library_add(lib, &t->base);
static const TinyBlocks_SlotDesc win_in[] = {
{"título", TB_VALUE_TEXT}, {"largura", TB_VALUE_INTEGER}, {"altura", TB_VALUE_INTEGER},
{"cena", TB_VALUE_BLOCK}, {"entrada", TB_VALUE_BLOCK}, {"principal", TB_VALUE_INTEGER},
};
static const TinyBlocks_SlotDesc win_out[] = {{"aberta", TB_VALUE_INTEGER}};
t = tb_type_block_create(rt, "Graphics.Window", win_in, 6, win_out, 1, eval_window);
if (!t) return false;
tb_type_block_set_instance_hooks(t, sizeof(WinState), win_instance_init, win_instance_deinit);
tb_library_add(lib, &t->base);
t = tb_type_block_create(rt, "Graphics.Run", NULL, 0, NULL, 0, eval_run);
if (!t) return false;
tb_library_add(lib, &t->base);
return true;
}
static void graphics_lib_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
(void)rt; (void)lib;
if (s_backend_ready && s_backend->shutdown) s_backend->shutdown();
s_backend_ready = false;
}
TINYBLOCKS_DEFINE_LIBRARY(graphics,
"tinyblocks-graphics",
"1.0.0",
graphics_lib_init,
graphics_lib_deinit)
const TinyBlocks_LibraryDescriptor* tb_graphics_get_library(void) {
return &_tb_lib_desc_graphics;
}
@@ -0,0 +1,36 @@
#ifndef TINYBLOCKS_MCP_H
#define TINYBLOCKS_MCP_H
#include <stdbool.h>
#ifdef _WIN32
# define TB_MCP_API __declspec(dllexport)
#else
# define TB_MCP_API __attribute__((visibility("default")))
#endif
/*
* tb_mcp — cliente MCP (Model Context Protocol) sobre transporte HTTP
* e stdio, implementado em Python via tinyblocks-python.
*
* Transport HTTP (streamable): url = "http://host:port/mcp"
* Transport stdio: url = "stdio://npx @modelcontextprotocol/server-filesystem /tmp"
*
* Todas as funções retornam string heap-alocada (caller frees) ou NULL em erro.
*/
TB_MCP_API bool tb_mcp_init(void);
TB_MCP_API void tb_mcp_deinit(void);
/* Lista ferramentas disponíveis → JSON array de objetos {name, description} */
TB_MCP_API char* tb_mcp_list_tools(const char* url);
/* Chama uma ferramenta com argumentos JSON → resultado JSON */
TB_MCP_API char* tb_mcp_call_tool(const char* url,
const char* tool_name,
const char* args_json);
/* Ping: verifica se o servidor responde → "ok" ou mensagem de erro */
TB_MCP_API char* tb_mcp_ping(const char* url);
#endif /* TINYBLOCKS_MCP_H */
+125
View File
@@ -0,0 +1,125 @@
#define _POSIX_C_SOURCE 200809L
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "tinyblocks-mcp/tb_mcp.h"
#include "tinyblocks-python/tb_python.h"
/* Código Python gerado por: xxd -i tb_mcp.py > tb_mcp_py.h */
#include "tb_mcp_py.h"
/* ── Singleton ───────────────────────────────────────────────────────────── */
static bool s_module_loaded = false;
static bool ensure_module(void) {
if (s_module_loaded) return true;
/*
* Executa o módulo Python em __main__ para que as funções persistam
* entre chamadas. tb_mcp_py é unsigned char[] gerado pelo xxd -i.
*/
char* err = tb_python_exec_main((const char*)tb_mcp_py);
bool ok = (err != NULL && strlen(err) == 0);
if (!ok && err) fprintf(stderr, "[tinyblocks-mcp] erro ao carregar modulo Python:\n%s\n", err);
free(err);
s_module_loaded = ok;
return ok;
}
TB_MCP_API bool tb_mcp_init(void) {
if (!tb_python_init()) return false;
return ensure_module();
}
TB_MCP_API void tb_mcp_deinit(void) {
s_module_loaded = false;
tb_python_deinit();
}
/* ── Helper: escapa string para literal Python ───────────────────────────── */
static char* py_str(const char* s) {
size_t n = strlen(s);
char* out = malloc(n * 4 + 3);
if (!out) return NULL;
char* p = out;
*p++ = '"';
for (size_t i = 0; i < n; i++) {
unsigned char c = (unsigned char)s[i];
if (c == '"') { *p++ = '\\'; *p++ = '"'; }
else if (c == '\\') { *p++ = '\\'; *p++ = '\\'; }
else if (c == '\n') { *p++ = '\\'; *p++ = 'n'; }
else if (c == '\r') { *p++ = '\\'; *p++ = 'r'; }
else if (c < 0x20) {
p += sprintf(p, "\\x%02x", c);
} else {
*p++ = (char)c;
}
}
*p++ = '"';
*p = '\0';
return out;
}
/* ── Helper genérico: monta e executa chamada Python fn(arg...) ─────────── */
static char* py_call(const char* fn, const char* const* args, int n) {
if (!ensure_module()) return strdup("erro: modulo MCP nao carregado");
/* Constrói "print(fn(arg0, arg1, ...))" */
size_t total = strlen(fn) + 16;
char** esc = malloc(n * sizeof(char*));
if (!esc) return strdup("erro: memoria");
for (int i = 0; i < n; i++) {
esc[i] = py_str(args[i]);
if (!esc[i]) {
for (int j = 0; j < i; j++) free(esc[j]);
free(esc);
return strdup("erro: memoria");
}
total += strlen(esc[i]) + 2;
}
char* code = malloc(total + 16);
if (!code) {
for (int i = 0; i < n; i++) free(esc[i]);
free(esc);
return strdup("erro: memoria");
}
char* p = code;
p += sprintf(p, "print(%s(", fn);
for (int i = 0; i < n; i++) {
if (i > 0) { *p++ = ','; *p++ = ' '; }
p += sprintf(p, "%s", esc[i]);
}
sprintf(p, "))");
for (int i = 0; i < n; i++) free(esc[i]);
free(esc);
char* out = tb_python_exec_main(code);
free(code);
/* Remove trailing newline */
if (out) {
size_t len = strlen(out);
while (len > 0 && (out[len-1] == '\n' || out[len-1] == '\r'))
out[--len] = '\0';
}
return out ? out : strdup("");
}
/* ── API pública ─────────────────────────────────────────────────────────── */
TB_MCP_API char* tb_mcp_ping(const char* url) {
const char* args[] = {url};
return py_call("mcp_ping", args, 1);
}
TB_MCP_API char* tb_mcp_list_tools(const char* url) {
const char* args[] = {url};
return py_call("mcp_list_tools", args, 1);
}
TB_MCP_API char* tb_mcp_call_tool(const char* url, const char* tool_name, const char* args_json) {
const char* args[] = {url, tool_name, args_json ? args_json : "{}"};
return py_call("mcp_call_tool", args, 3);
}
+115
View File
@@ -0,0 +1,115 @@
import json
def _http_jsonrpc(url, method, params):
import urllib.request, urllib.error
payload = json.dumps({
"jsonrpc": "2.0",
"id": 1,
"method": method,
"params": params
}).encode()
req = urllib.request.Request(
url,
data=payload,
headers={
"Content-Type": "application/json",
"Accept": "application/json",
}
)
try:
with urllib.request.urlopen(req, timeout=15) as r:
body = r.read().decode()
except urllib.error.HTTPError as e:
return {"error": {"code": e.code, "message": e.reason}}
except Exception as e:
return {"error": {"code": -1, "message": str(e)}}
try:
return json.loads(body)
except Exception as e:
return {"error": {"code": -2, "message": "invalid JSON: " + str(e)}}
def _stdio_jsonrpc(cmd, method, params):
import subprocess
args = cmd.split()
try:
proc = subprocess.Popen(
args,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL
)
except FileNotFoundError as e:
return {"error": {"code": -1, "message": str(e)}}
def send(obj):
line = (json.dumps(obj) + "\n").encode()
proc.stdin.write(line)
proc.stdin.flush()
def recv():
line = proc.stdout.readline()
if not line:
return {}
return json.loads(line.decode().strip())
try:
send({"jsonrpc":"2.0","id":1,"method":"initialize","params":{
"protocolVersion":"2024-11-05",
"capabilities":{},
"clientInfo":{"name":"tinyblocks-mcp","version":"1.0"}
}})
recv()
send({"jsonrpc":"2.0","method":"notifications/initialized","params":{}})
send({"jsonrpc":"2.0","id":2,"method":method,"params":params})
resp = recv()
return resp
except Exception as e:
return {"error":{"code":-1,"message":str(e)}}
finally:
proc.terminate()
proc.wait(timeout=3)
def _dispatch(url, method, params):
if url.startswith("stdio://"):
return _stdio_jsonrpc(url[len("stdio://"):], method, params)
else:
return _http_jsonrpc(url, method, params)
def mcp_ping(url):
resp = _dispatch(url, "ping", {})
if "error" in resp:
return "erro: " + resp["error"].get("message", str(resp["error"]))
return "ok"
def mcp_list_tools(url):
resp = _dispatch(url, "tools/list", {})
if "error" in resp:
return "erro: " + resp["error"].get("message", str(resp["error"]))
result = resp.get("result", resp)
tools = result.get("tools", [])
out = []
for t in tools:
name = t.get("name","?")
desc = t.get("description","")
out.append(name + ": " + desc)
return "\n".join(out) if out else "(nenhuma ferramenta)"
def mcp_call_tool(url, tool_name, args_json):
try:
args = json.loads(args_json) if args_json and args_json.strip() else {}
except Exception as e:
return "erro: args JSON invalido: " + str(e)
resp = _dispatch(url, "tools/call", {"name": tool_name, "arguments": args})
if "error" in resp:
return "erro: " + resp["error"].get("message", str(resp["error"]))
result = resp.get("result", resp)
content = result.get("content", result)
if isinstance(content, list):
parts = []
for item in content:
if isinstance(item, dict):
parts.append(item.get("text", json.dumps(item)))
else:
parts.append(str(item))
return "\n".join(parts)
return json.dumps(content, ensure_ascii=False, indent=2)
+314
View File
@@ -0,0 +1,314 @@
unsigned char tb_mcp_py[] = {
0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x20, 0x6a, 0x73, 0x6f, 0x6e, 0x0a,
0x0a, 0x64, 0x65, 0x66, 0x20, 0x5f, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x6a,
0x73, 0x6f, 0x6e, 0x72, 0x70, 0x63, 0x28, 0x75, 0x72, 0x6c, 0x2c, 0x20,
0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x2c, 0x20, 0x70, 0x61, 0x72, 0x61,
0x6d, 0x73, 0x29, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x6d, 0x70,
0x6f, 0x72, 0x74, 0x20, 0x75, 0x72, 0x6c, 0x6c, 0x69, 0x62, 0x2e, 0x72,
0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2c, 0x20, 0x75, 0x72, 0x6c, 0x6c,
0x69, 0x62, 0x2e, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x20, 0x3d, 0x20, 0x6a,
0x73, 0x6f, 0x6e, 0x2e, 0x64, 0x75, 0x6d, 0x70, 0x73, 0x28, 0x7b, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x6a, 0x73, 0x6f,
0x6e, 0x72, 0x70, 0x63, 0x22, 0x3a, 0x20, 0x22, 0x32, 0x2e, 0x30, 0x22,
0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x69,
0x64, 0x22, 0x3a, 0x20, 0x31, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x22, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x22, 0x3a,
0x20, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x2c, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73,
0x22, 0x3a, 0x20, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x7d, 0x29, 0x2e, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x65, 0x28,
0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x71, 0x20, 0x3d, 0x20,
0x75, 0x72, 0x6c, 0x6c, 0x69, 0x62, 0x2e, 0x72, 0x65, 0x71, 0x75, 0x65,
0x73, 0x74, 0x2e, 0x52, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x28, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x75, 0x72, 0x6c, 0x2c,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64, 0x61, 0x74,
0x61, 0x3d, 0x70, 0x61, 0x79, 0x6c, 0x6f, 0x61, 0x64, 0x2c, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x68, 0x65, 0x61, 0x64, 0x65,
0x72, 0x73, 0x3d, 0x7b, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e,
0x74, 0x2d, 0x54, 0x79, 0x70, 0x65, 0x22, 0x3a, 0x20, 0x22, 0x61, 0x70,
0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x6a, 0x73,
0x6f, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x41, 0x63, 0x63, 0x65, 0x70, 0x74,
0x22, 0x3a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x61, 0x70,
0x70, 0x6c, 0x69, 0x63, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x2f, 0x6a, 0x73,
0x6f, 0x6e, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x29, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x74, 0x72, 0x79, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x75, 0x72, 0x6c, 0x6c, 0x69,
0x62, 0x2e, 0x72, 0x65, 0x71, 0x75, 0x65, 0x73, 0x74, 0x2e, 0x75, 0x72,
0x6c, 0x6f, 0x70, 0x65, 0x6e, 0x28, 0x72, 0x65, 0x71, 0x2c, 0x20, 0x74,
0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74, 0x3d, 0x31, 0x35, 0x29, 0x20, 0x61,
0x73, 0x20, 0x72, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x62, 0x6f, 0x64, 0x79, 0x20, 0x3d, 0x20,
0x72, 0x2e, 0x72, 0x65, 0x61, 0x64, 0x28, 0x29, 0x2e, 0x64, 0x65, 0x63,
0x6f, 0x64, 0x65, 0x28, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x65, 0x78,
0x63, 0x65, 0x70, 0x74, 0x20, 0x75, 0x72, 0x6c, 0x6c, 0x69, 0x62, 0x2e,
0x65, 0x72, 0x72, 0x6f, 0x72, 0x2e, 0x48, 0x54, 0x54, 0x50, 0x45, 0x72,
0x72, 0x6f, 0x72, 0x20, 0x61, 0x73, 0x20, 0x65, 0x3a, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e,
0x20, 0x7b, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x3a, 0x20, 0x7b,
0x22, 0x63, 0x6f, 0x64, 0x65, 0x22, 0x3a, 0x20, 0x65, 0x2e, 0x63, 0x6f,
0x64, 0x65, 0x2c, 0x20, 0x22, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65,
0x22, 0x3a, 0x20, 0x65, 0x2e, 0x72, 0x65, 0x61, 0x73, 0x6f, 0x6e, 0x7d,
0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x65, 0x78, 0x63, 0x65, 0x70, 0x74,
0x20, 0x45, 0x78, 0x63, 0x65, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x61,
0x73, 0x20, 0x65, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x7b, 0x22, 0x65, 0x72,
0x72, 0x6f, 0x72, 0x22, 0x3a, 0x20, 0x7b, 0x22, 0x63, 0x6f, 0x64, 0x65,
0x22, 0x3a, 0x20, 0x2d, 0x31, 0x2c, 0x20, 0x22, 0x6d, 0x65, 0x73, 0x73,
0x61, 0x67, 0x65, 0x22, 0x3a, 0x20, 0x73, 0x74, 0x72, 0x28, 0x65, 0x29,
0x7d, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x74, 0x72, 0x79, 0x3a, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75,
0x72, 0x6e, 0x20, 0x6a, 0x73, 0x6f, 0x6e, 0x2e, 0x6c, 0x6f, 0x61, 0x64,
0x73, 0x28, 0x62, 0x6f, 0x64, 0x79, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x65, 0x78, 0x63, 0x65, 0x70, 0x74, 0x20, 0x45, 0x78, 0x63, 0x65, 0x70,
0x74, 0x69, 0x6f, 0x6e, 0x20, 0x61, 0x73, 0x20, 0x65, 0x3a, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72,
0x6e, 0x20, 0x7b, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x3a, 0x20,
0x7b, 0x22, 0x63, 0x6f, 0x64, 0x65, 0x22, 0x3a, 0x20, 0x2d, 0x32, 0x2c,
0x20, 0x22, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x3a, 0x20,
0x22, 0x69, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x20, 0x4a, 0x53, 0x4f,
0x4e, 0x3a, 0x20, 0x22, 0x20, 0x2b, 0x20, 0x73, 0x74, 0x72, 0x28, 0x65,
0x29, 0x7d, 0x7d, 0x0a, 0x0a, 0x64, 0x65, 0x66, 0x20, 0x5f, 0x73, 0x74,
0x64, 0x69, 0x6f, 0x5f, 0x6a, 0x73, 0x6f, 0x6e, 0x72, 0x70, 0x63, 0x28,
0x63, 0x6d, 0x64, 0x2c, 0x20, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x2c,
0x20, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x29, 0x3a, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x69, 0x6d, 0x70, 0x6f, 0x72, 0x74, 0x20, 0x73, 0x75, 0x62,
0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x61, 0x72, 0x67, 0x73, 0x20, 0x3d, 0x20, 0x63, 0x6d, 0x64, 0x2e, 0x73,
0x70, 0x6c, 0x69, 0x74, 0x28, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x74,
0x72, 0x79, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x70, 0x72, 0x6f, 0x63, 0x20, 0x3d, 0x20, 0x73, 0x75, 0x62, 0x70, 0x72,
0x6f, 0x63, 0x65, 0x73, 0x73, 0x2e, 0x50, 0x6f, 0x70, 0x65, 0x6e, 0x28,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x61, 0x72, 0x67, 0x73, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x74, 0x64, 0x69, 0x6e,
0x3d, 0x73, 0x75, 0x62, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x2e,
0x50, 0x49, 0x50, 0x45, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x74, 0x64, 0x6f, 0x75, 0x74,
0x3d, 0x73, 0x75, 0x62, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x2e,
0x50, 0x49, 0x50, 0x45, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x74, 0x64, 0x65, 0x72, 0x72,
0x3d, 0x73, 0x75, 0x62, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x2e,
0x44, 0x45, 0x56, 0x4e, 0x55, 0x4c, 0x4c, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x65, 0x78,
0x63, 0x65, 0x70, 0x74, 0x20, 0x46, 0x69, 0x6c, 0x65, 0x4e, 0x6f, 0x74,
0x46, 0x6f, 0x75, 0x6e, 0x64, 0x45, 0x72, 0x72, 0x6f, 0x72, 0x20, 0x61,
0x73, 0x20, 0x65, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x7b, 0x22, 0x65, 0x72,
0x72, 0x6f, 0x72, 0x22, 0x3a, 0x20, 0x7b, 0x22, 0x63, 0x6f, 0x64, 0x65,
0x22, 0x3a, 0x20, 0x2d, 0x31, 0x2c, 0x20, 0x22, 0x6d, 0x65, 0x73, 0x73,
0x61, 0x67, 0x65, 0x22, 0x3a, 0x20, 0x73, 0x74, 0x72, 0x28, 0x65, 0x29,
0x7d, 0x7d, 0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x64, 0x65, 0x66, 0x20,
0x73, 0x65, 0x6e, 0x64, 0x28, 0x6f, 0x62, 0x6a, 0x29, 0x3a, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c, 0x69, 0x6e, 0x65, 0x20,
0x3d, 0x20, 0x28, 0x6a, 0x73, 0x6f, 0x6e, 0x2e, 0x64, 0x75, 0x6d, 0x70,
0x73, 0x28, 0x6f, 0x62, 0x6a, 0x29, 0x20, 0x2b, 0x20, 0x22, 0x5c, 0x6e,
0x22, 0x29, 0x2e, 0x65, 0x6e, 0x63, 0x6f, 0x64, 0x65, 0x28, 0x29, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x70, 0x72, 0x6f, 0x63,
0x2e, 0x73, 0x74, 0x64, 0x69, 0x6e, 0x2e, 0x77, 0x72, 0x69, 0x74, 0x65,
0x28, 0x6c, 0x69, 0x6e, 0x65, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x70, 0x72, 0x6f, 0x63, 0x2e, 0x73, 0x74, 0x64, 0x69,
0x6e, 0x2e, 0x66, 0x6c, 0x75, 0x73, 0x68, 0x28, 0x29, 0x0a, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x64, 0x65, 0x66, 0x20, 0x72, 0x65, 0x63, 0x76, 0x28,
0x29, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x6c,
0x69, 0x6e, 0x65, 0x20, 0x3d, 0x20, 0x70, 0x72, 0x6f, 0x63, 0x2e, 0x73,
0x74, 0x64, 0x6f, 0x75, 0x74, 0x2e, 0x72, 0x65, 0x61, 0x64, 0x6c, 0x69,
0x6e, 0x65, 0x28, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x69, 0x66, 0x20, 0x6e, 0x6f, 0x74, 0x20, 0x6c, 0x69, 0x6e, 0x65,
0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x7b, 0x7d, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75,
0x72, 0x6e, 0x20, 0x6a, 0x73, 0x6f, 0x6e, 0x2e, 0x6c, 0x6f, 0x61, 0x64,
0x73, 0x28, 0x6c, 0x69, 0x6e, 0x65, 0x2e, 0x64, 0x65, 0x63, 0x6f, 0x64,
0x65, 0x28, 0x29, 0x2e, 0x73, 0x74, 0x72, 0x69, 0x70, 0x28, 0x29, 0x29,
0x0a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x74, 0x72, 0x79, 0x3a, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x65, 0x6e, 0x64, 0x28,
0x7b, 0x22, 0x6a, 0x73, 0x6f, 0x6e, 0x72, 0x70, 0x63, 0x22, 0x3a, 0x22,
0x32, 0x2e, 0x30, 0x22, 0x2c, 0x22, 0x69, 0x64, 0x22, 0x3a, 0x31, 0x2c,
0x22, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x22, 0x3a, 0x22, 0x69, 0x6e,
0x69, 0x74, 0x69, 0x61, 0x6c, 0x69, 0x7a, 0x65, 0x22, 0x2c, 0x22, 0x70,
0x61, 0x72, 0x61, 0x6d, 0x73, 0x22, 0x3a, 0x7b, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x70, 0x72,
0x6f, 0x74, 0x6f, 0x63, 0x6f, 0x6c, 0x56, 0x65, 0x72, 0x73, 0x69, 0x6f,
0x6e, 0x22, 0x3a, 0x22, 0x32, 0x30, 0x32, 0x34, 0x2d, 0x31, 0x31, 0x2d,
0x30, 0x35, 0x22, 0x2c, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x22, 0x63, 0x61, 0x70, 0x61, 0x62, 0x69,
0x6c, 0x69, 0x74, 0x69, 0x65, 0x73, 0x22, 0x3a, 0x7b, 0x7d, 0x2c, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x22, 0x63, 0x6c, 0x69, 0x65, 0x6e, 0x74, 0x49, 0x6e, 0x66, 0x6f, 0x22,
0x3a, 0x7b, 0x22, 0x6e, 0x61, 0x6d, 0x65, 0x22, 0x3a, 0x22, 0x74, 0x69,
0x6e, 0x79, 0x62, 0x6c, 0x6f, 0x63, 0x6b, 0x73, 0x2d, 0x6d, 0x63, 0x70,
0x22, 0x2c, 0x22, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0x3a,
0x22, 0x31, 0x2e, 0x30, 0x22, 0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x7d, 0x7d, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x72, 0x65, 0x63, 0x76, 0x28, 0x29, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x73, 0x65, 0x6e, 0x64, 0x28, 0x7b,
0x22, 0x6a, 0x73, 0x6f, 0x6e, 0x72, 0x70, 0x63, 0x22, 0x3a, 0x22, 0x32,
0x2e, 0x30, 0x22, 0x2c, 0x22, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x22,
0x3a, 0x22, 0x6e, 0x6f, 0x74, 0x69, 0x66, 0x69, 0x63, 0x61, 0x74, 0x69,
0x6f, 0x6e, 0x73, 0x2f, 0x69, 0x6e, 0x69, 0x74, 0x69, 0x61, 0x6c, 0x69,
0x7a, 0x65, 0x64, 0x22, 0x2c, 0x22, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73,
0x22, 0x3a, 0x7b, 0x7d, 0x7d, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x73, 0x65, 0x6e, 0x64, 0x28, 0x7b, 0x22, 0x6a, 0x73,
0x6f, 0x6e, 0x72, 0x70, 0x63, 0x22, 0x3a, 0x22, 0x32, 0x2e, 0x30, 0x22,
0x2c, 0x22, 0x69, 0x64, 0x22, 0x3a, 0x32, 0x2c, 0x22, 0x6d, 0x65, 0x74,
0x68, 0x6f, 0x64, 0x22, 0x3a, 0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x2c,
0x22, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x22, 0x3a, 0x70, 0x61, 0x72,
0x61, 0x6d, 0x73, 0x7d, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x72, 0x65, 0x73, 0x70, 0x20, 0x3d, 0x20, 0x72, 0x65, 0x63,
0x76, 0x28, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x72, 0x65, 0x73, 0x70, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x65, 0x78, 0x63, 0x65, 0x70, 0x74, 0x20, 0x45,
0x78, 0x63, 0x65, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x61, 0x73, 0x20,
0x65, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72,
0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x7b, 0x22, 0x65, 0x72, 0x72, 0x6f,
0x72, 0x22, 0x3a, 0x7b, 0x22, 0x63, 0x6f, 0x64, 0x65, 0x22, 0x3a, 0x2d,
0x31, 0x2c, 0x22, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x3a,
0x73, 0x74, 0x72, 0x28, 0x65, 0x29, 0x7d, 0x7d, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x66, 0x69, 0x6e, 0x61, 0x6c, 0x6c, 0x79, 0x3a, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x70, 0x72, 0x6f, 0x63, 0x2e, 0x74,
0x65, 0x72, 0x6d, 0x69, 0x6e, 0x61, 0x74, 0x65, 0x28, 0x29, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x70, 0x72, 0x6f, 0x63, 0x2e,
0x77, 0x61, 0x69, 0x74, 0x28, 0x74, 0x69, 0x6d, 0x65, 0x6f, 0x75, 0x74,
0x3d, 0x33, 0x29, 0x0a, 0x0a, 0x64, 0x65, 0x66, 0x20, 0x5f, 0x64, 0x69,
0x73, 0x70, 0x61, 0x74, 0x63, 0x68, 0x28, 0x75, 0x72, 0x6c, 0x2c, 0x20,
0x6d, 0x65, 0x74, 0x68, 0x6f, 0x64, 0x2c, 0x20, 0x70, 0x61, 0x72, 0x61,
0x6d, 0x73, 0x29, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20,
0x75, 0x72, 0x6c, 0x2e, 0x73, 0x74, 0x61, 0x72, 0x74, 0x73, 0x77, 0x69,
0x74, 0x68, 0x28, 0x22, 0x73, 0x74, 0x64, 0x69, 0x6f, 0x3a, 0x2f, 0x2f,
0x22, 0x29, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x5f, 0x73, 0x74, 0x64, 0x69,
0x6f, 0x5f, 0x6a, 0x73, 0x6f, 0x6e, 0x72, 0x70, 0x63, 0x28, 0x75, 0x72,
0x6c, 0x5b, 0x6c, 0x65, 0x6e, 0x28, 0x22, 0x73, 0x74, 0x64, 0x69, 0x6f,
0x3a, 0x2f, 0x2f, 0x22, 0x29, 0x3a, 0x5d, 0x2c, 0x20, 0x6d, 0x65, 0x74,
0x68, 0x6f, 0x64, 0x2c, 0x20, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x29,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x65, 0x6c, 0x73, 0x65, 0x3a, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72,
0x6e, 0x20, 0x5f, 0x68, 0x74, 0x74, 0x70, 0x5f, 0x6a, 0x73, 0x6f, 0x6e,
0x72, 0x70, 0x63, 0x28, 0x75, 0x72, 0x6c, 0x2c, 0x20, 0x6d, 0x65, 0x74,
0x68, 0x6f, 0x64, 0x2c, 0x20, 0x70, 0x61, 0x72, 0x61, 0x6d, 0x73, 0x29,
0x0a, 0x0a, 0x64, 0x65, 0x66, 0x20, 0x6d, 0x63, 0x70, 0x5f, 0x70, 0x69,
0x6e, 0x67, 0x28, 0x75, 0x72, 0x6c, 0x29, 0x3a, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x72, 0x65, 0x73, 0x70, 0x20, 0x3d, 0x20, 0x5f, 0x64, 0x69, 0x73,
0x70, 0x61, 0x74, 0x63, 0x68, 0x28, 0x75, 0x72, 0x6c, 0x2c, 0x20, 0x22,
0x70, 0x69, 0x6e, 0x67, 0x22, 0x2c, 0x20, 0x7b, 0x7d, 0x29, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x72,
0x22, 0x20, 0x69, 0x6e, 0x20, 0x72, 0x65, 0x73, 0x70, 0x3a, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72,
0x6e, 0x20, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x3a, 0x20, 0x22, 0x20, 0x2b,
0x20, 0x72, 0x65, 0x73, 0x70, 0x5b, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x72,
0x22, 0x5d, 0x2e, 0x67, 0x65, 0x74, 0x28, 0x22, 0x6d, 0x65, 0x73, 0x73,
0x61, 0x67, 0x65, 0x22, 0x2c, 0x20, 0x73, 0x74, 0x72, 0x28, 0x72, 0x65,
0x73, 0x70, 0x5b, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x5d, 0x29,
0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e,
0x20, 0x22, 0x6f, 0x6b, 0x22, 0x0a, 0x0a, 0x64, 0x65, 0x66, 0x20, 0x6d,
0x63, 0x70, 0x5f, 0x6c, 0x69, 0x73, 0x74, 0x5f, 0x74, 0x6f, 0x6f, 0x6c,
0x73, 0x28, 0x75, 0x72, 0x6c, 0x29, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x72, 0x65, 0x73, 0x70, 0x20, 0x3d, 0x20, 0x5f, 0x64, 0x69, 0x73, 0x70,
0x61, 0x74, 0x63, 0x68, 0x28, 0x75, 0x72, 0x6c, 0x2c, 0x20, 0x22, 0x74,
0x6f, 0x6f, 0x6c, 0x73, 0x2f, 0x6c, 0x69, 0x73, 0x74, 0x22, 0x2c, 0x20,
0x7b, 0x7d, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x22,
0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x20, 0x69, 0x6e, 0x20, 0x72, 0x65,
0x73, 0x70, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x22, 0x65, 0x72, 0x72, 0x6f,
0x3a, 0x20, 0x22, 0x20, 0x2b, 0x20, 0x72, 0x65, 0x73, 0x70, 0x5b, 0x22,
0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x5d, 0x2e, 0x67, 0x65, 0x74, 0x28,
0x22, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x2c, 0x20, 0x73,
0x74, 0x72, 0x28, 0x72, 0x65, 0x73, 0x70, 0x5b, 0x22, 0x65, 0x72, 0x72,
0x6f, 0x72, 0x22, 0x5d, 0x29, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x72,
0x65, 0x73, 0x75, 0x6c, 0x74, 0x20, 0x3d, 0x20, 0x72, 0x65, 0x73, 0x70,
0x2e, 0x67, 0x65, 0x74, 0x28, 0x22, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74,
0x22, 0x2c, 0x20, 0x72, 0x65, 0x73, 0x70, 0x29, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x74, 0x6f, 0x6f, 0x6c, 0x73, 0x20, 0x3d, 0x20, 0x72, 0x65, 0x73,
0x75, 0x6c, 0x74, 0x2e, 0x67, 0x65, 0x74, 0x28, 0x22, 0x74, 0x6f, 0x6f,
0x6c, 0x73, 0x22, 0x2c, 0x20, 0x5b, 0x5d, 0x29, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x6f, 0x75, 0x74, 0x20, 0x3d, 0x20, 0x5b, 0x5d, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x66, 0x6f, 0x72, 0x20, 0x74, 0x20, 0x69, 0x6e, 0x20, 0x74,
0x6f, 0x6f, 0x6c, 0x73, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x20, 0x3d, 0x20, 0x74, 0x2e, 0x67,
0x65, 0x74, 0x28, 0x22, 0x6e, 0x61, 0x6d, 0x65, 0x22, 0x2c, 0x22, 0x3f,
0x22, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x64,
0x65, 0x73, 0x63, 0x20, 0x3d, 0x20, 0x74, 0x2e, 0x67, 0x65, 0x74, 0x28,
0x22, 0x64, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6f, 0x6e,
0x22, 0x2c, 0x22, 0x22, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x6f, 0x75, 0x74, 0x2e, 0x61, 0x70, 0x70, 0x65, 0x6e, 0x64,
0x28, 0x6e, 0x61, 0x6d, 0x65, 0x20, 0x2b, 0x20, 0x22, 0x3a, 0x20, 0x22,
0x20, 0x2b, 0x20, 0x64, 0x65, 0x73, 0x63, 0x29, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x22, 0x5c, 0x6e, 0x22,
0x2e, 0x6a, 0x6f, 0x69, 0x6e, 0x28, 0x6f, 0x75, 0x74, 0x29, 0x20, 0x69,
0x66, 0x20, 0x6f, 0x75, 0x74, 0x20, 0x65, 0x6c, 0x73, 0x65, 0x20, 0x22,
0x28, 0x6e, 0x65, 0x6e, 0x68, 0x75, 0x6d, 0x61, 0x20, 0x66, 0x65, 0x72,
0x72, 0x61, 0x6d, 0x65, 0x6e, 0x74, 0x61, 0x29, 0x22, 0x0a, 0x0a, 0x64,
0x65, 0x66, 0x20, 0x6d, 0x63, 0x70, 0x5f, 0x63, 0x61, 0x6c, 0x6c, 0x5f,
0x74, 0x6f, 0x6f, 0x6c, 0x28, 0x75, 0x72, 0x6c, 0x2c, 0x20, 0x74, 0x6f,
0x6f, 0x6c, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x2c, 0x20, 0x61, 0x72, 0x67,
0x73, 0x5f, 0x6a, 0x73, 0x6f, 0x6e, 0x29, 0x3a, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x74, 0x72, 0x79, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x61, 0x72, 0x67, 0x73, 0x20, 0x3d, 0x20, 0x6a, 0x73, 0x6f,
0x6e, 0x2e, 0x6c, 0x6f, 0x61, 0x64, 0x73, 0x28, 0x61, 0x72, 0x67, 0x73,
0x5f, 0x6a, 0x73, 0x6f, 0x6e, 0x29, 0x20, 0x69, 0x66, 0x20, 0x61, 0x72,
0x67, 0x73, 0x5f, 0x6a, 0x73, 0x6f, 0x6e, 0x20, 0x61, 0x6e, 0x64, 0x20,
0x61, 0x72, 0x67, 0x73, 0x5f, 0x6a, 0x73, 0x6f, 0x6e, 0x2e, 0x73, 0x74,
0x72, 0x69, 0x70, 0x28, 0x29, 0x20, 0x65, 0x6c, 0x73, 0x65, 0x20, 0x7b,
0x7d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x65, 0x78, 0x63, 0x65, 0x70, 0x74,
0x20, 0x45, 0x78, 0x63, 0x65, 0x70, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x61,
0x73, 0x20, 0x65, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x22, 0x65, 0x72, 0x72,
0x6f, 0x3a, 0x20, 0x61, 0x72, 0x67, 0x73, 0x20, 0x4a, 0x53, 0x4f, 0x4e,
0x20, 0x69, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x6f, 0x3a, 0x20, 0x22,
0x20, 0x2b, 0x20, 0x73, 0x74, 0x72, 0x28, 0x65, 0x29, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x72, 0x65, 0x73, 0x70, 0x20, 0x3d, 0x20, 0x5f, 0x64, 0x69,
0x73, 0x70, 0x61, 0x74, 0x63, 0x68, 0x28, 0x75, 0x72, 0x6c, 0x2c, 0x20,
0x22, 0x74, 0x6f, 0x6f, 0x6c, 0x73, 0x2f, 0x63, 0x61, 0x6c, 0x6c, 0x22,
0x2c, 0x20, 0x7b, 0x22, 0x6e, 0x61, 0x6d, 0x65, 0x22, 0x3a, 0x20, 0x74,
0x6f, 0x6f, 0x6c, 0x5f, 0x6e, 0x61, 0x6d, 0x65, 0x2c, 0x20, 0x22, 0x61,
0x72, 0x67, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x73, 0x22, 0x3a, 0x20, 0x61,
0x72, 0x67, 0x73, 0x7d, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66,
0x20, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x20, 0x69, 0x6e, 0x20,
0x72, 0x65, 0x73, 0x70, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x22, 0x65, 0x72,
0x72, 0x6f, 0x3a, 0x20, 0x22, 0x20, 0x2b, 0x20, 0x72, 0x65, 0x73, 0x70,
0x5b, 0x22, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x22, 0x5d, 0x2e, 0x67, 0x65,
0x74, 0x28, 0x22, 0x6d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x22, 0x2c,
0x20, 0x73, 0x74, 0x72, 0x28, 0x72, 0x65, 0x73, 0x70, 0x5b, 0x22, 0x65,
0x72, 0x72, 0x6f, 0x72, 0x22, 0x5d, 0x29, 0x29, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x20, 0x3d, 0x20, 0x72, 0x65,
0x73, 0x70, 0x2e, 0x67, 0x65, 0x74, 0x28, 0x22, 0x72, 0x65, 0x73, 0x75,
0x6c, 0x74, 0x22, 0x2c, 0x20, 0x72, 0x65, 0x73, 0x70, 0x29, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x20, 0x3d,
0x20, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74, 0x2e, 0x67, 0x65, 0x74, 0x28,
0x22, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x22, 0x2c, 0x20, 0x72,
0x65, 0x73, 0x75, 0x6c, 0x74, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x69,
0x66, 0x20, 0x69, 0x73, 0x69, 0x6e, 0x73, 0x74, 0x61, 0x6e, 0x63, 0x65,
0x28, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x2c, 0x20, 0x6c, 0x69,
0x73, 0x74, 0x29, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x70, 0x61, 0x72, 0x74, 0x73, 0x20, 0x3d, 0x20, 0x5b, 0x5d, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x66, 0x6f, 0x72, 0x20,
0x69, 0x74, 0x65, 0x6d, 0x20, 0x69, 0x6e, 0x20, 0x63, 0x6f, 0x6e, 0x74,
0x65, 0x6e, 0x74, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x69, 0x66, 0x20, 0x69, 0x73, 0x69, 0x6e,
0x73, 0x74, 0x61, 0x6e, 0x63, 0x65, 0x28, 0x69, 0x74, 0x65, 0x6d, 0x2c,
0x20, 0x64, 0x69, 0x63, 0x74, 0x29, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x70, 0x61, 0x72, 0x74, 0x73, 0x2e, 0x61, 0x70, 0x70, 0x65, 0x6e, 0x64,
0x28, 0x69, 0x74, 0x65, 0x6d, 0x2e, 0x67, 0x65, 0x74, 0x28, 0x22, 0x74,
0x65, 0x78, 0x74, 0x22, 0x2c, 0x20, 0x6a, 0x73, 0x6f, 0x6e, 0x2e, 0x64,
0x75, 0x6d, 0x70, 0x73, 0x28, 0x69, 0x74, 0x65, 0x6d, 0x29, 0x29, 0x29,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x65, 0x6c, 0x73, 0x65, 0x3a, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x70,
0x61, 0x72, 0x74, 0x73, 0x2e, 0x61, 0x70, 0x70, 0x65, 0x6e, 0x64, 0x28,
0x73, 0x74, 0x72, 0x28, 0x69, 0x74, 0x65, 0x6d, 0x29, 0x29, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x72, 0x65, 0x74, 0x75, 0x72,
0x6e, 0x20, 0x22, 0x5c, 0x6e, 0x22, 0x2e, 0x6a, 0x6f, 0x69, 0x6e, 0x28,
0x70, 0x61, 0x72, 0x74, 0x73, 0x29, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x72,
0x65, 0x74, 0x75, 0x72, 0x6e, 0x20, 0x6a, 0x73, 0x6f, 0x6e, 0x2e, 0x64,
0x75, 0x6d, 0x70, 0x73, 0x28, 0x63, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74,
0x2c, 0x20, 0x65, 0x6e, 0x73, 0x75, 0x72, 0x65, 0x5f, 0x61, 0x73, 0x63,
0x69, 0x69, 0x3d, 0x46, 0x61, 0x6c, 0x73, 0x65, 0x2c, 0x20, 0x69, 0x6e,
0x64, 0x65, 0x6e, 0x74, 0x3d, 0x32, 0x29, 0x0a
};
unsigned int tb_mcp_py_len = 3728;
@@ -0,0 +1,52 @@
#ifndef TINYBLOCKS_PYTHON_H
#define TINYBLOCKS_PYTHON_H
#include <stdbool.h>
#ifdef _WIN32
# define TB_PYTHON_API __declspec(dllexport)
#else
# define TB_PYTHON_API __attribute__((visibility("default")))
#endif
/*
* tb_python — wrapper fino sobre o interpretador CPython embutido.
*
* O interpretador é compartilhado em todo o processo (singleton ref-counted).
* Compile a lib como .so compartilhada para que python.so e mcp.so usem o
* mesmo intérprete: libtinyblocks-python.so.
*/
TB_PYTHON_API bool tb_python_init(void);
TB_PYTHON_API void tb_python_deinit(void);
/*
* Avalia uma expressão Python.
* names/vals: variáveis disponíveis no namespace (n itens).
* Retorna string heap-alocada com o resultado (caller frees) ou NULL em erro.
*/
TB_PYTHON_API char* tb_python_eval(const char* expr,
const char* const* names,
const double* vals, int n);
/*
* Executa código Python arbitrário.
* Captura stdout+stderr e os retorna como string heap-alocada (caller frees).
*/
TB_PYTHON_API char* tb_python_run(const char* code);
/*
* Executa código passando variáveis como locais (nome=valor float).
* Equivalente a tb_python_run mas com namespace preenchido.
*/
TB_PYTHON_API char* tb_python_run_with_vars(const char* code,
const char* const* names,
const double* vals, int n);
/*
* Executa código no namespace __main__ (definições persistem entre chamadas).
* Retorna stdout+stderr capturado (caller frees).
*/
TB_PYTHON_API char* tb_python_exec_main(const char* code);
#endif /* TINYBLOCKS_PYTHON_H */
+179
View File
@@ -0,0 +1,179 @@
#define PY_SSIZE_T_CLEAN
#include <Python.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "tinyblocks-python/tb_python.h"
/* ── Singleton ref-counted ───────────────────────────────────────────────── */
static int s_refs = 0;
TB_PYTHON_API bool tb_python_init(void) {
if (s_refs++ > 0) return true;
if (Py_IsInitialized()) return true;
Py_Initialize();
/* Garante que stdout/stderr padrão existam (modo embutido pode omití-los) */
PyRun_SimpleString(
"import sys, io\n"
"if not hasattr(sys,'_tb_orig_stdout'):\n"
" sys._tb_orig_stdout = sys.stdout\n"
" sys._tb_orig_stderr = sys.stderr\n"
);
return Py_IsInitialized();
}
TB_PYTHON_API void tb_python_deinit(void) {
if (s_refs <= 0) return;
if (--s_refs == 0 && Py_IsInitialized())
Py_FinalizeEx();
}
/* ── Helper: captura stdout+stderr de uma execução ──────────────────────── */
static char* capture_run(const char* code, PyObject* local_dict) {
/* StringIO para capturar output */
PyObject* io = PyImport_ImportModule("io");
PyObject* buf = PyObject_CallMethod(io, "StringIO", NULL);
PyObject* sys = PyImport_ImportModule("sys");
PyObject_SetAttrString(sys, "stdout", buf);
PyObject_SetAttrString(sys, "stderr", buf);
PyObject* globals = PyDict_New();
PyObject* builtins = PyEval_GetBuiltins();
PyDict_SetItemString(globals, "__builtins__", builtins);
PyObject* result = PyRun_String(code, Py_file_input, globals,
local_dict ? local_dict : globals);
if (!result) {
PyErr_Print(); /* vai para buf via stderr */
PyErr_Clear();
}
Py_XDECREF(result);
Py_DECREF(globals);
/* Restaura stdout/stderr */
PyObject* orig_out = PyObject_GetAttrString(sys, "_tb_orig_stdout");
PyObject* orig_err = PyObject_GetAttrString(sys, "_tb_orig_stderr");
if (orig_out) PyObject_SetAttrString(sys, "stdout", orig_out);
if (orig_err) PyObject_SetAttrString(sys, "stderr", orig_err);
Py_XDECREF(orig_out);
Py_XDECREF(orig_err);
PyObject* val = PyObject_CallMethod(buf, "getvalue", NULL);
const char* s = val ? PyUnicode_AsUTF8(val) : NULL;
char* out = strdup(s ? s : "");
Py_XDECREF(val);
Py_DECREF(buf);
Py_DECREF(io);
Py_DECREF(sys);
return out;
}
/* ── API pública ─────────────────────────────────────────────────────────── */
TB_PYTHON_API char* tb_python_run(const char* code) {
if (!code || !Py_IsInitialized()) return strdup("");
return capture_run(code, NULL);
}
/*
* Executa código no namespace __main__ (definições persistem entre chamadas).
* Ideal para carregar módulos/funções que serão chamados depois.
*/
TB_PYTHON_API char* tb_python_exec_main(const char* code) {
if (!code || !Py_IsInitialized()) return strdup("");
PyObject* main_mod = PyImport_AddModule("__main__"); /* borrowed */
PyObject* main_dict = PyModule_GetDict(main_mod); /* borrowed */
/* Redireciona stdout/stderr */
PyObject* io = PyImport_ImportModule("io");
PyObject* buf = PyObject_CallMethod(io, "StringIO", NULL);
PyObject* sys = PyImport_ImportModule("sys");
PyObject_SetAttrString(sys, "stdout", buf);
PyObject_SetAttrString(sys, "stderr", buf);
/* Executa com main_dict como globals E locals — definições persistem */
PyObject* result = PyRun_String(code, Py_file_input, main_dict, main_dict);
if (!result) { PyErr_Print(); PyErr_Clear(); }
Py_XDECREF(result);
/* Restaura stdout/stderr */
PyObject* orig_out = PyObject_GetAttrString(sys, "_tb_orig_stdout");
PyObject* orig_err = PyObject_GetAttrString(sys, "_tb_orig_stderr");
if (orig_out) PyObject_SetAttrString(sys, "stdout", orig_out);
if (orig_err) PyObject_SetAttrString(sys, "stderr", orig_err);
Py_XDECREF(orig_out);
Py_XDECREF(orig_err);
PyObject* val = PyObject_CallMethod(buf, "getvalue", NULL);
const char* s = val ? PyUnicode_AsUTF8(val) : NULL;
char* out = strdup(s ? s : "");
Py_XDECREF(val);
Py_DECREF(buf);
Py_DECREF(io);
Py_DECREF(sys);
return out;
}
TB_PYTHON_API char* tb_python_run_with_vars(const char* code,
const char* const* names,
const double* vals, int n) {
if (!code || !Py_IsInitialized()) return strdup("");
PyObject* locals = PyDict_New();
for (int i = 0; i < n; i++) {
if (!names[i]) continue;
PyObject* v = PyFloat_FromDouble(vals[i]);
PyDict_SetItemString(locals, names[i], v);
Py_DECREF(v);
}
char* out = capture_run(code, locals);
Py_DECREF(locals);
return out;
}
TB_PYTHON_API char* tb_python_eval(const char* expr,
const char* const* names, const double* vals, int n) {
if (!expr || !Py_IsInitialized()) return strdup("<erro: Python não inicializado>");
PyObject* globals = PyDict_New();
PyObject* builtins = PyEval_GetBuiltins();
PyDict_SetItemString(globals, "__builtins__", builtins);
for (int i = 0; i < n; i++) {
if (!names[i]) continue;
PyObject* v = PyFloat_FromDouble(vals[i]);
PyDict_SetItemString(globals, names[i], v);
Py_DECREF(v);
}
PyObject* result = PyRun_String(expr, Py_eval_input, globals, globals);
char* out = NULL;
if (result) {
PyObject* str = PyObject_Str(result);
const char* s = str ? PyUnicode_AsUTF8(str) : NULL;
out = strdup(s ? s : "None");
Py_XDECREF(str);
Py_DECREF(result);
} else {
PyObject* exc = PyErr_GetRaisedException();
PyObject* str = exc ? PyObject_Str(exc) : NULL;
const char* s = str ? PyUnicode_AsUTF8(str) : NULL;
char buf[256];
snprintf(buf, sizeof(buf), "<erro: %s>", s ? s : "?");
out = strdup(buf);
Py_XDECREF(str);
Py_XDECREF(exc);
PyErr_Clear();
}
Py_DECREF(globals);
return out;
}
+30
View File
@@ -0,0 +1,30 @@
CC := gcc
CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \
-I../../include \
$(shell sdl2-config --cflags)
LDFLAGS := $(shell sdl2-config --libs)
BUILD := ../../build
LIB_SO := $(BUILD)/libtinyblocks-sdl2.so
LIB_A := $(BUILD)/libtinyblocks-sdl2.a
OBJ := $(BUILD)/tb_sdl2.o
.PHONY: all clean shared static
all: shared static
shared: $(LIB_SO)
static: $(LIB_A)
$(OBJ): src/tb_sdl2.c include/tb_sdl2.h
@mkdir -p $(BUILD)
$(CC) $(CFLAGS) -fPIC -c src/tb_sdl2.c -o $@
$(LIB_SO): $(OBJ)
$(CC) -shared -o $@ $^ $(LDFLAGS)
$(LIB_A): $(OBJ)
ar rcs $@ $^
clean:
$(RM) $(OBJ) $(LIB_SO) $(LIB_A)
@@ -0,0 +1,61 @@
/*
* TinyBlocks — tb_sdl2.h
*
* TypeBlocks disponíveis após registrar esta library:
*
* SDL2.Events — expõe o estado de eventos do frame corrente (sem inputs;
* outputs pré-preenchidos pelo SDL2.App antes de cada on_draw)
*
* SDL2.App — cria janela, roda o loop principal, chama on_draw na scene.
* in: title(text), w(int), h(int), scene(block), events(block)
*
* Blocos primitivos (uso manual):
* SDL2.Init / SDL2.Quit
* SDL2.Window / SDL2.DestroyWindow
* SDL2.Renderer / SDL2.DestroyRenderer
* SDL2.SetDrawColor / SDL2.Clear / SDL2.FillRect / SDL2.DrawRect
* SDL2.Present / SDL2.Delay / SDL2.PollEvent
*/
#ifndef TINYBLOCKS_SDL2_H
#define TINYBLOCKS_SDL2_H
#include <tinyblocks/tinyblocks.h>
TB_API const TinyBlocks_LibraryDescriptor* tb_sdl2_get_library(void);
TB_API const TinyBlocks_LibraryDescriptor* tinyblocks_get_library(void);
/* Implementação do contrato de backend da interface tinyblocks-graphics
* (struct definida em tb_graphics.h; declarada aqui só por nome para que
* quem usa os blocos SDL2.* não precise do header da interface). */
struct TinyBlocks_GraphicsBackend;
TB_API const struct TinyBlocks_GraphicsBackend* tb_sdl2_graphics_backend(void);
/* ── Índices de output do bloco SDL2.Events ──────────────────────────────── */
#define SDL2_EV_MOUSE_X 0 /* real: posição X do mouse */
#define SDL2_EV_MOUSE_Y 1 /* real: posição Y do mouse */
#define SDL2_EV_MOUSE_L_HELD 2 /* int: botão esquerdo pressionado (estado) */
#define SDL2_EV_MOUSE_R_HELD 3 /* int: botão direito pressionado (estado) */
#define SDL2_EV_MOUSE_L_DOWN 4 /* int: 1 se pressionado neste frame */
#define SDL2_EV_MOUSE_L_UP 5 /* int: 1 se solto neste frame */
#define SDL2_EV_MOUSE_R_DOWN 6 /* int: 1 se pressionado neste frame */
#define SDL2_EV_MOUSE_R_UP 7 /* int: 1 se solto neste frame */
#define SDL2_EV_SCROLL_DY 8 /* real: scroll vertical deste frame */
#define SDL2_EV_KEY_SCANCODE 9 /* int: SDL_Scancode da tecla pressionada */
#define SDL2_EV_KEY_MOD 10 /* int: SDL_Keymod (KMOD_CTRL etc.) */
#define SDL2_EV_KEY_REPEAT 11 /* int: 1 se é repeat de key held */
#define SDL2_EV_TEXT_INPUT 12 /* text: texto digitado neste frame */
#define SDL2_EV_QUIT 13 /* int: 1 se janela foi fechada */
#define SDL2_EV_WIN_W 14 /* int: largura atual da janela */
#define SDL2_EV_WIN_H 15 /* int: altura atual da janela */
#define SDL2_EV_DROP_FILE 16 /* text: caminho de arquivo arrastado */
#define SDL2_EV_SCROLL_DX 17 /* real: scroll horizontal deste frame */
#define SDL2_EV_MOD_STATE 18 /* int: SDL_GetModState() deste frame */
#define SDL2_EV_COUNT 19 /* total de outputs */
/* ── Constantes de tipo de evento (SDL2.PollEvent legado) ───────────────── */
#define TB_SDL2_EVENT_NONE 0
#define TB_SDL2_EVENT_QUIT 256
#define TB_SDL2_EVENT_KEYDOWN 768
#define TB_SDL2_EVENT_KEYUP 769
#endif /* TINYBLOCKS_SDL2_H */
File diff suppressed because it is too large. Load diff
+252
View File
@@ -0,0 +1,252 @@
#include <string.h>
#include <stdio.h>
#include "tinyblocks/tinyblocks.h"
/* ── Alocação da estrutura base ──────────────────────────────────────────── */
TinyBlocks_Block* tb_block_alloc_base(TinyBlocks* rt,
TinyBlocks_BlockKind kind,
size_t struct_size,
uint32_t input_count,
uint32_t output_count,
const TinyBlocks_BlockVTable* vtable)
{
TinyBlocks_Block* b = tb_alloc(rt, struct_size);
if (!b) return NULL;
b->kind = kind;
b->vtable = vtable;
b->id = tb_rt_next_id(rt);
b->input_count = input_count;
b->output_count = output_count;
b->dirty = true;
if (input_count > 0) {
b->inputs = tb_alloc(rt, input_count * sizeof(TinyBlocks_Connection));
if (!b->inputs) { tb_free(rt, b); return NULL; }
}
if (output_count > 0) {
b->outputs = tb_alloc(rt, output_count * sizeof(TinyBlocks_Value));
if (!b->outputs) { tb_free(rt, b->inputs); tb_free(rt, b); return NULL; }
}
tb_rt_register_block(rt, b);
return b;
}
/* ── Vtable padrão para blocos definidos por TypeBlock ───────────────────── */
static void default_eval(TinyBlocks_Block* self, TinyBlocks* rt)
{
if (self->type && self->type->eval_fn)
self->type->eval_fn(self, rt);
self->dirty = false;
}
static void default_destroy(TinyBlocks_Block* self, TinyBlocks* rt)
{
if (self->type && self->type->instance_deinit)
self->type->instance_deinit(self, rt);
tb_free(rt, self->userdata);
}
static size_t default_to_string(TinyBlocks_Block* self, TinyBlocks* rt,
char* buf, size_t buf_size)
{
(void)rt;
const char* tname = self->type ? self->type->type_name : "Block";
const char* bname = self->name ? self->name : "";
return (size_t)snprintf(buf, buf_size,
"[%s#%llu%s%s]",
tname, (unsigned long long)self->id,
bname[0] ? " " : "", bname);
}
static TinyBlocks_Block* default_clone(const TinyBlocks_Block* self, TinyBlocks* rt)
{
TinyBlocks_Block* c = tb_block_create(rt, self->type);
if (!c) return NULL;
if (self->name) c->name = tb_strdup(rt, self->name);
/* copia conexões */
memcpy(c->inputs, self->inputs, self->input_count * sizeof(TinyBlocks_Connection));
/* copia outputs */
for (uint32_t i = 0; i < self->output_count; ++i)
c->outputs[i] = tb_value_clone(self->outputs[i]);
return c;
}
static const TinyBlocks_BlockVTable s_default_vtable = {
.eval = default_eval,
.destroy = default_destroy,
.to_string = default_to_string,
.clone = default_clone,
};
/* ── Criação via TypeBlock ───────────────────────────────────────────────── */
TinyBlocks_Block* tb_block_create(TinyBlocks* rt, TinyBlocks_TypeBlock* type)
{
if (!type) {
tinyblocks_set_error(rt, "tb_block_create: type is NULL");
return NULL;
}
TinyBlocks_Block* b = tb_block_alloc_base(rt,
TB_KIND_BLOCK,
sizeof(TinyBlocks_Block),
type->input_desc_count,
type->output_desc_count,
&s_default_vtable);
if (!b) return NULL;
b->type = type;
/* Inicializa userdata por instância */
if (type->instance_userdata_size > 0) {
b->userdata = tb_alloc(rt, type->instance_userdata_size);
if (!b->userdata) {
tb_block_destroy(b, rt);
return NULL;
}
}
if (type->instance_init && !type->instance_init(b, rt)) {
tb_block_destroy(b, rt);
return NULL;
}
return b;
}
/* ── Destruição ──────────────────────────────────────────────────────────── */
void tb_block_destroy(TinyBlocks_Block* block, TinyBlocks* rt)
{
if (!block) return;
tb_rt_unregister_block(rt, block);
if (block->vtable && block->vtable->destroy)
block->vtable->destroy(block, rt);
tb_free(rt, block->name);
/* Libera valores de default dos inputs */
for (uint32_t i = 0; i < block->input_count; ++i)
tb_value_free(&block->inputs[i].default_value);
tb_free(rt, block->inputs);
for (uint32_t i = 0; i < block->output_count; ++i)
tb_value_free(&block->outputs[i]);
tb_free(rt, block->outputs);
tb_free(rt, block);
}
/* ── Avaliação ───────────────────────────────────────────────────────────── */
void tb_block_eval(TinyBlocks_Block* block, TinyBlocks* rt)
{
if (!block || !block->vtable || !block->vtable->eval) return;
/* Detecta ciclo: bloco já está sendo avaliado nesta chamada recursiva */
if (block->in_eval) {
tinyblocks_set_error(rt, "ciclo detectado em '%s' — conexão ignorada",
block->type ? block->type->type_name : "?");
return;
}
block->in_eval = true;
/* Avalia fontes conectadas primeiro (lazy) */
for (uint32_t i = 0; i < block->input_count; ++i) {
TinyBlocks_Connection* conn = &block->inputs[i];
if (conn->source && conn->source->dirty)
tb_block_eval(conn->source, rt);
}
block->vtable->eval(block, rt);
block->in_eval = false;
}
/* ── Clone ───────────────────────────────────────────────────────────────── */
TinyBlocks_Block* tb_block_clone(const TinyBlocks_Block* block, TinyBlocks* rt)
{
if (!block || !block->vtable || !block->vtable->clone) return NULL;
return block->vtable->clone(block, rt);
}
/* ── Representação textual ───────────────────────────────────────────────── */
size_t tb_block_to_string(TinyBlocks_Block* block, TinyBlocks* rt,
char* buf, size_t buf_size)
{
if (!block || !buf || buf_size == 0) return 0;
if (block->vtable && block->vtable->to_string)
return block->vtable->to_string(block, rt, buf, buf_size);
return (size_t)snprintf(buf, buf_size, "[Block#%llu]",
(unsigned long long)block->id);
}
/* ── Conexões ────────────────────────────────────────────────────────────── */
bool tb_block_connect(TinyBlocks_Block* target, uint32_t input_idx,
TinyBlocks_Block* source, uint32_t output_idx)
{
if (!target || input_idx >= target->input_count) return false;
if (!source || output_idx >= source->output_count) return false;
TinyBlocks_Connection* conn = &target->inputs[input_idx];
conn->source = source;
conn->output_idx = output_idx;
target->dirty = true;
return true;
}
void tb_block_disconnect(TinyBlocks_Block* target, uint32_t input_idx)
{
if (!target || input_idx >= target->input_count) return;
target->inputs[input_idx].source = NULL;
target->dirty = true;
}
bool tb_block_set_default(TinyBlocks_Block* target, uint32_t input_idx,
TinyBlocks_Value default_value)
{
if (!target || input_idx >= target->input_count) return false;
tb_value_free(&target->inputs[input_idx].default_value);
target->inputs[input_idx].default_value = tb_value_clone(default_value);
return true;
}
/* ── Acesso a valores em eval_fn ─────────────────────────────────────────── */
TinyBlocks_Value tb_block_get_input(TinyBlocks_Block* self, TinyBlocks* rt,
uint32_t input_idx)
{
if (!self || input_idx >= self->input_count) return tb_value_none();
TinyBlocks_Connection* conn = &self->inputs[input_idx];
if (conn->source) {
if (conn->source->dirty) tb_block_eval(conn->source, rt);
if (conn->output_idx < conn->source->output_count)
return conn->source->outputs[conn->output_idx];
}
return conn->default_value;
}
/* Toma ownership de v — o caller NÃO deve liberar v depois desta chamada.
Se precisar manter v, passe tb_value_clone(v) em vez de v. */
void tb_block_set_output(TinyBlocks_Block* self, uint32_t output_idx,
TinyBlocks_Value v)
{
if (!self || output_idx >= self->output_count) return;
tb_value_free(&self->outputs[output_idx]);
self->outputs[output_idx] = v;
}
/* ── Downcasting seguro ──────────────────────────────────────────────────── */
TinyBlocks_TypeBlock* tb_block_as_type (TinyBlocks_Block* b)
{ return b && b->kind == TB_KIND_TYPE ? (TinyBlocks_TypeBlock*)b : NULL; }
TinyBlocks_LibraryBlock* tb_block_as_library(TinyBlocks_Block* b)
{ return b && b->kind == TB_KIND_LIBRARY ? (TinyBlocks_LibraryBlock*)b : NULL; }
TinyBlocks_TextBlock* tb_block_as_text (TinyBlocks_Block* b)
{ return b && b->kind == TB_KIND_TEXT ? (TinyBlocks_TextBlock*)b : NULL; }
TinyBlocks_IntegerBlock* tb_block_as_integer(TinyBlocks_Block* b)
{ return b && b->kind == TB_KIND_INTEGER ? (TinyBlocks_IntegerBlock*)b : NULL; }
TinyBlocks_RealBlock* tb_block_as_real (TinyBlocks_Block* b)
{ return b && b->kind == TB_KIND_REAL ? (TinyBlocks_RealBlock*)b : NULL; }
+68
View File
@@ -0,0 +1,68 @@
#include <stdio.h>
#include "tinyblocks/tinyblocks.h"
/* ── Vtable ──────────────────────────────────────────────────────────────── */
static void integer_eval(TinyBlocks_Block* self, TinyBlocks* rt)
{
(void)rt;
TinyBlocks_IntegerBlock* ib = (TinyBlocks_IntegerBlock*)self;
tb_block_set_output(self, 0, tb_value_integer(ib->value));
self->dirty = false;
}
static void integer_destroy(TinyBlocks_Block* self, TinyBlocks* rt)
{
(void)self; (void)rt; /* nada a liberar além do base */
}
static size_t integer_to_string(TinyBlocks_Block* self, TinyBlocks* rt,
char* buf, size_t sz)
{
(void)rt;
TinyBlocks_IntegerBlock* ib = (TinyBlocks_IntegerBlock*)self;
return (size_t)snprintf(buf, sz, "%lld", (long long)ib->value);
}
static TinyBlocks_Block* integer_clone(const TinyBlocks_Block* self, TinyBlocks* rt)
{
const TinyBlocks_IntegerBlock* ib = (const TinyBlocks_IntegerBlock*)self;
TinyBlocks_IntegerBlock* clone = tb_integer_block_create(rt, ib->value);
if (clone && self->name) clone->base.name = tb_strdup(rt, self->name);
return (TinyBlocks_Block*)clone;
}
static const TinyBlocks_BlockVTable s_integer_vtable = {
.eval = integer_eval,
.destroy = integer_destroy,
.to_string = integer_to_string,
.clone = integer_clone,
};
/* ── Ciclo de vida ───────────────────────────────────────────────────────── */
TinyBlocks_IntegerBlock* tb_integer_block_create(TinyBlocks* rt, int64_t value)
{
TinyBlocks_IntegerBlock* ib = (TinyBlocks_IntegerBlock*)tb_block_alloc_base(
rt, TB_KIND_INTEGER, sizeof(TinyBlocks_IntegerBlock),
0, 1, &s_integer_vtable);
if (!ib) return NULL;
ib->value = value;
return ib;
}
void tb_integer_block_destroy(TinyBlocks_IntegerBlock* ib, TinyBlocks* rt)
{
tb_block_destroy(&ib->base, rt);
}
/* ── Acesso ──────────────────────────────────────────────────────────────── */
int64_t tb_integer_block_get(const TinyBlocks_IntegerBlock* ib)
{
return ib ? ib->value : 0;
}
void tb_integer_block_set(TinyBlocks_IntegerBlock* ib, int64_t value)
{
if (!ib) return;
ib->value = value;
ib->base.dirty = true;
}
+526
View File
@@ -0,0 +1,526 @@
#define _POSIX_C_SOURCE 200809L
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <ctype.h>
#include <math.h>
#include "tinyblocks/tinyblocks.h"
struct TinyBlocks_JsonValue {
TinyBlocks_JsonKind kind;
int32_t ref;
union {
bool boolean;
double number;
char* string;
struct {
TinyBlocks_JsonValue** items;
uint32_t count, capacity;
} array;
struct {
char** keys;
TinyBlocks_JsonValue** values;
uint32_t count, capacity;
} object;
} as;
};
/* ══════════════════════════════════════════════════════════════════════════
* Construtores / ciclo de vida
* ══════════════════════════════════════════════════════════════════════════ */
static TinyBlocks_JsonValue* json_alloc(TinyBlocks_JsonKind kind) {
TinyBlocks_JsonValue* j = calloc(1, sizeof(TinyBlocks_JsonValue));
if (!j) return NULL;
j->kind = kind;
j->ref = 1;
return j;
}
TinyBlocks_JsonValue* tb_json_null(void) { return json_alloc(TB_JSON_NULL); }
TinyBlocks_JsonValue* tb_json_bool(bool b) {
TinyBlocks_JsonValue* j = json_alloc(TB_JSON_BOOL);
if (j) j->as.boolean = b;
return j;
}
TinyBlocks_JsonValue* tb_json_number(double d) {
TinyBlocks_JsonValue* j = json_alloc(TB_JSON_NUMBER);
if (j) j->as.number = d;
return j;
}
TinyBlocks_JsonValue* tb_json_string(const char* s) {
TinyBlocks_JsonValue* j = json_alloc(TB_JSON_STRING);
if (!j) return NULL;
j->as.string = strdup(s ? s : "");
return j;
}
TinyBlocks_JsonValue* tb_json_array(void) { return json_alloc(TB_JSON_ARRAY); }
TinyBlocks_JsonValue* tb_json_object(void) { return json_alloc(TB_JSON_OBJECT); }
static void json_destroy(TinyBlocks_JsonValue* j) {
switch (j->kind) {
case TB_JSON_STRING:
free(j->as.string);
break;
case TB_JSON_ARRAY:
for (uint32_t i = 0; i < j->as.array.count; i++)
tb_json_release(j->as.array.items[i]);
free(j->as.array.items);
break;
case TB_JSON_OBJECT:
for (uint32_t i = 0; i < j->as.object.count; i++) {
free(j->as.object.keys[i]);
tb_json_release(j->as.object.values[i]);
}
free(j->as.object.keys);
free(j->as.object.values);
break;
default:
break;
}
free(j);
}
void tb_json_retain(TinyBlocks_JsonValue* j) {
if (j) j->ref++;
}
void tb_json_release(TinyBlocks_JsonValue* j) {
if (!j) return;
if (--j->ref <= 0) json_destroy(j);
}
TinyBlocks_JsonValue* tb_json_clone(const TinyBlocks_JsonValue* j) {
if (!j) return NULL;
switch (j->kind) {
case TB_JSON_NULL: return tb_json_null();
case TB_JSON_BOOL: return tb_json_bool(j->as.boolean);
case TB_JSON_NUMBER: return tb_json_number(j->as.number);
case TB_JSON_STRING: return tb_json_string(j->as.string);
case TB_JSON_ARRAY: {
TinyBlocks_JsonValue* out = tb_json_array();
if (!out) return NULL;
for (uint32_t i = 0; i < j->as.array.count; i++) {
TinyBlocks_JsonValue* item = tb_json_clone(j->as.array.items[i]);
tb_json_array_push(out, item);
tb_json_release(item);
}
return out;
}
case TB_JSON_OBJECT: {
TinyBlocks_JsonValue* out = tb_json_object();
if (!out) return NULL;
for (uint32_t i = 0; i < j->as.object.count; i++) {
TinyBlocks_JsonValue* val = tb_json_clone(j->as.object.values[i]);
tb_json_object_set(out, j->as.object.keys[i], val);
tb_json_release(val);
}
return out;
}
}
return tb_json_null();
}
/* ══════════════════════════════════════════════════════════════════════════
* Inspeção
* ══════════════════════════════════════════════════════════════════════════ */
TinyBlocks_JsonKind tb_json_kind(const TinyBlocks_JsonValue* j) {
return j ? j->kind : TB_JSON_NULL;
}
const char* tb_json_kind_name(const TinyBlocks_JsonValue* j) {
switch (tb_json_kind(j)) {
case TB_JSON_NULL: return "null";
case TB_JSON_BOOL: return "bool";
case TB_JSON_NUMBER: return "number";
case TB_JSON_STRING: return "string";
case TB_JSON_ARRAY: return "array";
case TB_JSON_OBJECT: return "object";
}
return "null";
}
bool tb_json_as_bool(const TinyBlocks_JsonValue* j, bool def) {
if (!j) return def;
if (j->kind == TB_JSON_BOOL) return j->as.boolean;
if (j->kind == TB_JSON_NUMBER) return j->as.number != 0.0;
return def;
}
double tb_json_as_number(const TinyBlocks_JsonValue* j, double def) {
if (!j) return def;
if (j->kind == TB_JSON_NUMBER) return j->as.number;
if (j->kind == TB_JSON_BOOL) return j->as.boolean ? 1.0 : 0.0;
return def;
}
const char* tb_json_as_string(const TinyBlocks_JsonValue* j) {
if (!j || j->kind != TB_JSON_STRING) return NULL;
return j->as.string;
}
/* ══════════════════════════════════════════════════════════════════════════
* Arrays
* ══════════════════════════════════════════════════════════════════════════ */
bool tb_json_array_push(TinyBlocks_JsonValue* arr, TinyBlocks_JsonValue* item) {
if (!arr || arr->kind != TB_JSON_ARRAY || !item) return false;
if (arr->as.array.count == arr->as.array.capacity) {
uint32_t cap = arr->as.array.capacity ? arr->as.array.capacity * 2 : 8;
TinyBlocks_JsonValue** items = realloc(arr->as.array.items, cap * sizeof(*items));
if (!items) return false;
arr->as.array.items = items;
arr->as.array.capacity = cap;
}
tb_json_retain(item);
arr->as.array.items[arr->as.array.count++] = item;
return true;
}
uint32_t tb_json_array_length(const TinyBlocks_JsonValue* arr) {
return (arr && arr->kind == TB_JSON_ARRAY) ? arr->as.array.count : 0;
}
TinyBlocks_JsonValue* tb_json_array_get(const TinyBlocks_JsonValue* arr, uint32_t idx) {
if (!arr || arr->kind != TB_JSON_ARRAY || idx >= arr->as.array.count) return NULL;
TinyBlocks_JsonValue* v = arr->as.array.items[idx];
tb_json_retain(v);
return v;
}
/* ══════════════════════════════════════════════════════════════════════════
* Objetos
* ══════════════════════════════════════════════════════════════════════════ */
bool tb_json_object_set(TinyBlocks_JsonValue* obj, const char* key, TinyBlocks_JsonValue* val) {
if (!obj || obj->kind != TB_JSON_OBJECT || !key || !val) return false;
for (uint32_t i = 0; i < obj->as.object.count; i++) {
if (strcmp(obj->as.object.keys[i], key) == 0) {
tb_json_release(obj->as.object.values[i]);
tb_json_retain(val);
obj->as.object.values[i] = val;
return true;
}
}
if (obj->as.object.count == obj->as.object.capacity) {
uint32_t cap = obj->as.object.capacity ? obj->as.object.capacity * 2 : 8;
char** keys = realloc(obj->as.object.keys, cap * sizeof(*keys));
TinyBlocks_JsonValue** values = realloc(obj->as.object.values, cap * sizeof(*values));
if (!keys || !values) { free(keys); free(values); return false; }
obj->as.object.keys = keys;
obj->as.object.values = values;
obj->as.object.capacity = cap;
}
obj->as.object.keys[obj->as.object.count] = strdup(key);
tb_json_retain(val);
obj->as.object.values[obj->as.object.count] = val;
obj->as.object.count++;
return true;
}
uint32_t tb_json_object_length(const TinyBlocks_JsonValue* obj) {
return (obj && obj->kind == TB_JSON_OBJECT) ? obj->as.object.count : 0;
}
const char* tb_json_object_key_at(const TinyBlocks_JsonValue* obj, uint32_t idx) {
if (!obj || obj->kind != TB_JSON_OBJECT || idx >= obj->as.object.count) return NULL;
return obj->as.object.keys[idx];
}
TinyBlocks_JsonValue* tb_json_object_get(const TinyBlocks_JsonValue* obj, const char* key) {
if (!obj || obj->kind != TB_JSON_OBJECT || !key) return NULL;
for (uint32_t i = 0; i < obj->as.object.count; i++) {
if (strcmp(obj->as.object.keys[i], key) == 0) {
tb_json_retain(obj->as.object.values[i]);
return obj->as.object.values[i];
}
}
return NULL;
}
/* ══════════════════════════════════════════════════════════════════════════
* Parser (recursive-descent, RFC 8259 simplificado)
* ══════════════════════════════════════════════════════════════════════════ */
typedef struct { const char* p; const char* end; char* err; size_t errcap; } JsonParser;
static void parser_fail(JsonParser* ps, const char* msg) {
if (ps->err && ps->errcap) snprintf(ps->err, ps->errcap, "%s", msg);
}
static void skip_ws(JsonParser* ps) {
while (ps->p < ps->end && isspace((unsigned char)*ps->p)) ps->p++;
}
static TinyBlocks_JsonValue* parse_value(JsonParser* ps);
static bool parse_literal(JsonParser* ps, const char* lit) {
size_t n = strlen(lit);
if ((size_t)(ps->end - ps->p) < n) return false;
if (memcmp(ps->p, lit, n) != 0) return false;
ps->p += n;
return true;
}
static char* parse_string_raw(JsonParser* ps) {
if (ps->p >= ps->end || *ps->p != '"') { parser_fail(ps, "esperado '\"'"); return NULL; }
ps->p++;
size_t cap = 32, len = 0;
char* buf = malloc(cap);
if (!buf) return NULL;
while (ps->p < ps->end && *ps->p != '"') {
unsigned char c = (unsigned char)*ps->p++;
char out = (char)c;
if (c == '\\') {
if (ps->p >= ps->end) { free(buf); parser_fail(ps, "string truncada"); return NULL; }
char esc = *ps->p++;
switch (esc) {
case '"': out = '"'; break;
case '\\': out = '\\'; break;
case '/': out = '/'; break;
case 'b': out = '\b'; break;
case 'f': out = '\f'; break;
case 'n': out = '\n'; break;
case 'r': out = '\r'; break;
case 't': out = '\t'; break;
case 'u': {
if (ps->end - ps->p < 4) { free(buf); parser_fail(ps, "\\u incompleto"); return NULL; }
unsigned cp = 0;
for (int i = 0; i < 4; i++) {
char h = ps->p[i];
cp <<= 4;
if (h >= '0' && h <= '9') cp |= (unsigned)(h - '0');
else if (h >= 'a' && h <= 'f') cp |= (unsigned)(h - 'a' + 10);
else if (h >= 'A' && h <= 'F') cp |= (unsigned)(h - 'A' + 10);
else { free(buf); parser_fail(ps, "\\u inválido"); return NULL; }
}
ps->p += 4;
/* codifica em UTF-8 (apenas BMP, sem pares substitutos) */
if (len + 4 >= cap) { cap *= 2; buf = realloc(buf, cap); if (!buf) return NULL; }
if (cp < 0x80) {
buf[len++] = (char)cp;
} else if (cp < 0x800) {
buf[len++] = (char)(0xC0 | (cp >> 6));
buf[len++] = (char)(0x80 | (cp & 0x3F));
} else {
buf[len++] = (char)(0xE0 | (cp >> 12));
buf[len++] = (char)(0x80 | ((cp >> 6) & 0x3F));
buf[len++] = (char)(0x80 | (cp & 0x3F));
}
continue;
}
default:
free(buf); parser_fail(ps, "escape inválido"); return NULL;
}
}
if (len + 1 >= cap) { cap *= 2; buf = realloc(buf, cap); if (!buf) return NULL; }
buf[len++] = out;
}
if (ps->p >= ps->end) { free(buf); parser_fail(ps, "string não terminada"); return NULL; }
ps->p++; /* fecha '"' */
buf[len] = '\0';
return buf;
}
static TinyBlocks_JsonValue* parse_number(JsonParser* ps) {
const char* start = ps->p;
if (ps->p < ps->end && *ps->p == '-') ps->p++;
while (ps->p < ps->end && isdigit((unsigned char)*ps->p)) ps->p++;
if (ps->p < ps->end && *ps->p == '.') {
ps->p++;
while (ps->p < ps->end && isdigit((unsigned char)*ps->p)) ps->p++;
}
if (ps->p < ps->end && (*ps->p == 'e' || *ps->p == 'E')) {
ps->p++;
if (ps->p < ps->end && (*ps->p == '+' || *ps->p == '-')) ps->p++;
while (ps->p < ps->end && isdigit((unsigned char)*ps->p)) ps->p++;
}
if (ps->p == start) { parser_fail(ps, "número inválido"); return NULL; }
char tmp[64];
size_t n = (size_t)(ps->p - start);
if (n >= sizeof(tmp)) n = sizeof(tmp) - 1;
memcpy(tmp, start, n);
tmp[n] = '\0';
return tb_json_number(strtod(tmp, NULL));
}
static TinyBlocks_JsonValue* parse_array(JsonParser* ps) {
ps->p++; /* '[' */
TinyBlocks_JsonValue* arr = tb_json_array();
skip_ws(ps);
if (ps->p < ps->end && *ps->p == ']') { ps->p++; return arr; }
for (;;) {
skip_ws(ps);
TinyBlocks_JsonValue* item = parse_value(ps);
if (!item) { tb_json_release(arr); return NULL; }
tb_json_array_push(arr, item);
tb_json_release(item);
skip_ws(ps);
if (ps->p < ps->end && *ps->p == ',') { ps->p++; continue; }
if (ps->p < ps->end && *ps->p == ']') { ps->p++; break; }
tb_json_release(arr); parser_fail(ps, "esperado ',' ou ']'"); return NULL;
}
return arr;
}
static TinyBlocks_JsonValue* parse_object(JsonParser* ps) {
ps->p++; /* '{' */
TinyBlocks_JsonValue* obj = tb_json_object();
skip_ws(ps);
if (ps->p < ps->end && *ps->p == '}') { ps->p++; return obj; }
for (;;) {
skip_ws(ps);
char* key = parse_string_raw(ps);
if (!key) { tb_json_release(obj); return NULL; }
skip_ws(ps);
if (ps->p >= ps->end || *ps->p != ':') { free(key); tb_json_release(obj); parser_fail(ps, "esperado ':'"); return NULL; }
ps->p++;
skip_ws(ps);
TinyBlocks_JsonValue* val = parse_value(ps);
if (!val) { free(key); tb_json_release(obj); return NULL; }
tb_json_object_set(obj, key, val);
free(key);
tb_json_release(val);
skip_ws(ps);
if (ps->p < ps->end && *ps->p == ',') { ps->p++; continue; }
if (ps->p < ps->end && *ps->p == '}') { ps->p++; break; }
tb_json_release(obj); parser_fail(ps, "esperado ',' ou '}'"); return NULL;
}
return obj;
}
static TinyBlocks_JsonValue* parse_value(JsonParser* ps) {
skip_ws(ps);
if (ps->p >= ps->end) { parser_fail(ps, "fim inesperado"); return NULL; }
char c = *ps->p;
if (c == '{') return parse_object(ps);
if (c == '[') return parse_array(ps);
if (c == '"') {
char* s = parse_string_raw(ps);
if (!s) return NULL;
TinyBlocks_JsonValue* j = tb_json_string(s);
free(s);
return j;
}
if (c == '-' || isdigit((unsigned char)c)) return parse_number(ps);
if (parse_literal(ps, "true")) return tb_json_bool(true);
if (parse_literal(ps, "false")) return tb_json_bool(false);
if (parse_literal(ps, "null")) return tb_json_null();
parser_fail(ps, "token inesperado");
return NULL;
}
TinyBlocks_JsonValue* tb_json_parse(const char* text, char* errbuf, size_t errbuf_size) {
if (!text) { if (errbuf && errbuf_size) snprintf(errbuf, errbuf_size, "texto nulo"); return NULL; }
JsonParser ps = { .p = text, .end = text + strlen(text), .err = errbuf, .errcap = errbuf_size };
TinyBlocks_JsonValue* v = parse_value(&ps);
if (!v) return NULL;
skip_ws(&ps);
if (ps.p != ps.end) {
tb_json_release(v);
if (errbuf && errbuf_size) snprintf(errbuf, errbuf_size, "lixo após valor JSON");
return NULL;
}
return v;
}
/* ══════════════════════════════════════════════════════════════════════════
* Stringify
* ══════════════════════════════════════════════════════════════════════════ */
typedef struct { char* buf; size_t len, cap; } StrBuf;
static void sb_ensure(StrBuf* sb, size_t extra) {
if (sb->len + extra + 1 <= sb->cap) return;
size_t cap = sb->cap ? sb->cap * 2 : 64;
while (cap < sb->len + extra + 1) cap *= 2;
sb->buf = realloc(sb->buf, cap);
sb->cap = cap;
}
static void sb_append(StrBuf* sb, const char* s) {
size_t n = strlen(s);
sb_ensure(sb, n);
memcpy(sb->buf + sb->len, s, n);
sb->len += n;
sb->buf[sb->len] = '\0';
}
static void sb_append_quoted(StrBuf* sb, const char* s) {
sb_append(sb, "\"");
for (const unsigned char* p = (const unsigned char*)s; *p; p++) {
char tmp[8];
switch (*p) {
case '"': sb_append(sb, "\\\""); break;
case '\\': sb_append(sb, "\\\\"); break;
case '\n': sb_append(sb, "\\n"); break;
case '\r': sb_append(sb, "\\r"); break;
case '\t': sb_append(sb, "\\t"); break;
default:
if (*p < 0x20) { snprintf(tmp, sizeof(tmp), "\\u%04x", *p); sb_append(sb, tmp); }
else { tmp[0] = (char)*p; tmp[1] = '\0'; sb_append(sb, tmp); }
}
}
sb_append(sb, "\"");
}
static void stringify_rec(StrBuf* sb, const TinyBlocks_JsonValue* j) {
if (!j) { sb_append(sb, "null"); return; }
char tmp[64];
switch (j->kind) {
case TB_JSON_NULL:
sb_append(sb, "null");
break;
case TB_JSON_BOOL:
sb_append(sb, j->as.boolean ? "true" : "false");
break;
case TB_JSON_NUMBER:
if (isfinite(j->as.number) && j->as.number == (double)(int64_t)j->as.number)
snprintf(tmp, sizeof(tmp), "%lld", (long long)j->as.number);
else
snprintf(tmp, sizeof(tmp), "%g", j->as.number);
sb_append(sb, tmp);
break;
case TB_JSON_STRING:
sb_append_quoted(sb, j->as.string);
break;
case TB_JSON_ARRAY:
sb_append(sb, "[");
for (uint32_t i = 0; i < j->as.array.count; i++) {
if (i) sb_append(sb, ",");
stringify_rec(sb, j->as.array.items[i]);
}
sb_append(sb, "]");
break;
case TB_JSON_OBJECT:
sb_append(sb, "{");
for (uint32_t i = 0; i < j->as.object.count; i++) {
if (i) sb_append(sb, ",");
sb_append_quoted(sb, j->as.object.keys[i]);
sb_append(sb, ":");
stringify_rec(sb, j->as.object.values[i]);
}
sb_append(sb, "}");
break;
}
}
char* tb_json_stringify(const TinyBlocks_JsonValue* j) {
StrBuf sb = {0};
stringify_rec(&sb, j);
if (!sb.buf) sb.buf = strdup("null");
return sb.buf;
}
/* ══════════════════════════════════════════════════════════════════════════
* Helpers para TinyBlocks_Value
* ══════════════════════════════════════════════════════════════════════════ */
TinyBlocks_Value tb_value_json(TinyBlocks_JsonValue* j) {
TinyBlocks_Value v = { .kind = TB_VALUE_JSON, .as.json = j };
if (j) tb_json_retain(j);
return v;
}
TinyBlocks_JsonValue* tb_value_as_json(TinyBlocks_Value v) {
return v.kind == TB_VALUE_JSON ? v.as.json : NULL;
}
+190
View File
@@ -0,0 +1,190 @@
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "tinyblocks/tinyblocks.h"
#ifdef __linux__
# include <dlfcn.h>
#endif
/* ── Vtable de LibraryBlock ──────────────────────────────────────────────── */
static void lib_eval(TinyBlocks_Block* self, TinyBlocks* rt)
{
/* Libraries não avaliam diretamente; servem como namespaces */
(void)self; (void)rt;
self->dirty = false;
}
static void lib_destroy(TinyBlocks_Block* self, TinyBlocks* rt)
{
TinyBlocks_LibraryBlock* lib = (TinyBlocks_LibraryBlock*)self;
tb_rt_unregister_library(rt, lib);
/* Destrói blocos contidos */
for (uint32_t i = 0; i < lib->block_count; ++i)
tb_block_destroy(lib->blocks[i], rt);
tb_free(rt, lib->blocks);
}
static size_t lib_to_string(TinyBlocks_Block* self, TinyBlocks* rt,
char* buf, size_t sz)
{
(void)rt;
return (size_t)snprintf(buf, sz, "[Library:%s (%u blocks)]",
self->name ? self->name : "?",
((TinyBlocks_LibraryBlock*)self)->block_count);
}
static TinyBlocks_Block* lib_clone(const TinyBlocks_Block* self, TinyBlocks* rt)
{
/* Clonar uma library cria uma nova library vazia com o mesmo nome */
return (TinyBlocks_Block*)tb_library_block_create(rt, self->name);
}
static const TinyBlocks_BlockVTable s_lib_vtable = {
.eval = lib_eval,
.destroy = lib_destroy,
.to_string = lib_to_string,
.clone = lib_clone,
};
/* ── Criação ─────────────────────────────────────────────────────────────── */
TinyBlocks_LibraryBlock* tb_library_block_create(TinyBlocks* rt, const char* name)
{
TinyBlocks_LibraryBlock* lib = (TinyBlocks_LibraryBlock*)tb_block_alloc_base(
rt, TB_KIND_LIBRARY, sizeof(TinyBlocks_LibraryBlock),
0, 0, &s_lib_vtable);
if (!lib) return NULL;
lib->base.name = tb_strdup(rt, name);
lib->block_capacity = 16;
lib->blocks = tb_alloc(rt, lib->block_capacity * sizeof(TinyBlocks_Block*));
if (!lib->blocks) {
tb_block_destroy(&lib->base, rt);
return NULL;
}
tb_rt_register_library(rt, lib);
return lib;
}
void tb_library_block_destroy(TinyBlocks_LibraryBlock* lib, TinyBlocks* rt)
{
tb_block_destroy(&lib->base, rt);
}
/* ── Gerenciamento de blocos contidos ────────────────────────────────────── */
bool tb_library_add(TinyBlocks_LibraryBlock* lib, TinyBlocks_Block* block)
{
if (!lib || !block) return false;
if (lib->block_count >= lib->block_capacity) {
uint32_t new_cap = lib->block_capacity * 2;
/* A library pertence a um runtime — mas não temos rt aqui.
Solução: guardar rt no lib_userdata NÃO é a API pública.
Usamos realloc direto pois este array não usa o alocador customizado
(trade-off documentado: arrays de library usam realloc). */
TinyBlocks_Block** arr = realloc(lib->blocks,
new_cap * sizeof(TinyBlocks_Block*));
if (!arr) return false;
lib->blocks = arr;
lib->block_capacity = new_cap;
}
lib->blocks[lib->block_count++] = block;
block->parent = &lib->base;
return true;
}
bool tb_library_remove_at(TinyBlocks_LibraryBlock* lib, uint32_t index)
{
if (!lib || index >= lib->block_count) return false;
lib->blocks[index]->parent = NULL;
lib->blocks[index] = lib->blocks[--lib->block_count];
return true;
}
TinyBlocks_Block* tb_library_find(TinyBlocks_LibraryBlock* lib, const char* name)
{
if (!lib || !name) return NULL;
for (uint32_t i = 0; i < lib->block_count; ++i) {
TinyBlocks_Block* b = lib->blocks[i];
/* Compara pelo nome do bloco ou pelo type_name se for TypeBlock */
if (b->name && strcmp(b->name, name) == 0) return b;
if (b->kind == TB_KIND_TYPE) {
TinyBlocks_TypeBlock* tb = (TinyBlocks_TypeBlock*)b;
if (tb->type_name && strcmp(tb->type_name, name) == 0) return b;
}
}
return NULL;
}
/* ── Carregamento dinâmico ───────────────────────────────────────────────── */
TinyBlocks_LibraryBlock* tb_library_load(TinyBlocks* rt, const char* path)
{
#ifdef __linux__
void* handle = dlopen(path, RTLD_NOW | RTLD_LOCAL);
if (!handle) {
tinyblocks_set_error(rt, "tb_library_load: dlopen failed: %s", dlerror());
return NULL;
}
typedef const TinyBlocks_LibraryDescriptor* (*GetLibFn)(void);
GetLibFn get_lib = (GetLibFn)(uintptr_t)dlsym(handle, TINYBLOCKS_LIBRARY_SYMBOL);
if (!get_lib) {
tinyblocks_set_error(rt, "tb_library_load: symbol '%s' not found in %s",
TINYBLOCKS_LIBRARY_SYMBOL, path);
dlclose(handle);
return NULL;
}
const TinyBlocks_LibraryDescriptor* desc = get_lib();
TinyBlocks_LibraryBlock* lib = tb_library_register(rt, desc);
if (!lib) { dlclose(handle); return NULL; }
/* Guarda handle para dlclose no deinit */
if (rt->dl_handle_count >= rt->dl_handle_capacity) {
uint32_t nc = rt->dl_handle_capacity * 2;
void** arr = realloc(rt->dl_handles, nc * sizeof(void*));
if (!arr) { tb_library_unload(rt, lib); dlclose(handle); return NULL; }
rt->dl_handles = arr;
rt->dl_handle_capacity = nc;
}
rt->dl_handles[rt->dl_handle_count++] = handle;
return lib;
#else
(void)path;
tinyblocks_set_error(rt, "tb_library_load: not supported on this platform");
return NULL;
#endif
}
void tb_library_unload(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib)
{
if (!lib) return;
if (lib->on_unload) lib->on_unload(lib, rt);
tb_library_block_destroy(lib, rt);
}
TinyBlocks_LibraryBlock* tb_library_register(TinyBlocks* rt,
const TinyBlocks_LibraryDescriptor* desc)
{
if (!desc) {
tinyblocks_set_error(rt, "tb_library_register: descriptor is NULL");
return NULL;
}
TinyBlocks_LibraryBlock* lib = tb_library_block_create(rt, desc->name);
if (!lib) return NULL;
if (desc->init && !desc->init(rt, lib)) {
tinyblocks_set_error(rt, "tb_library_register: init failed for '%s'",
desc->name ? desc->name : "?");
tb_library_block_destroy(lib, rt);
return NULL;
}
if (lib->on_load && !lib->on_load(lib, rt)) {
tb_library_block_destroy(lib, rt);
return NULL;
}
return lib;
}
+68
View File
@@ -0,0 +1,68 @@
#include <stdio.h>
#include "tinyblocks/tinyblocks.h"
/* ── Vtable ──────────────────────────────────────────────────────────────── */
static void real_eval(TinyBlocks_Block* self, TinyBlocks* rt)
{
(void)rt;
TinyBlocks_RealBlock* rb = (TinyBlocks_RealBlock*)self;
tb_block_set_output(self, 0, tb_value_real(rb->value));
self->dirty = false;
}
static void real_destroy(TinyBlocks_Block* self, TinyBlocks* rt)
{
(void)self; (void)rt;
}
static size_t real_to_string(TinyBlocks_Block* self, TinyBlocks* rt,
char* buf, size_t sz)
{
(void)rt;
TinyBlocks_RealBlock* rb = (TinyBlocks_RealBlock*)self;
return (size_t)snprintf(buf, sz, "%g", rb->value);
}
static TinyBlocks_Block* real_clone(const TinyBlocks_Block* self, TinyBlocks* rt)
{
const TinyBlocks_RealBlock* rb = (const TinyBlocks_RealBlock*)self;
TinyBlocks_RealBlock* clone = tb_real_block_create(rt, rb->value);
if (clone && self->name) clone->base.name = tb_strdup(rt, self->name);
return (TinyBlocks_Block*)clone;
}
static const TinyBlocks_BlockVTable s_real_vtable = {
.eval = real_eval,
.destroy = real_destroy,
.to_string = real_to_string,
.clone = real_clone,
};
/* ── Ciclo de vida ───────────────────────────────────────────────────────── */
TinyBlocks_RealBlock* tb_real_block_create(TinyBlocks* rt, double value)
{
TinyBlocks_RealBlock* rb = (TinyBlocks_RealBlock*)tb_block_alloc_base(
rt, TB_KIND_REAL, sizeof(TinyBlocks_RealBlock),
0, 1, &s_real_vtable);
if (!rb) return NULL;
rb->value = value;
return rb;
}
void tb_real_block_destroy(TinyBlocks_RealBlock* rb, TinyBlocks* rt)
{
tb_block_destroy(&rb->base, rt);
}
/* ── Acesso ──────────────────────────────────────────────────────────────── */
double tb_real_block_get(const TinyBlocks_RealBlock* rb)
{
return rb ? rb->value : 0.0;
}
void tb_real_block_set(TinyBlocks_RealBlock* rb, double value)
{
if (!rb) return;
rb->value = value;
rb->base.dirty = true;
}
+165
View File
@@ -0,0 +1,165 @@
#define _POSIX_C_SOURCE 200809L
#include <string.h>
#include <stddef.h>
#include "tinyblocks/tb_renderable_block.h"
/* ── Pool estático — 4 frames em paralelo é suficiente para qualquer backend ─ */
#define POOL_CAP 4
static TinyBlocks_RenderableBlock s_pool[POOL_CAP];
static bool s_used[POOL_CAP];
TinyBlocks_RenderableBlock* tb_renderable_acquire(void) {
for (int i = 0; i < POOL_CAP; i++) {
if (!s_used[i]) {
s_used[i] = true;
s_pool[i].count = 0;
return &s_pool[i];
}
}
return NULL;
}
void tb_renderable_release(TinyBlocks_RenderableBlock* rb) {
for (int i = 0; i < POOL_CAP; i++) {
if (&s_pool[i] == rb) { s_used[i] = false; return; }
}
}
void tb_renderable_release_all(void) {
for (int i = 0; i < POOL_CAP; i++)
s_used[i] = false;
}
/* ── Append interno ─────────────────────────────────────────────────────────── */
static TinyBlocks_DrawCmd* append(TinyBlocks_RenderableBlock* rb) {
if (!rb || rb->count >= TB_DRAW_CMD_CAP) return NULL;
TinyBlocks_DrawCmd* c = &rb->cmds[rb->count++];
memset(c, 0, sizeof(*c));
return c;
}
/* ── Helpers públicos ────────────────────────────────────────────────────────── */
void tb_draw_clear(TinyBlocks_RenderableBlock* rb,
float r, float g, float b, float a) {
TinyBlocks_DrawCmd* c = append(rb); if (!c) return;
c->kind = TB_DRAW_CLEAR;
c->r=r; c->g=g; c->b=b; c->a=a;
}
void tb_draw_fill_rect(TinyBlocks_RenderableBlock* rb,
float x, float y, float w, float h,
float r, float g, float b, float a) {
TinyBlocks_DrawCmd* c = append(rb); if (!c) return;
c->kind = TB_DRAW_FILL_RECT;
c->x=x; c->y=y; c->w=w; c->h=h;
c->r=r; c->g=g; c->b=b; c->a=a;
}
void tb_draw_fill_rrect(TinyBlocks_RenderableBlock* rb,
float x, float y, float w, float h, float radius,
float r, float g, float b, float a) {
TinyBlocks_DrawCmd* c = append(rb); if (!c) return;
c->kind = TB_DRAW_FILL_RRECT;
c->x=x; c->y=y; c->w=w; c->h=h; c->param=radius;
c->r=r; c->g=g; c->b=b; c->a=a;
}
void tb_draw_fill_circle(TinyBlocks_RenderableBlock* rb,
float cx, float cy, float radius,
float r, float g, float b, float a) {
TinyBlocks_DrawCmd* c = append(rb); if (!c) return;
c->kind = TB_DRAW_FILL_CIRCLE;
c->x=cx; c->y=cy; c->param=radius;
c->r=r; c->g=g; c->b=b; c->a=a;
}
void tb_draw_stroke_line(TinyBlocks_RenderableBlock* rb,
float x1, float y1, float x2, float y2, float stroke_w,
float r, float g, float b, float a) {
TinyBlocks_DrawCmd* c = append(rb); if (!c) return;
c->kind = TB_DRAW_STROKE_LINE;
c->x=x1; c->y=y1; c->w=x2; c->h=y2; c->param=stroke_w;
c->r=r; c->g=g; c->b=b; c->a=a;
}
void tb_draw_stroke_circle(TinyBlocks_RenderableBlock* rb,
float cx, float cy, float radius, float stroke_w,
float r, float g, float b, float a) {
TinyBlocks_DrawCmd* c = append(rb); if (!c) return;
c->kind = TB_DRAW_STROKE_CIRCLE;
c->x=cx; c->y=cy; c->param=radius; c->w=stroke_w;
c->r=r; c->g=g; c->b=b; c->a=a;
}
void tb_draw_stroke_rect(TinyBlocks_RenderableBlock* rb,
float x, float y, float w, float h, float stroke_w,
float r, float g, float b, float a) {
TinyBlocks_DrawCmd* c = append(rb); if (!c) return;
c->kind = TB_DRAW_STROKE_RECT;
c->x=x; c->y=y; c->w=w; c->h=h; c->param=stroke_w;
c->r=r; c->g=g; c->b=b; c->a=a;
}
void tb_draw_set_clip(TinyBlocks_RenderableBlock* rb,
float x, float y, float w, float h) {
TinyBlocks_DrawCmd* c = append(rb); if (!c) return;
c->kind = TB_DRAW_SET_CLIP;
c->x=x; c->y=y; c->w=w; c->h=h;
}
void tb_draw_clear_clip(TinyBlocks_RenderableBlock* rb) {
TinyBlocks_DrawCmd* c = append(rb); if (!c) return;
c->kind = TB_DRAW_CLEAR_CLIP;
}
void tb_draw_text(TinyBlocks_RenderableBlock* rb,
float x, float y, const char* text, float font_size,
float r, float g, float b, float a) {
if (!text || !text[0]) return;
TinyBlocks_DrawCmd* c = append(rb); if (!c) return;
c->kind = TB_DRAW_TEXT;
c->x=x; c->y=y;
c->font_size = font_size;
c->r=r; c->g=g; c->b=b; c->a=a;
strncpy(c->text, text, sizeof(c->text) - 1);
}
void tb_draw_merge_offset(TinyBlocks_RenderableBlock* dst,
const TinyBlocks_RenderableBlock* src,
float dx, float dy) {
if (!dst || !src) return;
for (uint32_t i = 0; i < src->count && dst->count < TB_DRAW_CMD_CAP; i++) {
TinyBlocks_DrawCmd cmd = src->cmds[i];
switch (cmd.kind) {
case TB_DRAW_FILL_RECT:
case TB_DRAW_FILL_RRECT:
case TB_DRAW_STROKE_RECT:
case TB_DRAW_SET_CLIP:
case TB_DRAW_TEXT:
cmd.x += dx; cmd.y += dy;
break;
case TB_DRAW_FILL_CIRCLE:
case TB_DRAW_STROKE_CIRCLE:
cmd.x += dx; cmd.y += dy;
break;
case TB_DRAW_STROKE_LINE:
cmd.x += dx; cmd.y += dy;
cmd.w += dx; cmd.h += dy;
break;
case TB_DRAW_CLEAR:
case TB_DRAW_CLEAR_CLIP:
break;
}
dst->cmds[dst->count++] = cmd;
}
}
float tb_measure_text(const char* text, float font_size) {
if (!text) return 0.f;
size_t len = 0;
for (const char* p = text; *p; p++) {
if ((*p & 0xC0) != 0x80) len++; /* conta codepoints UTF-8 */
}
return (float)len * font_size * 0.55f;
}
+88
View File
@@ -0,0 +1,88 @@
#include <string.h>
#define _POSIX_C_SOURCE 200809L
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "tinyblocks/tinyblocks.h"
/* ── Vtable ──────────────────────────────────────────────────────────────── */
static void text_eval(TinyBlocks_Block* self, TinyBlocks* rt)
{
(void)rt;
TinyBlocks_TextBlock* tb = (TinyBlocks_TextBlock*)self;
tb_block_set_output(self, 0, tb_value_text(tb->value));
self->dirty = false;
}
static void text_destroy(TinyBlocks_Block* self, TinyBlocks* rt)
{
TinyBlocks_TextBlock* tb = (TinyBlocks_TextBlock*)self;
tb_free(rt, tb->value);
}
static size_t text_to_string(TinyBlocks_Block* self, TinyBlocks* rt,
char* buf, size_t sz)
{
(void)rt;
TinyBlocks_TextBlock* tb = (TinyBlocks_TextBlock*)self;
return (size_t)snprintf(buf, sz, "\"%s\"", tb->value ? tb->value : "");
}
static TinyBlocks_Block* text_clone(const TinyBlocks_Block* self, TinyBlocks* rt)
{
const TinyBlocks_TextBlock* tb = (const TinyBlocks_TextBlock*)self;
TinyBlocks_TextBlock* clone = tb_text_block_create(rt, tb->value);
if (clone && self->name) clone->base.name = tb_strdup(rt, self->name);
return (TinyBlocks_Block*)clone;
}
static const TinyBlocks_BlockVTable s_text_vtable = {
.eval = text_eval,
.destroy = text_destroy,
.to_string = text_to_string,
.clone = text_clone,
};
/* ── Ciclo de vida ───────────────────────────────────────────────────────── */
TinyBlocks_TextBlock* tb_text_block_create(TinyBlocks* rt, const char* value)
{
TinyBlocks_TextBlock* tb = (TinyBlocks_TextBlock*)tb_block_alloc_base(
rt, TB_KIND_TEXT, sizeof(TinyBlocks_TextBlock),
0, 1, &s_text_vtable);
if (!tb) return NULL;
tb->value = tb_strdup(rt, value ? value : "");
return tb;
}
void tb_text_block_destroy(TinyBlocks_TextBlock* tb, TinyBlocks* rt)
{
tb_block_destroy(&tb->base, rt);
}
/* ── Acesso ──────────────────────────────────────────────────────────────── */
const char* tb_text_block_get(const TinyBlocks_TextBlock* tb)
{
return tb ? tb->value : NULL;
}
void tb_text_block_set(TinyBlocks_TextBlock* tb, const char* value)
{
if (!tb) return;
/* Usa realloc para evitar precisar de rt aqui */
char* copy = value ? strdup(value) : strdup("");
free(tb->value);
tb->value = copy;
tb->base.dirty = true;
}
void tb_text_block_append(TinyBlocks_TextBlock* tb, const char* suffix)
{
if (!tb || !suffix) return;
size_t old_len = tb->value ? strlen(tb->value) : 0;
size_t suf_len = strlen(suffix);
char* buf = realloc(tb->value, old_len + suf_len + 1);
if (!buf) return;
memcpy(buf + old_len, suffix, suf_len + 1);
tb->value = buf;
tb->base.dirty = true;
}
+113
View File
@@ -0,0 +1,113 @@
#include <string.h>
#include <stdio.h>
#include "tinyblocks/tinyblocks.h"
/* ── Vtable de TypeBlock ─────────────────────────────────────────────────── */
static void type_eval(TinyBlocks_Block* self, TinyBlocks* rt)
{
/* Um TypeBlock em si não avalia; serve como fábrica/descritor */
(void)self; (void)rt;
self->dirty = false;
}
static void type_destroy(TinyBlocks_Block* self, TinyBlocks* rt)
{
TinyBlocks_TypeBlock* tb = (TinyBlocks_TypeBlock*)self;
tb_rt_unregister_type(rt, tb);
tb_free(rt, tb->type_name);
for (uint32_t i = 0; i < tb->input_desc_count; ++i)
tb_free(rt, (void*)tb->input_descs[i].name);
tb_free(rt, tb->input_descs);
for (uint32_t i = 0; i < tb->output_desc_count; ++i)
tb_free(rt, (void*)tb->output_descs[i].name);
tb_free(rt, tb->output_descs);
}
static size_t type_to_string(TinyBlocks_Block* self, TinyBlocks* rt,
char* buf, size_t sz)
{
(void)rt;
TinyBlocks_TypeBlock* tb = (TinyBlocks_TypeBlock*)self;
return (size_t)snprintf(buf, sz, "[Type:%s]",
tb->type_name ? tb->type_name : "?");
}
static TinyBlocks_Block* type_clone(const TinyBlocks_Block* self, TinyBlocks* rt)
{
const TinyBlocks_TypeBlock* src = (const TinyBlocks_TypeBlock*)self;
return (TinyBlocks_Block*)tb_type_block_create(rt, src->type_name,
src->input_descs, src->input_desc_count,
src->output_descs, src->output_desc_count,
src->eval_fn);
}
static const TinyBlocks_BlockVTable s_type_vtable = {
.eval = type_eval,
.destroy = type_destroy,
.to_string = type_to_string,
.clone = type_clone,
};
/* ── Criação ─────────────────────────────────────────────────────────────── */
TinyBlocks_TypeBlock* tb_type_block_create(
TinyBlocks* rt,
const char* type_name,
const TinyBlocks_SlotDesc* input_descs, uint32_t input_count,
const TinyBlocks_SlotDesc* output_descs, uint32_t output_count,
void (*eval_fn)(TinyBlocks_Block* self, TinyBlocks* rt))
{
TinyBlocks_TypeBlock* tb = (TinyBlocks_TypeBlock*)tb_block_alloc_base(
rt, TB_KIND_TYPE, sizeof(TinyBlocks_TypeBlock),
0, 0, &s_type_vtable);
if (!tb) return NULL;
tb->type_name = tb_strdup(rt, type_name);
tb->eval_fn = eval_fn;
tb->input_desc_count = input_count;
tb->output_desc_count = output_count;
if (input_count > 0) {
tb->input_descs = tb_alloc(rt, input_count * sizeof(TinyBlocks_SlotDesc));
if (!tb->input_descs) goto fail;
memcpy(tb->input_descs, input_descs, input_count * sizeof(TinyBlocks_SlotDesc));
/* Duplica os nomes dos slots */
for (uint32_t i = 0; i < input_count; ++i)
tb->input_descs[i].name = tb_strdup(rt, input_descs[i].name);
}
if (output_count > 0) {
tb->output_descs = tb_alloc(rt, output_count * sizeof(TinyBlocks_SlotDesc));
if (!tb->output_descs) goto fail;
memcpy(tb->output_descs, output_descs, output_count * sizeof(TinyBlocks_SlotDesc));
for (uint32_t i = 0; i < output_count; ++i)
tb->output_descs[i].name = tb_strdup(rt, output_descs[i].name);
}
tb_rt_register_type(rt, tb);
return tb;
fail:
tb_block_destroy(&tb->base, rt);
return NULL;
}
void tb_type_block_destroy(TinyBlocks_TypeBlock* tb, TinyBlocks* rt)
{
tb_block_destroy(&tb->base, rt);
}
void tb_type_block_set_instance_hooks(
TinyBlocks_TypeBlock* tb,
size_t instance_userdata_size,
bool (*init )(TinyBlocks_Block* self, TinyBlocks* rt),
void (*deinit)(TinyBlocks_Block* self, TinyBlocks* rt))
{
if (!tb) return;
tb->instance_userdata_size = instance_userdata_size;
tb->instance_init = init;
tb->instance_deinit = deinit;
}
TinyBlocks_TypeBlock* tb_type_block_find(TinyBlocks* rt, const char* type_name)
{
return tb_rt_find_type(rt, type_name);
}
+62
View File
@@ -0,0 +1,62 @@
#define _POSIX_C_SOURCE 200809L
#include <stdlib.h>
#include <string.h>
#include "tinyblocks/tinyblocks.h"
TinyBlocks_Value tb_value_none(void)
{
TinyBlocks_Value v = { .kind = TB_VALUE_NONE };
return v;
}
TinyBlocks_Value tb_value_integer(int64_t n)
{
TinyBlocks_Value v = { .kind = TB_VALUE_INTEGER, .as.integer = n };
return v;
}
TinyBlocks_Value tb_value_real(double d)
{
TinyBlocks_Value v = { .kind = TB_VALUE_REAL, .as.real = d };
return v;
}
TinyBlocks_Value tb_value_text(const char* str)
{
TinyBlocks_Value v = { .kind = TB_VALUE_TEXT };
v.as.text = str ? strdup(str) : NULL;
return v;
}
TinyBlocks_Value tb_value_block(TinyBlocks_Block* block)
{
TinyBlocks_Value v = { .kind = TB_VALUE_BLOCK, .as.block = block };
return v;
}
TinyBlocks_Value tb_value_clone(TinyBlocks_Value v)
{
if (v.kind == TB_VALUE_TEXT && v.as.text)
return tb_value_text(v.as.text);
if (v.kind == TB_VALUE_VECTOR && v.as.vector)
tb_vector_data_retain(v.as.vector);
if (v.kind == TB_VALUE_JSON && v.as.json)
tb_json_retain(v.as.json);
return v;
}
void tb_value_free(TinyBlocks_Value* v)
{
if (!v) return;
if (v->kind == TB_VALUE_TEXT) {
free(v->as.text);
v->as.text = NULL;
} else if (v->kind == TB_VALUE_VECTOR) {
tb_vector_data_release(v->as.vector);
v->as.vector = NULL;
} else if (v->kind == TB_VALUE_JSON) {
tb_json_release(v->as.json);
v->as.json = NULL;
}
v->kind = TB_VALUE_NONE;
}
+190
View File
@@ -0,0 +1,190 @@
#define _POSIX_C_SOURCE 200809L
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "tinyblocks/tinyblocks.h"
/* ══════════════════════════════════════════════════════════════════════════
* TinyBlocks_VectorData — buffer de comandos ref-counted
* ══════════════════════════════════════════════════════════════════════════ */
TinyBlocks_VectorData* tb_vector_data_create(void) {
TinyBlocks_VectorData* v = malloc(sizeof(TinyBlocks_VectorData));
if (!v) return NULL;
v->capacity = 16;
v->count = 0;
v->ref = 1;
v->cmds = malloc(v->capacity * sizeof(TinyBlocks_VCmd));
if (!v->cmds) { free(v); return NULL; }
return v;
}
void tb_vector_data_retain(TinyBlocks_VectorData* v) {
if (v) v->ref++;
}
void tb_vector_data_release(TinyBlocks_VectorData* v) {
if (!v) return;
if (--v->ref <= 0) { free(v->cmds); free(v); }
}
TinyBlocks_VectorData* tb_vector_data_clone(const TinyBlocks_VectorData* src) {
if (!src) return NULL;
TinyBlocks_VectorData* v = tb_vector_data_create();
if (!v) return NULL;
for (uint32_t i = 0; i < src->count; i++)
tb_vector_data_push(v, src->cmds[i]);
return v;
}
bool tb_vector_data_push(TinyBlocks_VectorData* v, TinyBlocks_VCmd cmd) {
if (!v) return false;
if (v->count >= v->capacity) {
uint32_t nc = v->capacity * 2;
TinyBlocks_VCmd* a = realloc(v->cmds, nc * sizeof(TinyBlocks_VCmd));
if (!a) return false;
v->cmds = a; v->capacity = nc;
}
v->cmds[v->count++] = cmd;
return true;
}
/* ── Construtores de conveniência ────────────────────────────────────────── */
#define PUSH0(v,k) tb_vector_data_push(v, (TinyBlocks_VCmd){(k), {0}})
#define PUSH2(v,k,a,b) tb_vector_data_push(v, (TinyBlocks_VCmd){(k), {(a),(b)}})
#define PUSH4(v,k,a,b,c,d) tb_vector_data_push(v,(TinyBlocks_VCmd){(k),{(a),(b),(c),(d)}})
#define PUSH5(v,k,a,b,c,d,e) tb_vector_data_push(v,(TinyBlocks_VCmd){(k),{(a),(b),(c),(d),(e)}})
bool tb_vector_begin_path(TinyBlocks_VectorData* v) { return PUSH0(v, TB_VCMD_BEGIN_PATH); }
bool tb_vector_move_to (TinyBlocks_VectorData* v, float x, float y) { return PUSH2(v, TB_VCMD_MOVE_TO, x,y); }
bool tb_vector_line_to (TinyBlocks_VectorData* v, float x, float y) { return PUSH2(v, TB_VCMD_LINE_TO, x,y); }
bool tb_vector_close_path(TinyBlocks_VectorData* v) { return PUSH0(v, TB_VCMD_CLOSE_PATH); }
bool tb_vector_stroke(TinyBlocks_VectorData* v, float r, float g, float b, float a, float w) {
return PUSH5(v, TB_VCMD_STROKE, r, g, b, a, w);
}
bool tb_vector_fill(TinyBlocks_VectorData* v, float r, float g, float b, float a) {
return PUSH4(v, TB_VCMD_FILL, r, g, b, a);
}
bool tb_vector_rect(TinyBlocks_VectorData* v, float x, float y, float w, float h) {
return PUSH4(v, TB_VCMD_RECT, x, y, w, h);
}
bool tb_vector_circle(TinyBlocks_VectorData* v, float cx, float cy, float radius) {
return PUSH5(v, TB_VCMD_CIRCLE, cx, cy, radius, 0, 0);
}
#undef PUSH0
#undef PUSH2
#undef PUSH4
#undef PUSH5
/* ── Value helpers ───────────────────────────────────────────────────────── */
TinyBlocks_Value tb_value_vector(TinyBlocks_VectorData* v) {
TinyBlocks_Value val;
val.kind = TB_VALUE_VECTOR;
val.as.vector = v;
if (v) v->ref++; /* tb_value retém a referência */
return val;
}
TinyBlocks_VectorData* tb_value_as_vector(TinyBlocks_Value v) {
return v.kind == TB_VALUE_VECTOR ? v.as.vector : NULL;
}
/* ── RenderableBlock play ────────────────────────────────────────────────── */
void tb_draw_ctx_play(TinyBlocks_RenderableBlock* rb, TinyBlocks_VectorData* v) {
if (!rb || !v) return;
float px = 0.f, py = 0.f; /* ponto atual do path */
float sx = 0.f, sy = 0.f; /* início do path (close_path) */
float fr = 1.f, fg = 1.f, fb = 1.f, fa = 1.f; /* cor de fill/stroke atual */
for (uint32_t i = 0; i < v->count; i++) {
TinyBlocks_VCmd* c = &v->cmds[i];
switch (c->kind) {
case TB_VCMD_BEGIN_PATH:
break;
case TB_VCMD_MOVE_TO:
px = sx = c->args[0]; py = sy = c->args[1]; break;
case TB_VCMD_LINE_TO:
tb_draw_stroke_line(rb, px, py, c->args[0], c->args[1], 1.f, fr, fg, fb, fa);
px = c->args[0]; py = c->args[1];
break;
case TB_VCMD_CLOSE_PATH:
tb_draw_stroke_line(rb, px, py, sx, sy, 1.f, fr, fg, fb, fa);
px = sx; py = sy;
break;
case TB_VCMD_STROKE:
fr = c->args[0]; fg = c->args[1]; fb = c->args[2]; fa = c->args[3];
break;
case TB_VCMD_FILL:
fr = c->args[0]; fg = c->args[1]; fb = c->args[2]; fa = c->args[3];
break;
case TB_VCMD_RECT:
tb_draw_fill_rect(rb, c->args[0], c->args[1], c->args[2], c->args[3],
fr, fg, fb, fa);
break;
case TB_VCMD_CIRCLE:
tb_draw_fill_circle(rb, c->args[0], c->args[1], c->args[2], fr, fg, fb, fa);
break;
}
}
}
/* ══════════════════════════════════════════════════════════════════════════
* TinyBlocks_VectorBlock — block kind TB_KIND_VECTOR
* ══════════════════════════════════════════════════════════════════════════ */
static void vec_eval(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)rt;
TinyBlocks_VectorBlock* vb = (TinyBlocks_VectorBlock*)self;
/* Coloca o VectorData no output[0] como valor (com retain) */
if (self->output_count > 0)
tb_block_set_output(self, 0, tb_value_vector(vb->data));
self->dirty = false;
}
static void vec_destroy(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)rt;
TinyBlocks_VectorBlock* vb = (TinyBlocks_VectorBlock*)self;
tb_vector_data_release(vb->data);
vb->data = NULL;
}
static size_t vec_to_string(TinyBlocks_Block* self, TinyBlocks* rt,
char* buf, size_t sz) {
(void)rt;
TinyBlocks_VectorBlock* vb = (TinyBlocks_VectorBlock*)self;
return (size_t)snprintf(buf, sz, "[Vector %u cmds]",
vb->data ? vb->data->count : 0u);
}
static TinyBlocks_Block* vec_clone(const TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_VectorBlock* src = (TinyBlocks_VectorBlock*)self;
TinyBlocks_VectorBlock* dst = tb_vector_block_create(rt);
if (!dst) return NULL;
if (src->data) {
dst->data = tb_vector_data_clone(src->data);
}
return &dst->base;
}
static const TinyBlocks_BlockVTable s_vec_vtable = {
.eval = vec_eval,
.destroy = vec_destroy,
.to_string = vec_to_string,
.clone = vec_clone,
};
TinyBlocks_VectorBlock* tb_vector_block_create(TinyBlocks* rt) {
TinyBlocks_VectorBlock* b = (TinyBlocks_VectorBlock*)tb_block_alloc_base(
rt, TB_KIND_VECTOR, sizeof(TinyBlocks_VectorBlock),
0, 1, &s_vec_vtable);
if (!b) return NULL;
b->data = tb_vector_data_create();
return b;
}
void tb_vector_block_set_data(TinyBlocks_VectorBlock* b, TinyBlocks_VectorData* v) {
if (!b) return;
tb_vector_data_release(b->data);
b->data = v;
if (v) v->ref++;
b->base.dirty = true;
}
+240
View File
@@ -0,0 +1,240 @@
#define _POSIX_C_SOURCE 200809L
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <stdarg.h>
#include "tinyblocks/tinyblocks.h"
/* ── Alocador padrão ─────────────────────────────────────────────────────── */
static void* default_alloc(size_t size, void* ud) { (void)ud; return malloc(size); }
static void default_free (void* ptr, void* ud) { (void)ud; free(ptr); }
/* ── Inicialização ───────────────────────────────────────────────────────── */
bool tinyblocks_init(TinyBlocks** out_rt, const TinyBlocks_InitOptions* opts)
{
if (!out_rt) return false;
TinyBlocks_AllocFn alloc_fn = opts && opts->alloc ? opts->alloc : default_alloc;
TinyBlocks_FreeFn free_fn = opts && opts->free_fn ? opts->free_fn : default_free;
void* alloc_ud = opts ? opts->alloc_userdata : NULL;
TinyBlocks* rt = alloc_fn(sizeof(TinyBlocks), alloc_ud);
if (!rt) return false;
memset(rt, 0, sizeof(TinyBlocks));
rt->alloc = alloc_fn;
rt->free = free_fn;
rt->alloc_userdata = alloc_ud;
rt->next_id = 1;
uint32_t bcap = (opts && opts->initial_block_cap) ? opts->initial_block_cap : 64;
uint32_t tcap = (opts && opts->initial_type_cap) ? opts->initial_type_cap : 32;
uint32_t lcap = (opts && opts->initial_library_cap) ? opts->initial_library_cap : 16;
rt->blocks = alloc_fn(bcap * sizeof(TinyBlocks_Block*), alloc_ud);
rt->types = alloc_fn(tcap * sizeof(TinyBlocks_TypeBlock*), alloc_ud);
rt->libraries = alloc_fn(lcap * sizeof(TinyBlocks_LibraryBlock*), alloc_ud);
rt->dl_handles= alloc_fn(lcap * sizeof(void*), alloc_ud);
if (!rt->blocks || !rt->types || !rt->libraries || !rt->dl_handles) {
if (rt->blocks) free_fn(rt->blocks, alloc_ud);
if (rt->types) free_fn(rt->types, alloc_ud);
if (rt->libraries) free_fn(rt->libraries, alloc_ud);
if (rt->dl_handles)free_fn(rt->dl_handles,alloc_ud);
free_fn(rt, alloc_ud);
return false;
}
rt->block_capacity = bcap;
rt->type_capacity = tcap;
rt->library_capacity = lcap;
rt->dl_handle_capacity = lcap;
*out_rt = rt;
return true;
}
/* ── Desinicialização ────────────────────────────────────────────────────── */
void tinyblocks_deinit(TinyBlocks** rt_ptr)
{
if (!rt_ptr || !*rt_ptr) return;
TinyBlocks* rt = *rt_ptr;
/* Fase 1: destruir instâncias (KB_KIND_BLOCK) primeiro.
Elas referenciam TypeBlocks via ->type; devem ser liberadas antes
das libraries que contêm esses TypeBlocks. */
{
uint32_t i = rt->block_count;
while (i > 0) {
TinyBlocks_Block* b = rt->blocks[i - 1];
if (b->kind == TB_KIND_BLOCK) {
tb_block_destroy(b, rt); /* remove de rt->blocks e libera */
i = rt->block_count; /* reinicia: o array mudou de tamanho */
} else {
--i;
}
}
}
/* Fase 2: descarregar libraries (invoca on_unload e destrói TypeBlocks). */
while (rt->library_count > 0) {
TinyBlocks_LibraryBlock* lib = rt->libraries[rt->library_count - 1];
if (lib->on_unload) lib->on_unload(lib, rt);
tb_library_block_destroy(lib, rt);
}
/* Fase 3: TypeBlocks e primitivos órfãos (não pertencentes a nenhuma library). */
while (rt->block_count > 0) {
TinyBlocks_Block* b = rt->blocks[rt->block_count - 1];
tb_block_destroy(b, rt);
}
#ifdef __linux__
/* Fecha dl handles (apenas no Linux por enquanto) */
for (uint32_t i = 0; i < rt->dl_handle_count; ++i) {
extern int dlclose(void*);
dlclose(rt->dl_handles[i]);
}
#endif
TinyBlocks_FreeFn free_fn = rt->free;
void* alloc_ud = rt->alloc_userdata;
free_fn(rt->blocks, alloc_ud);
free_fn(rt->types, alloc_ud);
free_fn(rt->libraries, alloc_ud);
free_fn(rt->dl_handles, alloc_ud);
free_fn(rt, alloc_ud);
*rt_ptr = NULL;
}
/* ── Alocação ────────────────────────────────────────────────────────────── */
void* tb_alloc(TinyBlocks* rt, size_t size)
{
void* p = rt->alloc(size, rt->alloc_userdata);
if (p) memset(p, 0, size);
return p;
}
void tb_free(TinyBlocks* rt, void* ptr)
{
if (ptr) rt->free(ptr, rt->alloc_userdata);
}
char* tb_strdup(TinyBlocks* rt, const char* str)
{
if (!str) return NULL;
size_t n = strlen(str) + 1;
char* p = rt->alloc(n, rt->alloc_userdata);
if (p) memcpy(p, str, n);
return p;
}
/* ── Geração de ID ───────────────────────────────────────────────────────── */
uint64_t tb_rt_next_id(TinyBlocks* rt) { return rt->next_id++; }
/* ── Registro de blocos ──────────────────────────────────────────────────── */
static bool grow_array(TinyBlocks* rt, void*** arr, uint32_t* cap, uint32_t count)
{
if (count < *cap) return true;
uint32_t new_cap = (*cap) * 2;
void** new_arr = rt->alloc(new_cap * sizeof(void*), rt->alloc_userdata);
if (!new_arr) return false;
memcpy(new_arr, *arr, count * sizeof(void*));
rt->free(*arr, rt->alloc_userdata);
*arr = new_arr;
*cap = new_cap;
return true;
}
bool tb_rt_register_block(TinyBlocks* rt, TinyBlocks_Block* block)
{
if (!grow_array(rt, (void***)&rt->blocks, &rt->block_capacity, rt->block_count))
return false;
rt->blocks[rt->block_count++] = block;
return true;
}
void tb_rt_unregister_block(TinyBlocks* rt, TinyBlocks_Block* block)
{
for (uint32_t i = 0; i < rt->block_count; ++i) {
if (rt->blocks[i] == block) {
rt->blocks[i] = rt->blocks[--rt->block_count];
return;
}
}
}
bool tb_rt_register_type(TinyBlocks* rt, TinyBlocks_TypeBlock* type)
{
if (!grow_array(rt, (void***)&rt->types, &rt->type_capacity, rt->type_count))
return false;
rt->types[rt->type_count++] = type;
return true;
}
void tb_rt_unregister_type(TinyBlocks* rt, TinyBlocks_TypeBlock* type)
{
for (uint32_t i = 0; i < rt->type_count; ++i) {
if (rt->types[i] == type) {
rt->types[i] = rt->types[--rt->type_count];
return;
}
}
}
bool tb_rt_register_library(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib)
{
if (!grow_array(rt, (void***)&rt->libraries, &rt->library_capacity, rt->library_count))
return false;
rt->libraries[rt->library_count++] = lib;
return true;
}
void tb_rt_unregister_library(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib)
{
for (uint32_t i = 0; i < rt->library_count; ++i) {
if (rt->libraries[i] == lib) {
rt->libraries[i] = rt->libraries[--rt->library_count];
return;
}
}
}
/* ── Busca ───────────────────────────────────────────────────────────────── */
TinyBlocks_Block* tb_rt_find_block(TinyBlocks* rt, uint64_t id)
{
for (uint32_t i = 0; i < rt->block_count; ++i)
if (rt->blocks[i]->id == id) return rt->blocks[i];
return NULL;
}
TinyBlocks_TypeBlock* tb_rt_find_type(TinyBlocks* rt, const char* name)
{
for (uint32_t i = 0; i < rt->type_count; ++i)
if (rt->types[i]->type_name && strcmp(rt->types[i]->type_name, name) == 0)
return rt->types[i];
return NULL;
}
TinyBlocks_LibraryBlock* tb_rt_find_library(TinyBlocks* rt, const char* name)
{
for (uint32_t i = 0; i < rt->library_count; ++i)
if (rt->libraries[i]->base.name &&
strcmp(rt->libraries[i]->base.name, name) == 0)
return rt->libraries[i];
return NULL;
}
/* ── Erros ───────────────────────────────────────────────────────────────── */
const char* tinyblocks_last_error(TinyBlocks* rt) { return rt->error; }
void tinyblocks_clear_error(TinyBlocks* rt) { rt->error[0] = '\0'; }
void tinyblocks_set_error(TinyBlocks* rt, const char* fmt, ...)
{
va_list ap;
va_start(ap, fmt);
vsnprintf(rt->error, sizeof(rt->error), fmt, ap);
va_end(ap);
}