Files
tinyblocks/libraries/tinyblocks-3d/src/tb_3d.c
T
mguinhosandClaude Opus 5 d5c16a5237 3D: shader de vértice (o "compile o shader" descobre o estágio)
- novo bloco "mude a posição do vértice para x y z" (Shader.Vertex): a
  pilha que o usa vira um shader de VÉRTICE; a que usa "cor do pixel" vira
  de FRAGMENTO; misturar os dois dá erro claro
- o GLSL gerado é tb_vert (vértice) ou tb_shade (fragmento); o software
  roda o mesmo programa vértice a vértice
- OpenGL e Vulkan montam o programa do estágio certo e juntam com o
  estágio padrão (posição intacta / cor do objeto com luz)
- Tb3dShader ganha "stage"; Tb3dRenderer.compile leva o estágio;
  TB_3D_RENDERER_VERSION -> 5
- docs regeradas (blocos, referência da API, libraries, pendências) e
  exemplo examples/jogo-3d/onda.sb (esfera que pulsa)
- test-3d: o shader de vértice dá igual nos 3 renderizadores

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-10-29 00:58:21 -03:00

1128 lines
51 KiB
C

/*
* TinyBlocks - tb_3d.c
* A cena 3D (objetos com nome, camera, luz), as malhas fixas, o
* rasterizador em software, a escolha do renderizador e os blocos da
* categoria "3D".
*/
#define _POSIX_C_SOURCE 200809L
#include <ctype.h>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <tinyblocks/tinyblocks.h>
#include <tinyblocks/tb_image.h>
#include <time.h>
#include "tb_3d.h"
#include "d3_internal.h"
#define PI_F 3.14159265358979f
/* == Matematica (column-major: m[col * 4 + row]) ====================== */
void tb_3d_mat_identity(float m[16]) {
memset(m, 0, 16 * sizeof(float));
m[0] = m[5] = m[10] = m[15] = 1.f;
}
void tb_3d_mat_mul(float out[16], const float a[16], const float b[16]) {
float r[16];
for (int c = 0; c < 4; c++)
for (int i = 0; i < 4; i++) {
float s = 0;
for (int k = 0; k < 4; k++) s += a[k * 4 + i] * b[c * 4 + k];
r[c * 4 + i] = s;
}
memcpy(out, r, sizeof(r));
}
void tb_3d_mat_perspective(float m[16], float fovy_deg, float aspect, float zn, float zf) {
float f = 1.f / tanf(fovy_deg * PI_F / 360.f);
memset(m, 0, 16 * sizeof(float));
m[0] = f / aspect;
m[5] = f;
m[10] = (zf + zn) / (zn - zf);
m[11] = -1.f;
m[14] = 2.f * zf * zn / (zn - zf);
}
static void v3_sub(float o[3], const float a[3], const float b[3]) { o[0] = a[0] - b[0]; o[1] = a[1] - b[1]; o[2] = a[2] - b[2]; }
static void v3_cross(float o[3], const float a[3], const float b[3]) {
float r[3] = { a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] };
memcpy(o, r, sizeof(r));
}
static float v3_dot(const float a[3], const float b[3]) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; }
static void v3_norm(float v[3]) {
float l = sqrtf(v3_dot(v, v));
if (l > 1e-12f) { v[0] /= l; v[1] /= l; v[2] /= l; }
}
void tb_3d_mat_look_at(float m[16], const float eye[3], const float at[3], const float up[3]) {
float f[3], s[3], u[3];
v3_sub(f, at, eye); v3_norm(f);
v3_cross(s, f, up);
if (v3_dot(s, s) < 1e-10f) { /* olhando reto para cima/baixo */
float alt[3] = { 0, 0, 1 };
v3_cross(s, f, alt);
}
v3_norm(s);
v3_cross(u, s, f);
tb_3d_mat_identity(m);
m[0] = s[0]; m[4] = s[1]; m[8] = s[2];
m[1] = u[0]; m[5] = u[1]; m[9] = u[2];
m[2] = -f[0]; m[6] = -f[1]; m[10] = -f[2];
m[12] = -v3_dot(s, eye); m[13] = -v3_dot(u, eye); m[14] = v3_dot(f, eye);
}
/* Rotacao Y (yaw) * X (pitch) * Z (roll), em graus: a 3x3 em colunas */
static void rot3(float r[9], const float deg[3]) {
float ax = deg[0] * PI_F / 180.f, ay = deg[1] * PI_F / 180.f, az = deg[2] * PI_F / 180.f;
float cx = cosf(ax), sx = sinf(ax), cy = cosf(ay), sy = sinf(ay), cz = cosf(az), sz = sinf(az);
/* Ry*Rx*Rz, linha i coluna j em r[j*3+i] */
float m[3][3] = {
{ cy * cz + sy * sx * sz, -cy * sz + sy * sx * cz, sy * cx },
{ cx * sz, cx * cz, -sx },
{ -sy * cz + cy * sx * sz, sy * sz + cy * sx * cz, cy * cx },
};
for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) r[j * 3 + i] = m[i][j];
}
/* == Malhas fixas (tamanho 1, centradas na origem) ===================== */
typedef struct { float* v; uint32_t* ix; int vn, in, vcap, icap; } MeshBuf;
static void mb_vert(MeshBuf* b, float x, float y, float z, float nx, float ny, float nz, float u, float v) {
if (b->vn == b->vcap) { b->vcap = b->vcap ? b->vcap * 2 : 64; b->v = realloc(b->v, (size_t)b->vcap * 8 * sizeof(float)); }
float* p = b->v + (size_t)b->vn * 8;
p[0] = x; p[1] = y; p[2] = z; p[3] = nx; p[4] = ny; p[5] = nz; p[6] = u; p[7] = v;
b->vn++;
}
static void mb_tri(MeshBuf* b, int i0, int i1, int i2) {
if (b->in + 3 > b->icap) { b->icap = b->icap ? b->icap * 2 : 96; b->ix = realloc(b->ix, (size_t)b->icap * sizeof(uint32_t)); }
b->ix[b->in++] = (uint32_t)i0; b->ix[b->in++] = (uint32_t)i1; b->ix[b->in++] = (uint32_t)i2;
}
enum { K_CUBE, K_SPHERE, K_PLANE, K_CYLINDER, K_COUNT, K_CUSTOM };
static Tb3dMesh s_mesh[K_COUNT];
static MeshBuf s_mb[K_COUNT];
static void build_cube(MeshBuf* b) {
static const float n[6][3] = { {1,0,0}, {-1,0,0}, {0,1,0}, {0,-1,0}, {0,0,1}, {0,0,-1} };
for (int f = 0; f < 6; f++) {
float N[3] = { n[f][0], n[f][1], n[f][2] }, U[3], V[3];
float a[3] = { fabsf(N[1]) > 0.5f ? 1.f : 0.f, fabsf(N[1]) > 0.5f ? 0.f : 1.f, 0 };
v3_cross(U, N, a); v3_cross(V, N, U); /* U x V = N: frente para fora */
int base = b->vn;
for (int k = 0; k < 4; k++) {
float su = (k == 1 || k == 2) ? 0.5f : -0.5f, sv = (k >= 2) ? 0.5f : -0.5f;
mb_vert(b, N[0] * 0.5f + U[0] * su + V[0] * sv, N[1] * 0.5f + U[1] * su + V[1] * sv,
N[2] * 0.5f + U[2] * su + V[2] * sv, N[0], N[1], N[2], su + 0.5f, sv + 0.5f);
}
mb_tri(b, base, base + 1, base + 2);
mb_tri(b, base, base + 2, base + 3);
}
}
static void build_sphere(MeshBuf* b, int seg, int ring) {
for (int r = 0; r <= ring; r++) {
float th = PI_F * r / ring;
for (int s = 0; s <= seg; s++) {
float ph = 2 * PI_F * s / seg;
float x = sinf(th) * cosf(ph), y = cosf(th), z = sinf(th) * sinf(ph);
mb_vert(b, x * 0.5f, y * 0.5f, z * 0.5f, x, y, z, (float)s / seg, 1.f - (float)r / ring);
}
}
for (int r = 0; r < ring; r++)
for (int s = 0; s < seg; s++) {
int a = r * (seg + 1) + s, c = a + seg + 1;
mb_tri(b, a, a + 1, c);
mb_tri(b, a + 1, c + 1, c);
}
}
static void build_plane(MeshBuf* b) {
mb_vert(b, -0.5f, 0, -0.5f, 0, 1, 0, 0, 0);
mb_vert(b, -0.5f, 0, 0.5f, 0, 1, 0, 0, 1);
mb_vert(b, 0.5f, 0, 0.5f, 0, 1, 0, 1, 1);
mb_vert(b, 0.5f, 0, -0.5f, 0, 1, 0, 1, 0);
mb_tri(b, 0, 1, 2);
mb_tri(b, 0, 2, 3);
}
static void build_cylinder(MeshBuf* b, int seg) {
for (int s = 0; s <= seg; s++) { /* lateral */
float ph = 2 * PI_F * s / seg, x = cosf(ph), z = sinf(ph);
mb_vert(b, x * 0.5f, -0.5f, z * 0.5f, x, 0, z, (float)s / seg, 0);
mb_vert(b, x * 0.5f, 0.5f, z * 0.5f, x, 0, z, (float)s / seg, 1);
}
for (int s = 0; s < seg; s++) {
int a = s * 2;
mb_tri(b, a, a + 1, a + 2);
mb_tri(b, a + 1, a + 3, a + 2);
}
for (int cap = 0; cap < 2; cap++) { /* tampas */
float y = cap ? 0.5f : -0.5f, ny = cap ? 1.f : -1.f;
int c = b->vn;
mb_vert(b, 0, y, 0, 0, ny, 0, 0.5f, 0.5f);
for (int s = 0; s <= seg; s++) {
float ph = 2 * PI_F * s / seg;
mb_vert(b, cosf(ph) * 0.5f, y, sinf(ph) * 0.5f, 0, ny, 0, cosf(ph) * 0.5f + 0.5f, sinf(ph) * 0.5f + 0.5f);
}
for (int s = 0; s < seg; s++) {
if (cap) mb_tri(b, c, c + 2 + s, c + 1 + s);
else mb_tri(b, c, c + 1 + s, c + 2 + s);
}
}
}
static void meshes_build(void) {
if (s_mesh[0].id) return;
build_cube(&s_mb[K_CUBE]);
build_sphere(&s_mb[K_SPHERE], 20, 14);
build_plane(&s_mb[K_PLANE]);
build_cylinder(&s_mb[K_CYLINDER], 24);
for (int k = 0; k < K_COUNT; k++)
s_mesh[k] = (Tb3dMesh){ k + 1, 1u, s_mb[k].v, s_mb[k].vn, s_mb[k].ix, s_mb[k].in };
}
static void meshes_free(void) {
for (int k = 0; k < K_COUNT; k++) { free(s_mb[k].v); free(s_mb[k].ix); memset(&s_mb[k], 0, sizeof(s_mb[k])); }
memset(s_mesh, 0, sizeof(s_mesh));
}
/* == Cena =============================================================== */
/* Malha personalizada em construcao: os blocos vao empilhando vertices,
normais, texcoords e triangulos; "finalize a malha" vira os arrays que o
renderizador desenha. Normais vazias sao calculadas das faces. */
typedef struct {
float* v; int vn, vcap; /* x y z por vertice */
float* n; int nn, ncap; /* nx ny nz por vertice */
float* t; int tn, tcap; /* u v por vertice */
int* f; int fn, fcap; /* 3 indices por triangulo (1-based) */
} MeshBuild;
typedef struct {
char name[48];
int kind;
float pos[3], rot[3], scale[3], color[4];
bool visible;
struct Shd* shader; /* NULL = luz padrao */
MeshBuild mb; /* malha personalizada (K_CUSTOM) */
Tb3dMesh mesh; /* a malha finalizada */
float bmin[3], bmax[3]; /* caixa local ("encosta em") */
} Obj;
static void mesh_clear(Obj* o) {
free(o->mb.v); free(o->mb.n); free(o->mb.t); free(o->mb.f);
memset(&o->mb, 0, sizeof(o->mb));
free((void*)o->mesh.verts); free((void*)o->mesh.index);
memset(&o->mesh, 0, sizeof(o->mesh));
o->bmin[0] = o->bmin[1] = o->bmin[2] = 0;
o->bmax[0] = o->bmax[1] = o->bmax[2] = 0;
}
/* Shader compilado ("compile o shader [pilha]"): o valor que viaja num
bloco-handle; o handle e cada objeto que o usa guardam uma referencia. */
typedef struct Shd {
Tb3dShader pub; /* primeiro: o renderizador ve so isto */
D3Program* prog; /* nos (interpretador do software) */
int refs;
} Shd;
static int s_shd_seq; /* ids unicos por compilacao */
static int s_mesh_seq = 5; /* ids unicos de malha (1..4 sao fixas) */
static Shd* shd_retain(Shd* s) { if (s) s->refs++; return s; }
static void shd_release(Shd* s) {
if (!s || --s->refs > 0) return;
d3_shader_free(s->prog);
for (int i = 0; i < s->pub.bin_n; i++) free(s->pub.bin[i].data);
free(s);
}
static double now_s(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (double)ts.tv_sec + ts.tv_nsec * 1e-9;
}
#define MAX_OBJS 4096
static struct {
Obj* o;
int n, cap;
float eye[3], at[3], fov;
float light[3], ambient, sky[4];
char want[16]; /* "" = automatico */
char used[64], err[160];
double t0; /* "nova cena 3D" (o "tempo" dos shaders) */
} S;
static void scene_reset(void) {
for (int i = 0; i < S.n; i++) { shd_release(S.o[i].shader); mesh_clear(&S.o[i]); }
S.n = 0;
S.eye[0] = 0; S.eye[1] = 6; S.eye[2] = 10;
S.at[0] = S.at[1] = S.at[2] = 0;
S.fov = 60;
S.light[0] = 0.4f; S.light[1] = 1.f; S.light[2] = 0.6f;
v3_norm(S.light);
S.ambient = 0.35f;
S.sky[0] = 0.53f; S.sky[1] = 0.78f; S.sky[2] = 0.98f; S.sky[3] = 1;
S.t0 = now_s();
}
static Obj* find(const char* name) {
for (int i = 0; i < S.n; i++) if (!strcmp(S.o[i].name, name)) return &S.o[i];
return NULL;
}
/* Cores: nomes em portugues ou #rrggbb (tambem usada pelo compilador de shaders) */
bool d3_color_of(const char* c, float out[4]) {
static const struct { const char* n; uint32_t rgb; } tab[] = {
{"vermelho", 0xe03131}, {"verde", 0x2f9e44}, {"azul", 0x1c7ed6}, {"amarelo", 0xfcc419},
{"laranja", 0xf76707}, {"roxo", 0x7048e8}, {"rosa", 0xe64980}, {"ciano", 0x15aabf},
{"marrom", 0x8b5a2b}, {"cinza", 0x868e96}, {"branco", 0xf8f9fa}, {"preto", 0x212529},
{"dourado", 0xf0b400},
};
while (c && isspace((unsigned char)*c)) c++;
if (!c || !*c) return false;
uint32_t rgb = 0;
bool ok = false;
if (c[0] == '#' && strlen(c) >= 7) { rgb = (uint32_t)strtoul(c + 1, NULL, 16); ok = true; }
for (size_t i = 0; !ok && i < sizeof(tab) / sizeof(tab[0]); i++)
if (!strcasecmp(c, tab[i].n)) { rgb = tab[i].rgb; ok = true; }
if (!ok) return false;
out[0] = ((rgb >> 16) & 255) / 255.f; out[1] = ((rgb >> 8) & 255) / 255.f;
out[2] = (rgb & 255) / 255.f; out[3] = 1;
return true;
}
/* model = T * R * S; normal = R * S^-1 */
static void obj_matrices(const Obj* o, float model[16], float normal[9]) {
float r[9];
rot3(r, o->rot);
tb_3d_mat_identity(model);
for (int j = 0; j < 3; j++)
for (int i = 0; i < 3; i++) model[j * 4 + i] = r[j * 3 + i] * o->scale[j];
model[12] = o->pos[0]; model[13] = o->pos[1]; model[14] = o->pos[2];
for (int j = 0; j < 3; j++) {
float inv = fabsf(o->scale[j]) > 1e-6f ? 1.f / o->scale[j] : 0.f;
for (int i = 0; i < 3; i++) normal[j * 3 + i] = r[j * 3 + i] * inv;
}
}
/* Caixa alinhada aos eixos do objeto no mundo (para "encosta em") */
static void obj_aabb(const Obj* o, float lo[3], float hi[3]) {
float r[9];
rot3(r, o->rot);
if (o->kind == K_CUSTOM) {
float c[3], h[3], cw[3], e[3] = { 0, 0, 0 };
for (int k = 0; k < 3; k++) {
c[k] = (o->bmin[k] + o->bmax[k]) * 0.5f;
h[k] = (o->bmax[k] - o->bmin[k]) * 0.5f;
}
for (int i = 0; i < 3; i++) {
float s = 0;
for (int j = 0; j < 3; j++) s += r[j * 3 + i] * (c[j] * o->scale[j]);
cw[i] = s;
for (int j = 0; j < 3; j++) e[i] += fabsf(r[j * 3 + i] * o->scale[j]) * h[j];
}
for (int i = 0; i < 3; i++) { lo[i] = o->pos[i] + cw[i] - e[i]; hi[i] = o->pos[i] + cw[i] + e[i]; }
return;
}
float h[3] = { fabsf(o->scale[0]) * 0.5f, fabsf(o->scale[1]) * 0.5f, fabsf(o->scale[2]) * 0.5f };
if (o->kind == K_PLANE) h[1] = 0.01f;
for (int i = 0; i < 3; i++) {
float e = 0;
for (int j = 0; j < 3; j++) e += fabsf(r[j * 3 + i]) * h[j];
lo[i] = o->pos[i] - e; hi[i] = o->pos[i] + e;
}
}
/* Monta o quadro (a lista de desenhos vive ate o proximo quadro) */
static Tb3dDraw* s_draws;
static int s_draws_cap;
static bool frame_build(Tb3dFrame* f, int w, int h) {
meshes_build();
memset(f, 0, sizeof(*f));
f->width = w; f->height = h;
float up[3] = { 0, 1, 0 };
tb_3d_mat_look_at(f->view, S.eye, S.at, up);
tb_3d_mat_perspective(f->proj, S.fov, (float)w / (float)h, 0.1f, 500.f);
tb_3d_mat_mul(f->viewproj, f->proj, f->view);
memcpy(f->sky, S.sky, sizeof(f->sky));
memcpy(f->light_dir, S.light, sizeof(f->light_dir));
f->ambient = S.ambient;
f->time = (float)(now_s() - S.t0);
if (S.n > s_draws_cap) {
Tb3dDraw* d = realloc(s_draws, (size_t)S.n * sizeof(*d));
if (!d) return false;
s_draws = d; s_draws_cap = S.n;
}
int n = 0;
for (int i = 0; i < S.n; i++) {
const Obj* o = &S.o[i];
if (!o->visible) continue;
Tb3dDraw* d = &s_draws[n++];
if (o->kind == K_CUSTOM) {
if (o->mesh.icount <= 0) { n--; continue; }
d->mesh = &o->mesh;
} else {
d->mesh = &s_mesh[o->kind];
}
obj_matrices(o, d->model, d->normal);
tb_3d_mat_mul(d->mvp, f->viewproj, d->model);
memcpy(d->color, o->color, sizeof(d->color));
d->shader = o->shader ? &o->shader->pub : NULL;
}
f->draws = s_draws;
f->draw_count = n;
return true;
}
/* == Rasterizador em software ======================================== */
/* Vertice no clip + cor (luz por vertice) + ponto e normal no mundo (shader).
Tudo float, para o corte no plano de perto interpolar campo a campo. */
typedef struct { float x, y, z, w, r, g, b, P[3], N[3], L[3], uv[2]; } CV;
#define CV_N ((int)(sizeof(CV) / sizeof(float)))
/* Quem o rasterizador esta desenhando agora (shader do objeto) */
static const D3Program* s_prog;
static const D3Program* s_vprog; /* shader de vertice (ou NULL) */
static const Tb3dFrame* s_frame;
static float s_base[3];
static float* s_zbuf;
static size_t s_zcap;
static void raster_tri(const CV* a, const CV* b, const CV* c, int W, int H, uint8_t* px) {
float ax = (a->x / a->w * 0.5f + 0.5f) * W, ay = (0.5f - a->y / a->w * 0.5f) * H, az = a->z / a->w;
float bx = (b->x / b->w * 0.5f + 0.5f) * W, by = (0.5f - b->y / b->w * 0.5f) * H, bz = b->z / b->w;
float cx = (c->x / c->w * 0.5f + 0.5f) * W, cy = (0.5f - c->y / c->w * 0.5f) * H, cz = c->z / c->w;
float area = (bx - ax) * (cy - ay) - (by - ay) * (cx - ax);
if (fabsf(area) < 1e-8f) return;
int x0 = (int)floorf(fminf(ax, fminf(bx, cx))), x1 = (int)ceilf(fmaxf(ax, fmaxf(bx, cx)));
int y0 = (int)floorf(fminf(ay, fminf(by, cy))), y1 = (int)ceilf(fmaxf(ay, fmaxf(by, cy)));
if (x0 < 0) x0 = 0;
if (y0 < 0) y0 = 0;
if (x1 > W) x1 = W;
if (y1 > H) y1 = H;
float inv = 1.f / area;
for (int y = y0; y < y1; y++) {
float py = y + 0.5f;
for (int x = x0; x < x1; x++) {
float pxf = x + 0.5f;
float w0 = ((bx - pxf) * (cy - py) - (by - py) * (cx - pxf)) * inv;
float w1 = ((cx - pxf) * (ay - py) - (cy - py) * (ax - pxf)) * inv;
float w2 = 1.f - w0 - w1;
if (w0 < 0 || w1 < 0 || w2 < 0) continue;
float z = w0 * az + w1 * bz + w2 * cz;
if (z < -1.f || z > 1.f) continue;
float* zb = &s_zbuf[(size_t)y * W + x];
if (z >= *zb) continue;
*zb = z;
uint8_t* p = px + ((size_t)y * W + x) * 4;
float r, g, bl;
if (s_prog) { /* shader: ponto e normal com perspectiva */
float q0 = w0 / a->w, q1 = w1 / b->w, q2 = w2 / c->w, qs = 1.f / (q0 + q1 + q2);
D3Pixel in;
for (int k = 0; k < 3; k++) {
in.P[k] = (q0 * a->P[k] + q1 * b->P[k] + q2 * c->P[k]) * qs;
in.N[k] = (q0 * a->N[k] + q1 * b->N[k] + q2 * c->N[k]) * qs;
in.L[k] = (q0 * a->L[k] + q1 * b->L[k] + q2 * c->L[k]) * qs;
in.base[k] = s_base[k];
}
in.uv[0] = (q0 * a->uv[0] + q1 * b->uv[0] + q2 * c->uv[0]) * qs;
in.uv[1] = (q0 * a->uv[1] + q1 * b->uv[1] + q2 * c->uv[1]) * qs;
v3_norm(in.N);
float lam = v3_dot(in.N, s_frame->light_dir);
in.light = s_frame->ambient + (1.f - s_frame->ambient) * (lam > 0 ? lam : 0);
in.time = s_frame->time;
float o[3];
d3_shader_run(s_prog, &in, o);
r = o[0]; g = o[1]; bl = o[2];
} else {
r = w0 * a->r + w1 * b->r + w2 * c->r;
g = w0 * a->g + w1 * b->g + w2 * c->g;
bl = w0 * a->b + w1 * b->b + w2 * c->b;
}
p[0] = (uint8_t)(fminf(r, 1.f) * 255.f + .5f);
p[1] = (uint8_t)(fminf(g, 1.f) * 255.f + .5f);
p[2] = (uint8_t)(fminf(bl, 1.f) * 255.f + .5f);
p[3] = 255;
}
}
}
/* Corta o triangulo no plano de perto (z + w >= 0) e desenha o resultado */
static void clip_and_raster(const CV in[3], int W, int H, uint8_t* px) {
CV out[4];
int n = 0;
for (int i = 0; i < 3; i++) {
const CV* p = &in[i];
const CV* q = &in[(i + 1) % 3];
float dp = p->z + p->w, dq = q->z + q->w;
if (dp >= 0) out[n++] = *p;
if ((dp >= 0) != (dq >= 0)) {
float t = dp / (dp - dq);
CV m;
const float* fp = (const float*)p; const float* fq = (const float*)q;
float* fm = (float*)&m;
for (int k = 0; k < CV_N; k++) fm[k] = fp[k] + (fq[k] - fp[k]) * t;
out[n++] = m;
}
}
for (int i = 1; i + 1 < n; i++) raster_tri(&out[0], &out[i], &out[i + 1], W, H, px);
}
/* Cor de um vertice: lambert por vertice (o GL e o Vulkan fazem igual) */
static void shade(const Tb3dFrame* f, const Tb3dDraw* d, const float* v, CV* o) {
float lp[3] = { v[0], v[1], v[2] };
if (s_vprog) { /* shader de vertice: move o vertice */
D3Pixel in;
in.P[0] = v[0]; in.P[1] = v[1]; in.P[2] = v[2];
in.N[0] = v[3]; in.N[1] = v[4]; in.N[2] = v[5];
in.L[0] = v[0]; in.L[1] = v[1]; in.L[2] = v[2];
in.uv[0] = v[6]; in.uv[1] = v[7];
in.base[0] = d->color[0]; in.base[1] = d->color[1]; in.base[2] = d->color[2];
in.light = 1.f; in.time = f->time;
d3_shader_run_vertex(s_vprog, &in, lp);
}
float p[4] = { lp[0], lp[1], lp[2], 1 }, c[4] = { 0 };
for (int i = 0; i < 4; i++)
for (int k = 0; k < 4; k++) c[i] += d->mvp[k * 4 + i] * p[k];
float n[3] = { 0 };
for (int i = 0; i < 3; i++)
for (int k = 0; k < 3; k++) n[i] += d->normal[k * 3 + i] * v[3 + k];
v3_norm(n);
for (int i = 0; i < 3; i++) { /* ponto no mundo (shader) */
o->P[i] = d->model[12 + i];
for (int k = 0; k < 3; k++) o->P[i] += d->model[k * 4 + i] * lp[k];
o->N[i] = n[i];
o->L[i] = lp[i]; /* vertice local (shader) */
}
o->uv[0] = v[6]; o->uv[1] = v[7];
float lam = v3_dot(n, f->light_dir);
float I = f->ambient + (1.f - f->ambient) * (lam > 0 ? lam : 0);
o->x = c[0]; o->y = c[1]; o->z = c[2]; o->w = c[3];
o->r = d->color[0] * I; o->g = d->color[1] * I; o->b = d->color[2] * I;
}
static bool sw_available(void) { return true; }
static const char* sw_device(void) { return "CPU"; }
static const char* sw_error(void) { return ""; }
static bool sw_render(const Tb3dFrame* f, uint8_t* px) {
int W = f->width, H = f->height;
size_t np = (size_t)W * H;
if (np > s_zcap) {
float* z = realloc(s_zbuf, np * sizeof(float));
if (!z) return false;
s_zbuf = z; s_zcap = np;
}
uint8_t sky[4] = { (uint8_t)(f->sky[0] * 255.f + .5f), (uint8_t)(f->sky[1] * 255.f + .5f),
(uint8_t)(f->sky[2] * 255.f + .5f), 255 };
for (size_t i = 0; i < np; i++) { memcpy(px + i * 4, sky, 4); s_zbuf[i] = 1.f; }
CV* cv = NULL;
int cv_cap = 0;
for (int di = 0; di < f->draw_count; di++) {
const Tb3dDraw* d = &f->draws[di];
const Tb3dMesh* m = d->mesh;
if (m->vcount > cv_cap) {
CV* p = realloc(cv, (size_t)m->vcount * sizeof(CV));
if (!p) { free(cv); return false; }
cv = p; cv_cap = m->vcount;
}
const D3Program* prog = d->shader ? ((const Shd*)d->shader)->prog : NULL; /* pub e o 1o campo */
s_vprog = (prog && d3_shader_stage(prog) == D3_STAGE_VERTEX) ? prog : NULL;
s_prog = (prog && d3_shader_stage(prog) == D3_STAGE_FRAGMENT) ? prog : NULL;
s_frame = f;
memcpy(s_base, d->color, sizeof(s_base));
for (int i = 0; i < m->vcount; i++) shade(f, d, m->verts + (size_t)i * 8, &cv[i]);
for (int t = 0; t + 2 < m->icount; t += 3) {
CV tri[3] = { cv[m->index[t]], cv[m->index[t + 1]], cv[m->index[t + 2]] };
if (tri[0].z < -tri[0].w && tri[1].z < -tri[1].w && tri[2].z < -tri[2].w) continue;
clip_and_raster(tri, W, H, px);
}
}
free(cv);
s_prog = s_vprog = NULL;
return true;
}
static bool sw_shaders(void) { return true; }
static const Tb3dRenderer s_software = {
TB_3D_RENDERER_VERSION, "software", sw_available, sw_render, sw_device, sw_error, sw_shaders,
NULL /* interpreta os nos do proprio shader: sem binario */ };
const Tb3dRenderer* tb_3d_software_renderer(void) { return &s_software; }
/* == Escolha do renderizador ========================================= */
static bool s_need_shaders; /* o quadro tem objeto com shader */
static const Tb3dRenderer* renderer_of(TinyBlocks* rt, const char* lib_name) {
TinyBlocks_LibraryBlock* lib = tb_rt_find_library(rt, lib_name);
const Tb3dRenderer* r = lib ? lib->lib_userdata : NULL;
if (!r || r->version != TB_3D_RENDERER_VERSION || !r->available()) return NULL;
if (s_need_shaders && !r->shaders()) return NULL;
return r;
}
/* Na ordem: o pedido (ou Vulkan, OpenGL), e o software se nada servir */
static const Tb3dRenderer* pick(TinyBlocks* rt) {
if (!strcmp(S.want, "software")) return &s_software;
if (!strcmp(S.want, "vulkan")) { const Tb3dRenderer* r = renderer_of(rt, "tinyblocks-vk"); return r ? r : &s_software; }
if (!strcmp(S.want, "opengl")) { const Tb3dRenderer* r = renderer_of(rt, "tinyblocks-gl"); return r ? r : &s_software; }
const Tb3dRenderer* r = renderer_of(rt, "tinyblocks-vk");
if (!r) r = renderer_of(rt, "tinyblocks-gl");
return r ? r : &s_software;
}
/* == Blocos =========================================================== */
static const char* name_in(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) { return tb_block_input_text(self, rt, i); }
static Obj* need(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t i) {
const char* n = name_in(self, rt, i);
Obj* o = find(n);
if (!o) tinyblocks_set_error(rt, "não existe o objeto 3D '%s'", n);
return o;
}
static void vec_in(TinyBlocks_Block* self, TinyBlocks* rt, uint32_t first, float v[3]) {
for (int k = 0; k < 3; k++) v[k] = (float)tb_block_input_number(self, rt, first + (uint32_t)k, 0);
}
static void eval_scene(TinyBlocks_Block* self, TinyBlocks* rt) { (void)rt; scene_reset(); self->dirty = false; }
static void create(TinyBlocks_Block* self, TinyBlocks* rt, int kind) {
const char* n = name_in(self, rt, 0);
self->dirty = false;
if (!n[0]) { tinyblocks_set_error(rt, "dê um nome ao objeto 3D"); return; }
Obj* o = find(n);
if (!o) {
if (S.n >= MAX_OBJS) { tinyblocks_set_error(rt, "a cena já tem %d objetos", MAX_OBJS); return; }
if (S.n == S.cap) {
int nc = S.cap ? S.cap * 2 : 64;
Obj* p = realloc(S.o, (size_t)nc * sizeof(*p));
if (!p) { tinyblocks_set_error(rt, "sem memória"); return; }
S.o = p; S.cap = nc;
}
o = &S.o[S.n++];
memset(o, 0, sizeof(*o));
snprintf(o->name, sizeof(o->name), "%s", n);
}
mesh_clear(o);
o->kind = kind;
vec_in(self, rt, 1, o->pos);
o->rot[0] = o->rot[1] = o->rot[2] = 0;
o->scale[0] = o->scale[1] = o->scale[2] = 1;
if (kind == K_PLANE) { o->scale[0] = o->scale[2] = 10; }
o->color[0] = o->color[1] = o->color[2] = 0.8f; o->color[3] = 1;
o->visible = true;
shd_release(o->shader);
o->shader = NULL;
}
static void eval_cube(TinyBlocks_Block* s, TinyBlocks* rt) { create(s, rt, K_CUBE); }
static void eval_sphere(TinyBlocks_Block* s, TinyBlocks* rt) { create(s, rt, K_SPHERE); }
static void eval_plane(TinyBlocks_Block* s, TinyBlocks* rt) { create(s, rt, K_PLANE); }
static void eval_cylinder(TinyBlocks_Block* s, TinyBlocks* rt) { create(s, rt, K_CYLINDER); }
/* == Malha personalizada (leitor de .obj e afins) ===================== */
static Obj* obj_ensure(const char* n) {
Obj* o = find(n);
if (o) return o;
if (S.n >= MAX_OBJS) return NULL;
if (S.n == S.cap) {
int nc = S.cap ? S.cap * 2 : 64;
Obj* p = realloc(S.o, (size_t)nc * sizeof(*p));
if (!p) return NULL;
S.o = p; S.cap = nc;
}
o = &S.o[S.n++];
memset(o, 0, sizeof(*o));
snprintf(o->name, sizeof(o->name), "%s", n);
return o;
}
static Obj* mesh_need(TinyBlocks_Block* self, TinyBlocks* rt) {
const char* n = name_in(self, rt, 0);
Obj* o = find(n);
if (!o || o->kind != K_CUSTOM) { tinyblocks_set_error(rt, "não existe a malha '%s'", n); return NULL; }
return o;
}
static void eval_mesh_create(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
const char* n = name_in(self, rt, 0);
if (!n[0]) { tinyblocks_set_error(rt, "dê um nome à malha"); return; }
Obj* o = obj_ensure(n);
if (!o) { tinyblocks_set_error(rt, "a cena já tem objetos demais"); return; }
mesh_clear(o);
shd_release(o->shader); o->shader = NULL;
o->kind = K_CUSTOM;
o->pos[0] = o->pos[1] = o->pos[2] = 0;
o->rot[0] = o->rot[1] = o->rot[2] = 0;
o->scale[0] = o->scale[1] = o->scale[2] = 1;
o->color[0] = o->color[1] = o->color[2] = 0.8f; o->color[3] = 1;
o->visible = true;
}
static void mb_push3(float** a, int* n, int* cap, float x, float y, float z) {
if (*n == *cap) { *cap = *cap ? *cap * 2 : 64; *a = realloc(*a, (size_t)(*cap) * 3 * sizeof(float)); }
float* p = *a + (size_t)(*n) * 3; p[0] = x; p[1] = y; p[2] = z; (*n)++;
}
static void mb_push2(float** a, int* n, int* cap, float u, float v) {
if (*n == *cap) { *cap = *cap ? *cap * 2 : 64; *a = realloc(*a, (size_t)(*cap) * 2 * sizeof(float)); }
float* p = *a + (size_t)(*n) * 2; p[0] = u; p[1] = v; (*n)++;
}
static void eval_mesh_vert(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
Obj* o = mesh_need(self, rt); if (!o) return;
float v[3]; vec_in(self, rt, 1, v);
mb_push3(&o->mb.v, &o->mb.vn, &o->mb.vcap, v[0], v[1], v[2]);
}
static void eval_mesh_norm(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
Obj* o = mesh_need(self, rt); if (!o) return;
float v[3]; vec_in(self, rt, 1, v);
mb_push3(&o->mb.n, &o->mb.nn, &o->mb.ncap, v[0], v[1], v[2]);
}
static void eval_mesh_uv(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
Obj* o = mesh_need(self, rt); if (!o) return;
mb_push2(&o->mb.t, &o->mb.tn, &o->mb.tcap,
(float)tb_block_input_number(self, rt, 1, 0), (float)tb_block_input_number(self, rt, 2, 0));
}
static void eval_mesh_tri(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
Obj* o = mesh_need(self, rt); if (!o) return;
if (o->mb.fn + 3 > o->mb.fcap) { o->mb.fcap = o->mb.fcap ? o->mb.fcap * 2 : 96; o->mb.f = realloc(o->mb.f, (size_t)o->mb.fcap * sizeof(int)); }
for (int k = 0; k < 3; k++)
o->mb.f[o->mb.fn++] = (int)tb_block_input_number(self, rt, 1 + (uint32_t)k, 0);
}
static void eval_mesh_finish(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
Obj* o = mesh_need(self, rt); if (!o) return;
int vn = o->mb.vn;
if (vn <= 0) { tinyblocks_set_error(rt, "a malha '%s' não tem vértices", o->name); return; }
bool have_n = o->mb.nn >= vn;
float* verts = malloc((size_t)vn * 8 * sizeof(float));
uint32_t* idx = malloc((o->mb.fn > 0 ? (size_t)o->mb.fn : 1) * sizeof(uint32_t));
float* acc = have_n ? NULL : calloc((size_t)vn * 3, sizeof(float));
if (!verts || !idx || (!have_n && !acc)) { free(verts); free(idx); free(acc); tinyblocks_set_error(rt, "sem memória"); return; }
if (!have_n) /* normais: soma as das faces */
for (int f = 0; f + 2 < o->mb.fn; f += 3) {
int a = o->mb.f[f] - 1, b = o->mb.f[f + 1] - 1, c = o->mb.f[f + 2] - 1;
if (a < 0 || b < 0 || c < 0 || a >= vn || b >= vn || c >= vn) continue;
float e1[3], e2[3], cr[3];
for (int k = 0; k < 3; k++) { e1[k] = o->mb.v[b*3+k] - o->mb.v[a*3+k]; e2[k] = o->mb.v[c*3+k] - o->mb.v[a*3+k]; }
cr[0] = e1[1]*e2[2] - e1[2]*e2[1]; cr[1] = e1[2]*e2[0] - e1[0]*e2[2]; cr[2] = e1[0]*e2[1] - e1[1]*e2[0];
for (int k = 0; k < 3; k++) { acc[a*3+k] += cr[k]; acc[b*3+k] += cr[k]; acc[c*3+k] += cr[k]; }
}
o->bmin[0] = o->bmin[1] = o->bmin[2] = 1e30f;
o->bmax[0] = o->bmax[1] = o->bmax[2] = -1e30f;
for (int i = 0; i < vn; i++) {
float nx, ny, nz;
if (have_n) { nx = o->mb.n[i*3]; ny = o->mb.n[i*3+1]; nz = o->mb.n[i*3+2]; }
else { nx = acc[i*3]; ny = acc[i*3+1]; nz = acc[i*3+2]; }
float len = sqrtf(nx*nx + ny*ny + nz*nz);
if (len > 1e-6f) { nx /= len; ny /= len; nz /= len; } else { nx = 0; ny = 1; nz = 0; }
float* p = verts + (size_t)i * 8;
p[0] = o->mb.v[i*3]; p[1] = o->mb.v[i*3+1]; p[2] = o->mb.v[i*3+2];
p[3] = nx; p[4] = ny; p[5] = nz;
p[6] = i < o->mb.tn ? o->mb.t[i*2] : 0.f;
p[7] = i < o->mb.tn ? o->mb.t[i*2+1] : 0.f;
for (int k = 0; k < 3; k++) {
float c = o->mb.v[i*3+k];
if (c < o->bmin[k]) o->bmin[k] = c;
if (c > o->bmax[k]) o->bmax[k] = c;
}
}
int ic = 0;
for (int f = 0; f + 2 < o->mb.fn; f += 3) {
int a = o->mb.f[f] - 1, b = o->mb.f[f + 1] - 1, c = o->mb.f[f + 2] - 1;
if (a < 0 || b < 0 || c < 0 || a >= vn || b >= vn || c >= vn) continue;
idx[ic++] = (uint32_t)a; idx[ic++] = (uint32_t)b; idx[ic++] = (uint32_t)c;
}
free(acc);
free((void*)o->mesh.verts); free((void*)o->mesh.index);
if (o->mesh.id == 0) {
if (s_mesh_seq >= 256) { tinyblocks_set_error(rt, "malhas demais na cena"); free(verts); free(idx); return; }
o->mesh.id = s_mesh_seq++;
}
o->mesh.version++;
o->mesh.verts = verts; o->mesh.vcount = vn;
o->mesh.index = idx; o->mesh.icount = ic;
if (ic == 0) tinyblocks_set_error(rt, "a malha '%s' não tem triângulos", o->name);
}
#define OBJ_CMD(fname, body) \
static void fname(TinyBlocks_Block* self, TinyBlocks* rt) { \
self->dirty = false; Obj* o = need(self, rt, 0); if (!o) return; float v[3]; (void)v; body }
OBJ_CMD(eval_move_to, vec_in(self, rt, 1, v); memcpy(o->pos, v, sizeof(v));)
OBJ_CMD(eval_move_by, vec_in(self, rt, 1, v); for (int k = 0; k < 3; k++) o->pos[k] += v[k];)
OBJ_CMD(eval_rot_to, vec_in(self, rt, 1, v); memcpy(o->rot, v, sizeof(v));)
OBJ_CMD(eval_rot_by, vec_in(self, rt, 1, v); for (int k = 0; k < 3; k++) o->rot[k] = fmodf(o->rot[k] + v[k], 360.f);)
OBJ_CMD(eval_scale, vec_in(self, rt, 1, v); memcpy(o->scale, v, sizeof(v));)
OBJ_CMD(eval_show, o->visible = true;)
OBJ_CMD(eval_hide, o->visible = false;)
OBJ_CMD(eval_color, if (!d3_color_of(name_in(self, rt, 1), o->color))
tinyblocks_set_error(rt, "cor desconhecida '%s' (use um nome ou #rrggbb)", name_in(self, rt, 1));)
static void eval_delete(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
Obj* o = find(name_in(self, rt, 0));
if (o) {
shd_release(o->shader);
mesh_clear(o);
int i = (int)(o - S.o);
memmove(o, o + 1, (size_t)(S.n - i - 1) * sizeof(*o));
S.n--;
}
}
static void coord(TinyBlocks_Block* self, TinyBlocks* rt, int axis) {
self->dirty = false;
Obj* o = need(self, rt, 0);
if (o) tb_block_set_output(self, 0, tb_value_real(o->pos[axis]));
}
static void eval_x(TinyBlocks_Block* s, TinyBlocks* rt) { coord(s, rt, 0); }
static void eval_y(TinyBlocks_Block* s, TinyBlocks* rt) { coord(s, rt, 1); }
static void eval_z(TinyBlocks_Block* s, TinyBlocks* rt) { coord(s, rt, 2); }
static void eval_exists(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
tb_block_set_output(self, 0, tb_value_integer(find(name_in(self, rt, 0)) != NULL));
}
static void eval_touching(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
Obj* a = need(self, rt, 0);
Obj* b = a ? need(self, rt, 1) : NULL;
if (!a || !b) return;
float al[3], ah[3], bl[3], bh[3];
obj_aabb(a, al, ah); obj_aabb(b, bl, bh);
bool hit = a != b && a->visible && b->visible;
for (int k = 0; hit && k < 3; k++) hit = al[k] <= bh[k] && bl[k] <= ah[k];
tb_block_set_output(self, 0, tb_value_integer(hit));
}
static void eval_distance(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
Obj* a = need(self, rt, 0);
Obj* b = a ? need(self, rt, 1) : NULL;
if (!a || !b) return;
float d[3];
v3_sub(d, a->pos, b->pos);
tb_block_set_output(self, 0, tb_value_real(sqrtf(v3_dot(d, d))));
}
static void eval_camera(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
vec_in(self, rt, 0, S.eye);
vec_in(self, rt, 3, S.at);
}
static void eval_fov(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
float f = (float)tb_block_input_number(self, rt, 0, 60);
S.fov = f < 5 ? 5 : f > 170 ? 170 : f;
}
static void eval_light(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
float v[3];
vec_in(self, rt, 0, v);
if (v3_dot(v, v) < 1e-12f) { tinyblocks_set_error(rt, "a direção da luz não pode ser (0, 0, 0)"); return; }
v3_norm(v);
memcpy(S.light, v, sizeof(v));
}
static void eval_ambient(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
float a = (float)tb_block_input_number(self, rt, 0, 0.35);
S.ambient = a < 0 ? 0 : a > 1 ? 1 : a;
}
static void eval_sky(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
if (!d3_color_of(name_in(self, rt, 0), S.sky)) tinyblocks_set_error(rt, "cor desconhecida '%s'", name_in(self, rt, 0));
}
static void eval_use(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
const char* w = name_in(self, rt, 0);
if (!strcasecmp(w, "vulkan") || !strcasecmp(w, "vk")) snprintf(S.want, sizeof(S.want), "vulkan");
else if (!strcasecmp(w, "opengl") || !strcasecmp(w, "gl")) snprintf(S.want, sizeof(S.want), "opengl");
else if (!strcasecmp(w, "software")) snprintf(S.want, sizeof(S.want), "software");
else S.want[0] = 0;
}
static void eval_image(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
int w = (int)tb_block_input_integer(self, rt, 0, 480), h = (int)tb_block_input_integer(self, rt, 1, 360);
if (w < 8 || h < 8 || w > 4096 || h > 4096) { tinyblocks_set_error(rt, "tamanho da imagem fora de 8..4096"); return; }
Tb3dFrame f;
if (!frame_build(&f, w, h)) { tinyblocks_set_error(rt, "sem memória"); return; }
TinyBlocks_Image* img = tb_image_new(w, h, 4);
if (!img) { tinyblocks_set_error(rt, "sem memória"); return; }
s_need_shaders = false;
for (int i = 0; i < f.draw_count; i++) if (f.draws[i].shader) s_need_shaders = true;
const Tb3dRenderer* r = pick(rt);
if (!r->render(&f, tb_image_data(img))) {
snprintf(S.err, sizeof(S.err), "%s: %s", r->name, r->error());
r = &s_software; /* nao deixa o quadro vazio */
r->render(&f, tb_image_data(img));
}
snprintf(S.used, sizeof(S.used), "%s (%s)", r->name, r->device());
tb_block_set_output(self, 0, tb_value_image(img));
tb_image_release(img);
}
/* -- o bloco-handle do shader compilado --- */
typedef struct { Shd* s; TinyBlocks_Block* owner; } ShdHandle;
typedef struct { TinyBlocks_Block* handle; } ShdProducer;
static TinyBlocks_TypeBlock* s_t_shader;
static void shd_handle_deinit(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)rt;
ShdHandle* h = self->userdata;
if (!h) return;
shd_release(h->s);
h->s = NULL;
if (h->owner && h->owner->userdata && ((ShdProducer*)h->owner->userdata)->handle == self)
((ShdProducer*)h->owner->userdata)->handle = NULL;
}
static size_t shd_handle_text(TinyBlocks_Block* self, char* out, size_t cap) {
ShdHandle* h = self->userdata;
if (!h || !h->s) return (size_t)snprintf(out, cap, "shader vazio");
const Tb3dShader* p = &h->s->pub;
if (!p->bin_n) return (size_t)snprintf(out, cap, "shader compilado");
char buf[256]; /* o tamanho devolvido e o real, mesmo com cap 0 */
size_t n = (size_t)snprintf(buf, sizeof(buf), "shader compilado (");
for (int i = 0; i < p->bin_n && n < sizeof(buf); i++)
n += (size_t)snprintf(buf + n, sizeof(buf) - n, "%s%s: %zu bytes", i ? ", " : "", p->bin[i].renderer, p->bin[i].size);
if (n < sizeof(buf)) snprintf(buf + n, sizeof(buf) - n, ")");
return (size_t)snprintf(out, cap, "%s", buf);
}
static void shd_producer_deinit(TinyBlocks_Block* self, TinyBlocks* rt) {
ShdProducer* p = self->userdata;
if (p && p->handle) {
TinyBlocks_Block* h = p->handle;
p->handle = NULL;
((ShdHandle*)h->userdata)->owner = NULL;
tb_block_destroy(h, rt);
}
}
static Shd* shd_of(TinyBlocks_Value v) {
if (v.kind != TB_VALUE_BLOCK || !v.as.block || v.as.block->type != s_t_shader) return NULL;
ShdHandle* h = v.as.block->userdata;
return h ? h->s : NULL;
}
/* Pede o binario a cada renderizador disponivel (o formato e dele: a 3d so
guarda). Quem nao compila antes desenha a partir do GLSL. */
static void shd_binaries(TinyBlocks* rt, Shd* sh) {
static const char* libs[] = { "tinyblocks-vk", "tinyblocks-gl" };
for (int i = 0; i < 2 && sh->pub.bin_n < TB_3D_MAX_BINARIES; i++) {
TinyBlocks_LibraryBlock* lib = tb_rt_find_library(rt, libs[i]);
const Tb3dRenderer* r = lib ? lib->lib_userdata : NULL;
if (!r || r->version != TB_3D_RENDERER_VERSION || !r->compile || !r->available() || !r->shaders()) continue;
Tb3dBinary* b = &sh->pub.bin[sh->pub.bin_n];
char err[200];
if (!r->compile(sh->pub.glsl, sh->pub.stage, &b->data, &b->size, err, sizeof(err))) {
snprintf(S.err, sizeof(S.err), "%s: %.140s", r->name, err);
continue;
}
snprintf(b->renderer, sizeof(b->renderer), "%s", r->name);
sh->pub.bin_n++;
}
}
/* "compile o shader [pilha]": le o codigo da pilha (nao a executa) e
devolve o shader compilado: nos (software), GLSL e o binario de cada
renderizador */
static void eval_shader(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
TinyBlocks_Value v = tb_block_get_input(self, rt, 0);
char err[200];
D3Program* prog = d3_shader_compile(v.kind == TB_VALUE_JSON ? v.as.json : NULL, err, sizeof(err));
if (!prog) { tinyblocks_set_error(rt, "shader: %s", err); return; }
Shd* sh = calloc(1, sizeof(*sh));
if (!sh) { d3_shader_free(prog); tinyblocks_set_error(rt, "sem memória"); return; }
sh->prog = prog;
sh->refs = 1;
sh->pub.id = ++s_shd_seq;
sh->pub.version = 1;
sh->pub.stage = d3_shader_stage(prog) == D3_STAGE_VERTEX ? TB_3D_STAGE_VERTEX : TB_3D_STAGE_FRAGMENT;
sh->pub.glsl = d3_shader_glsl(prog);
shd_binaries(rt, sh);
ShdProducer* p = self->userdata;
if (!p->handle) { /* um handle por bloco: muda o conteudo */
p->handle = tb_block_create(rt, s_t_shader);
if (!p->handle) { shd_release(sh); return; }
((ShdHandle*)p->handle->userdata)->owner = self;
}
ShdHandle* h = p->handle->userdata;
shd_release(h->s);
h->s = sh;
tb_block_set_output(self, 0, tb_value_block(p->handle));
}
static void eval_shader_use(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
Obj* o = need(self, rt, 1);
if (!o) return;
TinyBlocks_Value v = tb_block_get_input(self, rt, 0);
Shd* sh = shd_of(v);
if (!sh) {
char* t = tb_value_to_string(v);
bool none = !t || !t[0] || !strcasecmp(t, "nenhum");
free(t);
if (!none) { tinyblocks_set_error(rt, "encaixe um shader compilado (\"compile o shader\" ou uma variável com ele)"); return; }
}
shd_release(o->shader);
o->shader = shd_retain(sh);
}
static void eval_shader_glsl(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
Shd* sh = shd_of(tb_block_get_input(self, rt, 0));
if (!sh) { tinyblocks_set_error(rt, "encaixe um shader compilado"); return; }
tb_block_set_output(self, 0, tb_value_text(sh->pub.glsl));
}
static void eval_renderer(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
if (!S.used[0]) { const Tb3dRenderer* r = pick(rt); snprintf(S.used, sizeof(S.used), "%s (%s)", r->name, r->device()); }
tb_block_set_output(self, 0, tb_value_text(S.used));
}
static void eval_count(TinyBlocks_Block* self, TinyBlocks* rt) {
(void)rt; self->dirty = false;
tb_block_set_output(self, 0, tb_value_integer(S.n));
}
/* == Registro ========================================================= */
enum { O_NONE, O_IMAGE, O_REAL, O_BOOL, O_TEXT, O_INT, O_SHADER };
typedef struct {
const char* name; const char* label; const char* defs;
int nin; TinyBlocks_ValueKind in[6];
int out;
int stack_slot; /* encaixe de pilha (-1 = nenhum) */
void (*fn)(TinyBlocks_Block*, TinyBlocks*); const char* fname; const char* doc;
} Spec;
#define T TB_VALUE_TEXT
#define I TB_VALUE_INTEGER
#define R TB_VALUE_REAL
#define S_(fn) fn, #fn
#define XYZ "|0|0|0"
static const Spec s_specs[] = {
{ "3D.Scene", "nova cena 3D", "", 0, {T}, O_NONE, -1, S_(eval_scene), "Apaga os objetos e volta câmera, luz e céu ao padrão" },
{ "3D.Cube", "crie cubo %1 em x %2 y %3 z %4", "jogador|0|0.5|0", 4, {T,R,R,R}, O_NONE, -1, S_(eval_cube), "Cubo de lado 1 com esse nome (troca se já existir)" },
{ "3D.Sphere", "crie esfera %1 em x %2 y %3 z %4", "bola|0|0.5|0", 4, {T,R,R,R}, O_NONE, -1, S_(eval_sphere), "Esfera de diâmetro 1" },
{ "3D.Plane", "crie plano %1 em x %2 y %3 z %4", "chão" XYZ, 4, {T,R,R,R}, O_NONE, -1, S_(eval_plane), "Plano deitado de 10 por 10" },
{ "3D.Cylinder", "crie cilindro %1 em x %2 y %3 z %4", "moeda|0|0.5|0", 4, {T,R,R,R}, O_NONE, -1, S_(eval_cylinder), "Cilindro em pé, diâmetro 1 e altura 1" },
{ "3D.MeshCreate", "crie a malha %1", "minha malha", 1, {T}, O_NONE, -1, S_(eval_mesh_create), "Começa uma malha personalizada (os vértices e triângulos vêm nos blocos seguintes)" },
{ "3D.MeshVertex", "na malha %1 adicione o vértice x %2 y %3 z %4", "minha malha|0|0|0", 4, {T,R,R,R}, O_NONE, -1, S_(eval_mesh_vert), "Empilha um vértice (posição) na malha" },
{ "3D.MeshNormal", "na malha %1 adicione a normal x %2 y %3 z %4", "minha malha|0|1|0", 4, {T,R,R,R}, O_NONE, -1, S_(eval_mesh_norm), "Empilha a normal de um vértice (sem nenhuma, a malha calcula das faces)" },
{ "3D.MeshUV", "na malha %1 adicione a texcoord u %2 v %3", "minha malha|0|0", 3, {T,R,R}, O_NONE, -1, S_(eval_mesh_uv), "Empilha a coordenada de textura (0 a 1) de um vértice" },
{ "3D.MeshTri", "na malha %1 adicione o triângulo %2 %3 %4", "minha malha|1|2|3", 4, {T,I,I,I}, O_NONE, -1, S_(eval_mesh_tri), "Um triângulo pelos números dos vértices (1 = o primeiro)" },
{ "3D.MeshFinish", "finalize a malha %1", "minha malha", 1, {T}, O_NONE, -1, S_(eval_mesh_finish), "Monta a malha (com as normais que faltam) e a deixa pronta para desenhar" },
{ "3D.MoveTo", "mova %1 para x %2 y %3 z %4", "jogador|0|0.5|0", 4, {T,R,R,R}, O_NONE, -1, S_(eval_move_to), "Põe o objeto nessa posição" },
{ "3D.MoveBy", "mova %1 por x %2 y %3 z %4", "jogador|0|0|0.1", 4, {T,R,R,R}, O_NONE, -1, S_(eval_move_by), "Soma à posição do objeto" },
{ "3D.RotateTo", "gire %1 para x %2 y %3 z %4 graus", "jogador|0|45|0", 4, {T,R,R,R}, O_NONE, -1, S_(eval_rot_to), "Rotação nos eixos x, y e z (em graus)" },
{ "3D.RotateBy", "gire %1 por x %2 y %3 z %4 graus", "jogador|0|5|0", 4, {T,R,R,R}, O_NONE, -1, S_(eval_rot_by), "Soma à rotação do objeto" },
{ "3D.Scale", "mude o tamanho de %1 para x %2 y %3 z %4", "chão|20|1|20", 4, {T,R,R,R}, O_NONE, -1, S_(eval_scale), "Escala do objeto em cada eixo" },
{ "3D.Color", "mude a cor de %1 para %2", "jogador|vermelho", 2, {T,T}, O_NONE, -1, S_(eval_color), "Cor por nome (vermelho, azul, dourado...) ou #rrggbb" },
{ "3D.Show", "mostre o objeto %1", "jogador", 1, {T}, O_NONE, -1, S_(eval_show), "Volta a desenhar o objeto" },
{ "3D.Hide", "esconda o objeto %1", "jogador", 1, {T}, O_NONE, -1, S_(eval_hide), "Deixa de desenhar o objeto (e ele não encosta)" },
{ "3D.Delete", "apague o objeto %1", "jogador", 1, {T}, O_NONE, -1, S_(eval_delete), "Tira o objeto da cena" },
{ "3D.X", "x do objeto %1", "jogador", 1, {T}, O_REAL, -1, S_(eval_x), "Posição x" },
{ "3D.Y", "y do objeto %1", "jogador", 1, {T}, O_REAL, -1, S_(eval_y), "Posição y" },
{ "3D.Z", "z do objeto %1", "jogador", 1, {T}, O_REAL, -1, S_(eval_z), "Posição z" },
{ "3D.Exists", "existe o objeto %1?", "jogador", 1, {T}, O_BOOL, -1, S_(eval_exists), "Verdadeiro se há um objeto com esse nome" },
{ "3D.Touching", "objeto %1 encosta em %2", "jogador|moeda", 2, {T,T}, O_BOOL, -1, S_(eval_touching), "As caixas dos dois objetos se cruzam?" },
{ "3D.Distance", "distância entre %1 e %2", "jogador|moeda", 2, {T,T}, O_REAL, -1, S_(eval_distance), "Distância entre os centros" },
{ "3D.Camera", "câmera em x %1 y %2 z %3 olhando para x %4 y %5 z %6", "0|6|10|0|0|0", 6, {R,R,R,R,R,R}, O_NONE, -1, S_(eval_camera), "Posição da câmera e o ponto para onde ela olha" },
{ "3D.Fov", "campo de visão da câmera %1 graus", "60", 1, {R}, O_NONE, -1, S_(eval_fov), "Ângulo vertical que a câmera enxerga" },
{ "3D.Light", "luz vindo de x %1 y %2 z %3", "0.4|1|0.6", 3, {R,R,R}, O_NONE, -1, S_(eval_light), "Direção de onde vem a luz do sol" },
{ "3D.Ambient", "luz ambiente %1", "0.35", 1, {R}, O_NONE, -1, S_(eval_ambient), "Claridade das partes na sombra (0 a 1)" },
{ "3D.Sky", "cor do céu %1", "#87c7fa", 1, {T}, O_NONE, -1, S_(eval_sky), "Cor do fundo" },
{ "3D.Image", "imagem da cena de %1 por %2", "480|360", 2, {I,I}, O_IMAGE, -1, S_(eval_image), "Desenha a cena numa imagem (use com \"desenhe\")" },
{ "3D.Use", "use o renderizador %1", "automático", 1, {T}, O_NONE, -1, S_(eval_use), "vulkan, opengl, software ou automático" },
{ "3D.Renderer", "renderizador da cena", "", 0, {T}, O_TEXT, -1, S_(eval_renderer), "Quem desenhou o último quadro (e em qual placa)" },
{ "3D.Count", "número de objetos 3D", "", 0, {T}, O_INT, -1, S_(eval_count), "Quantos objetos a cena tem" },
{ "3D.Shader", "compile o shader %1", "", 1, {TB_VALUE_JSON}, O_SHADER, 0, S_(eval_shader),
"Compila a pilha de blocos de Shader encaixada (não a executa) e devolve o shader compilado, com o binário de cada renderizador" },
{ "3D.ShaderUse", "use o shader %1 no objeto %2", "|chão", 2, {TB_VALUE_NONE,T}, O_NONE, -1, S_(eval_shader_use),
"O objeto passa a ser pintado pelo shader (vazio ou \"nenhum\" volta ao normal)" },
{ "3D.ShaderGlsl", "GLSL do shader %1", "", 1, {TB_VALUE_NONE}, O_TEXT, -1, S_(eval_shader_glsl),
"O código GLSL que o shader virou (para ver ou estudar)" },
};
#undef T
#undef I
#undef R
static bool d3_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
static const TinyBlocks_Category cat = { "3D", {0.36f, 0.42f, 0.86f, 1.f}, {0.25f, 0.30f, 0.66f, 1.f} };
tb_library_set_category(lib, &cat);
meshes_build();
scene_reset();
lib->lib_userdata = (void*)&s_software;
s_t_shader = tb_type_block_create(rt, "3D._Shader", NULL, 0, NULL, 0, NULL);
if (!s_t_shader) return false;
tb_type_block_set_flags(s_t_shader, TB_TYPE_HIDDEN);
tb_type_block_set_instance_hooks(s_t_shader, sizeof(ShdHandle), NULL, shd_handle_deinit);
tb_type_block_set_value_text(s_t_shader, shd_handle_text);
if (!tb_library_add(lib, &s_t_shader->base)) return false;
static const char* names[] = { "a", "b", "c", "d", "e", "f" };
for (size_t i = 0; i < sizeof(s_specs) / sizeof(s_specs[0]); i++) {
const Spec* sp = &s_specs[i];
TinyBlocks_SlotDesc in[6], out[1];
for (int k = 0; k < sp->nin; k++) in[k] = (TinyBlocks_SlotDesc){ names[k], sp->in[k] };
switch (sp->out) {
case O_IMAGE: out[0] = (TinyBlocks_SlotDesc){ "imagem", TB_VALUE_IMAGE }; break;
case O_REAL: out[0] = (TinyBlocks_SlotDesc){ "valor", TB_VALUE_REAL }; break;
case O_BOOL: out[0] = (TinyBlocks_SlotDesc){ "sim?", TB_VALUE_INTEGER }; break;
case O_TEXT: out[0] = (TinyBlocks_SlotDesc){ "texto", TB_VALUE_TEXT }; break;
case O_INT: out[0] = (TinyBlocks_SlotDesc){ "valor", TB_VALUE_INTEGER }; break;
case O_SHADER: out[0] = (TinyBlocks_SlotDesc){ "shader", TB_VALUE_BLOCK }; break;
default: break;
}
TinyBlocks_TypeBlock* t = tb_type_block_create(rt, sp->name, sp->nin ? in : NULL, (uint32_t)sp->nin,
sp->out ? out : NULL, sp->out ? 1u : 0u, sp->fn);
if (!t) return false;
tb_type_block_set_label(t, sp->label, sp->defs);
if (sp->stack_slot >= 0) tb_type_block_set_input_flags(t, (uint32_t)sp->stack_slot, TB_SLOT_STACK);
if (sp->out == O_SHADER) tb_type_block_set_instance_hooks(t, sizeof(ShdProducer), NULL, shd_producer_deinit);
tb_meta_declare(sp->name, sp->fname, __FILE__, sp->doc);
if (!tb_library_add(lib, &t->base)) return false;
}
return true;
}
static void d3_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
(void)rt;
lib->lib_userdata = NULL;
for (int i = 0; i < S.n; i++) shd_release(S.o[i].shader);
free(S.o); S.o = NULL; S.n = S.cap = 0;
free(s_draws); s_draws = NULL; s_draws_cap = 0;
free(s_zbuf); s_zbuf = NULL; s_zcap = 0;
meshes_free();
}
TINYBLOCKS_DEFINE_LIBRARY(d3, "tinyblocks-3d", "1.0.0", d3_init, d3_deinit)
const TinyBlocks_LibraryDescriptor* tb_3d_get_library(void) {
return &_tb_lib_desc_d3;
}