diff --git a/Makefile b/Makefile index 074d0fd..e12a9c1 100644 --- a/Makefile +++ b/Makefile @@ -26,6 +26,7 @@ CSV_DIR := $(LIBDIR)/tinyblocks-csv BP_DIR := $(LIBDIR)/tinyblocks-blueprint B64_DIR := $(LIBDIR)/tinyblocks-base64 CV_DIR := $(LIBDIR)/tinyblocks-curves +PPM_DIR := $(LIBDIR)/tinyblocks-ppm API_DIR := $(LIBDIR)/tinyblocks-api LIBM_DIR := $(LIBDIR)/tinyblocks-libman ED_DIR := $(LIBDIR)/tinyblocks-editor @@ -55,7 +56,8 @@ SRCS := src/tinyblocks.c \ src/tb_vector_block.c \ src/tb_renderable_block.c \ src/tb_stage.c \ - src/tb_json_block.c + src/tb_json_block.c \ + src/tb_image.c OBJS := $(patsubst src/%.c,$(BUILD)/%.o,$(SRCS)) OBJS_DBG := $(patsubst src/%.c,$(BUILD)/%-dbg.o,$(SRCS)) @@ -80,12 +82,12 @@ LIB_LDFLAGS := -L$(ED_DIR)/build -L$(GX_DIR)/build -L$(SD_DIR)/build \ .PHONY: all help debug release static shared example sdl2 clean run python-lib mcp-lib json \ editor run-editor run-sdl2 mylib vector customappearance graphics sdl2-backend test-editor \ appdir appimage run-appimage icon \ - test-toml test-plugin test-blueprint test-base64 test-curves \ + test-toml test-plugin test-blueprint test-base64 test-curves test-ppm \ category-libs category-sos libs \ lib-events lib-control lib-operators lib-variables lib-appearance lib-pen lib-fs \ lib-environ \ lib-editor lib-graphics lib-sdl2 lib-python lib-mcp lib-toml \ - lib-json lib-xml lib-csv lib-blueprint lib-base64 lib-curves lib-api lib-libman \ + lib-json lib-xml lib-csv lib-blueprint lib-base64 lib-curves lib-ppm lib-api lib-libman \ test-libman test-environ all: static example ## Compila a biblioteca estática e o exemplo hello (padrão) @@ -167,6 +169,9 @@ lib-base64: lib-curves: $(MAKE) -C $(CV_DIR) +lib-ppm: + $(MAKE) -C $(PPM_DIR) + lib-api: $(MAKE) -C $(API_DIR) @@ -187,8 +192,8 @@ lib-mcp: libs: static lib-events lib-control lib-operators lib-variables \ lib-appearance lib-pen lib-fs lib-environ lib-graphics lib-sdl2 lib-toml \ - lib-json lib-xml lib-csv lib-blueprint lib-base64 lib-curves lib-api lib-libman lib-editor - @echo "Libraries OK: category + graphics + sdl2 + toml + json + xml + csv + blueprint + base64 + curves + api + libman + editor" + lib-json lib-xml lib-csv lib-blueprint lib-base64 lib-curves lib-ppm lib-api lib-libman lib-editor + @echo "Libraries OK: category + graphics + sdl2 + toml + json + xml + csv + blueprint + base64 + curves + ppm + api + libman + editor" category-libs: static $(foreach l,$(CAT_LIBS),lib-$(l)) ## Compila as libraries de categoria (.a/.so) @echo "Build category libs OK" @@ -239,7 +244,7 @@ run-editor: editor ## Compila e abre o editor visual # ── Empacotamento AppImage ────────────────────────────────────────────── # Libraries com blocos (categoria) que vao empacotadas como extensoes. -APPIMAGE_LIBS := $(CAT_LIBS) toml json xml csv blueprint base64 curves +APPIMAGE_LIBS := $(CAT_LIBS) toml json xml csv blueprint base64 curves ppm APP_NAME := TinyBlocks APP_VER := 0.1.0 @@ -371,7 +376,7 @@ $(BUILD)/editor_harness: tests/editor_harness.c $(SRCS) \ @mkdir -p $(BUILD) $(CC) $(CFLAGS_DBG) \ -I$(ED_DIR)/include -I$(EDITOR_SRC) -I$(GFX_INC) $(CAT_INCS) -I$(BP_DIR)/include \ - -I$(API_DIR)/include -I$(LIBM_DIR)/include -I$(EN_DIR)/include -I$(TOML_DIR)/include -I$(CV_DIR)/include -I$(B64_DIR)/include \ + -I$(API_DIR)/include -I$(LIBM_DIR)/include -I$(EN_DIR)/include -I$(TOML_DIR)/include -I$(CV_DIR)/include -I$(B64_DIR)/include -I$(PPM_DIR)/include \ $(SRCS) \ $(EDITOR_SRC)/tb_editor.c $(EDITOR_SRC)/tb_stage_widget.c \ $(GX_DIR)/src/tb_graphics.c \ @@ -379,7 +384,7 @@ $(BUILD)/editor_harness: tests/editor_harness.c $(SRCS) \ $(API_DIR)/src/tb_api.c $(LIBM_DIR)/src/tb_libman.c \ $(TOML_LIB_SRCS) $(TOML_DIR)/src/tb_toml.c \ $(foreach l,$(CAT_LIBS),$(LIBDIR)/tinyblocks-$(l)/src/tb_$(l).c) \ - $(CV_DIR)/src/tb_curves.c $(B64_DIR)/src/tb_base64.c tests/editor_harness.c -o $@ -ldl -lm -rdynamic + $(CV_DIR)/src/tb_curves.c $(B64_DIR)/src/tb_base64.c $(PPM_DIR)/src/tb_ppm.c tests/editor_harness.c -o $@ -ldl -lm -rdynamic test-editor: $(BUILD)/editor_harness ## Roda o harness headless do editor (ASan/UBSan) ./$(BUILD)/editor_harness @@ -452,6 +457,16 @@ $(BUILD)/curves_test: tests/curves_test.c $(CV_DIR)/src/tb_curves.c static test-curves: $(BUILD)/curves_test ## Roda o teste da curves (ASan/UBSan) ./$(BUILD)/curves_test +# -- Teste da library ppm (usa o tipo imagem do core) --- +$(BUILD)/ppm_test: tests/ppm_test.c $(PPM_DIR)/src/tb_ppm.c static + @mkdir -p $(BUILD) + $(CC) $(CFLAGS_DBG) -I$(PPM_DIR)/include $(PPM_DIR)/src/tb_ppm.c \ + tests/ppm_test.c -o $@ \ + -Wl,--start-group $(LIB_A) -Wl,--end-group + +test-ppm: $(BUILD)/ppm_test ## Roda o teste da ppm (ASan/UBSan) + ./$(BUILD)/ppm_test + # -- Teste de plugin .so standalone --- FS_SO := $(FS_DIR)/build/libtinyblocks-fs.so @@ -468,7 +483,7 @@ clean: ## Remove os diretórios build/ (raiz e libraries) $(RM) -r $(BUILD) @for d in $(EV_DIR) $(CT_DIR) $(OP_DIR) $(VR_DIR) $(AP_DIR) $(PN_DIR) $(FS_DIR) \ $(TOML_DIR) $(JSON_DIR) $(XML_DIR) $(CSV_DIR) $(BP_DIR) \ - $(B64_DIR) $(CV_DIR) \ + $(B64_DIR) $(CV_DIR) $(PPM_DIR) \ $(API_DIR) $(LIBM_DIR) \ $(ED_DIR) $(GX_DIR) $(SD_DIR) $(PY_DIR) $(MC_DIR); do \ $(MAKE) -C $$d clean >/dev/null 2>&1 || true; \ diff --git a/include/tinyblocks/tb_defs.h b/include/tinyblocks/tb_defs.h index 0b3f6b0..31dff73 100644 --- a/include/tinyblocks/tb_defs.h +++ b/include/tinyblocks/tb_defs.h @@ -28,6 +28,7 @@ typedef struct TinyBlocks_VectorBlock TinyBlocks_VectorBlock; typedef struct TinyBlocks_VectorData TinyBlocks_VectorData; typedef struct TinyBlocks_RenderableBlock TinyBlocks_RenderableBlock; typedef struct TinyBlocks_JsonValue TinyBlocks_JsonValue; +typedef struct TinyBlocks_Image TinyBlocks_Image; /* -- Kinds de bloco --- */ typedef enum TinyBlocks_BlockKind { @@ -49,6 +50,7 @@ typedef enum TinyBlocks_ValueKind { TB_VALUE_BLOCK = 4, /* referência a qualquer bloco (handle opaco) */ TB_VALUE_VECTOR = 5, /* dados de vetor 2D (ref-counted) */ TB_VALUE_JSON = 6, /* valor JSON (ref-counted) */ + TB_VALUE_IMAGE = 7, /* imagem RGBA/cinza (ref-counted) */ } TinyBlocks_ValueKind; /* -- Valor com tag (flui entre slots) --- */ @@ -61,6 +63,7 @@ typedef struct TinyBlocks_Value { TinyBlocks_Block* block; /* ponteiro não-owning */ TinyBlocks_VectorData* vector; /* ref-counted (retain/release) */ TinyBlocks_JsonValue* json; /* ref-counted (retain/release) */ + TinyBlocks_Image* image; /* ref-counted (retain/release) */ } as; } TinyBlocks_Value; diff --git a/include/tinyblocks/tb_image.h b/include/tinyblocks/tb_image.h new file mode 100644 index 0000000..0088029 --- /dev/null +++ b/include/tinyblocks/tb_image.h @@ -0,0 +1,38 @@ +/* + * TinyBlocks - tb_image.h + * TinyBlocks_Image: mapa de pixels ref-counted que flui como valor entre + * blocos (TB_VALUE_IMAGE). Suporta 1 canal (cinza), 3 (RGB) e 4 (RGBA). + */ +#ifndef TINYBLOCKS_IMAGE_H +#define TINYBLOCKS_IMAGE_H + +#include "tb_block.h" + +/* -- Ciclo de vida --- */ +/* Cria uma imagem w*h com o numero de canais informado (1, 3 ou 4). + * Os pixels começam zerados (preto transparente/opaco conforme canais). */ +TB_API TinyBlocks_Image* tb_image_new(int w, int h, int channels); +TB_API void tb_image_retain (TinyBlocks_Image* img); +TB_API void tb_image_release(TinyBlocks_Image* img); + +/* Cria uma cópia independente (mesmos pixels). */ +TB_API TinyBlocks_Image* tb_image_clone(const TinyBlocks_Image* img); + +/* -- Inspeção --- */ +TB_API int tb_image_width (const TinyBlocks_Image* img); +TB_API int tb_image_height (const TinyBlocks_Image* img); +TB_API int tb_image_channels(const TinyBlocks_Image* img); +TB_API uint8_t* tb_image_data (TinyBlocks_Image* img); /* ponteiro mutável */ +TB_API const uint8_t* tb_image_data_const(const TinyBlocks_Image* img); + +/* -- Pixels (RGBA sempre; converte de/para o formato de origem) --- */ +TB_API bool tb_image_set_pixel(TinyBlocks_Image* img, int x, int y, + uint8_t r, uint8_t g, uint8_t b, uint8_t a); +TB_API bool tb_image_get_pixel(const TinyBlocks_Image* img, int x, int y, + uint8_t* r, uint8_t* g, uint8_t* b, uint8_t* a); + +/* -- Helpers para TinyBlocks_Value --- */ +TB_API TinyBlocks_Value tb_value_image (TinyBlocks_Image* img); /* retém ref */ +TB_API TinyBlocks_Image* tb_value_as_image(TinyBlocks_Value v); + +#endif /* TINYBLOCKS_IMAGE_H */ diff --git a/include/tinyblocks/tb_renderable_block.h b/include/tinyblocks/tb_renderable_block.h index 4e09257..1421da1 100644 --- a/include/tinyblocks/tb_renderable_block.h +++ b/include/tinyblocks/tb_renderable_block.h @@ -34,6 +34,7 @@ typedef enum { TB_DRAW_SET_CLIP, /* define rect de clip (coordenadas tela) */ TB_DRAW_CLEAR_CLIP, /* remove clip */ TB_DRAW_TEXT, /* texto (x,y=baseline-left; font_size em px) */ + TB_DRAW_IMAGE, /* imagem escalada em (x,y,w,h); ver field image */ } TinyBlocks_DrawCmdKind; typedef struct { @@ -43,6 +44,7 @@ typedef struct { float param; /* radius (rrect/circle), espessura (linha/stroke) */ float font_size; /* tamanho da fonte em pixels (TB_DRAW_TEXT) */ char text[128]; /* conteúdo do texto (TB_DRAW_TEXT) */ + const TinyBlocks_Image* image; /* pixels (TB_DRAW_IMAGE, não-owning) */ } TinyBlocks_DrawCmd; /* -- RenderableBlock --- */ @@ -103,6 +105,13 @@ TB_API void tb_draw_text (TinyBlocks_RenderableBlock* rb, float x, float y, const char* text, float font_size, float r, float g, float b, float a); +/* Desenha a imagem escalada para o retângulo (x,y,w,h). A imagem é + * ref-counted; o comando apenas guarda um ponteiro não-owning, portanto a + * imagem precisa continuar viva até o backend renderizar o frame. */ +TB_API void tb_draw_image (TinyBlocks_RenderableBlock* rb, + float x, float y, float w, float h, + const TinyBlocks_Image* image); + /* Mescla src em dst deslocando todas as coordenadas por (dx, dy). Usado pelo editor para incorporar sub-renderables de blocos com on_draw. */ TB_API void tb_draw_merge_offset(TinyBlocks_RenderableBlock* dst, diff --git a/include/tinyblocks/tinyblocks.h b/include/tinyblocks/tinyblocks.h index 8ec6c9d..16812ae 100644 --- a/include/tinyblocks/tinyblocks.h +++ b/include/tinyblocks/tinyblocks.h @@ -35,6 +35,7 @@ #include "tb_real_block.h" #include "tb_vector_block.h" #include "tb_json_block.h" +#include "tb_image.h" /* -- Runtime --- */ struct TinyBlocks { diff --git a/libraries/tinyblocks-editor/src/tb_editor.c b/libraries/tinyblocks-editor/src/tb_editor.c index cb73180..4161a11 100644 --- a/libraries/tinyblocks-editor/src/tb_editor.c +++ b/libraries/tinyblocks-editor/src/tb_editor.c @@ -250,6 +250,14 @@ static const BlockSpec s_specs[] = { /* Base64 */ {"Base64.Encode", "codifique em base64 %1", NULL}, {"Base64.Decode", "decodifique base64 %1", NULL}, + /* Imagens PPM (tipo imagem do core) */ + {"PPM.Load", "carregue a imagem %1", "imagem.ppm"}, + {"PPM.Save", "grave a imagem %1 em %2", "|saida.ppm"}, + {"PPM.New", "nova imagem(%1 x %2) cor r %3 g %4 b %5", "32|32|255|0|0"}, + {"PPM.Width", "largura de %1", NULL}, + {"PPM.Height", "altura de %1", NULL}, + {"PPM.SetPixel", "pinte %1 em (%2,%3) de r %4 g %5 b %6", "|0|0|0|0|0"}, + {"PPM.GetPixel", "cor de %1 em (%2,%3)", "|0|0"}, }; /* === @@ -401,6 +409,7 @@ typedef struct { int bubble_bi; char bubble_text[128]; TinyBlocks_JsonValue* bubble_json; /* lista de pontos (retida) ou NULL */ + TinyBlocks_Image* bubble_img; /* imagem (retida) ou NULL */ int last_click_bi; unsigned last_click_ms; @@ -576,6 +585,8 @@ static void value_to_str(const TinyBlocks_Value* v, char* buf, size_t cap) { case TB_VALUE_BLOCK: snprintf(buf, cap, "[bloco]"); break; case TB_VALUE_VECTOR: snprintf(buf, cap, "[vetor]"); break; case TB_VALUE_JSON: snprintf(buf, cap, "[json]"); break; + case TB_VALUE_IMAGE: snprintf(buf, cap, "[imagem %dx%d]", + tb_image_width(v->as.image), tb_image_height(v->as.image)); break; default: buf[0] = 0; break; } } @@ -1578,6 +1589,7 @@ static void run_flag(Ed* ed) { /* Libera o balão de resultado (texto + eventual lista de pontos) */ static void bubble_clear(Ed* ed) { if (ed->bubble_json) { tb_json_release(ed->bubble_json); ed->bubble_json = NULL; } + if (ed->bubble_img) { tb_image_release(ed->bubble_img); ed->bubble_img = NULL; } ed->bubble_bi = -1; ed->bubble_text[0] = 0; } @@ -1624,6 +1636,13 @@ static void bubble_set(Ed* ed, int root, TinyBlocks_Value* v) { (unsigned)tb_json_array_length(v->as.json)); return; } + if (v->kind == TB_VALUE_IMAGE && v->as.image) { + tb_image_retain(v->as.image); + ed->bubble_img = v->as.image; + snprintf(ed->bubble_text, sizeof(ed->bubble_text), "%dx%d", + tb_image_width(v->as.image), tb_image_height(v->as.image)); + return; + } value_to_str(v, ed->bubble_text, sizeof(ed->bubble_text)); if (!ed->bubble_text[0]) strcpy(ed->bubble_text, "(vazio)"); } @@ -2795,7 +2814,23 @@ static void render_workspace(Ed* ed, TinyBlocks_RenderableBlock* rb) { if (ed->bubble_bi >= 0 && CT.ws[ed->bubble_bi].used) { EdBlock* b = &CT.ws[ed->bubble_bi]; - if (ed->bubble_json) { + if (ed->bubble_img) { + /* Balão com prévia da imagem (escalada, mantendo proporção) */ + const float BW = 184, BH = 160, PAD = 10; + float bx = b->ax + ox + 8, by = b->ay + oy - (BH + 6); + rb_fill_rrect(rb, bx, by, BW, BH, 10, COL_BORDER); + rb_fill_rrect(rb, bx+1, by+1, BW-2, BH-2, 9, COL_WHITE); + rb_fill_rect(rb, bx + 16, by + BH - 2, 10, 5, COL_WHITE); + int iw = tb_image_width(ed->bubble_img); + int ih = tb_image_height(ed->bubble_img); + if (iw > 0 && ih > 0) { + float aw = BW - 2*PAD, ah = BH - 2*PAD - 12; + float sc = aw/iw < ah/ih ? aw/iw : ah/ih; + float dw = iw*sc, dh = ih*sc; + tb_draw_image(rb, bx + (BW-dw)*0.5f, by + (BH-12-dh)*0.5f, dw, dh, ed->bubble_img); + } + rb_text_c(rb, bx + 10, by + BH - 4, ed->bubble_text, COL_TEXT_DIM, 11.f); + } else if (ed->bubble_json) { /* Balão com prévia gráfica de uma lista de pontos (curva) */ const float BW = 180, BH = 140, PAD = 16; float bx = b->ax + ox + 8, by = b->ay + oy - (BH + 6); diff --git a/libraries/tinyblocks-ppm/Makefile b/libraries/tinyblocks-ppm/Makefile new file mode 100644 index 0000000..e83e8a6 --- /dev/null +++ b/libraries/tinyblocks-ppm/Makefile @@ -0,0 +1,28 @@ +# Makefile da library ppm (categoria "PPM") +CC := gcc +BUILD := build + +CFLAGS := -std=c11 -Wall -Wextra -pedantic -fvisibility=hidden \ + -D_POSIX_C_SOURCE=200809L -I../../include -Iinclude + +OBJ := $(BUILD)/tb_ppm.o +LIB_A := $(BUILD)/libtinyblocks-ppm.a +LIB_SO := $(BUILD)/libtinyblocks-ppm.so + +.PHONY: all static shared clean +all: static shared +static: $(LIB_A) +shared: $(LIB_SO) + +$(OBJ): src/tb_ppm.c include/tb_ppm.h + @mkdir -p $(BUILD) + $(CC) $(CFLAGS) -fPIC -c $< -o $@ + +$(LIB_A): $(OBJ) + ar rcs $@ $^ + +$(LIB_SO): $(OBJ) + $(CC) -shared -o $@ $^ + +clean: + $(RM) -r $(BUILD) diff --git a/libraries/tinyblocks-ppm/include/tb_ppm.h b/libraries/tinyblocks-ppm/include/tb_ppm.h new file mode 100644 index 0000000..d26427e --- /dev/null +++ b/libraries/tinyblocks-ppm/include/tb_ppm.h @@ -0,0 +1,19 @@ +/* + * TinyBlocks - tb_ppm.h + * Library tinyblocks-ppm: carrega/grava imagens Netpbm (P6 binario e P3 ASCII) + * como TinyBlocks_Image (TB_VALUE_IMAGE). Independente do editor. + */ +#ifndef TINYBLOCKS_PPM_H +#define TINYBLOCKS_PPM_H + +#include + +TB_API const TinyBlocks_LibraryDescriptor* tb_ppm_get_library(void); + +/* Carrega um .ppm (P6/P3). Retorna NULL em erro; use tb_ppm_last_error(). */ +TB_API TinyBlocks_Image* tb_ppm_load(const char* path); +/* Grava a imagem como P6 binario (converte cinza/RGBA para RGB). */ +TB_API bool tb_ppm_save(const TinyBlocks_Image* img, const char* path); +TB_API const char* tb_ppm_last_error(void); + +#endif /* TINYBLOCKS_PPM_H */ diff --git a/libraries/tinyblocks-ppm/library.toml b/libraries/tinyblocks-ppm/library.toml new file mode 100644 index 0000000..20cf780 --- /dev/null +++ b/libraries/tinyblocks-ppm/library.toml @@ -0,0 +1,15 @@ +# Metadados da library ppm. Lido pela UI/build sem recompilar o .so. +[library] +name = "tinyblocks-ppm" +version = "1.0.0" +category = "PPM" +description = "Imagens Netpbm (PPM): carregar, gravar e editar pixels" +color = [255, 167, 38, 255] +dark = [245, 124, 0, 255] + +[build] +sources = ["src/tb_ppm.c"] +includes = ["include"] +shared = "build/libtinyblocks-ppm.so" +static = "build/libtinyblocks-ppm.a" +depends = [] diff --git a/libraries/tinyblocks-ppm/src/tb_ppm.c b/libraries/tinyblocks-ppm/src/tb_ppm.c new file mode 100644 index 0000000..f3ea139 --- /dev/null +++ b/libraries/tinyblocks-ppm/src/tb_ppm.c @@ -0,0 +1,247 @@ +/* + * TinyBlocks - tb_ppm.c + * Categoria "PPM": PPM.Load / PPM.Save / PPM.New / PPM.Width / PPM.Height / + * PPM.SetPixel / PPM.GetPixel. Le e grava Netpbm (P6 binario e P3 ASCII). + */ +#define _POSIX_C_SOURCE 200809L +#include +#include +#include +#include +#include + +#include +#include "tb_ppm.h" + +static char s_err[200] = ""; +const char* tb_ppm_last_error(void) { return s_err; } + +/* Le um token (inteiro ou magic) pulando espacos e comentarios '#'. */ +static bool next_token(FILE* f, char* buf, size_t cap) { + int c; + /* pula espacos e comentarios */ + for (;;) { + c = fgetc(f); + if (c == EOF) return false; + if (c == '#') { while ((c = fgetc(f)) != EOF && c != '\n') {} continue; } + if (!isspace(c)) break; + } + size_t n = 0; + while (c != EOF && !isspace(c)) { + if (n + 1 < cap) buf[n++] = (char)c; + c = fgetc(f); + } + buf[n] = 0; + return n > 0; +} + +TinyBlocks_Image* tb_ppm_load(const char* path) { + s_err[0] = 0; + if (!path) { snprintf(s_err, sizeof(s_err), "caminho nulo"); return NULL; } + FILE* f = fopen(path, "rb"); + if (!f) { snprintf(s_err, sizeof(s_err), "nao abriu '%s'", path); return NULL; } + + char magic[8] = "", wbuf[24] = "", hbuf[24] = "", mbuf[24] = ""; + if (!next_token(f, magic, sizeof(magic)) || + (strcmp(magic, "P6") != 0 && strcmp(magic, "P3") != 0)) { + snprintf(s_err, sizeof(s_err), "formato PPM invalido (esperado P3/P6)"); + fclose(f); return NULL; + } + if (!next_token(f, wbuf, sizeof(wbuf)) || + !next_token(f, hbuf, sizeof(hbuf)) || + !next_token(f, mbuf, sizeof(mbuf))) { + snprintf(s_err, sizeof(s_err), "cabecalho PPM incompleto"); + fclose(f); return NULL; + } + int w = atoi(wbuf), h = atoi(hbuf), maxv = atoi(mbuf); + if (w <= 0 || h <= 0 || maxv <= 0 || maxv > 65535) { + snprintf(s_err, sizeof(s_err), "dimensoes/maxval invalidos"); + fclose(f); return NULL; + } + + TinyBlocks_Image* img = tb_image_new(w, h, 3); + if (!img) { snprintf(s_err, sizeof(s_err), "sem memoria"); fclose(f); return NULL; } + uint8_t* px = tb_image_data(img); + + if (strcmp(magic, "P6") == 0) { + int bytes = maxv > 255 ? 2 : 1; + for (size_t i = 0; i < (size_t)w * h * 3; i++) { + int v; + if (bytes == 2) { + int hi = fgetc(f), lo = fgetc(f); + if (hi == EOF || lo == EOF) { snprintf(s_err, sizeof(s_err), "dados truncados"); tb_image_release(img); fclose(f); return NULL; } + v = (hi << 8) | lo; + } else { + v = fgetc(f); + if (v == EOF) { snprintf(s_err, sizeof(s_err), "dados truncados"); tb_image_release(img); fclose(f); return NULL; } + } + px[i] = (uint8_t)((v * 255 + maxv/2) / maxv); + } + } else { + for (size_t i = 0; i < (size_t)w * h * 3; i++) { + char tb[24]; + if (!next_token(f, tb, sizeof(tb))) { snprintf(s_err, sizeof(s_err), "dados truncados"); tb_image_release(img); fclose(f); return NULL; } + int v = atoi(tb); + px[i] = (uint8_t)((v * 255 + maxv/2) / maxv); + } + } + fclose(f); + return img; +} + +bool tb_ppm_save(const TinyBlocks_Image* img, const char* path) { + s_err[0] = 0; + if (!img || !path) { snprintf(s_err, sizeof(s_err), "imagem/caminho nulo"); return false; } + int w = tb_image_width(img), h = tb_image_height(img); + if (w <= 0 || h <= 0) { snprintf(s_err, sizeof(s_err), "imagem vazia"); return false; } + FILE* f = fopen(path, "wb"); + if (!f) { snprintf(s_err, sizeof(s_err), "nao criou '%s'", path); return false; } + fprintf(f, "P6\n%d %d\n255\n", w, h); + for (int y = 0; y < h; y++) { + for (int x = 0; x < w; x++) { + uint8_t r, g, b, a; + tb_image_get_pixel(img, x, y, &r, &g, &b, &a); + fputc(r, f); fputc(g, f); fputc(b, f); + } + } + bool ok = (ferror(f) == 0); + fclose(f); + if (!ok) snprintf(s_err, sizeof(s_err), "erro ao gravar"); + return ok; +} + +/* -- Helpers de entrada -------------------------------------------------- */ + +static const char* in_text(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) { + TinyBlocks_Value v = tb_block_get_input(self, rt, i); + return (v.kind == TB_VALUE_TEXT && v.as.text) ? v.as.text : ""; +} +static double in_real(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) { + TinyBlocks_Value v = tb_block_get_input(self, rt, i); + if (v.kind == TB_VALUE_REAL) return v.as.real; + if (v.kind == TB_VALUE_INTEGER) return (double)v.as.integer; + if (v.kind == TB_VALUE_TEXT && v.as.text) return atof(v.as.text); + return 0.0; +} +static int in_int(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) { + return (int)in_real(self, rt, i); +} +static TinyBlocks_Image* in_img(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) { + TinyBlocks_Value v = tb_block_get_input(self, rt, i); + return v.kind == TB_VALUE_IMAGE ? v.as.image : NULL; +} + +static uint8_t clamp8(double v) { + if (v < 0) return 0; + if (v > 255) return 255; + return (uint8_t)(v + 0.5); +} + +/* -- Blocos -------------------------------------------------------------- */ + +static void eval_load(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Image* img = tb_ppm_load(in_text(self, rt, 0)); + if (!img) { tinyblocks_set_error(rt, "%s", tb_ppm_last_error()); self->dirty = false; return; } + tb_block_set_output(self, 0, tb_value_image(img)); + tb_image_release(img); + self->dirty = false; +} + +static void eval_save(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Image* img = in_img(self, rt, 0); + if (!img || !tb_ppm_save(img, in_text(self, rt, 1))) + tinyblocks_set_error(rt, "%s", tb_ppm_last_error()); + self->dirty = false; +} + +static void eval_new(TinyBlocks_Block* self, TinyBlocks* rt) { + int w = in_int(self, rt, 0), h = in_int(self, rt, 1); + TinyBlocks_Image* img = tb_image_new(w > 0 ? w : 1, h > 0 ? h : 1, 3); + if (!img) { tinyblocks_set_error(rt, "sem memoria"); self->dirty = false; return; } + uint8_t r = clamp8(in_real(self, rt, 2)); + uint8_t g = clamp8(in_real(self, rt, 3)); + uint8_t b = clamp8(in_real(self, rt, 4)); + for (int y = 0; y < h; y++) + for (int x = 0; x < w; x++) + tb_image_set_pixel(img, x, y, r, g, b, 255); + tb_block_set_output(self, 0, tb_value_image(img)); + tb_image_release(img); + self->dirty = false; +} + +static void eval_width(TinyBlocks_Block* self, TinyBlocks* rt) { + tb_block_set_output(self, 0, tb_value_integer(tb_image_width(in_img(self, rt, 0)))); + self->dirty = false; +} +static void eval_height(TinyBlocks_Block* self, TinyBlocks* rt) { + tb_block_set_output(self, 0, tb_value_integer(tb_image_height(in_img(self, rt, 0)))); + self->dirty = false; +} + +static void eval_setpixel(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Image* img = in_img(self, rt, 0); + if (!img) { tinyblocks_set_error(rt, "imagem invalida"); self->dirty = false; return; } + tb_image_set_pixel(img, in_int(self, rt, 1), in_int(self, rt, 2), + clamp8(in_real(self, rt, 3)), clamp8(in_real(self, rt, 4)), + clamp8(in_real(self, rt, 5)), 255); + self->dirty = false; +} + +static void eval_getpixel(TinyBlocks_Block* self, TinyBlocks* rt) { + TinyBlocks_Image* img = in_img(self, rt, 0); + uint8_t r = 0, g = 0, b = 0, a = 0; + tb_image_get_pixel(img, in_int(self, rt, 1), in_int(self, rt, 2), &r, &g, &b, &a); + TinyBlocks_JsonValue* arr = tb_json_array(); + tb_json_array_push(arr, tb_json_number(r)); + tb_json_array_push(arr, tb_json_number(g)); + tb_json_array_push(arr, tb_json_number(b)); + tb_block_set_output(self, 0, tb_value_json(arr)); + tb_json_release(arr); + self->dirty = false; +} + +/* -- Registro ------------------------------------------------------------ */ + +static bool reg(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib, const char* name, + const TinyBlocks_SlotDesc* in, uint32_t ni, + const TinyBlocks_SlotDesc* out, uint32_t no, + void (*fn)(TinyBlocks_Block*, TinyBlocks*)) { + TinyBlocks_TypeBlock* t = tb_type_block_create(rt, name, in, ni, out, no, fn); + return t && tb_library_add(lib, &t->base); +} + +static bool ppm_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { + static const TinyBlocks_Category cat = { + "PPM", + { 255/255.f, 167/255.f, 38/255.f, 1.f}, + { 245/255.f, 124/255.f, 0/255.f, 1.f}, + }; + tb_library_set_category(lib, &cat); + + static const TinyBlocks_SlotDesc img_out[] = {{"imagem", TB_VALUE_IMAGE}}; + static const TinyBlocks_SlotDesc n_out[] = {{"n", TB_VALUE_INTEGER}}; + static const TinyBlocks_SlotDesc rgb_out[] = {{"cor", TB_VALUE_JSON}}; + + static const TinyBlocks_SlotDesc load_in[] = {{"caminho", TB_VALUE_TEXT}}; + static const TinyBlocks_SlotDesc save_in[] = {{"imagem", TB_VALUE_IMAGE}, {"caminho", TB_VALUE_TEXT}}; + static const TinyBlocks_SlotDesc new_in[] = {{"largura",TB_VALUE_REAL},{"altura",TB_VALUE_REAL}, + {"r",TB_VALUE_REAL},{"g",TB_VALUE_REAL},{"b",TB_VALUE_REAL}}; + static const TinyBlocks_SlotDesc wh_in[] = {{"imagem", TB_VALUE_IMAGE}}; + static const TinyBlocks_SlotDesc setp_in[] = {{"imagem",TB_VALUE_IMAGE},{"x",TB_VALUE_INTEGER},{"y",TB_VALUE_INTEGER}, + {"r",TB_VALUE_REAL},{"g",TB_VALUE_REAL},{"b",TB_VALUE_REAL}}; + static const TinyBlocks_SlotDesc getp_in[] = {{"imagem",TB_VALUE_IMAGE},{"x",TB_VALUE_INTEGER},{"y",TB_VALUE_INTEGER}}; + + return reg(rt, lib, "PPM.Load", load_in, 1, img_out, 1, eval_load) + && reg(rt, lib, "PPM.Save", save_in, 2, NULL, 0, eval_save) + && reg(rt, lib, "PPM.New", new_in, 5, img_out, 1, eval_new) + && reg(rt, lib, "PPM.Width", wh_in, 1, n_out, 1, eval_width) + && reg(rt, lib, "PPM.Height", wh_in, 1, n_out, 1, eval_height) + && reg(rt, lib, "PPM.SetPixel", setp_in, 6, NULL, 0, eval_setpixel) + && reg(rt, lib, "PPM.GetPixel", getp_in, 3, rgb_out, 1, eval_getpixel); +} + +TINYBLOCKS_DEFINE_LIBRARY(ppm, "tinyblocks-ppm", "1.0.0", ppm_init, NULL) + +const TinyBlocks_LibraryDescriptor* tb_ppm_get_library(void) { + return &_tb_lib_desc_ppm; +} diff --git a/libraries/tinyblocks-sdl2/src/tb_sdl2.c b/libraries/tinyblocks-sdl2/src/tb_sdl2.c index 9016b4e..3e905ed 100644 --- a/libraries/tinyblocks-sdl2/src/tb_sdl2.c +++ b/libraries/tinyblocks-sdl2/src/tb_sdl2.c @@ -320,6 +320,47 @@ static void sdl2_execute(SDL_Renderer* ren, SDL_RenderSetClipRect(ren, NULL); break; + case TB_DRAW_IMAGE: + if (cmd->image) { + int iw = tb_image_width(cmd->image); + int ih = tb_image_height(cmd->image); + int ch = tb_image_channels(cmd->image); + const uint8_t* px = tb_image_data_const(cmd->image); + if (iw > 0 && ih > 0 && px) { + SDL_Surface* surf = NULL; + uint8_t* tmp = NULL; + if (ch == 4) { + surf = SDL_CreateRGBSurfaceWithFormatFrom((void*)px, iw, ih, 32, iw*4, + SDL_PIXELFORMAT_RGBA32); + } else if (ch == 3) { + surf = SDL_CreateRGBSurfaceWithFormatFrom((void*)px, iw, ih, 24, iw*3, + SDL_PIXELFORMAT_RGB24); + } else if (ch == 1) { + tmp = (uint8_t*)malloc((size_t)iw * (size_t)ih * 4); + if (tmp) { + size_t n = (size_t)iw * (size_t)ih; + for (size_t k = 0; k < n; k++) { + tmp[k*4+0] = tmp[k*4+1] = tmp[k*4+2] = px[k]; + tmp[k*4+3] = 255; + } + surf = SDL_CreateRGBSurfaceWithFormatFrom(tmp, iw, ih, 32, iw*4, + SDL_PIXELFORMAT_RGBA32); + } + } + if (surf) { + SDL_Texture* tex = SDL_CreateTextureFromSurface(ren, surf); + if (tex) { + SDL_Rect dst = {(int)cmd->x, (int)cmd->y, (int)cmd->w, (int)cmd->h}; + SDL_RenderCopy(ren, tex, NULL, &dst); + SDL_DestroyTexture(tex); + } + SDL_FreeSurface(surf); + } + free(tmp); + } + } + break; + case TB_DRAW_TEXT: if (cmd->text[0]) { TTF_Font* font = get_font((int)cmd->font_size); diff --git a/src/tb_image.c b/src/tb_image.c new file mode 100644 index 0000000..6aa74df --- /dev/null +++ b/src/tb_image.c @@ -0,0 +1,104 @@ +/* + * TinyBlocks - tb_image.c + * TinyBlocks_Image: buffer de pixels ref-counted com 1, 3 ou 4 canais. + */ +#include +#include + +#include "tinyblocks/tb_image.h" + +struct TinyBlocks_Image { + int refs; + int width; + int height; + int channels; /* 1 = cinza, 3 = RGB, 4 = RGBA */ + uint8_t* pixels; /* width * height * channels */ +}; + +static int valid_channels(int c) { return c == 1 || c == 3 || c == 4; } + +TinyBlocks_Image* tb_image_new(int w, int h, int channels) { + if (w <= 0 || h <= 0 || !valid_channels(channels)) return NULL; + TinyBlocks_Image* img = (TinyBlocks_Image*)calloc(1, sizeof(*img)); + if (!img) return NULL; + size_t n = (size_t)w * (size_t)h * (size_t)channels; + img->pixels = (uint8_t*)calloc(n ? n : 1, 1); + if (!img->pixels) { free(img); return NULL; } + img->refs = 1; + img->width = w; + img->height = h; + img->channels = channels; + return img; +} + +void tb_image_retain(TinyBlocks_Image* img) { + if (img) img->refs++; +} + +void tb_image_release(TinyBlocks_Image* img) { + if (!img) return; + if (--img->refs > 0) return; + free(img->pixels); + free(img); +} + +TinyBlocks_Image* tb_image_clone(const TinyBlocks_Image* img) { + if (!img) return NULL; + TinyBlocks_Image* c = tb_image_new(img->width, img->height, img->channels); + if (!c) return NULL; + size_t n = (size_t)img->width * (size_t)img->height * (size_t)img->channels; + memcpy(c->pixels, img->pixels, n); + return c; +} + +int tb_image_width (const TinyBlocks_Image* img) { return img ? img->width : 0; } +int tb_image_height (const TinyBlocks_Image* img) { return img ? img->height : 0; } +int tb_image_channels(const TinyBlocks_Image* img) { return img ? img->channels : 0; } + +uint8_t* tb_image_data (TinyBlocks_Image* img) { return img ? img->pixels : NULL; } +const uint8_t* tb_image_data_const(const TinyBlocks_Image* img) { return img ? img->pixels : NULL; } + +static bool in_bounds(const TinyBlocks_Image* img, int x, int y) { + return img && x >= 0 && y >= 0 && x < img->width && y < img->height; +} + +bool tb_image_set_pixel(TinyBlocks_Image* img, int x, int y, + uint8_t r, uint8_t g, uint8_t b, uint8_t a) { + if (!in_bounds(img, x, y)) return false; + uint8_t* p = img->pixels + ((size_t)y * img->width + x) * img->channels; + switch (img->channels) { + case 1: { unsigned v = (r * 299u + g * 587u + b * 114u) / 1000u; p[0] = (uint8_t)v; break; } + case 3: p[0] = r; p[1] = g; p[2] = b; break; + case 4: p[0] = r; p[1] = g; p[2] = b; p[3] = a; break; + default: return false; + } + return true; +} + +bool tb_image_get_pixel(const TinyBlocks_Image* img, int x, int y, + uint8_t* r, uint8_t* g, uint8_t* b, uint8_t* a) { + if (!in_bounds(img, x, y)) return false; + const uint8_t* p = img->pixels + ((size_t)y * img->width + x) * img->channels; + uint8_t rr = 0, gg = 0, bb = 0, aa = 255; + switch (img->channels) { + case 1: rr = gg = bb = p[0]; aa = 255; break; + case 3: rr = p[0]; gg = p[1]; bb = p[2]; aa = 255; break; + case 4: rr = p[0]; gg = p[1]; bb = p[2]; aa = p[3]; break; + default: return false; + } + if (r) *r = rr; + if (g) *g = gg; + if (b) *b = bb; + if (a) *a = aa; + return true; +} + +TinyBlocks_Value tb_value_image(TinyBlocks_Image* img) { + TinyBlocks_Value v = { .kind = TB_VALUE_IMAGE, .as.image = img }; + if (img) tb_image_retain(img); + return v; +} + +TinyBlocks_Image* tb_value_as_image(TinyBlocks_Value v) { + return v.kind == TB_VALUE_IMAGE ? v.as.image : NULL; +} diff --git a/src/tb_renderable_block.c b/src/tb_renderable_block.c index cf1af6a..7ea86b8 100644 --- a/src/tb_renderable_block.c +++ b/src/tb_renderable_block.c @@ -125,6 +125,16 @@ void tb_draw_text(TinyBlocks_RenderableBlock* rb, strncpy(c->text, text, sizeof(c->text) - 1); } +void tb_draw_image(TinyBlocks_RenderableBlock* rb, + float x, float y, float w, float h, + const TinyBlocks_Image* image) { + if (!image) return; + TinyBlocks_DrawCmd* c = append(rb); if (!c) return; + c->kind = TB_DRAW_IMAGE; + c->x = x; c->y = y; c->w = w; c->h = h; + c->image = image; +} + void tb_draw_merge_offset(TinyBlocks_RenderableBlock* dst, const TinyBlocks_RenderableBlock* src, float dx, float dy) { @@ -143,6 +153,9 @@ void tb_draw_merge_offset(TinyBlocks_RenderableBlock* dst, case TB_DRAW_STROKE_CIRCLE: cmd.x += dx; cmd.y += dy; break; + case TB_DRAW_IMAGE: + cmd.x += dx; cmd.y += dy; + break; case TB_DRAW_STROKE_LINE: cmd.x += dx; cmd.y += dy; cmd.w += dx; cmd.h += dy; diff --git a/src/tb_value.c b/src/tb_value.c index 52a74da..cd0e1b4 100644 --- a/src/tb_value.c +++ b/src/tb_value.c @@ -42,6 +42,8 @@ TinyBlocks_Value tb_value_clone(TinyBlocks_Value v) tb_vector_data_retain(v.as.vector); if (v.kind == TB_VALUE_JSON && v.as.json) tb_json_retain(v.as.json); + if (v.kind == TB_VALUE_IMAGE && v.as.image) + tb_image_retain(v.as.image); return v; } @@ -57,6 +59,9 @@ void tb_value_free(TinyBlocks_Value* v) } else if (v->kind == TB_VALUE_JSON) { tb_json_release(v->as.json); v->as.json = NULL; + } else if (v->kind == TB_VALUE_IMAGE) { + tb_image_release(v->as.image); + v->as.image = NULL; } v->kind = TB_VALUE_NONE; } diff --git a/tests/editor_harness.c b/tests/editor_harness.c index 0ae9b54..7c05292 100644 --- a/tests/editor_harness.c +++ b/tests/editor_harness.c @@ -16,6 +16,7 @@ #include #include #include +#include static TinyBlocks* rt; static TinyBlocks_Block *ev, *scene; @@ -126,6 +127,7 @@ int main(void) { tb_library_register(rt, tb_pen_get_library()); tb_library_register(rt, tb_curves_get_library()); tb_library_register(rt, tb_base64_get_library()); + tb_library_register(rt, tb_ppm_get_library()); tb_library_register(rt, tb_graphics_get_library()); tb_library_register(rt, tb_editor_get_library()); (void)eval_ev; @@ -438,6 +440,21 @@ int main(void) { } CHECK(ws_has("37 pontos"), "balão mostra a contagem de pontos da curva"); + /* 20. Previa de imagem: PPM.New em balão desenha TB_DRAW_IMAGE */ + if (need("PPM", R_CAT, 0, &x, &y)) click(x, y); + frame(0, 0, 0, 0, 0, 0, NULL); + if (need("nova imagem(", R_FLY, 0, &x, &y)) drag(x, y, 640, 520); + frame(0, 0, 0, 0, 0, 0, NULL); + if (need("nova imagem(", R_WS, 0, &x, &y)) { click(x, y); click(x, y); } + frame(0, 0, 0, 0, 0, 0, NULL); + { + int imgs = 0; + for (uint32_t i = 0; i < ncmd; i++) + if (cmds[i].kind == TB_DRAW_IMAGE) imgs++; + CHECK(imgs >= 1, "clique duplo numa imagem desenha TB_DRAW_IMAGE no balão"); + } + CHECK(ws_has("32x32"), "balão mostra as dimensões da imagem"); + printf("comandos de desenho no último frame: %u\n", ncmd); tinyblocks_deinit(&rt); printf(fails ? "\n%d FALHA(S)\n" : "\nTUDO OK\n", fails); diff --git a/tests/ppm_test.c b/tests/ppm_test.c new file mode 100644 index 0000000..d98fef2 --- /dev/null +++ b/tests/ppm_test.c @@ -0,0 +1,121 @@ +/* + * ppm_test.c - testa tinyblocks-ppm e o tipo imagem do core: + * TinyBlocks_Image (pixels, clone), leitura/gravacao P6 e P3, e os blocos. + */ +#include +#include +#include +#include +#include + +static int fails = 0; +#define CHECK(c, m) do { if (c) printf("ok %s\n", m); else { printf("FAIL %s\n", m); fails++; } } while (0) + +static void set_num(TinyBlocks_Block* b, uint32_t i, double v) { + TinyBlocks_Value vv = tb_value_real(v); + tb_block_set_default(b, i, vv); + tb_value_free(&vv); +} +int main(void) { + /* -- Tipo imagem (core) --- */ + TinyBlocks_Image* img = tb_image_new(4, 3, 3); + CHECK(img && tb_image_width(img) == 4 && tb_image_height(img) == 3 && + tb_image_channels(img) == 3, "tb_image_new cria 4x3 RGB"); + tb_image_set_pixel(img, 1, 2, 10, 20, 30, 255); + uint8_t r, g, b, a; + CHECK(tb_image_get_pixel(img, 1, 2, &r, &g, &b, &a) && r == 10 && g == 20 && b == 30, + "set/get pixel consistentes"); + CHECK(!tb_image_get_pixel(img, 9, 9, &r, &g, &b, &a), "pixel fora da imagem -> false"); + + TinyBlocks_Image* cp = tb_image_clone(img); + CHECK(cp && tb_image_get_pixel(cp, 1, 2, &r, &g, &b, &a) && r == 10, "clone copia os pixels"); + + /* valor ref-counted */ + TinyBlocks_Value vi = tb_value_image(img); + CHECK(vi.kind == TB_VALUE_IMAGE && tb_value_as_image(vi) == img, "tb_value_image/as_image"); + tb_value_free(&vi); /* solta o ref do valor */ + tb_image_release(cp); + tb_image_release(img); + + /* -- PPM: grava P6 e le de volta --- */ + TinyBlocks_Image* pic = tb_image_new(2, 2, 3); + tb_image_set_pixel(pic, 0, 0, 255, 0, 0, 255); + tb_image_set_pixel(pic, 1, 0, 0, 255, 0, 255); + tb_image_set_pixel(pic, 0, 1, 0, 0, 255, 255); + tb_image_set_pixel(pic, 1, 1, 255, 255, 0, 255); + CHECK(tb_ppm_save(pic, "build/ppm_test_out.ppm"), "tb_ppm_save grava P6"); + + TinyBlocks_Image* rd = tb_ppm_load("build/ppm_test_out.ppm"); + CHECK(rd && tb_image_width(rd) == 2 && tb_image_height(rd) == 2, "tb_ppm_load le as dimensoes"); + if (rd) { + tb_image_get_pixel(rd, 1, 1, &r, &g, &b, &a); + CHECK(r == 255 && g == 255 && b == 0, "pixel amarelo preservado no round-trip"); + } + remove("build/ppm_test_out.ppm"); + + /* -- PPM P3 (ASCII) escrito a mao --- */ + { + FILE* f = fopen("build/ppm_test_ascii.ppm", "wb"); + fprintf(f, "P3\n# comentario\n2 1\n255\n255 0 0 0 255 0\n"); + fclose(f); + TinyBlocks_Image* a3 = tb_ppm_load("build/ppm_test_ascii.ppm"); + CHECK(a3 && tb_image_width(a3) == 2 && tb_image_height(a3) == 1, "le P3 ASCII com comentario"); + if (a3) { + tb_image_get_pixel(a3, 0, 0, &r, &g, &b, &a); + tb_image_get_pixel(a3, 1, 0, &r, &g, &b, &a); + CHECK(g == 255 && r == 0, "segundo pixel do P3 = verde"); + } + if (a3) tb_image_release(a3); + remove("build/ppm_test_ascii.ppm"); + } + + /* arquivo inexistente */ + CHECK(tb_ppm_load("build/nao_existe.ppm") == NULL, "load de arquivo ausente -> NULL"); + CHECK(strlen(tb_ppm_last_error()) > 0, "mensagem de erro preenchida"); + tb_image_release(rd); + tb_image_release(pic); + + /* -- Blocos --- */ + TinyBlocks* rt; + tinyblocks_init(&rt, NULL); + tb_library_register(rt, tb_ppm_get_library()); + + const char* names[] = {"PPM.Load","PPM.Save","PPM.New","PPM.Width","PPM.Height", + "PPM.SetPixel","PPM.GetPixel"}; + int all = 1; + for (size_t i = 0; i < sizeof(names)/sizeof(names[0]); i++) + if (!tb_rt_find_type(rt, names[i])) { all = 0; printf(" falta %s\n", names[i]); } + CHECK(all, "todos os blocos PPM.* registrados"); + { + TinyBlocks_TypeBlock* t0 = tb_rt_find_type(rt, "PPM.New"); + const TinyBlocks_Category* cat = tb_library_category((const TinyBlocks_LibraryBlock*)t0->base.parent); + CHECK(cat && strcmp(cat->name, "PPM") == 0, "categoria 'PPM'"); + } + + /* PPM.New -> largura/altura */ + TinyBlocks_Block* bn = tb_block_create(rt, tb_rt_find_type(rt, "PPM.New")); + set_num(bn, 0, 3); set_num(bn, 1, 2); + set_num(bn, 2, 12); set_num(bn, 3, 34); set_num(bn, 4, 56); + tb_block_eval(bn, rt); + CHECK(bn->outputs[0].kind == TB_VALUE_IMAGE, "PPM.New devolve imagem"); + TinyBlocks_Image* bi = bn->outputs[0].as.image; + CHECK(tb_image_width(bi) == 3 && tb_image_height(bi) == 2, "PPM.New respeita dimensoes"); + tb_image_get_pixel(bi, 0, 0, &r, &g, &b, &a); + CHECK(r == 12 && g == 34 && b == 56, "PPM.New preenche com a cor"); + + TinyBlocks_Block* bw = tb_block_create(rt, tb_rt_find_type(rt, "PPM.Width")); + { + TinyBlocks_Value vv = tb_value_image(bi); + tb_block_set_default(bw, 0, vv); + tb_value_free(&vv); + } + tb_block_eval(bw, rt); + CHECK(bw->outputs[0].as.integer == 3, "PPM.Width -> 3"); + + tb_block_destroy(bn, rt); tb_block_destroy(bw, rt); + tinyblocks_deinit(&rt); + + if (fails) printf("\n%d FALHA(S)\n", fails); + else printf("\nTUDO OK\n"); + return fails != 0; +}