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

@@ -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)