/* * d3_test.c - testa a tinyblocks-3d pelos blocos (cena, objetos, colisao, * camera) e compara os renderizadores: o software e a referencia; o Vulkan * (tinyblocks-vk) e o OpenGL (tinyblocks-gl), se estiverem compilados e * houver placa/driver, precisam dar quase a mesma imagem. Grava * /tmp/tb_3d_.png. */ #include #include #include #include #include #include #include #include #ifdef WITH_GL #include #endif #ifdef WITH_VK #include #endif 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 TinyBlocks* rt; static TinyBlocks_Block* run(const char* type, const char* const* args, int n) { TinyBlocks_Block* x = tb_block_create(rt, tb_type_block_find(rt, type)); for (int i = 0; i < n; i++) if (args[i]) { TinyBlocks_Value t = tb_value_text(args[i]); tb_block_set_default(x, (uint32_t)i, t); tb_value_free(&t); } tb_block_eval(x, rt); return x; } #define RUN(type, ...) run(type, (const char* const[]){ __VA_ARGS__ }, (int)(sizeof((const char* const[]){ __VA_ARGS__ }) / sizeof(char*))) /* "compile o shader [pilha]" com o codigo (JSON) da pilha: o bloco (a saida e o shader compilado), ou NULL em erro */ static TinyBlocks_Block* compile_shader(const char* json) { TinyBlocks_Block* x = tb_block_create(rt, tb_type_block_find(rt, "3D.Shader")); TinyBlocks_JsonValue* j = tb_json_parse(json, NULL, 0); TinyBlocks_Value jv = tb_value_json(j); tb_block_set_default(x, 0, jv); tb_value_free(&jv); tb_json_release(j); tinyblocks_clear_error(rt); tb_block_eval(x, rt); return tinyblocks_last_error(rt)[0] ? NULL : x; } /* bloco com o shader (valor) na entrada 0 e um texto na 1 */ static TinyBlocks_Block* run_with_shader(const char* type, TinyBlocks_Block* sh, const char* obj) { TinyBlocks_Block* x = tb_block_create(rt, tb_type_block_find(rt, type)); tb_block_set_default(x, 0, sh->outputs[0]); if (obj) { TinyBlocks_Value t = tb_value_text(obj); tb_block_set_default(x, 1, t); tb_value_free(&t); } tb_block_eval(x, rt); return x; } #define BLK(t, ...) "{\"type\":\"" t "\",\"inputs\":[" __VA_ARGS__ "]}" #define BLK0(t) "{\"type\":\"" t "\",\"inputs\":[]}" static TinyBlocks_Image* render_with(const char* who) { RUN("3D.Use", who); TinyBlocks_Block* b = RUN("3D.Image", "320", "240"); if (b->outputs[0].kind != TB_VALUE_IMAGE) return NULL; TinyBlocks_Image* img = b->outputs[0].as.image; tb_image_retain(img); TinyBlocks_Block* r = RUN("3D.Renderer", NULL); printf(" renderizador: %s\n", r->outputs[0].kind == TB_VALUE_TEXT ? r->outputs[0].as.text : "?"); char path[64]; snprintf(path, sizeof(path), "/tmp/tb_3d_%s.png", who); tb_image_save(img, path); return img; } /* Diferenca media por canal (0..255) e fracao de pixels muito diferentes */ static void compare(const TinyBlocks_Image* a, const TinyBlocks_Image* b, double* mean, double* bad) { const uint8_t* p = tb_image_data_const(a); const uint8_t* q = tb_image_data_const(b); size_t n = (size_t)tb_image_width(a) * tb_image_height(a); double s = 0; size_t nb = 0; for (size_t i = 0; i < n; i++) { int d = 0; for (int c = 0; c < 3; c++) { int e = abs(p[i * 4 + c] - q[i * 4 + c]); s += e; if (e > d) d = e; } if (d > 40) nb++; } *mean = s / (n * 3.0); *bad = (double)nb / n; } int main(void) { setvbuf(stdout, NULL, _IOLBF, 0); tinyblocks_init(&rt, NULL); tb_library_register(rt, tb_png_get_library()); tb_library_register(rt, tb_3d_get_library()); #ifdef WITH_GL tb_library_register(rt, tb_gl_get_library()); #endif #ifdef WITH_VK tb_library_register(rt, tb_vk_get_library()); #endif RUN("3D.Scene", NULL); RUN("3D.Plane", "chão", "0", "0", "0"); RUN("3D.Scale", "chão", "12", "1", "12"); RUN("3D.Color", "chão", "verde"); RUN("3D.Cube", "jogador", "0", "0.5", "0"); RUN("3D.Color", "jogador", "vermelho"); RUN("3D.RotateTo", "jogador", "0", "30", "0"); RUN("3D.Sphere", "bola", "2", "0.5", "-1"); RUN("3D.Color", "bola", "azul"); RUN("3D.Cylinder", "moeda", "-2", "0.6", "1"); RUN("3D.Scale", "moeda", "0.8", "0.15", "0.8"); RUN("3D.RotateTo", "moeda", "90", "0", "0"); RUN("3D.Color", "moeda", "dourado"); RUN("3D.Camera", "0", "4", "7", "0", "0.5", "0"); CHECK(RUN("3D.Count", NULL)->outputs[0].as.integer == 4, "4 objetos na cena"); /* colisao e posicao */ CHECK(!RUN("3D.Touching", "jogador", "bola")->outputs[0].as.integer, "jogador longe da bola não encosta"); RUN("3D.MoveTo", "bola", "0.6", "0.5", "0"); CHECK(RUN("3D.Touching", "jogador", "bola")->outputs[0].as.integer, "jogador encosta na bola depois de movê-la"); CHECK(RUN("3D.Touching", "jogador", "chão")->outputs[0].as.integer, "cubo apoiado encosta no chão"); RUN("3D.MoveBy", "bola", "1.4", "0", "-1"); CHECK(fabs(RUN("3D.X", "bola")->outputs[0].as.real - 2.0) < 1e-5, "mova por soma à posição"); CHECK(fabs(RUN("3D.Distance", "jogador", "bola")->outputs[0].as.real - sqrt(5.0)) < 1e-4, "distância entre os centros"); TinyBlocks_Block* e = RUN("3D.Hide", "nada"); (void)e; CHECK(tinyblocks_last_error(rt)[0], "objeto que não existe dá erro"); tinyblocks_clear_error(rt); /* software: a referencia */ TinyBlocks_Image* sw = render_with("software"); CHECK(sw != NULL, "imagem da cena pelo software"); if (sw) { uint8_t r, g, b, a; tb_image_get_pixel(sw, 2, 2, &r, &g, &b, &a); CHECK(abs(r - 135) < 3 && abs(g - 199) < 3 && abs(b - 250) < 3, "o céu no canto"); tb_image_get_pixel(sw, 160, 118, &r, &g, &b, &a); CHECK(r > 120 && g < 80 && b < 80, "o cubo vermelho no meio"); tb_image_get_pixel(sw, 160, 230, &r, &g, &b, &a); CHECK(g > r && g > b, "o chão verde embaixo"); } const char* gpu[] = { "opengl", "vulkan" }; for (int pass = 0; pass < 2; pass++) { if (pass == 1) { /* -- shaders feitos com blocos: xadrez no chao, degrade na bola */ const char* xadrez = "[{\"type\":\"Control.IfElse\",\"inputs\":[" BLK("Operators.Eq", BLK("Math.Mod", BLK("Math.Add", BLK("Number.Floor", BLK0("Shader.X")) "," BLK("Number.Floor", BLK0("Shader.Z"))) ",2") ",0") "],\"mouths\":[[" BLK("Shader.Pixel", BLK("Math.Mul", BLK("Shader.Color", "\"branco\"") "," BLK0("Shader.Light"))) "],[" BLK("Shader.Pixel", BLK("Math.Mul", BLK("Shader.Color", "\"#333333\"") "," BLK0("Shader.Light"))) "]]}]"; TinyBlocks_Block* sx = compile_shader(xadrez); CHECK(sx && sx->outputs[0].kind == TB_VALUE_BLOCK, "compila o xadrez (se/senão, resto, arredonde, cor, luz): um valor"); const char* degrade = "[" BLK("Variables.Set", "\"t\"," BLK("Math.Div", BLK("Math.Add", BLK0("Shader.NY") ",1") ",2")) "," BLK("Shader.Pixel", BLK("Math.Mul", BLK("Shader.Mix", BLK("Shader.Color", "\"azul\"") "," BLK("Shader.Color", "\"branco\"") "," BLK("Variables.Get", "\"t\"")) "," BLK0("Shader.Light"))) "]"; TinyBlocks_Block* sd = compile_shader(degrade); CHECK(sd != NULL, "compila o degradê (variável local, misture)"); if (!sx || !sd) return 1; char vt[128]; tb_value_to_text(sx->outputs[0], vt, sizeof(vt)); printf(" valor: %s\n", vt); CHECK(strstr(vt, "vulkan: ") && strstr(vt, "opengl: "), "o shader compilado leva o binário de cada renderizador (Vulkan: SPIR-V; OpenGL: o do driver)"); run_with_shader("3D.ShaderUse", sx, "chão"); run_with_shader("3D.ShaderUse", sd, "bola"); CHECK(!tinyblocks_last_error(rt)[0], "use o shader no objeto"); TinyBlocks_Block* g = run_with_shader("3D.ShaderGlsl", sx, NULL); CHECK(g->outputs[0].kind == TB_VALUE_TEXT && strstr(g->outputs[0].as.text, "vec3 tb_shade(") && strstr(g->outputs[0].as.text, "mod("), "GLSL gerado"); CHECK(!compile_shader("[" BLK("Shader.Pixel", BLK0("Input.Timer")) "]") && strstr(tinyblocks_last_error(rt), "não pode ser usado num shader"), "bloco que não cabe num shader: erro claro"); CHECK(!compile_shader("[{\"type\":\"Control.If\",\"inputs\":[" BLK("Operators.Lt", BLK0("Shader.PixelColor") ",1") "],\"mouths\":[[]]}]") && strstr(tinyblocks_last_error(rt), "comparar números"), "comparar cor: erro claro"); tinyblocks_clear_error(rt); tb_image_release(sw); sw = render_with("software"); CHECK(sw != NULL, "cena com shaders pelo software"); if (sw) { uint8_t r, g2, b, a, r2, g3, b2; tb_image_get_pixel(sw, 40, 225, &r, &g2, &b, &a); tb_image_get_pixel(sw, 75, 225, &r2, &g3, &b2, &a); CHECK(abs(r - g2) < 4 && abs(r2 - g3) < 4 && abs(r - r2) > 60, "o chão virou xadrez (cinza claro e escuro)"); } } for (int i = 0; i < 2; i++) { const char* lib = i ? "tinyblocks-vk" : "tinyblocks-gl"; if (!tb_rt_find_library(rt, lib)) { printf("-- %s não compilado neste teste\n", gpu[i]); continue; } TinyBlocks_Image* img = render_with(gpu[i]); TinyBlocks_Block* r = RUN("3D.Renderer", NULL); const char* used = r->outputs[0].kind == TB_VALUE_TEXT ? r->outputs[0].as.text : ""; if (strncmp(used, gpu[i], strlen(gpu[i])) != 0) { printf("-- %s indisponível aqui (%s)\n", gpu[i], used); tb_image_release(img); continue; } double mean = 0, bad = 1; if (img && sw) compare(sw, img, &mean, &bad); printf(" %s x software: diferença média %.3f, pixels muito diferentes %.2f%%\n", gpu[i], mean, bad * 100); char m[96]; snprintf(m, sizeof(m), pass ? "%s com shaders desenha quase igual ao software" : "%s desenha quase igual ao software", gpu[i]); CHECK(img && mean < 4.0 && bad < 0.02, m); if (pass) { char path[64]; snprintf(path, sizeof(path), "/tmp/tb_3d_%s_shader.png", gpu[i]); tb_image_save(img, path); } tb_image_release(img); } } /* -- malha personalizada + uv: um quadrado pintado pelo uv -- */ { RUN("3D.Scene", NULL); RUN("3D.MeshCreate", "quad"); const char* vx[4][3] = { {"-1","-1","0"}, {"1","-1","0"}, {"1","1","0"}, {"-1","1","0"} }; const char* tx[4][2] = { {"0","0"}, {"1","0"}, {"1","1"}, {"0","1"} }; for (int i = 0; i < 4; i++) { RUN("3D.MeshVertex", "quad", vx[i][0], vx[i][1], vx[i][2]); RUN("3D.MeshUV", "quad", tx[i][0], tx[i][1]); } RUN("3D.MeshTri", "quad", "1", "2", "3"); RUN("3D.MeshTri", "quad", "1", "3", "4"); RUN("3D.MeshFinish", "quad"); CHECK(!tinyblocks_last_error(rt)[0], "malha personalizada: monta sem erro (normais calculadas)"); CHECK(RUN("3D.Count", NULL)->outputs[0].as.integer == 1, "a malha entra na cena como objeto"); CHECK(RUN("3D.X", "quad")->outputs[0].as.real == 0, "mova/gire valem para a malha também"); RUN("3D.Camera", "0", "0", "4", "0", "0", "0"); const char* uvsh = "[" BLK("Shader.Pixel", BLK("Shader.Rgb", BLK0("Shader.U") "," BLK0("Shader.V") "," "0")) "]"; TinyBlocks_Block* su = compile_shader(uvsh); CHECK(su != NULL, "shader com u do uv / v do uv compila"); if (su) { TinyBlocks_Block* g = run_with_shader("3D.ShaderGlsl", su, NULL); CHECK(g->outputs[0].kind == TB_VALUE_TEXT && strstr(g->outputs[0].as.text, "UV.x") && strstr(g->outputs[0].as.text, "UV.y"), "o GLSL gerado usa o uv"); run_with_shader("3D.ShaderUse", su, "quad"); } TinyBlocks_Image* ui = render_with("software"); CHECK(ui != NULL, "a malha personalizada desenha"); if (ui) { uint8_t l[4], r[4]; tb_image_get_pixel(ui, 125, 120, &l[0], &l[1], &l[2], &l[3]); tb_image_get_pixel(ui, 195, 120, &r[0], &r[1], &r[2], &r[3]); printf(" quad por uv: esquerda r=%d direita r=%d\n", l[0], r[0]); CHECK(r[0] > 150 && l[0] < 100, "o uv pinta da esquerda (u=0) para a direita (u=1)"); for (int i = 0; i < 2; i++) { const char* lib = i ? "tinyblocks-vk" : "tinyblocks-gl"; if (!tb_rt_find_library(rt, lib)) continue; TinyBlocks_Image* gi = render_with(gpu[i]); TinyBlocks_Block* gr = RUN("3D.Renderer", NULL); const char* used = gr->outputs[0].kind == TB_VALUE_TEXT ? gr->outputs[0].as.text : ""; if (strncmp(used, gpu[i], strlen(gpu[i])) != 0) { tb_image_release(gi); continue; } double mean = 0, bad = 1; if (gi) compare(ui, gi, &mean, &bad); printf(" malha %s x software: diferença média %.3f, pixels muito diferentes %.2f%%\n", gpu[i], mean, bad * 100); char m[96]; snprintf(m, sizeof(m), "a malha personalizada com uv desenha igual no %s", gpu[i]); CHECK(gi && mean < 4.0 && bad < 0.02, m); tb_image_release(gi); } } tb_image_release(ui); } tb_image_release(sw); tinyblocks_deinit(&rt); if (fails) printf("\n%d FALHA(S)\n", fails); else printf("\nTUDO OK\n"); return fails != 0; }