Converte símbolos Unicode decorativos dos comentários para ASCII

Substitui barras de caixa (─ ═ │ ┌ ┐ └ ┘ ├ ┤ ┬ ┴), travessões (—),
setas (→ ←), reticências (…), bullets (•), multiplicação (×) e
guillemets (› ‹) por equivalentes ASCII. Acentos portugueses são
preservados.
This commit is contained in:
mguinhos committed 2026-10-20 19:27:33 -03:00
1 parent 1cc0ff9d02
commit 90d47bf8a0
36 files changed
+327 -327

No files matched your search

+19 -19
View File
@@ -1,13 +1,13 @@
/* /*
* customappearance.c — Demonstração de on_draw (aparência personalizada de bloco). * customappearance.c - Demonstração de on_draw (aparência personalizada de bloco).
* *
* Blocos: * Blocos:
* Viz.ColorSwatch — inputs: r, g, b, a (0..1) → mostra quadrado colorido * 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.Gauge - inputs: value (0..1), r, g, b -> barra de progresso
* Viz.Star — inputs: r, g, b, a → estrela de 5 pontas (contorno) * 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 * Viz.BarChart - inputs: a, b, c, d (reais) -> mini gráfico de barras
* *
* make customappearance → build/customappearance.so * make customappearance -> build/customappearance.so
*/ */
#define _POSIX_C_SOURCE 200809L #define _POSIX_C_SOURCE 200809L
@@ -16,7 +16,7 @@
#include <tinyblocks/tinyblocks.h> #include <tinyblocks/tinyblocks.h>
#include <tinyblocks/tb_renderable_block.h> #include <tinyblocks/tb_renderable_block.h>
/* ── Helpers ─────────────────────────────────────────────────────────────── */ /* -- Helpers --- */
static float gf(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) { static float gf(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) {
TinyBlocks_Value v = tb_block_get_input(self, rt, 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_REAL) return (float)v.as.real;
@@ -32,9 +32,9 @@ static float out_f(TinyBlocks_Block* self, uint32_t idx) {
return 0.0f; return 0.0f;
} }
/* ══════════════════════════════════════════════════════════════════════════ /* ===
* Viz.ColorSwatch * Viz.ColorSwatch
* ══════════════════════════════════════════════════════════════════════════ */ * === */
static void eval_color_swatch(TinyBlocks_Block* self, TinyBlocks* rt) { static void eval_color_swatch(TinyBlocks_Block* self, TinyBlocks* rt) {
for (uint32_t i = 0; i < 4 && i < self->output_count; i++) 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))); tb_block_set_output(self, i, tb_value_real((double)gf(self, rt, i)));
@@ -76,9 +76,9 @@ static bool draw_color_swatch(TinyBlocks_Block* self, TinyBlocks* rt,
return true; return true;
} }
/* ══════════════════════════════════════════════════════════════════════════ /* ===
* Viz.Gauge * Viz.Gauge
* ══════════════════════════════════════════════════════════════════════════ */ * === */
static void eval_gauge(TinyBlocks_Block* self, TinyBlocks* rt) { static void eval_gauge(TinyBlocks_Block* self, TinyBlocks* rt) {
for (uint32_t i = 0; i < 4 && i < self->output_count; i++) 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))); tb_block_set_output(self, i, tb_value_real((double)gf(self, rt, i)));
@@ -116,9 +116,9 @@ static bool draw_gauge(TinyBlocks_Block* self, TinyBlocks* rt,
return true; return true;
} }
/* ══════════════════════════════════════════════════════════════════════════ /* ===
* Viz.Star * Viz.Star
* ══════════════════════════════════════════════════════════════════════════ */ * === */
static void eval_star(TinyBlocks_Block* self, TinyBlocks* rt) { static void eval_star(TinyBlocks_Block* self, TinyBlocks* rt) {
for (uint32_t i = 0; i < 4 && i < self->output_count; i++) 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))); tb_block_set_output(self, i, tb_value_real((double)gf(self, rt, i)));
@@ -166,9 +166,9 @@ static bool draw_star(TinyBlocks_Block* self, TinyBlocks* rt,
return true; return true;
} }
/* ══════════════════════════════════════════════════════════════════════════ /* ===
* Viz.BarChart * Viz.BarChart
* ══════════════════════════════════════════════════════════════════════════ */ * === */
static void eval_barchart(TinyBlocks_Block* self, TinyBlocks* rt) { static void eval_barchart(TinyBlocks_Block* self, TinyBlocks* rt) {
for (uint32_t i = 0; i < 4 && i < self->output_count; i++) 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))); tb_block_set_output(self, i, tb_value_real((double)gf(self, rt, i)));
@@ -218,9 +218,9 @@ static bool draw_barchart(TinyBlocks_Block* self, TinyBlocks* rt,
return true; return true;
} }
/* ══════════════════════════════════════════════════════════════════════════ /* ===
* Descritores de slots * Descritores de slots
* ══════════════════════════════════════════════════════════════════════════ */ * === */
static const TinyBlocks_SlotDesc rgba_in[] = { static const TinyBlocks_SlotDesc rgba_in[] = {
{"r", TB_VALUE_REAL}, {"g", TB_VALUE_REAL}, {"r", TB_VALUE_REAL}, {"g", TB_VALUE_REAL},
{"b", TB_VALUE_REAL}, {"a", TB_VALUE_REAL} {"b", TB_VALUE_REAL}, {"a", TB_VALUE_REAL}
@@ -246,9 +246,9 @@ static const TinyBlocks_SlotDesc chart_out[] = {
{"c", TB_VALUE_REAL}, {"d", TB_VALUE_REAL} {"c", TB_VALUE_REAL}, {"d", TB_VALUE_REAL}
}; };
/* ══════════════════════════════════════════════════════════════════════════ /* ===
* Registro * Registro
* ══════════════════════════════════════════════════════════════════════════ */ * === */
static bool ca_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { static bool ca_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
TinyBlocks_TypeBlock* t; TinyBlocks_TypeBlock* t;
+18 -18
View File
@@ -1,5 +1,5 @@
/* /*
* TinyBlocks — exemplo hello * TinyBlocks - exemplo hello
* *
* Demonstra: * Demonstra:
* 1. Inicializar o runtime * 1. Inicializar o runtime
@@ -11,7 +11,7 @@
#include <stdio.h> #include <stdio.h>
#include <tinyblocks/tinyblocks.h> #include <tinyblocks/tinyblocks.h>
/* ── TypeBlock: Math.Add ─────────────────────────────────────────────────── */ /* -- TypeBlock: Math.Add --- */
/* inputs: a(int), b(int) /* inputs: a(int), b(int)
* outputs: result(int) */ * outputs: result(int) */
static void eval_math_add(TinyBlocks_Block* self, TinyBlocks* rt) static void eval_math_add(TinyBlocks_Block* self, TinyBlocks* rt)
@@ -23,7 +23,7 @@ static void eval_math_add(TinyBlocks_Block* self, TinyBlocks* rt)
tb_block_set_output(self, 0, tb_value_integer(a + b)); tb_block_set_output(self, 0, tb_value_integer(a + b));
} }
/* ── TypeBlock: Math.Mul ─────────────────────────────────────────────────── */ /* -- TypeBlock: Math.Mul --- */
static void eval_math_mul(TinyBlocks_Block* self, TinyBlocks* rt) static void eval_math_mul(TinyBlocks_Block* self, TinyBlocks* rt)
{ {
TinyBlocks_Value va = tb_block_get_input(self, rt, 0); TinyBlocks_Value va = tb_block_get_input(self, rt, 0);
@@ -33,7 +33,7 @@ static void eval_math_mul(TinyBlocks_Block* self, TinyBlocks* rt)
tb_block_set_output(self, 0, tb_value_integer(a * b)); tb_block_set_output(self, 0, tb_value_integer(a * b));
} }
/* ── TypeBlock: IO.Print ─────────────────────────────────────────────────── */ /* -- TypeBlock: IO.Print --- */
/* inputs: label(text), value(int) /* inputs: label(text), value(int)
* outputs: (nenhum) */ * outputs: (nenhum) */
static void eval_io_print(TinyBlocks_Block* self, TinyBlocks* rt) static void eval_io_print(TinyBlocks_Block* self, TinyBlocks* rt)
@@ -54,7 +54,7 @@ static void eval_io_print(TinyBlocks_Block* self, TinyBlocks* rt)
printf("[IO.Print] %s = %s\n", label, valstr); printf("[IO.Print] %s = %s\n", label, valstr);
} }
/* ── TypeBlock: Math.Factorial (demonstra userdata por instância) ─────────── */ /* -- TypeBlock: Math.Factorial (demonstra userdata por instância) --- */
/* inputs: n(int) /* inputs: n(int)
* outputs: result(int) */ * outputs: result(int) */
typedef struct { int64_t memo; } FactorialData; typedef struct { int64_t memo; } FactorialData;
@@ -72,12 +72,12 @@ static void eval_math_factorial(TinyBlocks_Block* self, TinyBlocks* rt)
tb_block_set_output(self, 0, tb_value_integer(result)); tb_block_set_output(self, 0, tb_value_integer(result));
} }
/* ═══════════════════════════════════════════════════════════════════════════ /* ===
* main * main
* ═══════════════════════════════════════════════════════════════════════════ */ * === */
int main(void) int main(void)
{ {
printf("=== TinyBlocks — exemplo hello ===\n\n"); printf("=== TinyBlocks - exemplo hello ===\n\n");
/* 1. Inicializar runtime */ /* 1. Inicializar runtime */
TinyBlocks* rt = NULL; TinyBlocks* rt = NULL;
@@ -124,7 +124,7 @@ int main(void)
printf("[libs] Math=%u blocos, IO=%u bloco(s)\n\n", printf("[libs] Math=%u blocos, IO=%u bloco(s)\n\n",
lib_math->block_count, lib_io->block_count); lib_math->block_count, lib_io->block_count);
/* ── Exemplo 1: 3 + 4 ───────────────────────────────────────────────── */ /* -- Exemplo 1: 3 + 4 --- */
printf("--- Exemplo 1: 3 + 4 ---\n"); printf("--- Exemplo 1: 3 + 4 ---\n");
{ {
TinyBlocks_IntegerBlock* lit3 = tb_integer_block_create(rt, 3); TinyBlocks_IntegerBlock* lit3 = tb_integer_block_create(rt, 3);
@@ -133,13 +133,13 @@ int main(void)
TinyBlocks_Block* add = tb_block_create(rt, t_add); TinyBlocks_Block* add = tb_block_create(rt, t_add);
TinyBlocks_Block* print = tb_block_create(rt, t_print); TinyBlocks_Block* print = tb_block_create(rt, t_print);
/* Conecta: add.in[0] ← lit3.out[0] /* Conecta: add.in[0] <- lit3.out[0]
add.in[1] ← lit4.out[0] */ add.in[1] <- lit4.out[0] */
tb_block_connect(add, 0, &lit3->base, 0); tb_block_connect(add, 0, &lit3->base, 0);
tb_block_connect(add, 1, &lit4->base, 0); tb_block_connect(add, 1, &lit4->base, 0);
/* print.in[0] ← label.out[0] /* print.in[0] <- label.out[0]
print.in[1] ← add.out[0] */ print.in[1] <- add.out[0] */
tb_block_connect(print, 0, &label->base, 0); tb_block_connect(print, 0, &label->base, 0);
tb_block_connect(print, 1, add, 0); tb_block_connect(print, 1, add, 0);
@@ -147,7 +147,7 @@ int main(void)
tb_block_eval(print, rt); tb_block_eval(print, rt);
} }
/* ── Exemplo 2: (2 + 3) * 5 ────────────────────────────────────────── */ /* -- Exemplo 2: (2 + 3) * 5 --- */
printf("\n--- Exemplo 2: (2 + 3) * 5 ---\n"); printf("\n--- Exemplo 2: (2 + 3) * 5 ---\n");
{ {
TinyBlocks_IntegerBlock* lit2 = tb_integer_block_create(rt, 2); TinyBlocks_IntegerBlock* lit2 = tb_integer_block_create(rt, 2);
@@ -168,7 +168,7 @@ int main(void)
tb_block_eval(print, rt); tb_block_eval(print, rt);
} }
/* ── Exemplo 3: 7! (fatorial com userdata por instância) ────────────── */ /* -- Exemplo 3: 7! (fatorial com userdata por instância) --- */
printf("\n--- Exemplo 3: 7! ---\n"); printf("\n--- Exemplo 3: 7! ---\n");
{ {
TinyBlocks_IntegerBlock* lit7 = tb_integer_block_create(rt, 7); TinyBlocks_IntegerBlock* lit7 = tb_integer_block_create(rt, 7);
@@ -187,7 +187,7 @@ int main(void)
printf(" userdata.memo = %lld\n", (long long)d->memo); printf(" userdata.memo = %lld\n", (long long)d->memo);
} }
/* ── Exemplo 4: busca de tipo por nome ──────────────────────────────── */ /* -- Exemplo 4: busca de tipo por nome --- */
printf("\n--- Exemplo 4: busca de tipo por nome ---\n"); printf("\n--- Exemplo 4: busca de tipo por nome ---\n");
{ {
TinyBlocks_TypeBlock* found = tb_type_block_find(rt, "Math.Add"); TinyBlocks_TypeBlock* found = tb_type_block_find(rt, "Math.Add");
@@ -202,7 +202,7 @@ int main(void)
? ((TinyBlocks_TypeBlock*)b)->type_name : "?"); ? ((TinyBlocks_TypeBlock*)b)->type_name : "?");
} }
/* ── Exemplo 5: to_string ────────────────────────────────────────────── */ /* -- Exemplo 5: to_string --- */
printf("\n--- Exemplo 5: representação textual ---\n"); printf("\n--- Exemplo 5: representação textual ---\n");
{ {
TinyBlocks_IntegerBlock* ib = tb_integer_block_create(rt, 42); TinyBlocks_IntegerBlock* ib = tb_integer_block_create(rt, 42);
@@ -222,7 +222,7 @@ int main(void)
printf("TextBlock: %s\n", buf); printf("TextBlock: %s\n", buf);
} }
/* ── Resumo do runtime ───────────────────────────────────────────────── */ /* -- Resumo do runtime --- */
printf("\n--- Estado do runtime ---\n"); printf("\n--- Estado do runtime ---\n");
printf("blocks vivos: %u\n", rt->block_count); printf("blocks vivos: %u\n", rt->block_count);
printf("types: %u\n", rt->type_count); printf("types: %u\n", rt->type_count);
+26 -26
View File
@@ -1,24 +1,24 @@
/* /*
* json.c — Library de JSON para o TinyBlocks Editor. * json.c - Library de JSON para o TinyBlocks Editor.
* *
* Blocos incluídos: * Blocos incluídos:
* Json.Parse — texto -> json (null em caso de erro de sintaxe) * Json.Parse - texto -> json (null em caso de erro de sintaxe)
* Json.Stringify — json -> texto * Json.Stringify - json -> texto
* Json.Null — constrói json null * Json.Null - constrói json null
* Json.Bool — inteiro (0/1) -> json bool * Json.Bool - inteiro (0/1) -> json bool
* Json.Number — real -> json number * Json.Number - real -> json number
* Json.String — texto -> json string * Json.String - texto -> json string
* Json.Array — constrói array vazio * Json.Array - constrói array vazio
* Json.Object — constrói objeto vazio * Json.Object - constrói objeto vazio
* Json.Push — (array, valor) -> novo array com valor anexado * Json.Push - (array, valor) -> novo array com valor anexado
* Json.Set — (objeto, chave, valor) -> novo objeto com campo definido * Json.Set - (objeto, chave, valor) -> novo objeto com campo definido
* Json.Get — (objeto, chave) -> valor do campo, ou Json.Null * Json.Get - (objeto, chave) -> valor do campo, ou Json.Null
* Json.Index — (array, índice) -> valor na posição, 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.Length - (json) -> nº de elementos (array/objeto) ou 0
* Json.TypeOf — (json) -> "null"|"bool"|"number"|"string"|"array"|"object" * Json.TypeOf - (json) -> "null"|"bool"|"number"|"string"|"array"|"object"
* Json.ToNumber — (json, default) -> número (ou default se não for number/bool) * 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.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.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 * 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. * árvore, mantendo o fluxo de dados imutável como o resto do TinyBlocks.
@@ -27,7 +27,7 @@
* make json * make json
* *
* Para carregar no editor: * Para carregar no editor:
* Ctrl+O → build/json.so ou arraste build/json.so para a janela * Ctrl+O -> build/json.so ou arraste build/json.so para a janela
*/ */
#define _POSIX_C_SOURCE 200809L #define _POSIX_C_SOURCE 200809L
@@ -36,7 +36,7 @@
#include <tinyblocks/tinyblocks.h> #include <tinyblocks/tinyblocks.h>
/* ── Helpers de leitura de inputs ────────────────────────────────────────── */ /* -- Helpers de leitura de inputs --- */
static const char* gt(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) { static const char* gt(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) {
TinyBlocks_Value v = tb_block_get_input(self, rt, idx); TinyBlocks_Value v = tb_block_get_input(self, rt, idx);
return v.kind == TB_VALUE_TEXT ? v.as.text : ""; return v.kind == TB_VALUE_TEXT ? v.as.text : "";
@@ -68,9 +68,9 @@ static TinyBlocks_JsonValue* gj(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t
(self)->dirty = false; \ (self)->dirty = false; \
} while (0) } while (0)
/* ══════════════════════════════════════════════════════════════════════════ /* ===
* Implementações dos blocos * Implementações dos blocos
* ══════════════════════════════════════════════════════════════════════════ */ * === */
static void eval_parse(TinyBlocks_Block* self, TinyBlocks* rt) { static void eval_parse(TinyBlocks_Block* self, TinyBlocks* rt) {
char err[128] = {0}; char err[128] = {0};
@@ -191,9 +191,9 @@ static void eval_to_bool(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false; self->dirty = false;
} }
/* ══════════════════════════════════════════════════════════════════════════ /* ===
* Descritores de slots * Descritores de slots
* ══════════════════════════════════════════════════════════════════════════ */ * === */
static const TinyBlocks_SlotDesc out_json[] = {{"json", TB_VALUE_JSON}}; 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_text[] = {{"text", TB_VALUE_TEXT}};
static const TinyBlocks_SlotDesc out_integer[] = {{"n", TB_VALUE_INTEGER}}; static const TinyBlocks_SlotDesc out_integer[] = {{"n", TB_VALUE_INTEGER}};
@@ -217,9 +217,9 @@ static const TinyBlocks_SlotDesc in_json_real[] = {{"json", TB_VALUE_JSON},
static const TinyBlocks_SlotDesc in_json_int_def[] = {{"json", TB_VALUE_JSON}, static const TinyBlocks_SlotDesc in_json_int_def[] = {{"json", TB_VALUE_JSON},
{"def", TB_VALUE_INTEGER}}; {"def", TB_VALUE_INTEGER}};
/* ══════════════════════════════════════════════════════════════════════════ /* ===
* Registro da library * Registro da library
* ══════════════════════════════════════════════════════════════════════════ */ * === */
static bool json_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { static bool json_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
TinyBlocks_TypeBlock* t; TinyBlocks_TypeBlock* t;
+13 -13
View File
@@ -1,29 +1,29 @@
/* /*
* mcp.c — Plugin TinyBlocks com blocos MCP (Model Context Protocol). * mcp.c - Plugin TinyBlocks com blocos MCP (Model Context Protocol).
* *
* Blocos: * Blocos:
* MCP.Server — literal: armazena a URL do servidor MCP * MCP.Server - literal: armazena a URL do servidor MCP
* HTTP: "http://localhost:3000/mcp" * HTTP: "http://localhost:3000/mcp"
* stdio: "stdio://npx @modelcontextprotocol/server-filesystem /tmp" * stdio: "stdio://npx @modelcontextprotocol/server-filesystem /tmp"
* *
* MCP.Ping — input: url (text) → output: status (text) * MCP.Ping - input: url (text) -> output: status (text)
* Verifica se o servidor responde. * Verifica se o servidor responde.
* *
* MCP.ListTools — input: url (text) → output: tools (text) * MCP.ListTools - input: url (text) -> output: tools (text)
* Lista ferramentas disponíveis no servidor. * Lista ferramentas disponíveis no servidor.
* *
* MCP.Call — inputs: url, tool, args (text) → output: result (text) * MCP.Call - inputs: url, tool, args (text) -> output: result (text)
* Chama uma ferramenta com argumentos JSON. * Chama uma ferramenta com argumentos JSON.
* *
* Compilar: * Compilar:
* make mcp-lib * make mcp-lib
* *
* Carregar no editor: * Carregar no editor:
* ./build/editor build/mcp.so ou Ctrl+O → build/mcp.so * ./build/editor build/mcp.so ou Ctrl+O -> build/mcp.so
* *
* Exemplo de uso no editor: * Exemplo de uso no editor:
* [Literal.Text "stdio://npx @modelcontextprotocol/server-filesystem /tmp"] * [Literal.Text "stdio://npx @modelcontextprotocol/server-filesystem /tmp"]
* → [MCP.ListTools] → [IO.Print "tools"] * -> [MCP.ListTools] -> [IO.Print "tools"]
*/ */
#define _POSIX_C_SOURCE 200809L #define _POSIX_C_SOURCE 200809L
@@ -32,13 +32,13 @@
#include <tinyblocks/tinyblocks.h> #include <tinyblocks/tinyblocks.h>
#include <tinyblocks-mcp/tb_mcp.h> #include <tinyblocks-mcp/tb_mcp.h>
/* ── Helper: lê texto de slot ────────────────────────────────────────────── */ /* -- Helper: lê texto de slot --- */
static const char* gs(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) { static const char* gs(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) {
TinyBlocks_Value v = tb_block_get_input(self, rt, idx); TinyBlocks_Value v = tb_block_get_input(self, rt, idx);
return (v.kind == TB_VALUE_TEXT && v.as.text) ? v.as.text : ""; return (v.kind == TB_VALUE_TEXT && v.as.text) ? v.as.text : "";
} }
/* ── MCP.Ping ────────────────────────────────────────────────────────────── */ /* -- MCP.Ping --- */
static void eval_mcp_ping(TinyBlocks_Block* self, TinyBlocks* rt) { static void eval_mcp_ping(TinyBlocks_Block* self, TinyBlocks* rt) {
const char* url = gs(self, rt, 0); const char* url = gs(self, rt, 0);
char* result = tb_mcp_ping(url); char* result = tb_mcp_ping(url);
@@ -47,7 +47,7 @@ static void eval_mcp_ping(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false; self->dirty = false;
} }
/* ── MCP.ListTools ───────────────────────────────────────────────────────── */ /* -- MCP.ListTools --- */
static void eval_mcp_list_tools(TinyBlocks_Block* self, TinyBlocks* rt) { static void eval_mcp_list_tools(TinyBlocks_Block* self, TinyBlocks* rt) {
const char* url = gs(self, rt, 0); const char* url = gs(self, rt, 0);
char* result = tb_mcp_list_tools(url); char* result = tb_mcp_list_tools(url);
@@ -56,7 +56,7 @@ static void eval_mcp_list_tools(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false; self->dirty = false;
} }
/* ── MCP.Call ────────────────────────────────────────────────────────────── */ /* -- MCP.Call --- */
static void eval_mcp_call(TinyBlocks_Block* self, TinyBlocks* rt) { static void eval_mcp_call(TinyBlocks_Block* self, TinyBlocks* rt) {
const char* url = gs(self, rt, 0); const char* url = gs(self, rt, 0);
const char* tool = gs(self, rt, 1); const char* tool = gs(self, rt, 1);
@@ -67,7 +67,7 @@ static void eval_mcp_call(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false; self->dirty = false;
} }
/* ── Slots ───────────────────────────────────────────────────────────────── */ /* -- Slots --- */
static const TinyBlocks_SlotDesc url_in[] = {{"url", TB_VALUE_TEXT}}; static const TinyBlocks_SlotDesc url_in[] = {{"url", TB_VALUE_TEXT}};
static const TinyBlocks_SlotDesc call_in[] = {{"url", TB_VALUE_TEXT}, static const TinyBlocks_SlotDesc call_in[] = {{"url", TB_VALUE_TEXT},
{"tool", TB_VALUE_TEXT}, {"tool", TB_VALUE_TEXT},
@@ -76,7 +76,7 @@ static const TinyBlocks_SlotDesc status_out[] = {{"status", TB_VALUE_TEXT}};
static const TinyBlocks_SlotDesc tools_out[] = {{"tools", TB_VALUE_TEXT}}; static const TinyBlocks_SlotDesc tools_out[] = {{"tools", TB_VALUE_TEXT}};
static const TinyBlocks_SlotDesc result_out[] = {{"result", TB_VALUE_TEXT}}; static const TinyBlocks_SlotDesc result_out[] = {{"result", TB_VALUE_TEXT}};
/* ── Registro ────────────────────────────────────────────────────────────── */ /* -- Registro --- */
static bool mcp_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { static bool mcp_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
if (!tb_mcp_init()) return false; if (!tb_mcp_init()) return false;
+12 -12
View File
@@ -1,20 +1,20 @@
/* /*
* mylib.c — Library de exemplo para testar hot reload no TinyBlocks Editor. * mylib.c - Library de exemplo para testar hot reload no TinyBlocks Editor.
* *
* Blocos incluídos: * Blocos incluídos:
* Extra.Square — n² de um inteiro * Extra.Square - n^2 de um inteiro
* Extra.Cube — n³ de um inteiro * Extra.Cube - n^3 de um inteiro
* Extra.Clamp — limita valor entre min e max * Extra.Clamp - limita valor entre min e max
* Extra.Fibonacci — n-ésimo número de Fibonacci * Extra.Fibonacci - n-ésimo número de Fibonacci
* Extra.IsEven — 1 se par, 0 se ímpar * Extra.IsEven - 1 se par, 0 se ímpar
* Extra.IntToText — converte inteiro em texto * Extra.IntToText - converte inteiro em texto
* Extra.Pow — base elevado a exp (inteiros) * Extra.Pow - base elevado a exp (inteiros)
* *
* Para compilar: * Para compilar:
* make mylib * make mylib
* *
* Para carregar no editor: * Para carregar no editor:
* Ctrl+O → build/mylib.so ou arraste build/mylib.so para a janela * Ctrl+O -> build/mylib.so ou arraste build/mylib.so para a janela
*/ */
#define _POSIX_C_SOURCE 200809L #define _POSIX_C_SOURCE 200809L
@@ -24,7 +24,7 @@
#include <tinyblocks/tinyblocks.h> #include <tinyblocks/tinyblocks.h>
/* ── Slots reutilizáveis ─────────────────────────────────────────────────── */ /* -- Slots reutilizáveis --- */
static const TinyBlocks_SlotDesc in_n[] = {{"n", TB_VALUE_INTEGER}}; static const TinyBlocks_SlotDesc in_n[] = {{"n", TB_VALUE_INTEGER}};
static const TinyBlocks_SlotDesc in_ab[] = {{"a", TB_VALUE_INTEGER}, static const TinyBlocks_SlotDesc in_ab[] = {{"a", TB_VALUE_INTEGER},
{"b", TB_VALUE_INTEGER}}; {"b", TB_VALUE_INTEGER}};
@@ -34,7 +34,7 @@ static const TinyBlocks_SlotDesc in_clamp[]= {{"val", TB_VALUE_INTEGER},
static const TinyBlocks_SlotDesc out_int[] = {{"out", TB_VALUE_INTEGER}}; static const TinyBlocks_SlotDesc out_int[] = {{"out", TB_VALUE_INTEGER}};
static const TinyBlocks_SlotDesc out_txt[] = {{"out", TB_VALUE_TEXT}}; static const TinyBlocks_SlotDesc out_txt[] = {{"out", TB_VALUE_TEXT}};
/* ── Implementações ──────────────────────────────────────────────────────── */ /* -- Implementações --- */
static void eval_square(TinyBlocks_Block* self, TinyBlocks* rt) { static void eval_square(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Value v = tb_block_get_input(self, rt, 0); TinyBlocks_Value v = tb_block_get_input(self, rt, 0);
int64_t n = v.kind==TB_VALUE_INTEGER ? v.as.integer : 0; int64_t n = v.kind==TB_VALUE_INTEGER ? v.as.integer : 0;
@@ -94,7 +94,7 @@ static void eval_int_to_text(TinyBlocks_Block* self, TinyBlocks* rt) {
tb_block_set_output(self, 0, tb_value_text(buf)); tb_block_set_output(self, 0, tb_value_text(buf));
} }
/* ── Registro da library ─────────────────────────────────────────────────── */ /* -- Registro da library --- */
static bool mylib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { static bool mylib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
TinyBlocks_TypeBlock* t; TinyBlocks_TypeBlock* t;
+9 -9
View File
@@ -1,15 +1,15 @@
/* /*
* python.c — Plugin TinyBlocks com blocos Python.*. * python.c - Plugin TinyBlocks com blocos Python.*.
* *
* Blocos: * Blocos:
* Python.Eval — avalia expressão Python com variáveis x0..x3 * Python.Eval - avalia expressão Python com variáveis x0..x3
* Python.Run — executa script Python com variáveis x0..x3, captura stdout * Python.Run - executa script Python com variáveis x0..x3, captura stdout
* *
* Compilar: * Compilar:
* make python-lib * make python-lib
* *
* Carregar no editor: * Carregar no editor:
* ./build/editor build/python.so ou Ctrl+O → build/python.so * ./build/editor build/python.so ou Ctrl+O -> build/python.so
* *
* Exemplos de expressões: * Exemplos de expressões:
* x0 ** 2 + x1 ** 2 * x0 ** 2 + x1 ** 2
@@ -23,7 +23,7 @@
#include <tinyblocks/tinyblocks.h> #include <tinyblocks/tinyblocks.h>
#include <tinyblocks-python/tb_python.h> #include <tinyblocks-python/tb_python.h>
/* ── Helper: lê float de slot numérico ──────────────────────────────────── */ /* -- Helper: lê float de slot numérico --- */
static double gd(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) { static double gd(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) {
TinyBlocks_Value v = tb_block_get_input(self, rt, 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_REAL) return v.as.real;
@@ -36,7 +36,7 @@ static const char* gs(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) {
return (v.kind == TB_VALUE_TEXT && v.as.text) ? v.as.text : ""; return (v.kind == TB_VALUE_TEXT && v.as.text) ? v.as.text : "";
} }
/* ── Python.Eval ─────────────────────────────────────────────────────────── */ /* -- Python.Eval --- */
/* /*
* Inputs: expr (text), x0..x3 (real) * Inputs: expr (text), x0..x3 (real)
* Output: result (text) * Output: result (text)
@@ -52,7 +52,7 @@ static void eval_python_eval(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false; self->dirty = false;
} }
/* ── Python.Run ──────────────────────────────────────────────────────────── */ /* -- Python.Run --- */
/* /*
* Inputs: code (text), x0..x3 (real) * Inputs: code (text), x0..x3 (real)
* Output: stdout (text) * Output: stdout (text)
@@ -68,7 +68,7 @@ static void eval_python_run(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false; self->dirty = false;
} }
/* ── Slots ───────────────────────────────────────────────────────────────── */ /* -- Slots --- */
static const TinyBlocks_SlotDesc eval_in[] = { static const TinyBlocks_SlotDesc eval_in[] = {
{"expr", TB_VALUE_TEXT}, {"expr", TB_VALUE_TEXT},
{"x0", TB_VALUE_REAL}, {"x1", TB_VALUE_REAL}, {"x0", TB_VALUE_REAL}, {"x1", TB_VALUE_REAL},
@@ -82,7 +82,7 @@ static const TinyBlocks_SlotDesc run_in[] = {
static const TinyBlocks_SlotDesc text_out[] = {{"result", TB_VALUE_TEXT}}; static const TinyBlocks_SlotDesc text_out[] = {{"result", TB_VALUE_TEXT}};
static const TinyBlocks_SlotDesc stdout_out[]= {{"stdout", TB_VALUE_TEXT}}; static const TinyBlocks_SlotDesc stdout_out[]= {{"stdout", TB_VALUE_TEXT}};
/* ── Registro ────────────────────────────────────────────────────────────── */ /* -- Registro --- */
static bool py_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { static bool py_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
if (!tb_python_init()) return false; if (!tb_python_init()) return false;
+12 -12
View File
@@ -1,5 +1,5 @@
/* /*
* TinyBlocks — exemplo SDL2 * TinyBlocks - exemplo SDL2
* *
* Demonstra o uso da library tinyblocks-sdl2 registrada estaticamente. * Demonstra o uso da library tinyblocks-sdl2 registrada estaticamente.
* Abre uma janela 640x480, desenha um retângulo pulsante e fecha ao pressionar * Abre uma janela 640x480, desenha um retângulo pulsante e fecha ao pressionar
@@ -11,11 +11,11 @@
int main(void) int main(void)
{ {
/* ── Runtime ──────────────────────────────────────────────────────────── */ /* -- Runtime --- */
TinyBlocks* rt = NULL; TinyBlocks* rt = NULL;
if (!tinyblocks_init(&rt, NULL)) { fprintf(stderr, "init falhou\n"); return 1; } if (!tinyblocks_init(&rt, NULL)) { fprintf(stderr, "init falhou\n"); return 1; }
/* ── Registra a library SDL2 estaticamente ────────────────────────────── */ /* -- Registra a library SDL2 estaticamente --- */
TinyBlocks_LibraryBlock* sdl2 = tb_library_register(rt, tb_sdl2_get_library()); TinyBlocks_LibraryBlock* sdl2 = tb_library_register(rt, tb_sdl2_get_library());
if (!sdl2) { if (!sdl2) {
fprintf(stderr, "Falha ao registrar SDL2: %s\n", tinyblocks_last_error(rt)); fprintf(stderr, "Falha ao registrar SDL2: %s\n", tinyblocks_last_error(rt));
@@ -25,7 +25,7 @@ int main(void)
printf("Library '%s' carregada com %u blocos\n", printf("Library '%s' carregada com %u blocos\n",
sdl2->base.name, sdl2->block_count); sdl2->base.name, sdl2->block_count);
/* ── Busca os TypeBlocks que vamos usar ───────────────────────────────── */ /* -- Busca os TypeBlocks que vamos usar --- */
TinyBlocks_TypeBlock* T_Init = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.Init"); 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_Quit = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.Quit");
TinyBlocks_TypeBlock* T_Window = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.Window"); TinyBlocks_TypeBlock* T_Window = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.Window");
@@ -39,11 +39,11 @@ int main(void)
TinyBlocks_TypeBlock* T_DestroyRend = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.DestroyRenderer"); TinyBlocks_TypeBlock* T_DestroyRend = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.DestroyRenderer");
TinyBlocks_TypeBlock* T_Delay = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.Delay"); TinyBlocks_TypeBlock* T_Delay = (TinyBlocks_TypeBlock*)tb_library_find(sdl2, "SDL2.Delay");
/* ── SDL2.Init ────────────────────────────────────────────────────────── */ /* -- SDL2.Init --- */
TinyBlocks_Block* b_init = tb_block_create(rt, T_Init); TinyBlocks_Block* b_init = tb_block_create(rt, T_Init);
tb_block_eval(b_init, rt); tb_block_eval(b_init, rt);
/* ── SDL2.Window ─────────────────────────────────────────────────────── */ /* -- SDL2.Window --- */
TinyBlocks_TextBlock* lit_title = tb_text_block_create(rt, "TinyBlocks SDL2"); 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_cx = tb_integer_block_create(rt, -1); /* centered */
TinyBlocks_IntegerBlock* lit_cy = tb_integer_block_create(rt, -1); TinyBlocks_IntegerBlock* lit_cy = tb_integer_block_create(rt, -1);
@@ -58,12 +58,12 @@ int main(void)
tb_block_connect(b_window, 4, &lit_h->base, 0); tb_block_connect(b_window, 4, &lit_h->base, 0);
tb_block_eval(b_window, rt); tb_block_eval(b_window, rt);
/* ── SDL2.Renderer ───────────────────────────────────────────────────── */ /* -- SDL2.Renderer --- */
TinyBlocks_Block* b_renderer = tb_block_create(rt, T_Renderer); TinyBlocks_Block* b_renderer = tb_block_create(rt, T_Renderer);
tb_block_connect(b_renderer, 0, b_window, 0); tb_block_connect(b_renderer, 0, b_window, 0);
tb_block_eval(b_renderer, rt); tb_block_eval(b_renderer, rt);
/* ── Blocos reutilizáveis por frame ──────────────────────────────────── */ /* -- Blocos reutilizáveis por frame --- */
TinyBlocks_Block* b_poll = tb_block_create(rt, T_PollEvent); TinyBlocks_Block* b_poll = tb_block_create(rt, T_PollEvent);
TinyBlocks_Block* b_bg_color = tb_block_create(rt, T_SetColor); TinyBlocks_Block* b_bg_color = tb_block_create(rt, T_SetColor);
TinyBlocks_Block* b_clear = tb_block_create(rt, T_Clear); TinyBlocks_Block* b_clear = tb_block_create(rt, T_Clear);
@@ -93,7 +93,7 @@ int main(void)
tb_block_connect(b_rect_color, 3, &lit_b2->base, 0); tb_block_connect(b_rect_color, 3, &lit_b2->base, 0);
tb_block_connect(b_rect_color, 4, &lit_255->base, 0); tb_block_connect(b_rect_color, 4, &lit_255->base, 0);
/* Retângulo dinâmico — usaremos IntegerBlocks mutáveis para posição */ /* Retângulo dinâmico - usaremos IntegerBlocks mutáveis para posição */
TinyBlocks_IntegerBlock* lit_rx = tb_integer_block_create(rt, 100); TinyBlocks_IntegerBlock* lit_rx = tb_integer_block_create(rt, 100);
TinyBlocks_IntegerBlock* lit_ry = 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_rw = tb_integer_block_create(rt, 200);
@@ -109,7 +109,7 @@ int main(void)
TinyBlocks_IntegerBlock* lit_delay = tb_integer_block_create(rt, 16); /* ~60fps */ TinyBlocks_IntegerBlock* lit_delay = tb_integer_block_create(rt, 16); /* ~60fps */
tb_block_connect(b_delay, 0, &lit_delay->base, 0); tb_block_connect(b_delay, 0, &lit_delay->base, 0);
/* ── Loop principal ──────────────────────────────────────────────────── */ /* -- Loop principal --- */
printf("Janela aberta. Pressione Escape ou feche a janela para sair.\n"); printf("Janela aberta. Pressione Escape ou feche a janela para sair.\n");
int running = 1; int running = 1;
@@ -135,7 +135,7 @@ int main(void)
: 1.0 - (frame % 60) / 60.0))); : 1.0 - (frame % 60) / 60.0)));
tb_integer_block_set(lit_rx, 80 + offset); tb_integer_block_set(lit_rx, 80 + offset);
/* Renderização — cada bloco é avaliado na ordem correta */ /* Renderização - cada bloco é avaliado na ordem correta */
b_bg_color->dirty = true; tb_block_eval(b_bg_color, rt); b_bg_color->dirty = true; tb_block_eval(b_bg_color, rt);
b_clear->dirty = true; tb_block_eval(b_clear, 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_color->dirty = true; tb_block_eval(b_rect_color, rt);
@@ -144,7 +144,7 @@ int main(void)
b_delay->dirty = true; tb_block_eval(b_delay, rt); b_delay->dirty = true; tb_block_eval(b_delay, rt);
} }
/* ── Limpeza SDL2 via blocos ──────────────────────────────────────────── */ /* -- Limpeza SDL2 via blocos --- */
TinyBlocks_Block* b_drend = tb_block_create(rt, T_DestroyRend); TinyBlocks_Block* b_drend = tb_block_create(rt, T_DestroyRend);
TinyBlocks_Block* b_dwin = tb_block_create(rt, T_DestroyWin); TinyBlocks_Block* b_dwin = tb_block_create(rt, T_DestroyWin);
TinyBlocks_Block* b_quit = tb_block_create(rt, T_Quit); TinyBlocks_Block* b_quit = tb_block_create(rt, T_Quit);
+20 -20
View File
@@ -1,16 +1,16 @@
/* /*
* vector.c — Library de vetor 2D para o TinyBlocks Editor. * vector.c - Library de vetor 2D para o TinyBlocks Editor.
* *
* Blocos incluídos: * Blocos incluídos:
* Vector.BeginPath — inicia um novo path (sem inputs) * Vector.BeginPath - inicia um novo path (sem inputs)
* Vector.MoveTo — move caneta para (x, y) * Vector.MoveTo - move caneta para (x, y)
* Vector.LineTo — linha até (x, y) * Vector.LineTo - linha até (x, y)
* Vector.ClosePath — fecha sub-path atual * Vector.ClosePath - fecha sub-path atual
* Vector.Stroke — aplica traçado com cor/espessura RGBA * Vector.Stroke - aplica traçado com cor/espessura RGBA
* Vector.Fill — aplica preenchimento RGBA ao path * Vector.Fill - aplica preenchimento RGBA ao path
* Vector.Rect — retângulo preenchido (usa Fill por cima) * Vector.Rect - retângulo preenchido (usa Fill por cima)
* Vector.Circle — círculo preenchido * Vector.Circle - círculo preenchido
* Vector.Render — recebe vector e desenha no corpo do bloco (on_draw) * 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 * 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. * um novo com o comando acrescentado. Combine-os com Vector.Render no final.
@@ -19,7 +19,7 @@
* make vector * make vector
* *
* Para carregar no editor: * Para carregar no editor:
* Ctrl+O → build/vector.so ou arraste build/vector.so para a janela * Ctrl+O -> build/vector.so ou arraste build/vector.so para a janela
*/ */
#define _POSIX_C_SOURCE 200809L #define _POSIX_C_SOURCE 200809L
@@ -29,7 +29,7 @@
#include <tinyblocks/tinyblocks.h> #include <tinyblocks/tinyblocks.h>
#include <tinyblocks/tb_renderable_block.h> #include <tinyblocks/tb_renderable_block.h>
/* ── Helper: lê float de qualquer slot numérico ──────────────────────────── */ /* -- Helper: lê float de qualquer slot numérico --- */
static float gf(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) { static float gf(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t idx) {
TinyBlocks_Value v = tb_block_get_input(self, rt, 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_REAL) return (float)v.as.real;
@@ -51,9 +51,9 @@ static TinyBlocks_VectorData* clone_vec(TinyBlocks_Block* self, TinyBlocks* rt)
(self)->dirty = false; \ (self)->dirty = false; \
} while(0) } while(0)
/* ══════════════════════════════════════════════════════════════════════════ /* ===
* Implementações dos blocos * Implementações dos blocos
* ══════════════════════════════════════════════════════════════════════════ */ * === */
static void eval_begin_path(TinyBlocks_Block* self, TinyBlocks* rt) { static void eval_begin_path(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)rt; (void)rt;
@@ -115,7 +115,7 @@ static void eval_circle(TinyBlocks_Block* self, TinyBlocks* rt) {
EMIT_VEC(self, v); EMIT_VEC(self, v);
} }
/* Vector.Render — passa o vetor adiante e tem on_render para preview */ /* Vector.Render - passa o vetor adiante e tem on_render para preview */
static void eval_render(TinyBlocks_Block* self, TinyBlocks* rt) { static void eval_render(TinyBlocks_Block* self, TinyBlocks* rt) {
TinyBlocks_Value v = tb_block_get_input(self, rt, 0); TinyBlocks_Value v = tb_block_get_input(self, rt, 0);
/* Clona para manter o vector vivo no output (get_input é não-owning) */ /* Clona para manter o vector vivo no output (get_input é não-owning) */
@@ -138,9 +138,9 @@ static bool on_draw_vector(TinyBlocks_Block* self, TinyBlocks* rt,
return true; return true;
} }
/* ══════════════════════════════════════════════════════════════════════════ /* ===
* Descritores de slots * Descritores de slots
* ══════════════════════════════════════════════════════════════════════════ */ * === */
static const TinyBlocks_SlotDesc out_vec[] = {{"vec", TB_VALUE_VECTOR}}; 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[] = {{"vec", TB_VALUE_VECTOR}};
static const TinyBlocks_SlotDesc in_vec_xy[] = {{"vec", TB_VALUE_VECTOR}, static const TinyBlocks_SlotDesc in_vec_xy[] = {{"vec", TB_VALUE_VECTOR},
@@ -167,9 +167,9 @@ static const TinyBlocks_SlotDesc in_vec_cyr[] = {{"vec", TB_VALUE_VECTOR},
{"cy", TB_VALUE_REAL}, {"cy", TB_VALUE_REAL},
{"r", TB_VALUE_REAL}}; {"r", TB_VALUE_REAL}};
/* ══════════════════════════════════════════════════════════════════════════ /* ===
* Registro da library * Registro da library
* ══════════════════════════════════════════════════════════════════════════ */ * === */
static bool vector_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { static bool vector_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
TinyBlocks_TypeBlock* t; TinyBlocks_TypeBlock* t;
@@ -188,7 +188,7 @@ static bool vector_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
#undef REG #undef REG
/* Vector.Render tem on_draw — preview gráfico no corpo do bloco */ /* Vector.Render tem on_draw - preview gráfico no corpo do bloco */
t = tb_type_block_create(rt, "Vector.Render", t = tb_type_block_create(rt, "Vector.Render",
in_vec, 1, out_vec, 1, eval_render); in_vec, 1, out_vec, 1, eval_render);
if (t) { if (t) {
+10 -10
View File
@@ -1,16 +1,16 @@
/* /*
* TinyBlocks — tb_block.h * TinyBlocks - tb_block.h
* Estrutura base de todo bloco e operações polimórficas via vtable. * Estrutura base de todo bloco e operações polimórficas via vtable.
* *
* Todos os tipos concretos (TypeBlock, LibraryBlock, TextBlock…) começam com * Todos os tipos concretos (TypeBlock, LibraryBlock, TextBlock...) começam com
* um campo `TinyBlocks_Block base` — herança em C via primeiro membro. * um campo `TinyBlocks_Block base` - herança em C via primeiro membro.
*/ */
#ifndef TINYBLOCKS_BLOCK_H #ifndef TINYBLOCKS_BLOCK_H
#define TINYBLOCKS_BLOCK_H #define TINYBLOCKS_BLOCK_H
#include "tb_defs.h" #include "tb_defs.h"
/* ── Vtable de bloco ─────────────────────────────────────────────────────── */ /* -- Vtable de bloco --- */
typedef struct TinyBlocks_BlockVTable { typedef struct TinyBlocks_BlockVTable {
/* Avalia o bloco: lê inputs, processa, escreve outputs */ /* Avalia o bloco: lê inputs, processa, escreve outputs */
void (*eval) (TinyBlocks_Block* self, TinyBlocks* rt); void (*eval) (TinyBlocks_Block* self, TinyBlocks* rt);
@@ -23,7 +23,7 @@ typedef struct TinyBlocks_BlockVTable {
TinyBlocks_Block* (*clone) (const TinyBlocks_Block* self, TinyBlocks* rt); TinyBlocks_Block* (*clone) (const TinyBlocks_Block* self, TinyBlocks* rt);
} TinyBlocks_BlockVTable; } TinyBlocks_BlockVTable;
/* ── Estrutura base de todo bloco ────────────────────────────────────────── */ /* -- Estrutura base de todo bloco --- */
struct TinyBlocks_Block { struct TinyBlocks_Block {
TinyBlocks_BlockKind kind; TinyBlocks_BlockKind kind;
const TinyBlocks_BlockVTable* vtable; const TinyBlocks_BlockVTable* vtable;
@@ -48,7 +48,7 @@ struct TinyBlocks_Block {
bool in_eval; /* guard anti-ciclo */ bool in_eval; /* guard anti-ciclo */
}; };
/* ── Ciclo de vida ───────────────────────────────────────────────────────── */ /* -- Ciclo de vida --- */
/* Cria um bloco a partir de um TypeBlock; registra no runtime */ /* Cria um bloco a partir de um TypeBlock; registra no runtime */
TB_API TinyBlocks_Block* tb_block_create (TinyBlocks* rt, TinyBlocks_TypeBlock* type); TB_API TinyBlocks_Block* tb_block_create (TinyBlocks* rt, TinyBlocks_TypeBlock* type);
@@ -62,14 +62,14 @@ TB_API TinyBlocks_Block* tb_block_clone (const TinyBlocks_Block* block, TinyBlo
TB_API size_t tb_block_to_string(TinyBlocks_Block* block, TinyBlocks* rt, TB_API size_t tb_block_to_string(TinyBlocks_Block* block, TinyBlocks* rt,
char* buf, size_t buf_size); char* buf, size_t buf_size);
/* ── Conexões ────────────────────────────────────────────────────────────── */ /* -- Conexões --- */
TB_API bool tb_block_connect (TinyBlocks_Block* target, uint32_t input_idx, TB_API bool tb_block_connect (TinyBlocks_Block* target, uint32_t input_idx,
TinyBlocks_Block* source, uint32_t output_idx); TinyBlocks_Block* source, uint32_t output_idx);
TB_API void tb_block_disconnect(TinyBlocks_Block* target, uint32_t input_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, TB_API bool tb_block_set_default(TinyBlocks_Block* target, uint32_t input_idx,
TinyBlocks_Value default_value); TinyBlocks_Value default_value);
/* ── Acesso a valores (para uso dentro de eval_fn) ───────────────────────── */ /* -- Acesso a valores (para uso dentro de eval_fn) --- */
/* Retorna o valor do input[idx]; resolve a conexão se necessário */ /* 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, TB_API TinyBlocks_Value tb_block_get_input (TinyBlocks_Block* self, TinyBlocks* rt,
uint32_t input_idx); uint32_t input_idx);
@@ -77,14 +77,14 @@ TB_API TinyBlocks_Value tb_block_get_input (TinyBlocks_Block* self, TinyBlocks*
TB_API void tb_block_set_output(TinyBlocks_Block* self, TB_API void tb_block_set_output(TinyBlocks_Block* self,
uint32_t output_idx, TinyBlocks_Value v); uint32_t output_idx, TinyBlocks_Value v);
/* ── Downcasting seguro ──────────────────────────────────────────────────── */ /* -- Downcasting seguro --- */
TB_API TinyBlocks_TypeBlock* tb_block_as_type (TinyBlocks_Block* b); 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_LibraryBlock* tb_block_as_library(TinyBlocks_Block* b);
TB_API TinyBlocks_TextBlock* tb_block_as_text (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_IntegerBlock* tb_block_as_integer(TinyBlocks_Block* b);
TB_API TinyBlocks_RealBlock* tb_block_as_real (TinyBlocks_Block* b); TB_API TinyBlocks_RealBlock* tb_block_as_real (TinyBlocks_Block* b);
/* ── Helpers internos (usados por implementações de built-ins) ───────────── */ /* -- Helpers internos (usados por implementações de built-ins) --- */
TB_API TinyBlocks_Block* tb_block_alloc_base(TinyBlocks* rt, TB_API TinyBlocks_Block* tb_block_alloc_base(TinyBlocks* rt,
TinyBlocks_BlockKind kind, TinyBlocks_BlockKind kind,
size_t struct_size, size_t struct_size,
+12 -12
View File
@@ -1,5 +1,5 @@
/* /*
* TinyBlocks — tb_defs.h * TinyBlocks - tb_defs.h
* Forward declarations, enums e tipos primitivos compartilhados por todo o runtime. * Forward declarations, enums e tipos primitivos compartilhados por todo o runtime.
*/ */
#ifndef TINYBLOCKS_DEFS_H #ifndef TINYBLOCKS_DEFS_H
@@ -9,14 +9,14 @@
#include <stdint.h> #include <stdint.h>
#include <stdbool.h> #include <stdbool.h>
/* ── Visibilidade de API ─────────────────────────────────────────────────── */ /* -- Visibilidade de API --- */
#ifdef _WIN32 #ifdef _WIN32
# define TB_API __declspec(dllexport) # define TB_API __declspec(dllexport)
#else #else
# define TB_API __attribute__((visibility("default"))) # define TB_API __attribute__((visibility("default")))
#endif #endif
/* ── Forward declarations ────────────────────────────────────────────────── */ /* -- Forward declarations --- */
typedef struct TinyBlocks TinyBlocks; typedef struct TinyBlocks TinyBlocks;
typedef struct TinyBlocks_Block TinyBlocks_Block; typedef struct TinyBlocks_Block TinyBlocks_Block;
typedef struct TinyBlocks_TypeBlock TinyBlocks_TypeBlock; typedef struct TinyBlocks_TypeBlock TinyBlocks_TypeBlock;
@@ -29,7 +29,7 @@ typedef struct TinyBlocks_VectorData TinyBlocks_VectorData;
typedef struct TinyBlocks_RenderableBlock TinyBlocks_RenderableBlock; typedef struct TinyBlocks_RenderableBlock TinyBlocks_RenderableBlock;
typedef struct TinyBlocks_JsonValue TinyBlocks_JsonValue; typedef struct TinyBlocks_JsonValue TinyBlocks_JsonValue;
/* ── Kinds de bloco ──────────────────────────────────────────────────────── */ /* -- Kinds de bloco --- */
typedef enum TinyBlocks_BlockKind { typedef enum TinyBlocks_BlockKind {
TB_KIND_BLOCK = 0, /* bloco genérico / definido pelo usuário */ TB_KIND_BLOCK = 0, /* bloco genérico / definido pelo usuário */
TB_KIND_TYPE = 1, /* TinyBlocks_TypeBlock */ TB_KIND_TYPE = 1, /* TinyBlocks_TypeBlock */
@@ -40,7 +40,7 @@ typedef enum TinyBlocks_BlockKind {
TB_KIND_VECTOR = 6, /* TinyBlocks_VectorBlock */ TB_KIND_VECTOR = 6, /* TinyBlocks_VectorBlock */
} TinyBlocks_BlockKind; } TinyBlocks_BlockKind;
/* ── Kinds de valor (para slots) ─────────────────────────────────────────── */ /* -- Kinds de valor (para slots) --- */
typedef enum TinyBlocks_ValueKind { typedef enum TinyBlocks_ValueKind {
TB_VALUE_NONE = 0, TB_VALUE_NONE = 0,
TB_VALUE_INTEGER = 1, TB_VALUE_INTEGER = 1,
@@ -51,7 +51,7 @@ typedef enum TinyBlocks_ValueKind {
TB_VALUE_JSON = 6, /* valor JSON (ref-counted) */ TB_VALUE_JSON = 6, /* valor JSON (ref-counted) */
} TinyBlocks_ValueKind; } TinyBlocks_ValueKind;
/* ── Valor com tag (flui entre slots) ────────────────────────────────────── */ /* -- Valor com tag (flui entre slots) --- */
typedef struct TinyBlocks_Value { typedef struct TinyBlocks_Value {
TinyBlocks_ValueKind kind; TinyBlocks_ValueKind kind;
union { union {
@@ -64,9 +64,9 @@ typedef struct TinyBlocks_Value {
} as; } as;
} TinyBlocks_Value; } TinyBlocks_Value;
/* ══════════════════════════════════════════════════════════════════════════ /* ===
* Dados de vetor 2D (fluxo de comandos de desenho, ref-counted) * Dados de vetor 2D (fluxo de comandos de desenho, ref-counted)
* ══════════════════════════════════════════════════════════════════════════ */ * === */
typedef enum TinyBlocks_VCmdKind { typedef enum TinyBlocks_VCmdKind {
TB_VCMD_BEGIN_PATH = 0, /* nenhum arg */ TB_VCMD_BEGIN_PATH = 0, /* nenhum arg */
TB_VCMD_MOVE_TO, /* args[0]=x, args[1]=y */ TB_VCMD_MOVE_TO, /* args[0]=x, args[1]=y */
@@ -87,24 +87,24 @@ struct TinyBlocks_VectorData {
}; };
/* ── Descritor de slot (em TypeBlock — descreve a forma dos inputs/outputs) ─ */ /* -- Descritor de slot (em TypeBlock - descreve a forma dos inputs/outputs) - */
typedef struct TinyBlocks_SlotDesc { typedef struct TinyBlocks_SlotDesc {
const char* name; const char* name;
TinyBlocks_ValueKind expected_kind; /* TB_VALUE_NONE = aceita qualquer tipo */ TinyBlocks_ValueKind expected_kind; /* TB_VALUE_NONE = aceita qualquer tipo */
} TinyBlocks_SlotDesc; } TinyBlocks_SlotDesc;
/* ── Conexão de entrada (de qual bloco/slot este input lê) ───────────────── */ /* -- Conexão de entrada (de qual bloco/slot este input lê) --- */
typedef struct TinyBlocks_Connection { typedef struct TinyBlocks_Connection {
TinyBlocks_Block* source; /* bloco de origem (NULL se não conectado) */ TinyBlocks_Block* source; /* bloco de origem (NULL se não conectado) */
uint32_t output_idx; /* qual output slot da origem */ uint32_t output_idx; /* qual output slot da origem */
TinyBlocks_Value default_value; /* valor quando não há conexão */ TinyBlocks_Value default_value; /* valor quando não há conexão */
} TinyBlocks_Connection; } TinyBlocks_Connection;
/* ── Alocador customizável ───────────────────────────────────────────────── */ /* -- Alocador customizável --- */
typedef void* (*TinyBlocks_AllocFn)(size_t size, void* userdata); typedef void* (*TinyBlocks_AllocFn)(size_t size, void* userdata);
typedef void (*TinyBlocks_FreeFn) (void* ptr, void* userdata); typedef void (*TinyBlocks_FreeFn) (void* ptr, void* userdata);
/* ── Helpers para TinyBlocks_Value ──────────────────────────────────────── */ /* -- Helpers para TinyBlocks_Value --- */
TB_API TinyBlocks_Value tb_value_none(void); TB_API TinyBlocks_Value tb_value_none(void);
TB_API TinyBlocks_Value tb_value_integer(int64_t v); 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_real(double v);
+3 -3
View File
@@ -1,5 +1,5 @@
/* /*
* TinyBlocks — tb_integer_block.h * TinyBlocks - tb_integer_block.h
* TinyBlocks_IntegerBlock: bloco primitivo que contém um inteiro de 64 bits. * 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). * IntegerBlocks são literais: têm 0 inputs e 1 output (TB_VALUE_INTEGER).
@@ -14,12 +14,12 @@ struct TinyBlocks_IntegerBlock {
int64_t value; int64_t value;
}; };
/* ── Ciclo de vida ───────────────────────────────────────────────────────── */ /* -- Ciclo de vida --- */
TB_API TinyBlocks_IntegerBlock* tb_integer_block_create (TinyBlocks* rt, int64_t value); TB_API TinyBlocks_IntegerBlock* tb_integer_block_create (TinyBlocks* rt, int64_t value);
TB_API void tb_integer_block_destroy(TinyBlocks_IntegerBlock* ib, TB_API void tb_integer_block_destroy(TinyBlocks_IntegerBlock* ib,
TinyBlocks* rt); TinyBlocks* rt);
/* ── Acesso ao valor ─────────────────────────────────────────────────────── */ /* -- Acesso ao valor --- */
TB_API int64_t tb_integer_block_get(const TinyBlocks_IntegerBlock* ib); 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); TB_API void tb_integer_block_set(TinyBlocks_IntegerBlock* ib, int64_t value);
+7 -7
View File
@@ -1,5 +1,5 @@
/* /*
* TinyBlocks — tb_json_block.h * TinyBlocks - tb_json_block.h
* TinyBlocks_JsonValue: árvore JSON imutável e ref-counted que flui como valor * TinyBlocks_JsonValue: árvore JSON imutável e ref-counted que flui como valor
* entre blocos (TB_VALUE_JSON). * entre blocos (TB_VALUE_JSON).
* *
@@ -28,7 +28,7 @@ typedef enum TinyBlocks_JsonKind {
TB_JSON_OBJECT = 5, TB_JSON_OBJECT = 5,
} TinyBlocks_JsonKind; } TinyBlocks_JsonKind;
/* ── Ciclo de vida ───────────────────────────────────────────────────────── */ /* -- Ciclo de vida --- */
TB_API TinyBlocks_JsonValue* tb_json_null (void); TB_API TinyBlocks_JsonValue* tb_json_null (void);
TB_API TinyBlocks_JsonValue* tb_json_bool (bool b); TB_API TinyBlocks_JsonValue* tb_json_bool (bool b);
TB_API TinyBlocks_JsonValue* tb_json_number(double d); TB_API TinyBlocks_JsonValue* tb_json_number(double d);
@@ -40,7 +40,7 @@ TB_API void tb_json_retain (TinyBlocks_JsonValue* j);
TB_API void tb_json_release(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 */ TB_API TinyBlocks_JsonValue* tb_json_clone (const TinyBlocks_JsonValue* j); /* deep copy */
/* ── Inspeção ────────────────────────────────────────────────────────────── */ /* -- Inspeção --- */
TB_API TinyBlocks_JsonKind tb_json_kind (const TinyBlocks_JsonValue* j); 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 const char* tb_json_kind_name(const TinyBlocks_JsonValue* j);
@@ -48,24 +48,24 @@ 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 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 */ 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) ───────── */ /* -- 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 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 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 */ 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) ──────── */ /* -- 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 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 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 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 */ TB_API TinyBlocks_JsonValue* tb_json_object_get(const TinyBlocks_JsonValue* obj, const char* key); /* ref nova, ou NULL */
/* ── Parsing / serialização ──────────────────────────────────────────────── */ /* -- Parsing / serialização --- */
/* Retorna NULL em erro de sintaxe; se errbuf não for NULL, escreve a mensagem. */ /* 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); 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). */ /* Serializa para texto; retorna buffer heap-alocado (free() do chamador). */
TB_API char* tb_json_stringify(const TinyBlocks_JsonValue* j); TB_API char* tb_json_stringify(const TinyBlocks_JsonValue* j);
/* ── Helpers para TinyBlocks_Value ──────────────────────────────────────── */ /* -- Helpers para TinyBlocks_Value --- */
TB_API TinyBlocks_Value tb_value_json (TinyBlocks_JsonValue* j); /* retém ref */ TB_API TinyBlocks_Value tb_value_json (TinyBlocks_JsonValue* j); /* retém ref */
TB_API TinyBlocks_JsonValue* tb_value_as_json(TinyBlocks_Value v); TB_API TinyBlocks_JsonValue* tb_value_as_json(TinyBlocks_Value v);
+3 -3
View File
@@ -1,5 +1,5 @@
/* /*
* TinyBlocks — tb_real_block.h * TinyBlocks - tb_real_block.h
* TinyBlocks_RealBlock: bloco primitivo que contém um número real (double). * 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). * RealBlocks são literais: têm 0 inputs e 1 output (TB_VALUE_REAL).
@@ -14,12 +14,12 @@ struct TinyBlocks_RealBlock {
double value; double value;
}; };
/* ── Ciclo de vida ───────────────────────────────────────────────────────── */ /* -- Ciclo de vida --- */
TB_API TinyBlocks_RealBlock* tb_real_block_create (TinyBlocks* rt, double value); TB_API TinyBlocks_RealBlock* tb_real_block_create (TinyBlocks* rt, double value);
TB_API void tb_real_block_destroy(TinyBlocks_RealBlock* rb, TB_API void tb_real_block_destroy(TinyBlocks_RealBlock* rb,
TinyBlocks* rt); TinyBlocks* rt);
/* ── Acesso ao valor ─────────────────────────────────────────────────────── */ /* -- Acesso ao valor --- */
TB_API double tb_real_block_get(const TinyBlocks_RealBlock* rb); TB_API double tb_real_block_get(const TinyBlocks_RealBlock* rb);
TB_API void tb_real_block_set(TinyBlocks_RealBlock* rb, double value); TB_API void tb_real_block_set(TinyBlocks_RealBlock* rb, double value);
+6 -6
View File
@@ -1,5 +1,5 @@
/* /*
* TinyBlocks — tb_renderable_block.h * TinyBlocks - tb_renderable_block.h
* *
* TinyBlocks_RenderableBlock: lista de comandos de desenho produzida por on_draw. * TinyBlocks_RenderableBlock: lista de comandos de desenho produzida por on_draw.
* O backend (ex: SDL2.App) interpreta os comandos para renderizar na tela. * O backend (ex: SDL2.App) interpreta os comandos para renderizar na tela.
@@ -22,13 +22,13 @@
#include "tb_defs.h" #include "tb_defs.h"
/* ── Tipos de comando ──────────────────────────────────────────────────────── */ /* -- Tipos de comando --- */
typedef enum { typedef enum {
TB_DRAW_CLEAR, /* limpa toda a área com uma cor */ TB_DRAW_CLEAR, /* limpa toda a área com uma cor */
TB_DRAW_FILL_RECT, /* retângulo preenchido */ TB_DRAW_FILL_RECT, /* retângulo preenchido */
TB_DRAW_FILL_RRECT, /* retângulo com cantos arredondados (param=radius) */ 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_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_LINE, /* linha (x,y -> w,h como x2,y2; param=espessura) */
TB_DRAW_STROKE_RECT, /* contorno de retângulo (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_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_SET_CLIP, /* define rect de clip (coordenadas tela) */
@@ -45,7 +45,7 @@ typedef struct {
char text[128]; /* conteúdo do texto (TB_DRAW_TEXT) */ char text[128]; /* conteúdo do texto (TB_DRAW_TEXT) */
} TinyBlocks_DrawCmd; } TinyBlocks_DrawCmd;
/* ── RenderableBlock ───────────────────────────────────────────────────────── */ /* -- RenderableBlock --- */
#define TB_DRAW_CMD_CAP 8192 #define TB_DRAW_CMD_CAP 8192
struct TinyBlocks_RenderableBlock { struct TinyBlocks_RenderableBlock {
@@ -53,7 +53,7 @@ struct TinyBlocks_RenderableBlock {
uint32_t count; uint32_t count;
}; };
/* ── Pool de renderables (reset por frame, sem malloc durante o loop) ──────── */ /* -- Pool de renderables (reset por frame, sem malloc durante o loop) --- */
/* Adquire um renderable limpo do pool. Retorna NULL se esgotado. */ /* Adquire um renderable limpo do pool. Retorna NULL se esgotado. */
TB_API TinyBlocks_RenderableBlock* tb_renderable_acquire(void); TB_API TinyBlocks_RenderableBlock* tb_renderable_acquire(void);
@@ -65,7 +65,7 @@ TB_API void tb_renderable_release(TinyBlocks_RenderableBlock* rb);
depois que o backend terminar de renderizar). */ depois que o backend terminar de renderizar). */
TB_API void tb_renderable_release_all(void); TB_API void tb_renderable_release_all(void);
/* ── Helpers para acrescentar comandos ────────────────────────────────────── */ /* -- Helpers para acrescentar comandos --- */
TB_API void tb_draw_clear (TinyBlocks_RenderableBlock* rb, TB_API void tb_draw_clear (TinyBlocks_RenderableBlock* rb,
float r, float g, float b, float a); float r, float g, float b, float a);
+3 -3
View File
@@ -1,5 +1,5 @@
/* /*
* TinyBlocks — tb_text_block.h * TinyBlocks - tb_text_block.h
* TinyBlocks_TextBlock: bloco primitivo que contém um valor textual. * TinyBlocks_TextBlock: bloco primitivo que contém um valor textual.
* *
* TextBlocks são literais: têm 0 inputs e 1 output (TB_VALUE_TEXT). * TextBlocks são literais: têm 0 inputs e 1 output (TB_VALUE_TEXT).
@@ -15,12 +15,12 @@ struct TinyBlocks_TextBlock {
char* value; /* string heap-owned */ char* value; /* string heap-owned */
}; };
/* ── Ciclo de vida ───────────────────────────────────────────────────────── */ /* -- Ciclo de vida --- */
TB_API TinyBlocks_TextBlock* tb_text_block_create (TinyBlocks* rt, const char* value); TB_API TinyBlocks_TextBlock* tb_text_block_create (TinyBlocks* rt, const char* value);
TB_API void tb_text_block_destroy(TinyBlocks_TextBlock* tb, TB_API void tb_text_block_destroy(TinyBlocks_TextBlock* tb,
TinyBlocks* rt); TinyBlocks* rt);
/* ── Acesso ao valor ─────────────────────────────────────────────────────── */ /* -- Acesso ao valor --- */
TB_API const char* tb_text_block_get(const TinyBlocks_TextBlock* tb); 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); TB_API void tb_text_block_set(TinyBlocks_TextBlock* tb, const char* value);
+7 -7
View File
@@ -1,13 +1,13 @@
/* /*
* TinyBlocks — tb_type_block.h * TinyBlocks - tb_type_block.h
* TinyBlocks_TypeBlock: representa a "classe" de um bloco. * TinyBlocks_TypeBlock: representa a "classe" de um bloco.
* *
* Um TypeBlock define: * Um TypeBlock define:
* • O nome do tipo * * O nome do tipo
* • Os descritores de slots (inputs e outputs) * * Os descritores de slots (inputs e outputs)
* • A função de avaliação para instâncias * * A função de avaliação para instâncias
* • Hooks de init/deinit por instância * * Hooks de init/deinit por instância
* • Tamanho extra de userdata para instâncias * * Tamanho extra de userdata para instâncias
* *
* TypeBlocks são eles mesmos blocos (base.kind == TB_KIND_TYPE). * TypeBlocks são eles mesmos blocos (base.kind == TB_KIND_TYPE).
*/ */
@@ -45,7 +45,7 @@ struct TinyBlocks_TypeBlock {
TinyBlocks_RenderableBlock** dst); TinyBlocks_RenderableBlock** dst);
}; };
/* ── Criação de TypeBlock ────────────────────────────────────────────────── */ /* -- Criação de TypeBlock --- */
/* Cria e registra um TypeBlock no runtime */ /* Cria e registra um TypeBlock no runtime */
TB_API TinyBlocks_TypeBlock* tb_type_block_create( TB_API TinyBlocks_TypeBlock* tb_type_block_create(
+7 -7
View File
@@ -1,5 +1,5 @@
/* /*
* TinyBlocks — tb_vector_block.h * TinyBlocks - tb_vector_block.h
* TinyBlocks_VectorBlock: bloco que armazena dados de vetor 2D. * TinyBlocks_VectorBlock: bloco que armazena dados de vetor 2D.
* TinyBlocks_VectorData: comandos de desenho ref-counted que fluem como valores. * TinyBlocks_VectorData: comandos de desenho ref-counted que fluem como valores.
* *
@@ -22,13 +22,13 @@
#include "tb_block.h" #include "tb_block.h"
#include "tb_renderable_block.h" #include "tb_renderable_block.h"
/* ── TinyBlocks_VectorBlock — bloco que contém VectorData ───────────────── */ /* -- TinyBlocks_VectorBlock - bloco que contém VectorData --- */
struct TinyBlocks_VectorBlock { struct TinyBlocks_VectorBlock {
TinyBlocks_Block base; /* DEVE ser o primeiro campo */ TinyBlocks_Block base; /* DEVE ser o primeiro campo */
TinyBlocks_VectorData* data; TinyBlocks_VectorData* data;
}; };
/* ── Ciclo de vida de VectorData ────────────────────────────────────────── */ /* -- Ciclo de vida de VectorData --- */
TB_API TinyBlocks_VectorData* tb_vector_data_create (void); 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_retain (TinyBlocks_VectorData* v);
TB_API void tb_vector_data_release(TinyBlocks_VectorData* v); TB_API void tb_vector_data_release(TinyBlocks_VectorData* v);
@@ -36,7 +36,7 @@ TB_API TinyBlocks_VectorData* tb_vector_data_clone (const TinyBlocks_VectorData
TB_API bool tb_vector_data_push (TinyBlocks_VectorData* v, TB_API bool tb_vector_data_push (TinyBlocks_VectorData* v,
TinyBlocks_VCmd cmd); TinyBlocks_VCmd cmd);
/* ── Construtores de comandos ────────────────────────────────────────────── */ /* -- Construtores de comandos --- */
TB_API bool tb_vector_begin_path(TinyBlocks_VectorData* v); 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_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_line_to (TinyBlocks_VectorData* v, float x, float y);
@@ -50,16 +50,16 @@ TB_API bool tb_vector_rect (TinyBlocks_VectorData* v,
TB_API bool tb_vector_circle (TinyBlocks_VectorData* v, TB_API bool tb_vector_circle (TinyBlocks_VectorData* v,
float cx, float cy, float radius); float cx, float cy, float radius);
/* ── Helpers para TinyBlocks_Value ──────────────────────────────────────── */ /* -- Helpers para TinyBlocks_Value --- */
TB_API TinyBlocks_Value tb_value_vector (TinyBlocks_VectorData* v); TB_API TinyBlocks_Value tb_value_vector (TinyBlocks_VectorData* v);
TB_API TinyBlocks_VectorData* tb_value_as_vector(TinyBlocks_Value v); TB_API TinyBlocks_VectorData* tb_value_as_vector(TinyBlocks_Value v);
/* ── VectorBlock (bloco no grafo) ────────────────────────────────────────── */ /* -- VectorBlock (bloco no grafo) --- */
TB_API TinyBlocks_VectorBlock* tb_vector_block_create (TinyBlocks* rt); TB_API TinyBlocks_VectorBlock* tb_vector_block_create (TinyBlocks* rt);
TB_API void tb_vector_block_set_data (TinyBlocks_VectorBlock* b, TB_API void tb_vector_block_set_data (TinyBlocks_VectorBlock* b,
TinyBlocks_VectorData* v); TinyBlocks_VectorData* v);
/* ── Reprodução de VectorData via RenderableBlock ───────────────────────── */ /* -- Reprodução de VectorData via RenderableBlock --- */
TB_API void tb_draw_ctx_play(TinyBlocks_RenderableBlock* rb, TinyBlocks_VectorData* v); TB_API void tb_draw_ctx_play(TinyBlocks_RenderableBlock* rb, TinyBlocks_VectorData* v);
#endif /* TINYBLOCKS_VECTOR_BLOCK_H */ #endif /* TINYBLOCKS_VECTOR_BLOCK_H */
+10 -10
View File
@@ -1,9 +1,9 @@
/* /*
* TinyBlocks — tinyblocks.h * TinyBlocks - tinyblocks.h
* Cabeçalho principal do runtime. Inclua apenas este arquivo. * Cabeçalho principal do runtime. Inclua apenas este arquivo.
* *
* O struct TinyBlocks é o runtime da linguagem. Ele é completamente separado * O struct TinyBlocks é o runtime da linguagem. Ele é completamente separado
* de qualquer interface gráfica — GUIs são implementadas como LibraryBlocks. * de qualquer interface gráfica - GUIs são implementadas como LibraryBlocks.
* *
* Fluxo de uso mínimo: * Fluxo de uso mínimo:
* *
@@ -36,7 +36,7 @@
#include "tb_vector_block.h" #include "tb_vector_block.h"
#include "tb_json_block.h" #include "tb_json_block.h"
/* ── Runtime ─────────────────────────────────────────────────────────────── */ /* -- Runtime --- */
struct TinyBlocks { struct TinyBlocks {
/* Alocador (padrão: malloc/free) */ /* Alocador (padrão: malloc/free) */
TinyBlocks_AllocFn alloc; TinyBlocks_AllocFn alloc;
@@ -70,7 +70,7 @@ struct TinyBlocks {
char error[512]; char error[512];
}; };
/* ── Opções de inicialização ─────────────────────────────────────────────── */ /* -- Opções de inicialização --- */
typedef struct TinyBlocks_InitOptions { typedef struct TinyBlocks_InitOptions {
TinyBlocks_AllocFn alloc; /* NULL = malloc padrão */ TinyBlocks_AllocFn alloc; /* NULL = malloc padrão */
TinyBlocks_FreeFn free_fn; /* NULL = free padrão */ TinyBlocks_FreeFn free_fn; /* NULL = free padrão */
@@ -80,11 +80,11 @@ typedef struct TinyBlocks_InitOptions {
uint32_t initial_library_cap; /* 0 = 16 */ uint32_t initial_library_cap; /* 0 = 16 */
} TinyBlocks_InitOptions; } TinyBlocks_InitOptions;
/* ── Ciclo de vida do runtime ────────────────────────────────────────────── */ /* -- Ciclo de vida do runtime --- */
TB_API bool tinyblocks_init (TinyBlocks** out_rt, const TinyBlocks_InitOptions* opts); TB_API bool tinyblocks_init (TinyBlocks** out_rt, const TinyBlocks_InitOptions* opts);
TB_API void tinyblocks_deinit(TinyBlocks** rt); TB_API void tinyblocks_deinit(TinyBlocks** rt);
/* ── Registro interno (usado pelas implementações de bloco) ─────────────── */ /* -- Registro interno (usado pelas implementações de bloco) --- */
TB_API bool tb_rt_register_block (TinyBlocks* rt, TinyBlocks_Block* block); 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 void tb_rt_unregister_block(TinyBlocks* rt, TinyBlocks_Block* block);
TB_API bool tb_rt_register_type (TinyBlocks* rt, TinyBlocks_TypeBlock* type); TB_API bool tb_rt_register_type (TinyBlocks* rt, TinyBlocks_TypeBlock* type);
@@ -92,22 +92,22 @@ TB_API void tb_rt_unregister_type (TinyBlocks* rt, TinyBlocks_TypeBlock* typ
TB_API bool tb_rt_register_library(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib); TB_API bool tb_rt_register_library(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib);
TB_API void tb_rt_unregister_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 ─────────────────────────────────── */ /* -- Alocação com o alocador do runtime --- */
TB_API void* tb_alloc(TinyBlocks* rt, size_t size); TB_API void* tb_alloc(TinyBlocks* rt, size_t size);
TB_API void tb_free (TinyBlocks* rt, void* ptr); TB_API void tb_free (TinyBlocks* rt, void* ptr);
TB_API char* tb_strdup(TinyBlocks* rt, const char* str); TB_API char* tb_strdup(TinyBlocks* rt, const char* str);
/* ── Diagnósticos ────────────────────────────────────────────────────────── */ /* -- Diagnósticos --- */
TB_API const char* tinyblocks_last_error(TinyBlocks* rt); TB_API const char* tinyblocks_last_error(TinyBlocks* rt);
TB_API void tinyblocks_set_error (TinyBlocks* rt, const char* fmt, ...); TB_API void tinyblocks_set_error (TinyBlocks* rt, const char* fmt, ...);
TB_API void tinyblocks_clear_error(TinyBlocks* rt); TB_API void tinyblocks_clear_error(TinyBlocks* rt);
/* ── Busca no registro ───────────────────────────────────────────────────── */ /* -- Busca no registro --- */
TB_API TinyBlocks_Block* tb_rt_find_block (TinyBlocks* rt, uint64_t id); 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_TypeBlock* tb_rt_find_type (TinyBlocks* rt, const char* name);
TB_API TinyBlocks_LibraryBlock* tb_rt_find_library(TinyBlocks* rt, const char* name); TB_API TinyBlocks_LibraryBlock* tb_rt_find_library(TinyBlocks* rt, const char* name);
/* ── Geração de ID ───────────────────────────────────────────────────────── */ /* -- Geração de ID --- */
TB_API uint64_t tb_rt_next_id(TinyBlocks* rt); TB_API uint64_t tb_rt_next_id(TinyBlocks* rt);
#endif /* TINYBLOCKS_H */ #endif /* TINYBLOCKS_H */
@@ -1,5 +1,5 @@
/* /*
* TinyBlocks — tb_editor.h * TinyBlocks - tb_editor.h
* Editor visual block-based (estilo Scratch) implementado como LibraryBlock. * Editor visual block-based (estilo Scratch) implementado como LibraryBlock.
* *
* O editor é o próprio bloco "Editor.Scene": não abre janela nem processa * O editor é o próprio bloco "Editor.Scene": não abre janela nem processa
@@ -21,7 +21,7 @@
* TinyBlocks_Block* app = tb_block_create(rt, tb_type_block_find(rt,"SDL2.App")); * 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, 3, tb_value_block(scene));
* tb_block_set_default(app, 4, tb_value_block(events)); * tb_block_set_default(app, 4, tb_value_block(events));
* tb_block_eval(app, rt); // roda o loop principal — bloqueia até fechar * tb_block_eval(app, rt); // roda o loop principal - bloqueia até fechar
*/ */
#ifndef TINYBLOCKS_EDITOR_H #ifndef TINYBLOCKS_EDITOR_H
#define TINYBLOCKS_EDITOR_H #define TINYBLOCKS_EDITOR_H
@@ -1,5 +1,5 @@
/* /*
* TinyBlocks — tb_graphics.h * TinyBlocks - tb_graphics.h
* Interface gráfica do TinyBlocks: janelas, entrada, desenho e texto. * 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. * Tudo o que é gráfico passa por aqui antes de chegar a um backend concreto.
@@ -9,15 +9,15 @@
* - dinamicamente: tb_graphics_load_backend("build/libtinyblocks-sdl2.so"); * - dinamicamente: tb_graphics_load_backend("build/libtinyblocks-sdl2.so");
* (o .so exporta TINYBLOCKS_GRAPHICS_BACKEND_SYMBOL) * (o .so exporta TINYBLOCKS_GRAPHICS_BACKEND_SYMBOL)
* Sem escolha explícita usa o backend padrão de compilação (SDL2) ou, na * Sem escolha explícita usa o backend padrão de compilação (SDL2) ou, na
* falta dele, o backend nulo (headless — útil para testes). * falta dele, o backend nulo (headless - útil para testes).
* *
* TypeBlocks registrados por tb_graphics_get_library(): * TypeBlocks registrados por tb_graphics_get_library():
* Graphics.Input — estado de entrada de uma janela no frame (outputs GFX_IN_*) * 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) * 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) * in: título, largura, altura, cena(block), entrada(block), principal(int)
* Graphics.Run — roda o loop até a janela principal fechar * Graphics.Run - roda o loop até a janela principal fechar
* *
* Esta library não conhece nenhum consumidor (editor, palco…): só define o * 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. * contrato e despacha para o backend. Cenas são quaisquer blocos com on_draw.
* *
* Uso típico (host): * Uso típico (host):
@@ -35,7 +35,7 @@
#include <tinyblocks/tinyblocks.h> #include <tinyblocks/tinyblocks.h>
#include <tinyblocks/tb_renderable_block.h> #include <tinyblocks/tb_renderable_block.h>
/* ── Teclas (neutras; o backend traduz as suas) ──────────────────────────── */ /* -- Teclas (neutras; o backend traduz as suas) --- */
enum { enum {
TB_KEY_NONE = 0, TB_KEY_NONE = 0,
TB_KEY_ESCAPE, TB_KEY_RETURN, TB_KEY_BACKSPACE, TB_KEY_DELETE, TB_KEY_TAB, TB_KEY_ESCAPE, TB_KEY_RETURN, TB_KEY_BACKSPACE, TB_KEY_DELETE, TB_KEY_TAB,
@@ -48,12 +48,12 @@ enum {
TB_KEY_OTHER = 127 TB_KEY_OTHER = 127
}; };
/* ── Modificadores (bitmask) ─────────────────────────────────────────────── */ /* -- Modificadores (bitmask) --- */
#define TB_MOD_SHIFT 0x1 #define TB_MOD_SHIFT 0x1
#define TB_MOD_CTRL 0x2 #define TB_MOD_CTRL 0x2
#define TB_MOD_ALT 0x4 #define TB_MOD_ALT 0x4
/* ── Índices de output do bloco Graphics.Input ───────────────────────────── */ /* -- Í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_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_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_L_HELD 2 /* int: botão esquerdo pressionado (estado) */
@@ -89,7 +89,7 @@ typedef struct TinyBlocks_GfxInput {
int mod_state; int mod_state;
} TinyBlocks_GfxInput; } TinyBlocks_GfxInput;
/* ── Contrato de um backend gráfico ──────────────────────────────────────── */ /* -- Contrato de um backend gráfico --- */
typedef struct TinyBlocks_GraphicsBackend { typedef struct TinyBlocks_GraphicsBackend {
const char* name; const char* name;
bool (*init)(void); /* idempotente */ bool (*init)(void); /* idempotente */
@@ -107,7 +107,7 @@ typedef struct TinyBlocks_GraphicsBackend {
#define TINYBLOCKS_GRAPHICS_BACKEND_SYMBOL "tinyblocks_get_graphics_backend" #define TINYBLOCKS_GRAPHICS_BACKEND_SYMBOL "tinyblocks_get_graphics_backend"
typedef const TinyBlocks_GraphicsBackend* (*TinyBlocks_GetGraphicsBackendFn)(void); typedef const TinyBlocks_GraphicsBackend* (*TinyBlocks_GetGraphicsBackendFn)(void);
/* ── API ─────────────────────────────────────────────────────────────────── */ /* -- API --- */
TB_API const TinyBlocks_LibraryDescriptor* tb_graphics_get_library(void); TB_API const TinyBlocks_LibraryDescriptor* tb_graphics_get_library(void);
/* Escolhe o backend (antes de abrir a primeira janela) */ /* Escolhe o backend (antes de abrir a primeira janela) */
+18 -18
View File
@@ -1,5 +1,5 @@
/* /*
* TinyBlocks — tb_graphics.c * TinyBlocks - tb_graphics.c
* Interface gráfica: escolha de backend, janelas, entrada e loop principal. * Interface gráfica: escolha de backend, janelas, entrada e loop principal.
*/ */
#define _POSIX_C_SOURCE 200809L #define _POSIX_C_SOURCE 200809L
@@ -15,9 +15,9 @@
#include <tb_sdl2.h> #include <tb_sdl2.h>
#endif #endif
/* ══════════════════════════════════════════════════════════════════════════ /* ===
* Backend nulo (headless): janelas sem tela, entrada vazia, texto estimado * Backend nulo (headless): janelas sem tela, entrada vazia, texto estimado
* ══════════════════════════════════════════════════════════════════════════ */ * === */
typedef struct { int w, h; } NullWin; typedef struct { int w, h; } NullWin;
static bool null_init(void) { return true; } static bool null_init(void) { return true; }
@@ -52,9 +52,9 @@ static const TinyBlocks_GraphicsBackend s_null_backend = {
const TinyBlocks_GraphicsBackend* tb_graphics_null_backend(void) { return &s_null_backend; } const TinyBlocks_GraphicsBackend* tb_graphics_null_backend(void) { return &s_null_backend; }
/* ══════════════════════════════════════════════════════════════════════════ /* ===
* Escolha do backend * Escolha do backend
* ══════════════════════════════════════════════════════════════════════════ */ * === */
static const TinyBlocks_GraphicsBackend* s_backend = NULL; static const TinyBlocks_GraphicsBackend* s_backend = NULL;
static bool s_backend_ready = false; static bool s_backend_ready = false;
static void* s_backend_dl = NULL; static void* s_backend_dl = NULL;
@@ -120,11 +120,11 @@ bool tb_graphics_load_backend(const char* so_path) {
return true; return true;
} }
/* ══════════════════════════════════════════════════════════════════════════ /* ===
* Medição de texto * Medição de texto
* ══════════════════════════════════════════════════════════════════════════ */ * === */
/* Larguras de avanço da DejaVu Sans, em em, para ASCII 32..126 — estimativa /* 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). */ * usada quando o backend não sabe medir (ex: backend nulo). */
static const float s_adv[95] = { static const float s_adv[95] = {
.318f,.401f,.460f,.838f,.636f,.950f,.780f,.275f,.390f,.390f,.500f,.838f,.318f,.361f,.318f,.337f, .318f,.401f,.460f,.838f,.636f,.950f,.780f,.275f,.390f,.390f,.500f,.838f,.318f,.361f,.318f,.337f,
@@ -150,9 +150,9 @@ float tb_graphics_measure_text(const char* text, float font_size) {
return b->measure_text ? b->measure_text(text, font_size) : estimate_text(text, font_size); 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 * Graphics.Input - estado de entrada de uma janela no frame
* ══════════════════════════════════════════════════════════════════════════ */ * === */
static const TinyBlocks_SlotDesc s_input_outs[GFX_IN_COUNT] = { static const TinyBlocks_SlotDesc s_input_outs[GFX_IN_COUNT] = {
{"mouse_x", TB_VALUE_REAL}, {"mouse_y", TB_VALUE_REAL}, {"mouse_x", TB_VALUE_REAL}, {"mouse_y", TB_VALUE_REAL},
{"l_held", TB_VALUE_INTEGER}, {"r_held", TB_VALUE_INTEGER}, {"l_held", TB_VALUE_INTEGER}, {"r_held", TB_VALUE_INTEGER},
@@ -206,12 +206,12 @@ static void input_push(TinyBlocks_Block* b, const TinyBlocks_GfxInput* in) {
b->dirty = false; b->dirty = false;
} }
/* ══════════════════════════════════════════════════════════════════════════ /* ===
* Graphics.Window — uma janela do SO mostrando uma cena * Graphics.Window - uma janela do SO mostrando uma cena
* inputs: 0 título, 1 largura, 2 altura, 3 cena(block), 4 entrada(block), * 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) * 5 principal(int: fechar esta janela encerra o loop; padrão 1)
* output: 0 aberta(int) * output: 0 aberta(int)
* ══════════════════════════════════════════════════════════════════════════ */ * === */
typedef struct { void* handle; uint64_t id; bool open; } WinState; typedef struct { void* handle; uint64_t id; bool open; } WinState;
static int win_find(uint64_t id) { static int win_find(uint64_t id) {
@@ -275,9 +275,9 @@ bool tb_graphics_window_is_open(TinyBlocks_Block* window) {
return ((WinState*)window->userdata)->open; return ((WinState*)window->userdata)->open;
} }
/* ══════════════════════════════════════════════════════════════════════════ /* ===
* Loop principal * Loop principal
* ══════════════════════════════════════════════════════════════════════════ */ * === */
static void default_wait(void) { static void default_wait(void) {
struct timespec ts = { 0, 16 * 1000000L }; struct timespec ts = { 0, 16 * 1000000L };
nanosleep(&ts, NULL); nanosleep(&ts, NULL);
@@ -340,9 +340,9 @@ static void eval_run(TinyBlocks_Block* self, TinyBlocks* rt) {
tb_graphics_run(rt); tb_graphics_run(rt);
} }
/* ══════════════════════════════════════════════════════════════════════════ /* ===
* Registro da library * Registro da library
* ══════════════════════════════════════════════════════════════════════════ */ * === */
static bool graphics_lib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { static bool graphics_lib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
TinyBlocks_TypeBlock* t; TinyBlocks_TypeBlock* t;
@@ -10,7 +10,7 @@
#endif #endif
/* /*
* tb_mcp — cliente MCP (Model Context Protocol) sobre transporte HTTP * tb_mcp - cliente MCP (Model Context Protocol) sobre transporte HTTP
* e stdio, implementado em Python via tinyblocks-python. * e stdio, implementado em Python via tinyblocks-python.
* *
* Transport HTTP (streamable): url = "http://host:port/mcp" * Transport HTTP (streamable): url = "http://host:port/mcp"
@@ -22,15 +22,15 @@
TB_MCP_API bool tb_mcp_init(void); TB_MCP_API bool tb_mcp_init(void);
TB_MCP_API void tb_mcp_deinit(void); TB_MCP_API void tb_mcp_deinit(void);
/* Lista ferramentas disponíveis → JSON array de objetos {name, description} */ /* Lista ferramentas disponíveis -> JSON array de objetos {name, description} */
TB_MCP_API char* tb_mcp_list_tools(const char* url); TB_MCP_API char* tb_mcp_list_tools(const char* url);
/* Chama uma ferramenta com argumentos JSON → resultado JSON */ /* Chama uma ferramenta com argumentos JSON -> resultado JSON */
TB_MCP_API char* tb_mcp_call_tool(const char* url, TB_MCP_API char* tb_mcp_call_tool(const char* url,
const char* tool_name, const char* tool_name,
const char* args_json); const char* args_json);
/* Ping: verifica se o servidor responde → "ok" ou mensagem de erro */ /* Ping: verifica se o servidor responde -> "ok" ou mensagem de erro */
TB_MCP_API char* tb_mcp_ping(const char* url); TB_MCP_API char* tb_mcp_ping(const char* url);
#endif /* TINYBLOCKS_MCP_H */ #endif /* TINYBLOCKS_MCP_H */
+4 -4
View File
@@ -9,7 +9,7 @@
/* Código Python gerado por: xxd -i tb_mcp.py > tb_mcp_py.h */ /* Código Python gerado por: xxd -i tb_mcp.py > tb_mcp_py.h */
#include "tb_mcp_py.h" #include "tb_mcp_py.h"
/* ── Singleton ───────────────────────────────────────────────────────────── */ /* -- Singleton --- */
static bool s_module_loaded = false; static bool s_module_loaded = false;
static bool ensure_module(void) { static bool ensure_module(void) {
@@ -36,7 +36,7 @@ TB_MCP_API void tb_mcp_deinit(void) {
tb_python_deinit(); tb_python_deinit();
} }
/* ── Helper: escapa string para literal Python ───────────────────────────── */ /* -- Helper: escapa string para literal Python --- */
static char* py_str(const char* s) { static char* py_str(const char* s) {
size_t n = strlen(s); size_t n = strlen(s);
char* out = malloc(n * 4 + 3); char* out = malloc(n * 4 + 3);
@@ -60,7 +60,7 @@ static char* py_str(const char* s) {
return out; return out;
} }
/* ── Helper genérico: monta e executa chamada Python fn(arg...) ─────────── */ /* -- Helper genérico: monta e executa chamada Python fn(arg...) --- */
static char* py_call(const char* fn, const char* const* args, int n) { static char* py_call(const char* fn, const char* const* args, int n) {
if (!ensure_module()) return strdup("erro: modulo MCP nao carregado"); if (!ensure_module()) return strdup("erro: modulo MCP nao carregado");
@@ -108,7 +108,7 @@ static char* py_call(const char* fn, const char* const* args, int n) {
return out ? out : strdup(""); return out ? out : strdup("");
} }
/* ── API pública ─────────────────────────────────────────────────────────── */ /* -- API pública --- */
TB_MCP_API char* tb_mcp_ping(const char* url) { TB_MCP_API char* tb_mcp_ping(const char* url) {
const char* args[] = {url}; const char* args[] = {url};
return py_call("mcp_ping", args, 1); return py_call("mcp_ping", args, 1);
@@ -10,7 +10,7 @@
#endif #endif
/* /*
* tb_python — wrapper fino sobre o interpretador CPython embutido. * tb_python - wrapper fino sobre o interpretador CPython embutido.
* *
* O interpretador é compartilhado em todo o processo (singleton ref-counted). * 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 * Compile a lib como .so compartilhada para que python.so e mcp.so usem o
+4 -4
View File
@@ -7,7 +7,7 @@
#include "tinyblocks-python/tb_python.h" #include "tinyblocks-python/tb_python.h"
/* ── Singleton ref-counted ───────────────────────────────────────────────── */ /* -- Singleton ref-counted --- */
static int s_refs = 0; static int s_refs = 0;
TB_PYTHON_API bool tb_python_init(void) { TB_PYTHON_API bool tb_python_init(void) {
@@ -30,7 +30,7 @@ TB_PYTHON_API void tb_python_deinit(void) {
Py_FinalizeEx(); Py_FinalizeEx();
} }
/* ── Helper: captura stdout+stderr de uma execução ──────────────────────── */ /* -- Helper: captura stdout+stderr de uma execução --- */
static char* capture_run(const char* code, PyObject* local_dict) { static char* capture_run(const char* code, PyObject* local_dict) {
/* StringIO para capturar output */ /* StringIO para capturar output */
PyObject* io = PyImport_ImportModule("io"); PyObject* io = PyImport_ImportModule("io");
@@ -72,7 +72,7 @@ static char* capture_run(const char* code, PyObject* local_dict) {
return out; return out;
} }
/* ── API pública ─────────────────────────────────────────────────────────── */ /* -- API pública --- */
TB_PYTHON_API char* tb_python_run(const char* code) { TB_PYTHON_API char* tb_python_run(const char* code) {
if (!code || !Py_IsInitialized()) return strdup(""); if (!code || !Py_IsInitialized()) return strdup("");
return capture_run(code, NULL); return capture_run(code, NULL);
@@ -95,7 +95,7 @@ TB_PYTHON_API char* tb_python_exec_main(const char* code) {
PyObject_SetAttrString(sys, "stdout", buf); PyObject_SetAttrString(sys, "stdout", buf);
PyObject_SetAttrString(sys, "stderr", buf); PyObject_SetAttrString(sys, "stderr", buf);
/* Executa com main_dict como globals E locals — definições persistem */ /* Executa com main_dict como globals E locals - definições persistem */
PyObject* result = PyRun_String(code, Py_file_input, main_dict, main_dict); PyObject* result = PyRun_String(code, Py_file_input, main_dict, main_dict);
if (!result) { PyErr_Print(); PyErr_Clear(); } if (!result) { PyErr_Print(); PyErr_Clear(); }
Py_XDECREF(result); Py_XDECREF(result);
+5 -5
View File
@@ -1,12 +1,12 @@
/* /*
* TinyBlocks — tb_sdl2.h * TinyBlocks - tb_sdl2.h
* *
* TypeBlocks disponíveis após registrar esta library: * TypeBlocks disponíveis após registrar esta library:
* *
* SDL2.Events — expõe o estado de eventos do frame corrente (sem inputs; * SDL2.Events - expõe o estado de eventos do frame corrente (sem inputs;
* outputs pré-preenchidos pelo SDL2.App antes de cada on_draw) * outputs pré-preenchidos pelo SDL2.App antes de cada on_draw)
* *
* SDL2.App — cria janela, roda o loop principal, chama on_draw na scene. * SDL2.App - cria janela, roda o loop principal, chama on_draw na scene.
* in: title(text), w(int), h(int), scene(block), events(block) * in: title(text), w(int), h(int), scene(block), events(block)
* *
* Blocos primitivos (uso manual): * Blocos primitivos (uso manual):
@@ -30,7 +30,7 @@ TB_API const TinyBlocks_LibraryDescriptor* tinyblocks_get_library(void);
struct TinyBlocks_GraphicsBackend; struct TinyBlocks_GraphicsBackend;
TB_API const struct TinyBlocks_GraphicsBackend* tb_sdl2_graphics_backend(void); TB_API const struct TinyBlocks_GraphicsBackend* tb_sdl2_graphics_backend(void);
/* ── Índices de output do bloco SDL2.Events ──────────────────────────────── */ /* -- Índices de output do bloco SDL2.Events --- */
#define SDL2_EV_MOUSE_X 0 /* real: posição X do mouse */ #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_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_L_HELD 2 /* int: botão esquerdo pressionado (estado) */
@@ -52,7 +52,7 @@ TB_API const struct TinyBlocks_GraphicsBackend* tb_sdl2_graphics_backend(void);
#define SDL2_EV_MOD_STATE 18 /* int: SDL_GetModState() deste frame */ #define SDL2_EV_MOD_STATE 18 /* int: SDL_GetModState() deste frame */
#define SDL2_EV_COUNT 19 /* total de outputs */ #define SDL2_EV_COUNT 19 /* total de outputs */
/* ── Constantes de tipo de evento (SDL2.PollEvent legado) ───────────────── */ /* -- Constantes de tipo de evento (SDL2.PollEvent legado) --- */
#define TB_SDL2_EVENT_NONE 0 #define TB_SDL2_EVENT_NONE 0
#define TB_SDL2_EVENT_QUIT 256 #define TB_SDL2_EVENT_QUIT 256
#define TB_SDL2_EVENT_KEYDOWN 768 #define TB_SDL2_EVENT_KEYDOWN 768
+24 -24
View File
@@ -1,16 +1,16 @@
/* /*
* TinyBlocks — tb_sdl2.c * TinyBlocks - tb_sdl2.c
* Backend SDL2 para TinyBlocks. * Backend SDL2 para TinyBlocks.
* *
* Blocos principais: * Blocos principais:
* SDL2.Events — snapshot de eventos do frame, pré-preenchido pelo SDL2.App * SDL2.Events - snapshot de eventos do frame, pré-preenchido pelo SDL2.App
* SDL2.App — janela + renderer + loop principal + executor de renderables * SDL2.App - janela + renderer + loop principal + executor de renderables
* *
* Blocos primitivos legados: Init, Quit, Window, Renderer, etc. * Blocos primitivos legados: Init, Quit, Window, Renderer, etc.
* *
* Também implementa o contrato TinyBlocks_GraphicsBackend da interface * Também implementa o contrato TinyBlocks_GraphicsBackend da interface
* tinyblocks-graphics (várias janelas, entrada por janela, desenho com AA e * tinyblocks-graphics (várias janelas, entrada por janela, desenho com AA e
* medição de texto com a fonte real) — ver tb_sdl2_graphics_backend(). * medição de texto com a fonte real) - ver tb_sdl2_graphics_backend().
*/ */
#define _POSIX_C_SOURCE 200809L #define _POSIX_C_SOURCE 200809L
@@ -27,9 +27,9 @@
#include <tb_graphics.h> #include <tb_graphics.h>
#include "../include/tb_sdl2.h" #include "../include/tb_sdl2.h"
/* ═══════════════════════════════════════════════════════════════════════════ /* ===
* Handles opacos de Window/Renderer (blocos wrapper) * Handles opacos de Window/Renderer (blocos wrapper)
* ═══════════════════════════════════════════════════════════════════════════ */ * === */
static TinyBlocks_TypeBlock* s_type_window_handle = NULL; static TinyBlocks_TypeBlock* s_type_window_handle = NULL;
static TinyBlocks_TypeBlock* s_type_renderer_handle = NULL; static TinyBlocks_TypeBlock* s_type_renderer_handle = NULL;
@@ -44,9 +44,9 @@ static void eval_handle_noop(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)self; (void)rt; (void)self; (void)rt;
} }
/* ═══════════════════════════════════════════════════════════════════════════ /* ===
* Fonte TTF — cache por tamanho * Fonte TTF - cache por tamanho
* ═══════════════════════════════════════════════════════════════════════════ */ * === */
#define FONT_CACHE_CAP 8 #define FONT_CACHE_CAP 8
#define FONT_SEARCH_COUNT 6 #define FONT_SEARCH_COUNT 6
@@ -88,11 +88,11 @@ static void fonts_close_all(void) {
s_font_cache_n = 0; s_font_cache_n = 0;
} }
/* ═══════════════════════════════════════════════════════════════════════════ /* ===
* Executor de TinyBlocks_RenderableBlock via SDL2 * Executor de TinyBlocks_RenderableBlock via SDL2
* ═══════════════════════════════════════════════════════════════════════════ */ * === */
/* ── Rasterização com antialias ───────────────────────────────────────────── /* -- Rasterização com antialias ---
* As formas preenchidas são varridas linha a linha com AA_SUB sub-linhas por * As formas preenchidas são varridas linha a linha com AA_SUB sub-linhas por
* pixel e cobertura horizontal exata. Cada pixel é pintado uma única vez, com * pixel e cobertura horizontal exata. Cada pixel é pintado uma única vez, com
* alpha proporcional à cobertura: bordas suavizadas e sem overdraw (cores * alpha proporcional à cobertura: bordas suavizadas e sem overdraw (cores
@@ -349,9 +349,9 @@ static void sdl2_execute(SDL_Renderer* ren,
} }
} }
/* ═══════════════════════════════════════════════════════════════════════════ /* ===
* Backend da interface tinyblocks-graphics * Backend da interface tinyblocks-graphics
* ═══════════════════════════════════════════════════════════════════════════ */ * === */
typedef struct SdlWin { typedef struct SdlWin {
SDL_Window* win; SDL_Window* win;
SDL_Renderer* ren; SDL_Renderer* ren;
@@ -586,9 +586,9 @@ const TinyBlocks_GraphicsBackend* tinyblocks_get_graphics_backend(void) {
return &s_sdl2_backend; return &s_sdl2_backend;
} }
/* ═══════════════════════════════════════════════════════════════════════════ /* ===
* SDL2.Events — snapshot de eventos do frame * SDL2.Events - snapshot de eventos do frame
* ═══════════════════════════════════════════════════════════════════════════ */ * === */
static void eval_sdl2_events(TinyBlocks_Block* self, TinyBlocks* rt) { static void eval_sdl2_events(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)rt; (void)rt;
/* Outputs são pré-preenchidos pelo SDL2.App antes de cada frame. /* Outputs são pré-preenchidos pelo SDL2.App antes de cada frame.
@@ -658,9 +658,9 @@ static void events_push(TinyBlocks_Block* ev, const FrameEvents* fe) {
ev->dirty = false; ev->dirty = false;
} }
/* ═══════════════════════════════════════════════════════════════════════════ /* ===
* SDL2.App — janela + loop principal * SDL2.App - janela + loop principal
* ═══════════════════════════════════════════════════════════════════════════ */ * === */
typedef struct { typedef struct {
SDL_Window* win; SDL_Window* win;
SDL_Renderer* ren; SDL_Renderer* ren;
@@ -824,9 +824,9 @@ static void eval_sdl2_app(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false; self->dirty = false;
} }
/* ═══════════════════════════════════════════════════════════════════════════ /* ===
* Blocos primitivos legados * Blocos primitivos legados
* ═══════════════════════════════════════════════════════════════════════════ */ * === */
static void eval_sdl2_init(TinyBlocks_Block* self, TinyBlocks* rt) { static void eval_sdl2_init(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)self; (void)self;
if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_EVENTS) != 0) if (SDL_Init(SDL_INIT_VIDEO|SDL_INIT_EVENTS) != 0)
@@ -936,9 +936,9 @@ static void eval_sdl2_poll_event(TinyBlocks_Block* self, TinyBlocks* rt) {
} }
} }
/* ═══════════════════════════════════════════════════════════════════════════ /* ===
* Registro da library * Registro da library
* ═══════════════════════════════════════════════════════════════════════════ */ * === */
static bool sdl2_lib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { static bool sdl2_lib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
s_type_window_handle = tb_type_block_create(rt, "SDL2._WindowHandle", s_type_window_handle = tb_type_block_create(rt, "SDL2._WindowHandle",
NULL,0,NULL,0, eval_handle_noop); NULL,0,NULL,0, eval_handle_noop);
+12 -12
View File
@@ -2,7 +2,7 @@
#include <stdio.h> #include <stdio.h>
#include "tinyblocks/tinyblocks.h" #include "tinyblocks/tinyblocks.h"
/* ── Alocação da estrutura base ──────────────────────────────────────────── */ /* -- Alocação da estrutura base --- */
TinyBlocks_Block* tb_block_alloc_base(TinyBlocks* rt, TinyBlocks_Block* tb_block_alloc_base(TinyBlocks* rt,
TinyBlocks_BlockKind kind, TinyBlocks_BlockKind kind,
size_t struct_size, size_t struct_size,
@@ -33,7 +33,7 @@ TinyBlocks_Block* tb_block_alloc_base(TinyBlocks* rt,
return b; return b;
} }
/* ── Vtable padrão para blocos definidos por TypeBlock ───────────────────── */ /* -- Vtable padrão para blocos definidos por TypeBlock --- */
static void default_eval(TinyBlocks_Block* self, TinyBlocks* rt) static void default_eval(TinyBlocks_Block* self, TinyBlocks* rt)
{ {
if (self->type && self->type->eval_fn) if (self->type && self->type->eval_fn)
@@ -80,7 +80,7 @@ static const TinyBlocks_BlockVTable s_default_vtable = {
.clone = default_clone, .clone = default_clone,
}; };
/* ── Criação via TypeBlock ───────────────────────────────────────────────── */ /* -- Criação via TypeBlock --- */
TinyBlocks_Block* tb_block_create(TinyBlocks* rt, TinyBlocks_TypeBlock* type) TinyBlocks_Block* tb_block_create(TinyBlocks* rt, TinyBlocks_TypeBlock* type)
{ {
if (!type) { if (!type) {
@@ -115,7 +115,7 @@ TinyBlocks_Block* tb_block_create(TinyBlocks* rt, TinyBlocks_TypeBlock* type)
return b; return b;
} }
/* ── Destruição ──────────────────────────────────────────────────────────── */ /* -- Destruição --- */
void tb_block_destroy(TinyBlocks_Block* block, TinyBlocks* rt) void tb_block_destroy(TinyBlocks_Block* block, TinyBlocks* rt)
{ {
if (!block) return; if (!block) return;
@@ -138,14 +138,14 @@ void tb_block_destroy(TinyBlocks_Block* block, TinyBlocks* rt)
tb_free(rt, block); tb_free(rt, block);
} }
/* ── Avaliação ───────────────────────────────────────────────────────────── */ /* -- Avaliação --- */
void tb_block_eval(TinyBlocks_Block* block, TinyBlocks* rt) void tb_block_eval(TinyBlocks_Block* block, TinyBlocks* rt)
{ {
if (!block || !block->vtable || !block->vtable->eval) return; if (!block || !block->vtable || !block->vtable->eval) return;
/* Detecta ciclo: bloco já está sendo avaliado nesta chamada recursiva */ /* Detecta ciclo: bloco já está sendo avaliado nesta chamada recursiva */
if (block->in_eval) { if (block->in_eval) {
tinyblocks_set_error(rt, "ciclo detectado em '%s' — conexão ignorada", tinyblocks_set_error(rt, "ciclo detectado em '%s' - conexão ignorada",
block->type ? block->type->type_name : "?"); block->type ? block->type->type_name : "?");
return; return;
} }
@@ -162,14 +162,14 @@ void tb_block_eval(TinyBlocks_Block* block, TinyBlocks* rt)
block->in_eval = false; block->in_eval = false;
} }
/* ── Clone ───────────────────────────────────────────────────────────────── */ /* -- Clone --- */
TinyBlocks_Block* tb_block_clone(const TinyBlocks_Block* block, TinyBlocks* rt) TinyBlocks_Block* tb_block_clone(const TinyBlocks_Block* block, TinyBlocks* rt)
{ {
if (!block || !block->vtable || !block->vtable->clone) return NULL; if (!block || !block->vtable || !block->vtable->clone) return NULL;
return block->vtable->clone(block, rt); return block->vtable->clone(block, rt);
} }
/* ── Representação textual ───────────────────────────────────────────────── */ /* -- Representação textual --- */
size_t tb_block_to_string(TinyBlocks_Block* block, TinyBlocks* rt, size_t tb_block_to_string(TinyBlocks_Block* block, TinyBlocks* rt,
char* buf, size_t buf_size) char* buf, size_t buf_size)
{ {
@@ -180,7 +180,7 @@ size_t tb_block_to_string(TinyBlocks_Block* block, TinyBlocks* rt,
(unsigned long long)block->id); (unsigned long long)block->id);
} }
/* ── Conexões ────────────────────────────────────────────────────────────── */ /* -- Conexões --- */
bool tb_block_connect(TinyBlocks_Block* target, uint32_t input_idx, bool tb_block_connect(TinyBlocks_Block* target, uint32_t input_idx,
TinyBlocks_Block* source, uint32_t output_idx) TinyBlocks_Block* source, uint32_t output_idx)
{ {
@@ -210,7 +210,7 @@ bool tb_block_set_default(TinyBlocks_Block* target, uint32_t input_idx,
return true; return true;
} }
/* ── Acesso a valores em eval_fn ─────────────────────────────────────────── */ /* -- Acesso a valores em eval_fn --- */
TinyBlocks_Value tb_block_get_input(TinyBlocks_Block* self, TinyBlocks* rt, TinyBlocks_Value tb_block_get_input(TinyBlocks_Block* self, TinyBlocks* rt,
uint32_t input_idx) uint32_t input_idx)
{ {
@@ -225,7 +225,7 @@ TinyBlocks_Value tb_block_get_input(TinyBlocks_Block* self, TinyBlocks* rt,
return conn->default_value; return conn->default_value;
} }
/* Toma ownership de v — o caller NÃO deve liberar v depois desta chamada. /* 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. */ 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, void tb_block_set_output(TinyBlocks_Block* self, uint32_t output_idx,
TinyBlocks_Value v) TinyBlocks_Value v)
@@ -235,7 +235,7 @@ void tb_block_set_output(TinyBlocks_Block* self, uint32_t output_idx,
self->outputs[output_idx] = v; self->outputs[output_idx] = v;
} }
/* ── Downcasting seguro ──────────────────────────────────────────────────── */ /* -- Downcasting seguro --- */
TinyBlocks_TypeBlock* tb_block_as_type (TinyBlocks_Block* b) TinyBlocks_TypeBlock* tb_block_as_type (TinyBlocks_Block* b)
{ return b && b->kind == TB_KIND_TYPE ? (TinyBlocks_TypeBlock*)b : NULL; } { return b && b->kind == TB_KIND_TYPE ? (TinyBlocks_TypeBlock*)b : NULL; }
+3 -3
View File
@@ -1,7 +1,7 @@
#include <stdio.h> #include <stdio.h>
#include "tinyblocks/tinyblocks.h" #include "tinyblocks/tinyblocks.h"
/* ── Vtable ──────────────────────────────────────────────────────────────── */ /* -- Vtable --- */
static void integer_eval(TinyBlocks_Block* self, TinyBlocks* rt) static void integer_eval(TinyBlocks_Block* self, TinyBlocks* rt)
{ {
(void)rt; (void)rt;
@@ -38,7 +38,7 @@ static const TinyBlocks_BlockVTable s_integer_vtable = {
.clone = integer_clone, .clone = integer_clone,
}; };
/* ── Ciclo de vida ───────────────────────────────────────────────────────── */ /* -- Ciclo de vida --- */
TinyBlocks_IntegerBlock* tb_integer_block_create(TinyBlocks* rt, int64_t value) TinyBlocks_IntegerBlock* tb_integer_block_create(TinyBlocks* rt, int64_t value)
{ {
TinyBlocks_IntegerBlock* ib = (TinyBlocks_IntegerBlock*)tb_block_alloc_base( TinyBlocks_IntegerBlock* ib = (TinyBlocks_IntegerBlock*)tb_block_alloc_base(
@@ -54,7 +54,7 @@ void tb_integer_block_destroy(TinyBlocks_IntegerBlock* ib, TinyBlocks* rt)
tb_block_destroy(&ib->base, rt); tb_block_destroy(&ib->base, rt);
} }
/* ── Acesso ──────────────────────────────────────────────────────────────── */ /* -- Acesso --- */
int64_t tb_integer_block_get(const TinyBlocks_IntegerBlock* ib) int64_t tb_integer_block_get(const TinyBlocks_IntegerBlock* ib)
{ {
return ib ? ib->value : 0; return ib ? ib->value : 0;
+14 -14
View File
@@ -26,9 +26,9 @@ struct TinyBlocks_JsonValue {
} as; } as;
}; };
/* ══════════════════════════════════════════════════════════════════════════ /* ===
* Construtores / ciclo de vida * Construtores / ciclo de vida
* ══════════════════════════════════════════════════════════════════════════ */ * === */
static TinyBlocks_JsonValue* json_alloc(TinyBlocks_JsonKind kind) { static TinyBlocks_JsonValue* json_alloc(TinyBlocks_JsonKind kind) {
TinyBlocks_JsonValue* j = calloc(1, sizeof(TinyBlocks_JsonValue)); TinyBlocks_JsonValue* j = calloc(1, sizeof(TinyBlocks_JsonValue));
if (!j) return NULL; if (!j) return NULL;
@@ -125,9 +125,9 @@ TinyBlocks_JsonValue* tb_json_clone(const TinyBlocks_JsonValue* j) {
return tb_json_null(); return tb_json_null();
} }
/* ══════════════════════════════════════════════════════════════════════════ /* ===
* Inspeção * Inspeção
* ══════════════════════════════════════════════════════════════════════════ */ * === */
TinyBlocks_JsonKind tb_json_kind(const TinyBlocks_JsonValue* j) { TinyBlocks_JsonKind tb_json_kind(const TinyBlocks_JsonValue* j) {
return j ? j->kind : TB_JSON_NULL; return j ? j->kind : TB_JSON_NULL;
} }
@@ -163,9 +163,9 @@ const char* tb_json_as_string(const TinyBlocks_JsonValue* j) {
return j->as.string; return j->as.string;
} }
/* ══════════════════════════════════════════════════════════════════════════ /* ===
* Arrays * Arrays
* ══════════════════════════════════════════════════════════════════════════ */ * === */
bool tb_json_array_push(TinyBlocks_JsonValue* arr, TinyBlocks_JsonValue* item) { bool tb_json_array_push(TinyBlocks_JsonValue* arr, TinyBlocks_JsonValue* item) {
if (!arr || arr->kind != TB_JSON_ARRAY || !item) return false; if (!arr || arr->kind != TB_JSON_ARRAY || !item) return false;
if (arr->as.array.count == arr->as.array.capacity) { if (arr->as.array.count == arr->as.array.capacity) {
@@ -191,9 +191,9 @@ TinyBlocks_JsonValue* tb_json_array_get(const TinyBlocks_JsonValue* arr, uint32_
return v; return v;
} }
/* ══════════════════════════════════════════════════════════════════════════ /* ===
* Objetos * Objetos
* ══════════════════════════════════════════════════════════════════════════ */ * === */
bool tb_json_object_set(TinyBlocks_JsonValue* obj, const char* key, TinyBlocks_JsonValue* val) { 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; if (!obj || obj->kind != TB_JSON_OBJECT || !key || !val) return false;
for (uint32_t i = 0; i < obj->as.object.count; i++) { for (uint32_t i = 0; i < obj->as.object.count; i++) {
@@ -240,9 +240,9 @@ TinyBlocks_JsonValue* tb_json_object_get(const TinyBlocks_JsonValue* obj, const
return NULL; return NULL;
} }
/* ══════════════════════════════════════════════════════════════════════════ /* ===
* Parser (recursive-descent, RFC 8259 simplificado) * Parser (recursive-descent, RFC 8259 simplificado)
* ══════════════════════════════════════════════════════════════════════════ */ * === */
typedef struct { const char* p; const char* end; char* err; size_t errcap; } JsonParser; typedef struct { const char* p; const char* end; char* err; size_t errcap; } JsonParser;
static void parser_fail(JsonParser* ps, const char* msg) { static void parser_fail(JsonParser* ps, const char* msg) {
@@ -425,9 +425,9 @@ TinyBlocks_JsonValue* tb_json_parse(const char* text, char* errbuf, size_t errbu
return v; return v;
} }
/* ══════════════════════════════════════════════════════════════════════════ /* ===
* Stringify * Stringify
* ══════════════════════════════════════════════════════════════════════════ */ * === */
typedef struct { char* buf; size_t len, cap; } StrBuf; typedef struct { char* buf; size_t len, cap; } StrBuf;
static void sb_ensure(StrBuf* sb, size_t extra) { static void sb_ensure(StrBuf* sb, size_t extra) {
@@ -512,9 +512,9 @@ char* tb_json_stringify(const TinyBlocks_JsonValue* j) {
return sb.buf; return sb.buf;
} }
/* ══════════════════════════════════════════════════════════════════════════ /* ===
* Helpers para TinyBlocks_Value * Helpers para TinyBlocks_Value
* ══════════════════════════════════════════════════════════════════════════ */ * === */
TinyBlocks_Value tb_value_json(TinyBlocks_JsonValue* j) { TinyBlocks_Value tb_value_json(TinyBlocks_JsonValue* j) {
TinyBlocks_Value v = { .kind = TB_VALUE_JSON, .as.json = j }; TinyBlocks_Value v = { .kind = TB_VALUE_JSON, .as.json = j };
if (j) tb_json_retain(j); if (j) tb_json_retain(j);
+3 -3
View File
@@ -1,7 +1,7 @@
#include <stdio.h> #include <stdio.h>
#include "tinyblocks/tinyblocks.h" #include "tinyblocks/tinyblocks.h"
/* ── Vtable ──────────────────────────────────────────────────────────────── */ /* -- Vtable --- */
static void real_eval(TinyBlocks_Block* self, TinyBlocks* rt) static void real_eval(TinyBlocks_Block* self, TinyBlocks* rt)
{ {
(void)rt; (void)rt;
@@ -38,7 +38,7 @@ static const TinyBlocks_BlockVTable s_real_vtable = {
.clone = real_clone, .clone = real_clone,
}; };
/* ── Ciclo de vida ───────────────────────────────────────────────────────── */ /* -- Ciclo de vida --- */
TinyBlocks_RealBlock* tb_real_block_create(TinyBlocks* rt, double value) TinyBlocks_RealBlock* tb_real_block_create(TinyBlocks* rt, double value)
{ {
TinyBlocks_RealBlock* rb = (TinyBlocks_RealBlock*)tb_block_alloc_base( TinyBlocks_RealBlock* rb = (TinyBlocks_RealBlock*)tb_block_alloc_base(
@@ -54,7 +54,7 @@ void tb_real_block_destroy(TinyBlocks_RealBlock* rb, TinyBlocks* rt)
tb_block_destroy(&rb->base, rt); tb_block_destroy(&rb->base, rt);
} }
/* ── Acesso ──────────────────────────────────────────────────────────────── */ /* -- Acesso --- */
double tb_real_block_get(const TinyBlocks_RealBlock* rb) double tb_real_block_get(const TinyBlocks_RealBlock* rb)
{ {
return rb ? rb->value : 0.0; return rb ? rb->value : 0.0;
+3 -3
View File
@@ -3,7 +3,7 @@
#include <stddef.h> #include <stddef.h>
#include "tinyblocks/tb_renderable_block.h" #include "tinyblocks/tb_renderable_block.h"
/* ── Pool estático — 4 frames em paralelo é suficiente para qualquer backend ─ */ /* -- Pool estático - 4 frames em paralelo é suficiente para qualquer backend - */
#define POOL_CAP 4 #define POOL_CAP 4
static TinyBlocks_RenderableBlock s_pool[POOL_CAP]; static TinyBlocks_RenderableBlock s_pool[POOL_CAP];
@@ -31,7 +31,7 @@ void tb_renderable_release_all(void) {
s_used[i] = false; s_used[i] = false;
} }
/* ── Append interno ─────────────────────────────────────────────────────────── */ /* -- Append interno --- */
static TinyBlocks_DrawCmd* append(TinyBlocks_RenderableBlock* rb) { static TinyBlocks_DrawCmd* append(TinyBlocks_RenderableBlock* rb) {
if (!rb || rb->count >= TB_DRAW_CMD_CAP) return NULL; if (!rb || rb->count >= TB_DRAW_CMD_CAP) return NULL;
TinyBlocks_DrawCmd* c = &rb->cmds[rb->count++]; TinyBlocks_DrawCmd* c = &rb->cmds[rb->count++];
@@ -39,7 +39,7 @@ static TinyBlocks_DrawCmd* append(TinyBlocks_RenderableBlock* rb) {
return c; return c;
} }
/* ── Helpers públicos ────────────────────────────────────────────────────────── */ /* -- Helpers públicos --- */
void tb_draw_clear(TinyBlocks_RenderableBlock* rb, void tb_draw_clear(TinyBlocks_RenderableBlock* rb,
float r, float g, float b, float a) { float r, float g, float b, float a) {
TinyBlocks_DrawCmd* c = append(rb); if (!c) return; TinyBlocks_DrawCmd* c = append(rb); if (!c) return;
+3 -3
View File
@@ -5,7 +5,7 @@
#include <string.h> #include <string.h>
#include "tinyblocks/tinyblocks.h" #include "tinyblocks/tinyblocks.h"
/* ── Vtable ──────────────────────────────────────────────────────────────── */ /* -- Vtable --- */
static void text_eval(TinyBlocks_Block* self, TinyBlocks* rt) static void text_eval(TinyBlocks_Block* self, TinyBlocks* rt)
{ {
(void)rt; (void)rt;
@@ -43,7 +43,7 @@ static const TinyBlocks_BlockVTable s_text_vtable = {
.clone = text_clone, .clone = text_clone,
}; };
/* ── Ciclo de vida ───────────────────────────────────────────────────────── */ /* -- Ciclo de vida --- */
TinyBlocks_TextBlock* tb_text_block_create(TinyBlocks* rt, const char* value) TinyBlocks_TextBlock* tb_text_block_create(TinyBlocks* rt, const char* value)
{ {
TinyBlocks_TextBlock* tb = (TinyBlocks_TextBlock*)tb_block_alloc_base( TinyBlocks_TextBlock* tb = (TinyBlocks_TextBlock*)tb_block_alloc_base(
@@ -59,7 +59,7 @@ void tb_text_block_destroy(TinyBlocks_TextBlock* tb, TinyBlocks* rt)
tb_block_destroy(&tb->base, rt); tb_block_destroy(&tb->base, rt);
} }
/* ── Acesso ──────────────────────────────────────────────────────────────── */ /* -- Acesso --- */
const char* tb_text_block_get(const TinyBlocks_TextBlock* tb) const char* tb_text_block_get(const TinyBlocks_TextBlock* tb)
{ {
return tb ? tb->value : NULL; return tb ? tb->value : NULL;
+2 -2
View File
@@ -2,7 +2,7 @@
#include <stdio.h> #include <stdio.h>
#include "tinyblocks/tinyblocks.h" #include "tinyblocks/tinyblocks.h"
/* ── Vtable de TypeBlock ─────────────────────────────────────────────────── */ /* -- Vtable de TypeBlock --- */
static void type_eval(TinyBlocks_Block* self, TinyBlocks* rt) static void type_eval(TinyBlocks_Block* self, TinyBlocks* rt)
{ {
/* Um TypeBlock em si não avalia; serve como fábrica/descritor */ /* Um TypeBlock em si não avalia; serve como fábrica/descritor */
@@ -48,7 +48,7 @@ static const TinyBlocks_BlockVTable s_type_vtable = {
.clone = type_clone, .clone = type_clone,
}; };
/* ── Criação ─────────────────────────────────────────────────────────────── */ /* -- Criação --- */
TinyBlocks_TypeBlock* tb_type_block_create( TinyBlocks_TypeBlock* tb_type_block_create(
TinyBlocks* rt, TinyBlocks* rt,
const char* type_name, const char* type_name,
+9 -9
View File
@@ -4,9 +4,9 @@
#include <stdio.h> #include <stdio.h>
#include "tinyblocks/tinyblocks.h" #include "tinyblocks/tinyblocks.h"
/* ══════════════════════════════════════════════════════════════════════════ /* ===
* TinyBlocks_VectorData — buffer de comandos ref-counted * TinyBlocks_VectorData - buffer de comandos ref-counted
* ══════════════════════════════════════════════════════════════════════════ */ * === */
TinyBlocks_VectorData* tb_vector_data_create(void) { TinyBlocks_VectorData* tb_vector_data_create(void) {
TinyBlocks_VectorData* v = malloc(sizeof(TinyBlocks_VectorData)); TinyBlocks_VectorData* v = malloc(sizeof(TinyBlocks_VectorData));
if (!v) return NULL; if (!v) return NULL;
@@ -48,7 +48,7 @@ bool tb_vector_data_push(TinyBlocks_VectorData* v, TinyBlocks_VCmd cmd) {
return true; return true;
} }
/* ── Construtores de conveniência ────────────────────────────────────────── */ /* -- Construtores de conveniência --- */
#define PUSH0(v,k) tb_vector_data_push(v, (TinyBlocks_VCmd){(k), {0}}) #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 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 PUSH4(v,k,a,b,c,d) tb_vector_data_push(v,(TinyBlocks_VCmd){(k),{(a),(b),(c),(d)}})
@@ -77,7 +77,7 @@ bool tb_vector_circle(TinyBlocks_VectorData* v, float cx, float cy, float radius
#undef PUSH4 #undef PUSH4
#undef PUSH5 #undef PUSH5
/* ── Value helpers ───────────────────────────────────────────────────────── */ /* -- Value helpers --- */
TinyBlocks_Value tb_value_vector(TinyBlocks_VectorData* v) { TinyBlocks_Value tb_value_vector(TinyBlocks_VectorData* v) {
TinyBlocks_Value val; TinyBlocks_Value val;
val.kind = TB_VALUE_VECTOR; val.kind = TB_VALUE_VECTOR;
@@ -90,7 +90,7 @@ TinyBlocks_VectorData* tb_value_as_vector(TinyBlocks_Value v) {
return v.kind == TB_VALUE_VECTOR ? v.as.vector : NULL; return v.kind == TB_VALUE_VECTOR ? v.as.vector : NULL;
} }
/* ── RenderableBlock play ────────────────────────────────────────────────── */ /* -- RenderableBlock play --- */
void tb_draw_ctx_play(TinyBlocks_RenderableBlock* rb, TinyBlocks_VectorData* v) { void tb_draw_ctx_play(TinyBlocks_RenderableBlock* rb, TinyBlocks_VectorData* v) {
if (!rb || !v) return; if (!rb || !v) return;
float px = 0.f, py = 0.f; /* ponto atual do path */ float px = 0.f, py = 0.f; /* ponto atual do path */
@@ -128,9 +128,9 @@ void tb_draw_ctx_play(TinyBlocks_RenderableBlock* rb, TinyBlocks_VectorData* v)
} }
} }
/* ══════════════════════════════════════════════════════════════════════════ /* ===
* TinyBlocks_VectorBlock — block kind TB_KIND_VECTOR * TinyBlocks_VectorBlock - block kind TB_KIND_VECTOR
* ══════════════════════════════════════════════════════════════════════════ */ * === */
static void vec_eval(TinyBlocks_Block* self, TinyBlocks* rt) { static void vec_eval(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)rt; (void)rt;
TinyBlocks_VectorBlock* vb = (TinyBlocks_VectorBlock*)self; TinyBlocks_VectorBlock* vb = (TinyBlocks_VectorBlock*)self;
+8 -8
View File
@@ -5,11 +5,11 @@
#include <stdarg.h> #include <stdarg.h>
#include "tinyblocks/tinyblocks.h" #include "tinyblocks/tinyblocks.h"
/* ── Alocador padrão ─────────────────────────────────────────────────────── */ /* -- Alocador padrão --- */
static void* default_alloc(size_t size, void* ud) { (void)ud; return malloc(size); } 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); } static void default_free (void* ptr, void* ud) { (void)ud; free(ptr); }
/* ── Inicialização ───────────────────────────────────────────────────────── */ /* -- Inicialização --- */
bool tinyblocks_init(TinyBlocks** out_rt, const TinyBlocks_InitOptions* opts) bool tinyblocks_init(TinyBlocks** out_rt, const TinyBlocks_InitOptions* opts)
{ {
if (!out_rt) return false; if (!out_rt) return false;
@@ -54,7 +54,7 @@ bool tinyblocks_init(TinyBlocks** out_rt, const TinyBlocks_InitOptions* opts)
return true; return true;
} }
/* ── Desinicialização ────────────────────────────────────────────────────── */ /* -- Desinicialização --- */
void tinyblocks_deinit(TinyBlocks** rt_ptr) void tinyblocks_deinit(TinyBlocks** rt_ptr)
{ {
if (!rt_ptr || !*rt_ptr) return; if (!rt_ptr || !*rt_ptr) return;
@@ -109,7 +109,7 @@ void tinyblocks_deinit(TinyBlocks** rt_ptr)
*rt_ptr = NULL; *rt_ptr = NULL;
} }
/* ── Alocação ────────────────────────────────────────────────────────────── */ /* -- Alocação --- */
void* tb_alloc(TinyBlocks* rt, size_t size) void* tb_alloc(TinyBlocks* rt, size_t size)
{ {
void* p = rt->alloc(size, rt->alloc_userdata); void* p = rt->alloc(size, rt->alloc_userdata);
@@ -131,10 +131,10 @@ char* tb_strdup(TinyBlocks* rt, const char* str)
return p; return p;
} }
/* ── Geração de ID ───────────────────────────────────────────────────────── */ /* -- Geração de ID --- */
uint64_t tb_rt_next_id(TinyBlocks* rt) { return rt->next_id++; } uint64_t tb_rt_next_id(TinyBlocks* rt) { return rt->next_id++; }
/* ── Registro de blocos ──────────────────────────────────────────────────── */ /* -- Registro de blocos --- */
static bool grow_array(TinyBlocks* rt, void*** arr, uint32_t* cap, uint32_t count) static bool grow_array(TinyBlocks* rt, void*** arr, uint32_t* cap, uint32_t count)
{ {
if (count < *cap) return true; if (count < *cap) return true;
@@ -202,7 +202,7 @@ void tb_rt_unregister_library(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib)
} }
} }
/* ── Busca ───────────────────────────────────────────────────────────────── */ /* -- Busca --- */
TinyBlocks_Block* tb_rt_find_block(TinyBlocks* rt, uint64_t id) TinyBlocks_Block* tb_rt_find_block(TinyBlocks* rt, uint64_t id)
{ {
for (uint32_t i = 0; i < rt->block_count; ++i) for (uint32_t i = 0; i < rt->block_count; ++i)
@@ -227,7 +227,7 @@ TinyBlocks_LibraryBlock* tb_rt_find_library(TinyBlocks* rt, const char* name)
return NULL; return NULL;
} }
/* ── Erros ───────────────────────────────────────────────────────────────── */ /* -- Erros --- */
const char* tinyblocks_last_error(TinyBlocks* rt) { return rt->error; } const char* tinyblocks_last_error(TinyBlocks* rt) { return rt->error; }
void tinyblocks_clear_error(TinyBlocks* rt) { rt->error[0] = '\0'; } void tinyblocks_clear_error(TinyBlocks* rt) { rt->error[0] = '\0'; }