Shaders feitos com blocos: tinyblocks-shader e o compilador da 3d

"compile o shader [nome] com [pilha]" tem um encaixe de pilha: a pilha
nao roda, a 3d le o codigo dela e o compila (d3_shader.c) em nos com
tipo (numero, cor, condicao), de onde saem o GLSL da funcao tb_shade e um
interpretador para o renderizador em software (ponto e normal com
perspectiva, pixel a pixel). "use o shader [nome] no objeto" e "GLSL do
shader" completam.

tinyblocks-shader: o vocabulario (cor do pixel =, cor do pixel, cor do
objeto, luz, tempo, x/y/z do ponto e da normal, cor r g b, cor [nome],
misture, canais, brilho). Valem tambem as contas, comparacoes, o se/senao
e as variaveis comuns (viram locais do shader).

Contrato v2: Tb3dDraw.shader, Tb3dFrame.time, Tb3dRenderer.shaders. GL:
um programa por shader. Vulkan: o fragment compilado em execucao pela
libshaderc (dlopen) e push constants de 160 bytes; sem ela, a 3d usa o
OpenGL ou o software nesses quadros.

test-3d: xadrez e degrade iguais nos tres renderizadores (diferenca media
0,002), sem avisos da camada de validacao na NVIDIA, Intel e llvmpipe;
erros claros para bloco que nao cabe e para comparar cores.
examples/jogo-3d/shaders: ondas no chao e listras na bola.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mguinhosandClaude Opus 5.5 committed 2026-10-27 02:59:02 -03:00
1 parent a3bae660fb
commit 16009eca8e
27 files changed
+4376 -88

No files matched your search

+2 -2
View File
@@ -6,8 +6,8 @@ BUILD := build
CFLAGS := -std=c11 -O2 -Wall -Wextra -pedantic -fvisibility=hidden \
-D_POSIX_C_SOURCE=200809L -I../../include -Iinclude
SRCS := src/tb_3d.c
OBJS := $(BUILD)/tb_3d.o
SRCS := src/tb_3d.c src/d3_shader.c
OBJS := $(BUILD)/tb_3d.o $(BUILD)/d3_shader.o
LIB_A := $(BUILD)/libtinyblocks-3d.a
LIB_SO := $(BUILD)/libtinyblocks-3d.so
+20 -1
View File
@@ -29,7 +29,7 @@
#include <tinyblocks/tinyblocks.h>
#define TB_3D_LIB "tinyblocks-3d"
#define TB_3D_RENDERER_VERSION 1
#define TB_3D_RENDERER_VERSION 2
/* Malha: triangulos com posicao e normal (6 floats por vertice). As malhas
da cena sao fixas (cubo, esfera, plano e cilindro de tamanho 1): o
@@ -42,6 +42,21 @@ typedef struct Tb3dMesh {
int icount;
} Tb3dMesh;
/* Shader compilado ("compile o shader [nome] com [pilha]"): o corpo de uma
funcao GLSL que o renderizador poe no fragment shader:
vec3 tb_shade(vec3 P, vec3 N, vec3 base, float light, float time)
P = ponto no mundo, N = normal (normalizada), base = cor do objeto,
light = ambiente + (1 - ambiente) * max(N . luz, 0), time = segundos.
Devolve a cor do pixel (0..1). id fica igual enquanto o nome existir;
version muda a cada compilacao (o renderizador recompila). */
typedef struct Tb3dShader {
int id;
int version;
const char* glsl; /* a funcao tb_shade inteira (GLSL 330/450) */
} Tb3dShader;
/* Um objeto a desenhar */
typedef struct Tb3dDraw {
const Tb3dMesh* mesh;
@@ -50,6 +65,7 @@ typedef struct Tb3dDraw {
renderizadores nao precisam de matematica) */
float normal[9]; /* matriz das normais (3x3, colunas) */
float color[4]; /* RGBA 0..1 */
const Tb3dShader* shader; /* NULL = a luz padrao (lambert por vertice) */
} Tb3dDraw;
/* Um quadro: tudo o que o renderizador precisa */
@@ -61,6 +77,7 @@ typedef struct Tb3dFrame {
float sky[4]; /* cor de fundo */
float light_dir[3]; /* direcao PARA a luz, normalizada */
float ambient; /* 0..1 */
float time; /* segundos desde a "nova cena 3D" */
const Tb3dDraw* draws;
int draw_count;
} Tb3dFrame;
@@ -73,6 +90,8 @@ typedef struct Tb3dRenderer {
bool (*render)(const Tb3dFrame* f, uint8_t* rgba);
const char* (*device)(void); /* placa/driver em uso (texto) */
const char* (*error)(void); /* ultimo erro */
bool (*shaders)(void); /* desenha Tb3dDraw.shader? (false: a 3d
usa outro renderizador nesse quadro) */
} Tb3dRenderer;
TB_API const TinyBlocks_LibraryDescriptor* tb_3d_get_library(void);
+31
View File
@@ -0,0 +1,31 @@
/*
* TinyBlocks - d3_internal.h
* Partes internas da tinyblocks-3d compartilhadas entre os fontes: o
* compilador de shaders (d3_shader.c) e quem o usa (tb_3d.c).
*/
#ifndef TB_D3_INTERNAL_H
#define TB_D3_INTERNAL_H
#include <stdbool.h>
#include <tinyblocks/tinyblocks.h>
#include "tb_3d.h"
typedef struct D3Program D3Program; /* o shader compilado (opaco) */
/* Compila a pilha (o codigo de um encaixe TB_SLOT_STACK, em JSON).
NULL em erro, com a mensagem em err. */
D3Program* d3_shader_compile(const TinyBlocks_JsonValue* stack, char* err, size_t cap);
void d3_shader_free(D3Program* p);
const char* d3_shader_glsl(const D3Program* p); /* a funcao tb_shade */
/* Entradas de um pixel e a cor que sai (o interpretador do software) */
typedef struct {
float P[3], N[3], base[3];
float light, time;
} D3Pixel;
void d3_shader_run(const D3Program* p, const D3Pixel* in, float out[3]);
/* Cores por nome (vermelho, azul, dourado...) ou #rrggbb */
bool d3_color_of(const char* name, float out[4]);
#endif
+570
View File
@@ -0,0 +1,570 @@
/*
* TinyBlocks - d3_shader.c
* O compilador dos shaders feitos com blocos.
*
* Entrada: o codigo de uma pilha (JSON de um encaixe TB_SLOT_STACK, ver
* tb_defs.h). Saida: uma arvore compacta (nos num vetor) com o tipo de
* cada expressao (numero, cor ou condicao), de onde saem
* - o GLSL da funcao tb_shade (OpenGL e Vulkan), e
* - o interpretador usado pelo renderizador em software.
*
* Valores: numero (F), cor (V, tres canais) e condicao (B). Uma conta entre
* cor e numero vale para os tres canais (como no GLSL). No interpretador um
* numero e guardado repetido nos tres canais, entao as contas sao sempre por
* canal. Angulos em graus, como nos blocos de numero.
*/
#define _POSIX_C_SOURCE 200809L
#include <math.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <tinyblocks/tinyblocks.h>
#include "d3_internal.h"
enum { TF, TV, TB }; /* numero, cor, condicao */
enum {
/* expressoes */
E_CONST, E_VAR, E_PIX, E_BASE, E_LIGHT, E_TIME, E_P, E_N, /* E_P/E_N: canal em k[0] */
E_RGB, E_ADD, E_SUB, E_MUL, E_DIV, E_MOD, E_MIN, E_MAX, E_POW, E_MIX, E_CLAMP,
E_ABS, E_SQRT, E_FLOOR, E_CEIL, E_ROUND, E_SIN, E_COS, E_TAN, E_EXP, E_LN,
E_CHAN, E_GRAY, /* E_CHAN: canal em k[0] */
E_LT, E_EQ, E_GT, E_AND, E_OR, E_NOT,
/* comandos */
S_PIXEL, S_SET, S_IF,
};
typedef struct {
int op, type;
int a, b, c; /* filhos (expressoes) ou, no S_IF, as listas then (b) e else (c) */
int var; /* local (E_VAR, S_SET) */
float k[3]; /* constante (E_CONST) ou parametro */
int next; /* proximo comando da lista (-1 = fim) */
} Node;
#define MAX_LOCALS 32
struct D3Program {
Node* n;
int nn, cap;
int first; /* primeiro comando */
char local[MAX_LOCALS][32];
int ltype[MAX_LOCALS];
int nl;
char* glsl;
};
/* == Compilacao: JSON -> nos ========================================== */
typedef struct { D3Program* p; char* err; size_t cap; bool failed; } C;
static void fail(C* c, const char* fmt, ...) {
if (c->failed) return;
c->failed = true;
va_list ap;
va_start(ap, fmt);
vsnprintf(c->err, c->cap, fmt, ap);
va_end(ap);
}
static int node(C* c, int op, int type) {
D3Program* p = c->p;
if (p->nn == p->cap) {
int nc = p->cap ? p->cap * 2 : 64;
Node* q = realloc(p->n, (size_t)nc * sizeof(Node));
if (!q) { fail(c, "sem memória"); return -1; }
p->n = q; p->cap = nc;
}
Node* x = &p->n[p->nn];
memset(x, 0, sizeof(*x));
x->op = op; x->type = type; x->a = x->b = x->c = x->var = x->next = -1;
return p->nn++;
}
static const char* jtype(const TinyBlocks_JsonValue* j) {
TinyBlocks_JsonValue* t = j && tb_json_kind(j) == TB_JSON_OBJECT ? tb_json_object_get(j, "type") : NULL;
const char* s = t ? tb_json_as_string(t) : NULL;
tb_json_release(t); /* a string vive no objeto j */
return s ? s : "";
}
/* Entrada i do bloco j (ref nova ou NULL) */
static TinyBlocks_JsonValue* jin(const TinyBlocks_JsonValue* j, int i) {
TinyBlocks_JsonValue* ins = tb_json_object_get(j, "inputs");
TinyBlocks_JsonValue* v = ins ? tb_json_array_get(ins, (uint32_t)i) : NULL;
tb_json_release(ins);
return v;
}
static int expr(C* c, const TinyBlocks_JsonValue* j);
static int stmts(C* c, const TinyBlocks_JsonValue* arr);
static int expr_in(C* c, const TinyBlocks_JsonValue* j, int i) {
TinyBlocks_JsonValue* v = jin(j, i);
int r = expr(c, v);
tb_json_release(v);
return r;
}
static int constf(C* c, float f) {
int n = node(c, E_CONST, TF);
if (n >= 0) c->p->n[n].k[0] = c->p->n[n].k[1] = c->p->n[n].k[2] = f;
return n;
}
static int local_of(C* c, const char* name, int type, bool create) {
D3Program* p = c->p;
for (int i = 0; i < p->nl; i++) {
if (strcmp(p->local[i], name) != 0) continue;
if (type >= 0 && p->ltype[i] != type)
fail(c, "a variável \"%s\" guarda %s e recebeu %s", name, p->ltype[i] == TV ? "uma cor" : "um número",
type == TV ? "uma cor" : "um número");
return i;
}
if (!create) { fail(c, "a variável \"%s\" é usada antes de receber um valor no shader", name); return -1; }
if (p->nl == MAX_LOCALS) { fail(c, "o shader tem variáveis demais (máximo %d)", MAX_LOCALS); return -1; }
snprintf(p->local[p->nl], sizeof(p->local[0]), "%s", name);
p->ltype[p->nl] = type;
return p->nl++;
}
static int num_or_color(int a, int b) { return a == TV || b == TV ? TV : TF; }
static int binop(C* c, int op, int a, int b) {
if (a < 0 || b < 0) return -1;
int ta = c->p->n[a].type, tb = c->p->n[b].type;
if (ta == TB || tb == TB) { fail(c, "uma condição não entra numa conta"); return -1; }
int n = node(c, op, num_or_color(ta, tb));
if (n >= 0) { c->p->n[n].a = a; c->p->n[n].b = b; }
return n;
}
static int unop(C* c, int op, int a) {
if (a < 0) return -1;
if (c->p->n[a].type == TB) { fail(c, "uma condição não entra numa conta"); return -1; }
int n = node(c, op, c->p->n[a].type);
if (n >= 0) c->p->n[n].a = a;
return n;
}
static int compare(C* c, int op, int a, int b) {
if (a < 0 || b < 0) return -1;
if (c->p->n[a].type != TF || c->p->n[b].type != TF) { fail(c, "só dá para comparar números (use \"vermelho de\", \"brilho de\"...)"); return -1; }
int n = node(c, op, TB);
if (n >= 0) { c->p->n[n].a = a; c->p->n[n].b = b; }
return n;
}
static int logic(C* c, int op, int a, int b) {
if (a < 0 || (op != E_NOT && b < 0)) return -1;
if (c->p->n[a].type != TB || (op != E_NOT && c->p->n[b].type != TB)) { fail(c, "\"e\", \"ou\" e \"não\" juntam condições"); return -1; }
int n = node(c, op, TB);
if (n >= 0) { c->p->n[n].a = a; c->p->n[n].b = b; }
return n;
}
static int expr(C* c, const TinyBlocks_JsonValue* j) {
if (c->failed) return -1;
if (!j || tb_json_kind(j) == TB_JSON_NULL) return constf(c, 0);
if (tb_json_kind(j) == TB_JSON_NUMBER) return constf(c, (float)tb_json_as_number(j, 0));
if (tb_json_kind(j) == TB_JSON_STRING) {
const char* s = tb_json_as_string(j);
char* e;
double d = strtod(s, &e);
if (e != s && *e == 0) return constf(c, (float)d);
float col[4];
if (d3_color_of(s, col)) { /* "azul" num campo: a cor */
int n = node(c, E_CONST, TV);
if (n >= 0) memcpy(c->p->n[n].k, col, 3 * sizeof(float));
return n;
}
fail(c, "\"%s\" não é número nem cor", s);
return -1;
}
const char* t = jtype(j);
/* -- vocabulario do shader */
if (!strcmp(t, "Shader.PixelColor")) return node(c, E_PIX, TV);
if (!strcmp(t, "Shader.ObjectColor")) return node(c, E_BASE, TV);
if (!strcmp(t, "Shader.Light")) return node(c, E_LIGHT, TF);
if (!strcmp(t, "Shader.Time")) return node(c, E_TIME, TF);
const char* axes[] = { "Shader.X", "Shader.Y", "Shader.Z", "Shader.NX", "Shader.NY", "Shader.NZ" };
for (int k = 0; k < 6; k++)
if (!strcmp(t, axes[k])) {
int n = node(c, k < 3 ? E_P : E_N, TF);
if (n >= 0) c->p->n[n].k[0] = (float)(k % 3);
return n;
}
if (!strcmp(t, "Shader.Rgb")) {
int a = expr_in(c, j, 0), b = expr_in(c, j, 1), d = expr_in(c, j, 2);
if (a < 0 || b < 0 || d < 0) return -1;
if (c->p->n[a].type != TF || c->p->n[b].type != TF || c->p->n[d].type != TF) { fail(c, "\"cor r g b\" recebe três números"); return -1; }
int n = node(c, E_RGB, TV);
if (n >= 0) { c->p->n[n].a = a; c->p->n[n].b = b; c->p->n[n].c = d; }
return n;
}
if (!strcmp(t, "Shader.Color")) {
TinyBlocks_JsonValue* v = jin(j, 0);
const char* s = v ? tb_json_as_string(v) : NULL;
float col[4];
bool ok = s && d3_color_of(s, col);
if (!ok) fail(c, "cor desconhecida \"%s\" (use um nome ou #rrggbb)", s ? s : "");
tb_json_release(v);
if (!ok) return -1;
int n = node(c, E_CONST, TV);
if (n >= 0) memcpy(c->p->n[n].k, col, 3 * sizeof(float));
return n;
}
if (!strcmp(t, "Shader.Mix")) {
int a = expr_in(c, j, 0), b = expr_in(c, j, 1), d = expr_in(c, j, 2);
if (a < 0 || b < 0 || d < 0) return -1;
if (c->p->n[d].type != TF) { fail(c, "\"misture ... por\" recebe um número (0 a 1)"); return -1; }
int n = binop(c, E_MIX, a, b);
if (n >= 0) c->p->n[n].c = d;
return n;
}
if (!strcmp(t, "Shader.Red") || !strcmp(t, "Shader.Green") || !strcmp(t, "Shader.Blue")) {
int a = expr_in(c, j, 0);
if (a < 0) return -1;
if (c->p->n[a].type == TF) return a;
int n = node(c, E_CHAN, TF);
if (n >= 0) { c->p->n[n].a = a; c->p->n[n].k[0] = (float)(t[7] == 'R' ? 0 : t[7] == 'G' ? 1 : 2); }
return n;
}
if (!strcmp(t, "Shader.Gray")) {
int a = expr_in(c, j, 0);
if (a < 0) return -1;
if (c->p->n[a].type == TF) return a;
int n = node(c, E_GRAY, TF);
if (n >= 0) c->p->n[n].a = a;
return n;
}
/* -- contas e comparacoes comuns */
static const struct { const char* type; int op; int ar; } ops[] = {
{"Math.Add", E_ADD, 2}, {"Math.Sub", E_SUB, 2}, {"Math.Mul", E_MUL, 2}, {"Math.Div", E_DIV, 2},
{"Number.Div", E_DIV, 2}, {"Math.Mod", E_MOD, 2}, {"Math.Min", E_MIN, 2}, {"Math.Max", E_MAX, 2},
{"Number.Pow", E_POW, 2}, {"Math.Abs", E_ABS, 1}, {"Number.Sqrt", E_SQRT, 1},
{"Number.Floor", E_FLOOR, 1}, {"Number.Ceil", E_CEIL, 1}, {"Number.Round", E_ROUND, 1},
{"Number.Sin", E_SIN, 1}, {"Number.Cos", E_COS, 1}, {"Number.Tan", E_TAN, 1},
{"Number.Exp", E_EXP, 1}, {"Number.Ln", E_LN, 1},
};
for (size_t i = 0; i < sizeof(ops) / sizeof(ops[0]); i++) {
if (strcmp(t, ops[i].type) != 0) continue;
int a = expr_in(c, j, 0);
return ops[i].ar == 1 ? unop(c, ops[i].op, a) : binop(c, ops[i].op, a, expr_in(c, j, 1));
}
if (!strcmp(t, "Number.Pi")) return constf(c, 3.14159265f);
if (!strcmp(t, "Number.Clamp")) {
int x = expr_in(c, j, 0), lo = expr_in(c, j, 1), hi = expr_in(c, j, 2);
if (lo < 0 || hi < 0) return -1;
if (c->p->n[lo].type != TF || c->p->n[hi].type != TF) { fail(c, "os limites de \"limite\" são números"); return -1; }
int n = unop(c, E_CLAMP, x);
if (n >= 0) { c->p->n[n].b = lo; c->p->n[n].c = hi; }
return n;
}
if (!strcmp(t, "Operators.Lt")) return compare(c, E_LT, expr_in(c, j, 0), expr_in(c, j, 1));
if (!strcmp(t, "Operators.Eq")) return compare(c, E_EQ, expr_in(c, j, 0), expr_in(c, j, 1));
if (!strcmp(t, "Operators.Gt")) return compare(c, E_GT, expr_in(c, j, 0), expr_in(c, j, 1));
if (!strcmp(t, "Operators.And")) return logic(c, E_AND, expr_in(c, j, 0), expr_in(c, j, 1));
if (!strcmp(t, "Operators.Or")) return logic(c, E_OR, expr_in(c, j, 0), expr_in(c, j, 1));
if (!strcmp(t, "Operators.Not")) return logic(c, E_NOT, expr_in(c, j, 0), -1);
if (!strcmp(t, "Variables.Get")) {
TinyBlocks_JsonValue* v = jin(j, 0);
const char* nm = v ? tb_json_as_string(v) : NULL;
int l = nm ? local_of(c, nm, -1, false) : -1;
tb_json_release(v);
if (l < 0) return -1;
int n = node(c, E_VAR, c->p->ltype[l]);
if (n >= 0) c->p->n[n].var = l;
return n;
}
fail(c, "o bloco \"%s\" não pode ser usado num shader", t);
return -1;
}
/* mude/adicione: a local recebe o tipo do valor na primeira vez */
static int set_var(C* c, const TinyBlocks_JsonValue* j, bool change) {
TinyBlocks_JsonValue* v = jin(j, 0);
char nm[32];
snprintf(nm, sizeof(nm), "%s", v && tb_json_as_string(v) ? tb_json_as_string(v) : "");
tb_json_release(v);
if (!nm[0]) { fail(c, "\"mude\" sem nome de variável no shader"); return -1; }
int e = expr_in(c, j, 1);
if (e < 0) return -1;
if (c->p->n[e].type == TB) { fail(c, "uma variável do shader guarda número ou cor, não condição"); return -1; }
if (change) {
int l = local_of(c, nm, c->p->n[e].type, false);
if (l < 0) return -1;
int g = node(c, E_VAR, c->p->ltype[l]);
if (g < 0) return -1;
c->p->n[g].var = l;
e = binop(c, E_ADD, g, e);
if (e < 0) return -1;
}
int l = local_of(c, nm, c->p->n[e].type, true);
if (l < 0) return -1;
int n = node(c, S_SET, -1);
if (n >= 0) { c->p->n[n].var = l; c->p->n[n].a = e; }
return n;
}
static int stmt(C* c, const TinyBlocks_JsonValue* j) {
const char* t = jtype(j);
if (!strcmp(t, "Shader.Pixel")) {
int e = expr_in(c, j, 0);
if (e < 0) return -1;
if (c->p->n[e].type == TB) { fail(c, "\"cor do pixel =\" recebe uma cor ou um número"); return -1; }
int n = node(c, S_PIXEL, -1);
if (n >= 0) c->p->n[n].a = e;
return n;
}
if (!strcmp(t, "Variables.Set")) return set_var(c, j, false);
if (!strcmp(t, "Variables.Change")) return set_var(c, j, true);
if (!strcmp(t, "Control.If") || !strcmp(t, "Control.IfElse")) {
int cond = expr_in(c, j, 0);
if (cond < 0) return -1;
if (c->p->n[cond].type != TB) { fail(c, "o \"se\" do shader precisa de uma condição"); return -1; }
TinyBlocks_JsonValue* m = tb_json_object_get(j, "mouths");
TinyBlocks_JsonValue* m0 = m ? tb_json_array_get(m, 0) : NULL;
TinyBlocks_JsonValue* m1 = m ? tb_json_array_get(m, 1) : NULL;
int a = stmts(c, m0), b = m1 ? stmts(c, m1) : -1;
tb_json_release(m0); tb_json_release(m1); tb_json_release(m);
if (c->failed) return -1;
int n = node(c, S_IF, -1);
if (n >= 0) { c->p->n[n].a = cond; c->p->n[n].b = a; c->p->n[n].c = b; }
return n;
}
fail(c, "o comando \"%s\" não pode ser usado num shader", t);
return -1;
}
/* Lista de comandos ligada por next; -1 = vazia */
static int stmts(C* c, const TinyBlocks_JsonValue* arr) {
int first = -1, last = -1;
uint32_t n = arr && tb_json_kind(arr) == TB_JSON_ARRAY ? tb_json_array_length(arr) : 0;
for (uint32_t i = 0; i < n && !c->failed; i++) {
TinyBlocks_JsonValue* j = tb_json_array_get(arr, i);
int s = stmt(c, j);
tb_json_release(j);
if (s < 0) break;
if (last >= 0) c->p->n[last].next = s; else first = s;
last = s;
}
return first;
}
/* == GLSL ============================================================= */
typedef struct { char* s; size_t n, cap; } Str;
static void put(Str* o, const char* fmt, ...) {
va_list ap;
va_start(ap, fmt);
char tmp[512];
int k = vsnprintf(tmp, sizeof(tmp), fmt, ap);
va_end(ap);
if (k < 0) return;
if (o->n + (size_t)k + 1 > o->cap) {
size_t nc = o->cap ? o->cap * 2 : 1024;
while (nc < o->n + (size_t)k + 1) nc *= 2;
char* p = realloc(o->s, nc);
if (!p) return;
o->s = p; o->cap = nc;
}
memcpy(o->s + o->n, tmp, (size_t)k + 1);
o->n += (size_t)k;
}
static void gx(const D3Program* p, Str* o, int i);
/* filho como vec3 (quando o no e cor e o filho e numero) */
static void gv(const D3Program* p, Str* o, int i, bool as_vec) {
if (as_vec && p->n[i].type == TF) { put(o, "vec3("); gx(p, o, i); put(o, ")"); }
else gx(p, o, i);
}
static void gx(const D3Program* p, Str* o, int i) {
const Node* x = &p->n[i];
bool v = x->type == TV;
static const char* ch = "xyz";
switch (x->op) {
case E_CONST:
if (v) put(o, "vec3(%.6g, %.6g, %.6g)", x->k[0], x->k[1], x->k[2]);
else put(o, "%.6g", x->k[0]);
if (!v && x->k[0] == floorf(x->k[0]) && fabsf(x->k[0]) < 1e7f) put(o, ".0");
break;
case E_VAR: put(o, "l%d", x->var); break;
case E_PIX: put(o, "pix"); break;
case E_BASE: put(o, "base"); break;
case E_LIGHT: put(o, "light"); break;
case E_TIME: put(o, "time"); break;
case E_P: put(o, "P.%c", ch[(int)x->k[0]]); break;
case E_N: put(o, "N.%c", ch[(int)x->k[0]]); break;
case E_RGB: put(o, "vec3("); gx(p, o, x->a); put(o, ", "); gx(p, o, x->b); put(o, ", "); gx(p, o, x->c); put(o, ")"); break;
case E_ADD: case E_SUB: case E_MUL: case E_DIV:
put(o, "("); gx(p, o, x->a);
put(o, x->op == E_ADD ? " + " : x->op == E_SUB ? " - " : x->op == E_MUL ? " * " : " / ");
gx(p, o, x->b); put(o, ")");
break;
case E_MOD: case E_MIN: case E_MAX: case E_POW:
put(o, x->op == E_MOD ? "mod(" : x->op == E_MIN ? "min(" : x->op == E_MAX ? "max(" : "pow(");
gv(p, o, x->a, v); put(o, ", "); gv(p, o, x->b, v); put(o, ")");
break;
case E_MIX: put(o, "mix("); gv(p, o, x->a, v); put(o, ", "); gv(p, o, x->b, v); put(o, ", "); gx(p, o, x->c); put(o, ")"); break;
case E_CLAMP: put(o, "clamp("); gx(p, o, x->a); put(o, ", "); gx(p, o, x->b); put(o, ", "); gx(p, o, x->c); put(o, ")"); break;
case E_ABS: put(o, "abs("); gx(p, o, x->a); put(o, ")"); break;
case E_SQRT: put(o, "sqrt(max("); gx(p, o, x->a); put(o, ", 0.0))"); break;
case E_FLOOR: put(o, "floor("); gx(p, o, x->a); put(o, ")"); break;
case E_CEIL: put(o, "ceil("); gx(p, o, x->a); put(o, ")"); break;
case E_ROUND: put(o, "floor("); gx(p, o, x->a); put(o, " + 0.5)"); break;
case E_SIN: put(o, "sin(radians("); gx(p, o, x->a); put(o, "))"); break;
case E_COS: put(o, "cos(radians("); gx(p, o, x->a); put(o, "))"); break;
case E_TAN: put(o, "tan(radians("); gx(p, o, x->a); put(o, "))"); break;
case E_EXP: put(o, "exp("); gx(p, o, x->a); put(o, ")"); break;
case E_LN: put(o, "log(max("); gx(p, o, x->a); put(o, ", 1e-30))"); break;
case E_CHAN: put(o, "("); gx(p, o, x->a); put(o, ").%c", ch[(int)x->k[0]]); break;
case E_GRAY: put(o, "dot("); gx(p, o, x->a); put(o, ", vec3(0.299, 0.587, 0.114))"); break;
case E_LT: case E_EQ: case E_GT:
put(o, "("); gx(p, o, x->a);
put(o, x->op == E_LT ? " < " : x->op == E_GT ? " > " : " == ");
gx(p, o, x->b); put(o, ")");
break;
case E_AND: put(o, "("); gx(p, o, x->a); put(o, " && "); gx(p, o, x->b); put(o, ")"); break;
case E_OR: put(o, "("); gx(p, o, x->a); put(o, " || "); gx(p, o, x->b); put(o, ")"); break;
case E_NOT: put(o, "(!"); gx(p, o, x->a); put(o, ")"); break;
}
}
static void gs(const D3Program* p, Str* o, int i, int depth) {
for (; i >= 0; i = p->n[i].next) {
const Node* x = &p->n[i];
put(o, "%*s", depth * 4, "");
if (x->op == S_PIXEL) { put(o, "pix = "); gv(p, o, x->a, true); put(o, ";\n"); }
else if (x->op == S_SET) { put(o, "l%d = ", x->var); gx(p, o, x->a); put(o, ";\n"); }
else if (x->op == S_IF) {
put(o, "if "); gx(p, o, x->a); put(o, " {\n");
gs(p, o, x->b, depth + 1);
put(o, "%*s}", depth * 4, "");
if (x->c >= 0) { put(o, " else {\n"); gs(p, o, x->c, depth + 1); put(o, "%*s}", depth * 4, ""); }
put(o, "\n");
}
}
}
static char* emit_glsl(const D3Program* p) {
Str o = {0};
put(&o, "vec3 tb_shade(vec3 P, vec3 N, vec3 base, float light, float time) {\n");
put(&o, " vec3 pix = base * light;\n");
for (int i = 0; i < p->nl; i++)
put(&o, p->ltype[i] == TV ? " vec3 l%d = vec3(0.0);\n" : " float l%d = 0.0;\n", i);
gs(p, &o, p->first, 1);
put(&o, " return clamp(pix, 0.0, 1.0);\n}\n");
return o.s;
}
/* == API ============================================================== */
D3Program* d3_shader_compile(const TinyBlocks_JsonValue* stack, char* err, size_t cap) {
if (err && cap) err[0] = 0;
D3Program* p = calloc(1, sizeof(*p));
if (!p) { snprintf(err, cap, "sem memória"); return NULL; }
C c = { p, err, cap, false };
if (!stack || tb_json_kind(stack) != TB_JSON_ARRAY) fail(&c, "encaixe uma pilha de blocos de shader");
else p->first = stmts(&c, stack);
if (!c.failed && p->first < 0) fail(&c, "o shader está vazio (use \"cor do pixel = ...\")");
if (!c.failed) {
p->glsl = emit_glsl(p);
if (!p->glsl) fail(&c, "sem memória");
}
if (c.failed) { d3_shader_free(p); return NULL; }
return p;
}
void d3_shader_free(D3Program* p) {
if (!p) return;
free(p->n);
free(p->glsl);
free(p);
}
const char* d3_shader_glsl(const D3Program* p) { return p ? p->glsl : ""; }
/* == Interpretador (software): cada valor e um float[3] ================ */
typedef struct { const D3Pixel* in; float pix[3]; float loc[MAX_LOCALS][3]; } Run;
static float fmod_glsl(float a, float b) { return b == 0 ? 0 : a - b * floorf(a / b); }
static void ev(const D3Program* p, Run* r, int i, float o[3]) {
const Node* x = &p->n[i];
float a[3], b[3], c[3];
const float R = 3.14159265f / 180.f;
switch (x->op) {
case E_CONST: memcpy(o, x->k, sizeof(a)); return;
case E_VAR: memcpy(o, r->loc[x->var], sizeof(a)); return;
case E_PIX: memcpy(o, r->pix, sizeof(a)); return;
case E_BASE: memcpy(o, r->in->base, sizeof(a)); return;
case E_LIGHT: o[0] = o[1] = o[2] = r->in->light; return;
case E_TIME: o[0] = o[1] = o[2] = r->in->time; return;
case E_P: o[0] = o[1] = o[2] = r->in->P[(int)x->k[0]]; return;
case E_N: o[0] = o[1] = o[2] = r->in->N[(int)x->k[0]]; return;
case E_RGB: ev(p, r, x->a, a); ev(p, r, x->b, b); ev(p, r, x->c, c); o[0] = a[0]; o[1] = b[0]; o[2] = c[0]; return;
case E_CHAN: ev(p, r, x->a, a); o[0] = o[1] = o[2] = a[(int)x->k[0]]; return;
case E_GRAY: ev(p, r, x->a, a); o[0] = o[1] = o[2] = a[0] * 0.299f + a[1] * 0.587f + a[2] * 0.114f; return;
case E_LT: case E_EQ: case E_GT:
ev(p, r, x->a, a); ev(p, r, x->b, b);
o[0] = o[1] = o[2] = (x->op == E_LT ? a[0] < b[0] : x->op == E_GT ? a[0] > b[0] : a[0] == b[0]) ? 1.f : 0.f;
return;
case E_AND: ev(p, r, x->a, a); if (!a[0]) { o[0] = o[1] = o[2] = 0; return; } ev(p, r, x->b, o); return;
case E_OR: ev(p, r, x->a, a); if (a[0]) { o[0] = o[1] = o[2] = 1; return; } ev(p, r, x->b, o); return;
case E_NOT: ev(p, r, x->a, a); o[0] = o[1] = o[2] = a[0] ? 0.f : 1.f; return;
default: break;
}
ev(p, r, x->a, a);
if (x->b >= 0) ev(p, r, x->b, b);
if (x->c >= 0) ev(p, r, x->c, c);
for (int k = 0; k < 3; k++) {
float u = a[k], w = x->b >= 0 ? b[k] : 0;
switch (x->op) {
case E_ADD: o[k] = u + w; break;
case E_SUB: o[k] = u - w; break;
case E_MUL: o[k] = u * w; break;
case E_DIV: o[k] = u / w; break;
case E_MOD: o[k] = fmod_glsl(u, w); break;
case E_MIN: o[k] = fminf(u, w); break;
case E_MAX: o[k] = fmaxf(u, w); break;
case E_POW: o[k] = powf(u, w); break;
case E_MIX: o[k] = u + (w - u) * c[0]; break;
case E_CLAMP: o[k] = fminf(fmaxf(u, b[0]), c[0]); break;
case E_ABS: o[k] = fabsf(u); break;
case E_SQRT: o[k] = sqrtf(fmaxf(u, 0)); break;
case E_FLOOR: o[k] = floorf(u); break;
case E_CEIL: o[k] = ceilf(u); break;
case E_ROUND: o[k] = floorf(u + 0.5f); break;
case E_SIN: o[k] = sinf(u * R); break;
case E_COS: o[k] = cosf(u * R); break;
case E_TAN: o[k] = tanf(u * R); break;
case E_EXP: o[k] = expf(u); break;
case E_LN: o[k] = logf(fmaxf(u, 1e-30f)); break;
default: o[k] = 0; break;
}
}
}
static void ex(const D3Program* p, Run* r, int i) {
for (; i >= 0; i = p->n[i].next) {
const Node* x = &p->n[i];
if (x->op == S_PIXEL) ev(p, r, x->a, r->pix);
else if (x->op == S_SET) ev(p, r, x->a, r->loc[x->var]);
else if (x->op == S_IF) {
float c[3];
ev(p, r, x->a, c);
ex(p, r, c[0] ? x->b : x->c);
}
}
}
void d3_shader_run(const D3Program* p, const D3Pixel* in, float out[3]) {
Run r;
r.in = in;
for (int k = 0; k < 3; k++) r.pix[k] = in->base[k] * in->light;
memset(r.loc, 0, sizeof(float) * 3 * (size_t)(p->nl ? p->nl : 1));
ex(p, &r, p->first);
for (int k = 0; k < 3; k++) out[k] = fminf(fmaxf(r.pix[k], 0.f), 1.f);
}
+161 -43
View File
@@ -14,7 +14,9 @@
#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
@@ -194,8 +196,21 @@ typedef struct {
int kind;
float pos[3], rot[3], scale[3], color[4];
bool visible;
int shader; /* indice em s_shd (-1 = luz padrao) */
} Obj;
/* Shaders compilados, pelo nome ("compile o shader [nome] com [pilha]") */
typedef struct { Tb3dShader pub; char name[48]; D3Program* prog; } Shd;
#define MAX_SHADERS 64
static Shd s_shd[MAX_SHADERS];
static int s_shd_n;
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;
@@ -204,6 +219,7 @@ static struct {
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) {
@@ -215,6 +231,7 @@ static void scene_reset(void) {
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) {
@@ -223,8 +240,8 @@ static Obj* find(const char* name) {
}
/* Cores: nomes em portugues ou #rrggbb */
static bool color_of(const char* c, float out[4]) {
/* 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},
@@ -286,6 +303,7 @@ static bool frame_build(Tb3dFrame* f, int w, int h) {
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;
@@ -300,6 +318,7 @@ static bool frame_build(Tb3dFrame* f, int w, int h) {
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 >= 0 && o->shader < s_shd_n && s_shd[o->shader].prog ? &s_shd[o->shader].pub : NULL;
}
f->draws = s_draws;
f->draw_count = n;
@@ -307,7 +326,15 @@ static bool frame_build(Tb3dFrame* f, int w, int h) {
}
/* == Rasterizador em software ======================================== */
typedef struct { float x, y, z, w, r, g, b; } CV; /* vertice no clip + cor */
/* 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]; } 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 Tb3dFrame* s_frame;
static float s_base[3];
static float* s_zbuf;
static size_t s_zcap;
@@ -339,9 +366,27 @@ static void raster_tri(const CV* a, const CV* b, const CV* c, int W, int H, uint
if (z >= *zb) continue;
*zb = z;
uint8_t* p = px + ((size_t)y * W + x) * 4;
float r = w0 * a->r + w1 * b->r + w2 * c->r;
float g = w0 * a->g + w1 * b->g + w2 * c->g;
float bl = w0 * a->b + w1 * b->b + w2 * c->b;
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.base[k] = s_base[k];
}
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);
@@ -362,9 +407,9 @@ static void clip_and_raster(const CV in[3], int W, int H, uint8_t* px) {
if ((dp >= 0) != (dq >= 0)) {
float t = dp / (dp - dq);
CV m;
m.x = p->x + (q->x - p->x) * t; m.y = p->y + (q->y - p->y) * t;
m.z = p->z + (q->z - p->z) * t; m.w = p->w + (q->w - p->w) * t;
m.r = p->r + (q->r - p->r) * t; m.g = p->g + (q->g - p->g) * t; m.b = p->b + (q->b - p->b) * t;
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;
}
}
@@ -380,6 +425,11 @@ static void shade(const Tb3dFrame* f, const Tb3dDraw* d, const float* v, CV* o)
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] * v[k];
o->N[i] = n[i];
}
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];
@@ -412,6 +462,9 @@ static bool sw_render(const Tb3dFrame* f, uint8_t* px) {
cv = p; cv_cap = m->vcount;
}
for (int i = 0; i < m->vcount; i++) shade(f, d, m->verts + (size_t)i * 6, &cv[i]);
s_prog = d->shader ? s_shd[d->shader->id - 1].prog : NULL; /* id = indice + 1 */
s_frame = f;
memcpy(s_base, d->color, sizeof(s_base));
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;
@@ -419,20 +472,26 @@ static bool sw_render(const Tb3dFrame* f, uint8_t* px) {
}
}
free(cv);
s_prog = 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 };
TB_3D_RENDERER_VERSION, "software", sw_available, sw_render, sw_device, sw_error, sw_shaders };
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) return NULL;
return r->available() ? r : 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 */
@@ -485,6 +544,7 @@ static void create(TinyBlocks_Block* self, TinyBlocks* rt, int kind) {
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;
o->shader = -1;
}
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); }
@@ -501,7 +561,7 @@ OBJ_CMD(eval_rot_by, vec_in(self, rt, 1, v); for (int k = 0; k < 3; k++) o->r
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 (!color_of(name_in(self, rt, 1), o->color))
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) {
@@ -575,7 +635,7 @@ static void eval_ambient(TinyBlocks_Block* self, TinyBlocks* rt) {
static void eval_sky(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
if (!color_of(name_in(self, rt, 0), S.sky)) tinyblocks_set_error(rt, "cor desconhecida '%s'", name_in(self, rt, 0));
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) {
@@ -595,6 +655,8 @@ static void eval_image(TinyBlocks_Block* self, TinyBlocks* rt) {
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());
@@ -606,6 +668,52 @@ static void eval_image(TinyBlocks_Block* self, TinyBlocks* rt) {
tb_image_release(img);
}
static int shader_find(const char* name) {
for (int i = 0; i < s_shd_n; i++) if (!strcmp(s_shd[i].name, name)) return i;
return -1;
}
static void eval_shader_compile(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
const char* nm = name_in(self, rt, 0);
if (!nm[0]) { tinyblocks_set_error(rt, "dê um nome ao shader"); return; }
TinyBlocks_Value v = tb_block_get_input(self, rt, 1);
const TinyBlocks_JsonValue* code = v.kind == TB_VALUE_JSON ? v.as.json : NULL;
char err[200];
D3Program* prog = d3_shader_compile(code, err, sizeof(err));
if (!prog) { tinyblocks_set_error(rt, "shader \"%s\": %s", nm, err); return; }
int i = shader_find(nm);
if (i < 0) {
if (s_shd_n == MAX_SHADERS) { d3_shader_free(prog); tinyblocks_set_error(rt, "shaders demais (máximo %d)", MAX_SHADERS); return; }
i = s_shd_n++;
memset(&s_shd[i], 0, sizeof(s_shd[i]));
snprintf(s_shd[i].name, sizeof(s_shd[i].name), "%s", nm);
s_shd[i].pub.id = i + 1;
}
d3_shader_free(s_shd[i].prog);
s_shd[i].prog = prog;
s_shd[i].pub.glsl = d3_shader_glsl(prog);
s_shd[i].pub.version++;
}
static void eval_shader_use(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
Obj* o = need(self, rt, 1);
if (!o) return;
const char* nm = name_in(self, rt, 0);
if (!nm[0] || !strcasecmp(nm, "nenhum")) { o->shader = -1; return; }
int i = shader_find(nm);
if (i < 0) { tinyblocks_set_error(rt, "não existe o shader '%s' (compile antes)", nm); return; }
o->shader = i;
}
static void eval_shader_glsl(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
int i = shader_find(name_in(self, rt, 0));
if (i < 0) { tinyblocks_set_error(rt, "não existe o shader '%s'", name_in(self, rt, 0)); return; }
tb_block_set_output(self, 0, tb_value_text(s_shd[i].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()); }
@@ -624,6 +732,7 @@ 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;
@@ -633,35 +742,41 @@ typedef struct {
#define S_(fn) fn, #fn
#define XYZ "|0|0|0"
static const Spec s_specs[] = {
{ "3D.Scene", "nova cena 3D", "", 0, {T}, O_NONE, 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, 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, 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, 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, S_(eval_cylinder), "Cilindro em pé, diâmetro 1 e altura 1" },
{ "3D.MoveTo", "mova %1 para x %2 y %3 z %4", "jogador|0|0.5|0", 4, {T,R,R,R}, O_NONE, 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, 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, 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, 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, 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, S_(eval_color), "Cor por nome (vermelho, azul, dourado...) ou #rrggbb" },
{ "3D.Show", "mostre o objeto %1", "jogador", 1, {T}, O_NONE, S_(eval_show), "Volta a desenhar o objeto" },
{ "3D.Hide", "esconda o objeto %1", "jogador", 1, {T}, O_NONE, S_(eval_hide), "Deixa de desenhar o objeto (e ele não encosta)" },
{ "3D.Delete", "apague o objeto %1", "jogador", 1, {T}, O_NONE, S_(eval_delete), "Tira o objeto da cena" },
{ "3D.X", "x do objeto %1", "jogador", 1, {T}, O_REAL, S_(eval_x), "Posição x" },
{ "3D.Y", "y do objeto %1", "jogador", 1, {T}, O_REAL, S_(eval_y), "Posição y" },
{ "3D.Z", "z do objeto %1", "jogador", 1, {T}, O_REAL, S_(eval_z), "Posição z" },
{ "3D.Exists", "existe o objeto %1?", "jogador", 1, {T}, O_BOOL, 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, 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, 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, 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, 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, S_(eval_light), "Direção de onde vem a luz do sol" },
{ "3D.Ambient", "luz ambiente %1", "0.35", 1, {R}, O_NONE, S_(eval_ambient), "Claridade das partes na sombra (0 a 1)" },
{ "3D.Sky", "cor do céu %1", "#87c7fa", 1, {T}, O_NONE, S_(eval_sky), "Cor do fundo" },
{ "3D.Image", "imagem da cena de %1 por %2", "480|360", 2, {I,I}, O_IMAGE, S_(eval_image), "Desenha a cena numa imagem (use com \"desenhe\")" },
{ "3D.Use", "use o renderizador %1", "automático", 1, {T}, O_NONE, S_(eval_use), "vulkan, opengl, software ou automático" },
{ "3D.Renderer", "renderizador da cena", "", 0, {T}, O_TEXT, S_(eval_renderer), "Quem desenhou o último quadro (e em qual placa)" },
{ "3D.Count", "número de objetos 3D", "", 0, {T}, O_INT, S_(eval_count), "Quantos objetos a cena tem" },
{ "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.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.ShaderCompile", "compile o shader %1 com %2", "ondas|", 2, {T,TB_VALUE_JSON}, O_NONE, 1, S_(eval_shader_compile),
"Compila a pilha de blocos de Shader encaixada (não executa: lê os blocos)" },
{ "3D.ShaderUse", "use o shader %1 no objeto %2", "ondas|chão", 2, {T,T}, O_NONE, -1, S_(eval_shader_use),
"O objeto passa a ser pintado pelo shader (\"nenhum\" volta ao normal)" },
{ "3D.ShaderGlsl", "GLSL do shader %1", "ondas", 1, {T}, O_TEXT, -1, S_(eval_shader_glsl),
"O código GLSL que o shader virou (para ver ou estudar)" },
};
#undef T
#undef I
@@ -690,6 +805,7 @@ static bool d3_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
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);
tb_meta_declare(sp->name, sp->fname, __FILE__, sp->doc);
if (!tb_library_add(lib, &t->base)) return false;
}
@@ -702,6 +818,8 @@ static void d3_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
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;
for (int i = 0; i < s_shd_n; i++) d3_shader_free(s_shd[i].prog);
memset(s_shd, 0, sizeof(s_shd)); s_shd_n = 0;
meshes_free();
}
+93 -1
View File
@@ -41,6 +41,10 @@ static size_t s_rows_cap;
typedef struct { GLuint vao, vbo, ebo; int icount; } GpuMesh;
static GpuMesh s_mesh[32]; /* pelo id da malha */
/* Programas dos shaders feitos com blocos, pelo id (recompila se a versao muda) */
typedef struct { GLuint prog; int version; GLint mvp, model, nrm, color, light, ambient, time; } GpuShader;
static GpuShader s_shd[65];
static void fail(const char* fmt, const char* a) { snprintf(G.err, sizeof(G.err), fmt, a); }
static const char* VS =
@@ -65,6 +69,36 @@ static const char* FS =
"out vec4 o_color;\n"
"void main() { o_color = vec4(min(v_col, vec3(1.0)), 1.0); }\n";
static const char* VS_SHADER =
"#version 330 core\n"
"layout(location = 0) in vec3 a_pos;\n"
"layout(location = 1) in vec3 a_nrm;\n"
"uniform mat4 u_mvp;\n"
"uniform mat4 u_model;\n"
"uniform mat3 u_nrm;\n"
"out vec3 v_pos;\n"
"out vec3 v_nrm;\n"
"void main() {\n"
" gl_Position = u_mvp * vec4(a_pos, 1.0);\n"
" v_pos = (u_model * vec4(a_pos, 1.0)).xyz;\n"
" v_nrm = u_nrm * a_nrm;\n"
"}\n";
static const char* FS_HEAD =
"#version 330 core\n"
"in vec3 v_pos;\n"
"in vec3 v_nrm;\n"
"uniform vec4 u_color;\n"
"uniform vec3 u_light;\n"
"uniform float u_ambient;\n"
"uniform float u_time;\n"
"out vec4 o_color;\n";
static const char* FS_MAIN =
"void main() {\n"
" vec3 N = normalize(v_nrm);\n"
" float light = u_ambient + (1.0 - u_ambient) * max(dot(N, u_light), 0.0);\n"
" o_color = vec4(tb_shade(v_pos, N, u_color.rgb, light, u_time), 1.0);\n"
"}\n";
static GLuint shader(GLenum kind, const char* src) {
GLuint s = glCreateShader(kind);
glShaderSource(s, 1, &src, NULL);
@@ -81,6 +115,45 @@ static GLuint shader(GLenum kind, const char* src) {
return s;
}
static GLuint link(GLuint vs, GLuint fs) {
if (!vs || !fs) { if (vs) glDeleteShader(vs); if (fs) glDeleteShader(fs); return 0; }
GLuint p = glCreateProgram();
glAttachShader(p, vs);
glAttachShader(p, fs);
glLinkProgram(p);
glDeleteShader(vs);
glDeleteShader(fs);
GLint ok = 0;
glGetProgramiv(p, GL_LINK_STATUS, &ok);
if (!ok) { fail("%s", "o programa de shaders não ligou"); glDeleteProgram(p); return 0; }
return p;
}
/* O programa de um shader feito com blocos (compila na 1a vez e a cada versao) */
static GpuShader* gpu_shader(const Tb3dShader* sh) {
if (sh->id <= 0 || sh->id >= 65) { fail("%s", "id de shader inválido"); return NULL; }
GpuShader* g = &s_shd[sh->id];
if (g->prog && g->version == sh->version) return g;
if (g->prog) glDeleteProgram(g->prog);
memset(g, 0, sizeof(*g));
size_t n = strlen(FS_HEAD) + strlen(sh->glsl) + strlen(FS_MAIN) + 1;
char* fs = malloc(n);
if (!fs) return NULL;
snprintf(fs, n, "%s%s%s", FS_HEAD, sh->glsl, FS_MAIN);
g->prog = link(shader(GL_VERTEX_SHADER, VS_SHADER), shader(GL_FRAGMENT_SHADER, fs));
free(fs);
if (!g->prog) return NULL;
g->version = sh->version;
g->mvp = glGetUniformLocation(g->prog, "u_mvp");
g->model = glGetUniformLocation(g->prog, "u_model");
g->nrm = glGetUniformLocation(g->prog, "u_nrm");
g->color = glGetUniformLocation(g->prog, "u_color");
g->light = glGetUniformLocation(g->prog, "u_light");
g->ambient = glGetUniformLocation(g->prog, "u_ambient");
g->time = glGetUniformLocation(g->prog, "u_time");
return g;
}
static bool gl_setup(void) {
PFNEGLGETPLATFORMDISPLAYEXTPROC get_platform =
(PFNEGLGETPLATFORMDISPLAYEXTPROC)eglGetProcAddress("eglGetPlatformDisplayEXT");
@@ -175,6 +248,22 @@ static bool draw(const Tb3dFrame* f, uint8_t* out) {
const Tb3dDraw* d = &f->draws[i];
GpuMesh* g = gpu_mesh(d->mesh);
if (!g) continue;
if (d->shader) { /* shader feito com blocos */
GpuShader* sh = gpu_shader(d->shader);
if (!sh) return false; /* a 3d desenha esse quadro em software */
glUseProgram(sh->prog);
glUniformMatrix4fv(sh->mvp, 1, GL_FALSE, d->mvp);
glUniformMatrix4fv(sh->model, 1, GL_FALSE, d->model);
glUniformMatrix3fv(sh->nrm, 1, GL_FALSE, d->normal);
glUniform4fv(sh->color, 1, d->color);
glUniform3fv(sh->light, 1, f->light_dir);
glUniform1f(sh->ambient, f->ambient);
glUniform1f(sh->time, f->time);
glBindVertexArray(g->vao);
glDrawElements(GL_TRIANGLES, g->icount, GL_UNSIGNED_INT, (void*)0);
glUseProgram(s_prog);
continue;
}
glUniformMatrix4fv(u_mvp, 1, GL_FALSE, d->mvp);
glUniformMatrix3fv(u_nrm, 1, GL_FALSE, d->normal);
glUniform4fv(u_color, 1, d->color);
@@ -204,6 +293,8 @@ static void cleanup(void) {
glDeleteBuffers(1, &s_mesh[i].ebo);
}
memset(s_mesh, 0, sizeof(s_mesh));
for (int i = 0; i < 65; i++) if (s_shd[i].prog) glDeleteProgram(s_shd[i].prog);
memset(s_shd, 0, sizeof(s_shd));
if (s_prog) glDeleteProgram(s_prog);
if (s_fbo) { glDeleteFramebuffers(1, &s_fbo); glDeleteRenderbuffers(1, &s_color); glDeleteRenderbuffers(1, &s_depth); }
s_prog = s_fbo = s_color = s_depth = 0;
@@ -266,9 +357,10 @@ static bool gl_render(const Tb3dFrame* f, uint8_t* rgba) {
static const char* gl_device(void) { return G.device[0] ? G.device : "?"; }
static const char* gl_error(void) { return G.err; }
static bool gl_shaders(void) { return true; }
static const Tb3dRenderer s_renderer = {
TB_3D_RENDERER_VERSION, "opengl", gl_available, gl_render, gl_device, gl_error };
TB_3D_RENDERER_VERSION, "opengl", gl_available, gl_render, gl_device, gl_error, gl_shaders };
static bool lib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
(void)rt;
+30
View File
@@ -0,0 +1,30 @@
# Makefile da library shader (categoria "Shader")
# Constroi build/libtinyblocks-shader.a e build/libtinyblocks-shader.so
CC := gcc
BUILD := build
CFLAGS := -std=c11 -O2 -Wall -Wextra -pedantic -fvisibility=hidden \
-D_POSIX_C_SOURCE=200809L -I../../include -Iinclude
SRCS := src/tb_shader.c
OBJS := $(BUILD)/tb_shader.o
LIB_A := $(BUILD)/libtinyblocks-shader.a
LIB_SO := $(BUILD)/libtinyblocks-shader.so
.PHONY: all static shared clean
all: static shared
static: $(LIB_A)
shared: $(LIB_SO)
$(BUILD)/%.o: src/%.c $(wildcard include/*.h) $(wildcard src/*.h)
@mkdir -p $(BUILD)
$(CC) $(CFLAGS) -fPIC -c $< -o $@
$(LIB_A): $(OBJS)
ar rcs $@ $^
$(LIB_SO): $(OBJS)
$(CC) -shared -o $@ $^ -lm
clean:
$(RM) -r $(BUILD)
@@ -0,0 +1,24 @@
/*
* TinyBlocks - tb_shader.h
* Library tinyblocks-shader: o vocabulario dos shaders da 3D (categoria
* "Shader").
*
* Os blocos daqui nao rodam: sao palavras que o "compile o shader [nome]
* com [pilha]" da tinyblocks-3d le no codigo da pilha encaixada (encaixe
* TB_SLOT_STACK) e traduz para GLSL (OpenGL, Vulkan) ou para o interpretador
* do renderizador em software. Fora de um shader eles dao erro.
*
* Num shader valem tambem os blocos comuns de conta (+ - * /, resto, seno,
* cosseno, raiz, potencia, arredonde para baixo, limite, maior/menor,
* valor absoluto, pi), as comparacoes (< = > e ou nao), o "se" / "se senao"
* e as variaveis ("mude", "adicione", o valor), que viram variaveis locais
* do shader. Uma conta entre uma cor e um numero vale para os tres canais.
*/
#ifndef TINYBLOCKS_SHADER_H
#define TINYBLOCKS_SHADER_H
#include <tinyblocks/tinyblocks.h>
TB_API const TinyBlocks_LibraryDescriptor* tb_shader_get_library(void);
#endif /* TINYBLOCKS_SHADER_H */
+14
View File
@@ -0,0 +1,14 @@
# Metadados da library shader. Lido pela UI/build sem recompilar o .so.
[library]
name = "tinyblocks-shader"
version = "1.0.0"
category = "Shader"
description = "Blocos de shader (cor do pixel, luz, tempo, ponto, misture...): a tinyblocks-3d os compila para GLSL ou para o software"
color = [15, 163, 163, 255]
dark = [10, 122, 122, 255]
[build]
sources = ["src/tb_shader.c"]
includes = ["include"]
shared = "build/libtinyblocks-shader.so"
static = "build/libtinyblocks-shader.a"
@@ -0,0 +1,61 @@
/*
* TinyBlocks - tb_shader.c
* Os blocos da categoria "Shader" (so vocabulario: quem os entende e o
* compilador da tinyblocks-3d).
*/
#include <tinyblocks/tinyblocks.h>
#include "tb_shader.h"
static void eval_outside(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
tinyblocks_set_error(rt, "o bloco \"%s\" só funciona dentro de \"compile o shader\"",
self->type && self->type->label ? self->type->label : "de shader");
}
typedef struct { const char* name; const char* label; const char* defs; int nin; bool cmd; const char* doc; } Spec;
static const Spec s_specs[] = {
{ "Shader.Pixel", "cor do pixel = %1", "", 1, true, "Muda a cor do pixel (uma cor, ou um número para cinza)" },
{ "Shader.PixelColor", "cor do pixel", "", 0, false, "A cor do pixel até aqui (começa com a cor do objeto já iluminada)" },
{ "Shader.ObjectColor", "cor do objeto", "", 0, false, "A cor dada ao objeto (\"mude a cor de\"), sem luz" },
{ "Shader.Light", "luz", "", 0, false, "Claridade do ponto (luz ambiente + sol), de 0 a 1" },
{ "Shader.Time", "tempo", "", 0, false, "Segundos desde a \"nova cena 3D\"" },
{ "Shader.X", "x do ponto", "", 0, false, "Posição x do ponto no mundo" },
{ "Shader.Y", "y do ponto", "", 0, false, "Posição y do ponto no mundo" },
{ "Shader.Z", "z do ponto", "", 0, false, "Posição z do ponto no mundo" },
{ "Shader.NX", "x da normal", "", 0, false, "Para onde a superfície aponta (x, de -1 a 1)" },
{ "Shader.NY", "y da normal", "", 0, false, "Para onde a superfície aponta (y: 1 = para cima)" },
{ "Shader.NZ", "z da normal", "", 0, false, "Para onde a superfície aponta (z)" },
{ "Shader.Rgb", "cor r %1 g %2 b %3", "1|0.5|0", 3, false, "Uma cor pelos canais, de 0 a 1" },
{ "Shader.Color", "cor %1", "azul", 1, false, "Uma cor pelo nome (azul, dourado...) ou #rrggbb" },
{ "Shader.Mix", "misture %1 com %2 por %3", "||0.5", 3, false, "Mistura duas cores (ou números): 0 = a primeira, 1 = a segunda" },
{ "Shader.Red", "vermelho de %1", "", 1, false, "O canal vermelho de uma cor" },
{ "Shader.Green", "verde de %1", "", 1, false, "O canal verde de uma cor" },
{ "Shader.Blue", "azul de %1", "", 1, false, "O canal azul de uma cor" },
{ "Shader.Gray", "brilho de %1", "", 1, false, "Quão clara é a cor (0 = preto, 1 = branco)" },
};
static bool shader_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
static const TinyBlocks_Category cat = { "Shader", {0.06f, 0.64f, 0.64f, 1.f}, {0.04f, 0.48f, 0.48f, 1.f} };
tb_library_set_category(lib, &cat);
static const TinyBlocks_SlotDesc in[] = { {"a", TB_VALUE_NONE}, {"b", TB_VALUE_NONE}, {"c", TB_VALUE_NONE} };
static const TinyBlocks_SlotDesc out[] = { {"valor", TB_VALUE_NONE} };
for (size_t i = 0; i < sizeof(s_specs) / sizeof(s_specs[0]); i++) {
const Spec* sp = &s_specs[i];
TinyBlocks_TypeBlock* t = tb_type_block_create(rt, sp->name, sp->nin ? in : NULL, (uint32_t)sp->nin,
sp->cmd ? NULL : out, sp->cmd ? 0u : 1u, eval_outside);
if (!t) return false;
tb_type_block_set_label(t, sp->label, sp->defs);
tb_meta_declare(sp->name, "eval_outside", __FILE__, sp->doc);
if (!tb_library_add(lib, &t->base)) return false;
}
return true;
}
static void shader_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) { (void)rt; (void)lib; }
TINYBLOCKS_DEFINE_LIBRARY(shader, "tinyblocks-shader", "1.0.0", shader_init, shader_deinit)
const TinyBlocks_LibraryDescriptor* tb_shader_get_library(void) {
return &_tb_lib_desc_shader;
}
+5 -3
View File
@@ -24,15 +24,17 @@ $(LIB_A): $(OBJS)
ar rcs $@ $^
$(LIB_SO): $(OBJS)
$(CC) -shared -o $@ $^ -lvulkan -lm
$(CC) -shared -o $@ $^ -lvulkan -ldl -lm
clean:
$(RM) -r $(BUILD)
# Regera os shaders embutidos (precisa do glslc; o header gerado vai no git)
shaders: src/shaders/d3.vert src/shaders/d3.frag
shaders: src/shaders/d3.vert src/shaders/d3.frag src/shaders/d3_shd.vert
@mkdir -p $(BUILD)
glslc -O src/shaders/d3.vert -o $(BUILD)/d3.vert.spv
glslc -O src/shaders/d3.frag -o $(BUILD)/d3.frag.spv
python3 -I tools/spv2h.py src/tb_vk_shaders.h s_vert_spv=$(BUILD)/d3.vert.spv s_frag_spv=$(BUILD)/d3.frag.spv
glslc -O src/shaders/d3_shd.vert -o $(BUILD)/d3_shd.vert.spv
python3 -I tools/spv2h.py src/tb_vk_shaders.h s_vert_spv=$(BUILD)/d3.vert.spv s_frag_spv=$(BUILD)/d3.frag.spv \
s_vert_shd_spv=$(BUILD)/d3_shd.vert.spv
.PHONY: shaders
@@ -0,0 +1,18 @@
#version 450
// Vertice dos objetos com shader feito com blocos: passa o ponto e a normal
// no mundo para o fragment (que chama tb_shade). Push constants (160 bytes):
// mvp; model; color.rgb = cor do objeto, color.a = luz ambiente;
// light.xyz = direcao da luz, light.w = tempo.
layout(location = 0) in vec3 a_pos;
layout(location = 1) in vec3 a_nrm;
layout(push_constant) uniform PC { mat4 mvp; mat4 model; vec4 color; vec4 light; } pc;
layout(location = 0) out vec3 v_pos;
layout(location = 1) out vec3 v_nrm;
void main() {
vec4 p = pc.mvp * vec4(a_pos, 1.0);
p.z = (p.z + p.w) * 0.5; // z do GL (-1..1) para o do Vulkan (0..1)
gl_Position = p;
v_pos = (pc.model * vec4(a_pos, 1.0)).xyz;
v_nrm = transpose(inverse(mat3(pc.model))) * a_nrm;
}
+161 -27
View File
@@ -3,6 +3,7 @@
* Renderizador Vulkan (sem janela) da tinyblocks-3d.
*/
#define _POSIX_C_SOURCE 200809L
#include <dlfcn.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@@ -18,6 +19,24 @@
typedef struct { VkBuffer buf; VkDeviceMemory mem; void* map; VkDeviceSize size; } Buf;
typedef struct { Buf vb, ib; int icount; } GpuMesh;
/* Pipeline de um shader feito com blocos, pelo id (refeito se a versao muda) */
typedef struct { VkPipeline pipe; int version; } GpuShader;
/* -- libshaderc (GLSL -> SPIR-V em execucao), carregada por dlopen --------
So as funcoes da API C usadas aqui (a API e estavel; nao precisa do
header). Sem a biblioteca, a vk so nao desenha shaders feitos com blocos. */
typedef void* (*ShcInit)(void);
typedef void (*ShcRelease)(void*);
typedef void* (*ShcCompile)(void*, const char*, size_t, int, const char*, const char*, const void*);
typedef int (*ShcStatus)(const void*);
typedef size_t (*ShcLength)(const void*);
typedef const char* (*ShcBytes)(const void*);
static struct {
void* dl; void* compiler; bool tried;
ShcInit init; ShcRelease release_compiler, release_result; ShcCompile compile;
ShcStatus status; ShcLength length; ShcBytes bytes, error;
} SC;
static struct {
bool tried, ok;
char err[256], device[160];
@@ -34,6 +53,10 @@ static struct {
VkRenderPass pass;
VkPipelineLayout layout;
VkPipeline pipe;
VkPipelineLayout shd_layout; /* 160 bytes de push constants */
VkShaderModule shd_vert;
bool shd_ok; /* da para usar shaders feitos com blocos */
GpuShader shd[65];
/* alvo (recriado quando muda o tamanho) */
int w, h;
VkImage color, depth;
@@ -130,6 +153,36 @@ static bool pick_device(void) {
return false;
}
/* Pipeline com os estados fixos da vk (vertice pos+normal, profundidade,
viewport/scissor dinamicos) e os dois modulos dados */
static VkResult build_pipe(VkShaderModule vs, VkShaderModule fs, VkPipelineLayout layout, VkPipeline* out) {
VkPipelineShaderStageCreateInfo st[2] = {
{ VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, NULL, 0, VK_SHADER_STAGE_VERTEX_BIT, vs, "main", NULL },
{ VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, NULL, 0, VK_SHADER_STAGE_FRAGMENT_BIT, fs, "main", NULL },
};
VkVertexInputBindingDescription bind = { 0, 6 * sizeof(float), VK_VERTEX_INPUT_RATE_VERTEX };
VkVertexInputAttributeDescription attr[2] = { { 0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0 },
{ 1, 0, VK_FORMAT_R32G32B32_SFLOAT, 3 * sizeof(float) } };
VkPipelineVertexInputStateCreateInfo vi = { VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, NULL, 0, 1, &bind, 2, attr };
VkPipelineInputAssemblyStateCreateInfo ia = { VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, NULL, 0,
VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, VK_FALSE };
VkPipelineViewportStateCreateInfo vp = { VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, NULL, 0, 1, NULL, 1, NULL };
VkPipelineRasterizationStateCreateInfo rs = { VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, NULL, 0,
VK_FALSE, VK_FALSE, VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, VK_FALSE, 0, 0, 0, 1.f };
VkPipelineMultisampleStateCreateInfo ms = { VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, NULL, 0,
VK_SAMPLE_COUNT_1_BIT, VK_FALSE, 0, NULL, VK_FALSE, VK_FALSE };
VkPipelineDepthStencilStateCreateInfo ds = { VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO, NULL, 0,
VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS, VK_FALSE, VK_FALSE, {0}, {0}, 0, 1 };
VkPipelineColorBlendAttachmentState cba = { VK_FALSE, 0, 0, 0, 0, 0, 0, 0xf };
VkPipelineColorBlendStateCreateInfo cb = { VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, NULL, 0,
VK_FALSE, 0, 1, &cba, {0} };
VkDynamicState dyn_s[2] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
VkPipelineDynamicStateCreateInfo dyn = { VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO, NULL, 0, 2, dyn_s };
VkGraphicsPipelineCreateInfo gp = { VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, NULL, 0, 2, st, &vi, &ia, NULL,
&vp, &rs, &ms, &ds, &cb, &dyn, layout, V.pass, 0, VK_NULL_HANDLE, -1 };
return vkCreateGraphicsPipelines(V.dev, VK_NULL_HANDLE, 1, &gp, NULL, out);
}
static bool make_pipeline(void) {
VkAttachmentDescription att[2] = {
{ 0, VK_FORMAT_R8G8B8A8_UNORM, VK_SAMPLE_COUNT_1_BIT, VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_STORE_OP_STORE,
@@ -158,34 +211,21 @@ static bool make_pipeline(void) {
CK(vkCreateShaderModule(V.dev, &sm, NULL, &vs), "shader de vértice");
sm.codeSize = sizeof(s_frag_spv); sm.pCode = s_frag_spv;
CK(vkCreateShaderModule(V.dev, &sm, NULL, &fs), "shader de fragmento");
VkPipelineShaderStageCreateInfo st[2] = {
{ VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, NULL, 0, VK_SHADER_STAGE_VERTEX_BIT, vs, "main", NULL },
{ VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO, NULL, 0, VK_SHADER_STAGE_FRAGMENT_BIT, fs, "main", NULL },
};
VkVertexInputBindingDescription bind = { 0, 6 * sizeof(float), VK_VERTEX_INPUT_RATE_VERTEX };
VkVertexInputAttributeDescription attr[2] = { { 0, 0, VK_FORMAT_R32G32B32_SFLOAT, 0 },
{ 1, 0, VK_FORMAT_R32G32B32_SFLOAT, 3 * sizeof(float) } };
VkPipelineVertexInputStateCreateInfo vi = { VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO, NULL, 0, 1, &bind, 2, attr };
VkPipelineInputAssemblyStateCreateInfo ia = { VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO, NULL, 0,
VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, VK_FALSE };
VkPipelineViewportStateCreateInfo vp = { VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO, NULL, 0, 1, NULL, 1, NULL };
VkPipelineRasterizationStateCreateInfo rs = { VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO, NULL, 0,
VK_FALSE, VK_FALSE, VK_POLYGON_MODE_FILL, VK_CULL_MODE_NONE, VK_FRONT_FACE_COUNTER_CLOCKWISE, VK_FALSE, 0, 0, 0, 1.f };
VkPipelineMultisampleStateCreateInfo ms = { VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO, NULL, 0,
VK_SAMPLE_COUNT_1_BIT, VK_FALSE, 0, NULL, VK_FALSE, VK_FALSE };
VkPipelineDepthStencilStateCreateInfo ds = { VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO, NULL, 0,
VK_TRUE, VK_TRUE, VK_COMPARE_OP_LESS, VK_FALSE, VK_FALSE, {0}, {0}, 0, 1 };
VkPipelineColorBlendAttachmentState cba = { VK_FALSE, 0, 0, 0, 0, 0, 0, 0xf };
VkPipelineColorBlendStateCreateInfo cb = { VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO, NULL, 0,
VK_FALSE, 0, 1, &cba, {0} };
VkDynamicState dyn_s[2] = { VK_DYNAMIC_STATE_VIEWPORT, VK_DYNAMIC_STATE_SCISSOR };
VkPipelineDynamicStateCreateInfo dyn = { VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO, NULL, 0, 2, dyn_s };
VkGraphicsPipelineCreateInfo gp = { VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO, NULL, 0, 2, st, &vi, &ia, NULL,
&vp, &rs, &ms, &ds, &cb, &dyn, V.layout, V.pass, 0, VK_NULL_HANDLE, -1 };
VkResult r = vkCreateGraphicsPipelines(V.dev, VK_NULL_HANDLE, 1, &gp, NULL, &V.pipe);
VkResult r = build_pipe(vs, fs, V.layout, &V.pipe);
vkDestroyShaderModule(V.dev, vs, NULL);
vkDestroyShaderModule(V.dev, fs, NULL);
CK(r, "vkCreateGraphicsPipelines");
/* shaders feitos com blocos: o vertice e fixo; o fragment vem do bloco */
VkPhysicalDeviceProperties props;
vkGetPhysicalDeviceProperties(V.phys, &props);
if (props.limits.maxPushConstantsSize >= 160) {
VkPushConstantRange r2 = { VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT, 0, 160 };
VkPipelineLayoutCreateInfo pl2 = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, NULL, 0, 0, NULL, 1, &r2 };
VkShaderModuleCreateInfo sv = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, NULL, 0, sizeof(s_vert_shd_spv), s_vert_shd_spv };
V.shd_ok = vkCreatePipelineLayout(V.dev, &pl2, NULL, &V.shd_layout) == VK_SUCCESS &&
vkCreateShaderModule(V.dev, &sv, NULL, &V.shd_vert) == VK_SUCCESS;
}
return true;
}
@@ -280,10 +320,81 @@ static GpuMesh* gpu_mesh(const Tb3dMesh* m) {
return g;
}
static bool shaderc_load(void) {
if (SC.tried) return SC.compiler != NULL;
SC.tried = true;
const char* names[] = { "libshaderc_shared.so.1", "libshaderc.so.1", "libshaderc_shared.so", "libshaderc.so" };
for (int i = 0; i < 4 && !SC.dl; i++) SC.dl = dlopen(names[i], RTLD_NOW | RTLD_LOCAL);
if (!SC.dl) { snprintf(V.err, sizeof(V.err), "sem a libshaderc: shaders feitos com blocos não rodam no Vulkan"); return false; }
#define SYM(field, name) do { void* p_ = dlsym(SC.dl, name); memcpy(&SC.field, &p_, sizeof(p_)); } while (0)
SYM(init, "shaderc_compiler_initialize");
SYM(release_compiler, "shaderc_compiler_release");
SYM(compile, "shaderc_compile_into_spv");
SYM(status, "shaderc_result_get_compilation_status");
SYM(length, "shaderc_result_get_length");
SYM(bytes, "shaderc_result_get_bytes");
SYM(error, "shaderc_result_get_error_message");
SYM(release_result, "shaderc_result_release");
#undef SYM
if (SC.init && SC.compile && SC.status && SC.length && SC.bytes && SC.error && SC.release_result)
SC.compiler = SC.init();
if (!SC.compiler) snprintf(V.err, sizeof(V.err), "a libshaderc não iniciou");
return SC.compiler != NULL;
}
static const char* FS_HEAD =
"#version 450\n"
"layout(location = 0) in vec3 v_pos;\n"
"layout(location = 1) in vec3 v_nrm;\n"
"layout(push_constant) uniform PC { mat4 mvp; mat4 model; vec4 color; vec4 light; } pc;\n"
"layout(location = 0) out vec4 o_color;\n";
static const char* FS_MAIN =
"void main() {\n"
" vec3 N = normalize(v_nrm);\n"
" float light = pc.color.a + (1.0 - pc.color.a) * max(dot(N, pc.light.xyz), 0.0);\n"
" o_color = vec4(tb_shade(v_pos, N, pc.color.rgb, light, pc.light.w), 1.0);\n"
"}\n";
/* O pipeline de um shader feito com blocos (compila na 1a vez e a cada versao) */
static GpuShader* gpu_shader(const Tb3dShader* sh) {
if (sh->id <= 0 || sh->id >= 65) { snprintf(V.err, sizeof(V.err), "id de shader inválido"); return NULL; }
GpuShader* g = &V.shd[sh->id];
if (g->pipe && g->version == sh->version) return g;
if (!shaderc_load()) return NULL;
size_t n = strlen(FS_HEAD) + strlen(sh->glsl) + strlen(FS_MAIN) + 1;
char* src = malloc(n);
if (!src) return NULL;
snprintf(src, n, "%s%s%s", FS_HEAD, sh->glsl, FS_MAIN);
void* res = SC.compile(SC.compiler, src, strlen(src), 1 /* fragment */, "shader.frag", "main", NULL);
free(src);
if (!res || SC.status(res) != 0) {
snprintf(V.err, sizeof(V.err), "shaderc: %.200s", res ? SC.error(res) : "falhou");
if (res) SC.release_result(res);
return NULL;
}
VkShaderModuleCreateInfo sm = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, NULL, 0, SC.length(res),
(const uint32_t*)(const void*)SC.bytes(res) };
VkShaderModule fs;
VkResult r = vkCreateShaderModule(V.dev, &sm, NULL, &fs);
SC.release_result(res);
if (r != VK_SUCCESS) { snprintf(V.err, sizeof(V.err), "módulo do shader recusado (%d)", (int)r); return NULL; }
vkDeviceWaitIdle(V.dev);
if (g->pipe) vkDestroyPipeline(V.dev, g->pipe, NULL);
g->pipe = VK_NULL_HANDLE;
r = build_pipe(V.shd_vert, fs, V.shd_layout, &g->pipe);
vkDestroyShaderModule(V.dev, fs, NULL);
if (r != VK_SUCCESS) { snprintf(V.err, sizeof(V.err), "pipeline do shader recusado (%d)", (int)r); return NULL; }
g->version = sh->version;
return g;
}
static bool vk_draw(const Tb3dFrame* f, uint8_t* out) {
if (!target(f->width, f->height)) return false;
/* as malhas antes de gravar os comandos */
for (int i = 0; i < f->draw_count; i++) if (!gpu_mesh(f->draws[i].mesh)) return false;
for (int i = 0; i < f->draw_count; i++) {
if (!gpu_mesh(f->draws[i].mesh)) return false;
if (f->draws[i].shader && !gpu_shader(f->draws[i].shader)) return false; /* a 3d usa outro */
}
CK(vkResetCommandBuffer(V.cmd, 0), "vkResetCommandBuffer");
VkCommandBufferBeginInfo bi = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, NULL, VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, NULL };
CK(vkBeginCommandBuffer(V.cmd, &bi), "vkBeginCommandBuffer");
@@ -302,6 +413,22 @@ static bool vk_draw(const Tb3dFrame* f, uint8_t* out) {
for (int i = 0; i < f->draw_count; i++) {
const Tb3dDraw* d = &f->draws[i];
GpuMesh* g = gpu_mesh(d->mesh);
if (d->shader) { /* shader feito com blocos */
float pc[40];
memcpy(pc, d->mvp, sizeof(d->mvp));
memcpy(pc + 16, d->model, sizeof(d->model));
pc[32] = d->color[0]; pc[33] = d->color[1]; pc[34] = d->color[2]; pc[35] = f->ambient;
pc[36] = f->light_dir[0]; pc[37] = f->light_dir[1]; pc[38] = f->light_dir[2]; pc[39] = f->time;
vkCmdBindPipeline(V.cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, V.shd[d->shader->id].pipe);
vkCmdPushConstants(V.cmd, V.shd_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT,
0, sizeof(pc), pc);
VkDeviceSize off = 0;
vkCmdBindVertexBuffers(V.cmd, 0, 1, &g->vb.buf, &off);
vkCmdBindIndexBuffer(V.cmd, g->ib.buf, 0, VK_INDEX_TYPE_UINT32);
vkCmdDrawIndexed(V.cmd, (uint32_t)g->icount, 1, 0, 0, 0);
vkCmdBindPipeline(V.cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, V.pipe);
continue;
}
float pc[32];
memcpy(pc, d->mvp, sizeof(d->mvp));
for (int c = 0; c < 3; c++) {
@@ -339,6 +466,9 @@ static void vk_cleanup(void) {
vkDeviceWaitIdle(V.dev);
for (int i = 0; i < 32; i++) { buf_free(&V.mesh[i].vb); buf_free(&V.mesh[i].ib); }
target_free();
for (int i = 0; i < 65; i++) if (V.shd[i].pipe) vkDestroyPipeline(V.dev, V.shd[i].pipe, NULL);
if (V.shd_vert) vkDestroyShaderModule(V.dev, V.shd_vert, NULL);
if (V.shd_layout) vkDestroyPipelineLayout(V.dev, V.shd_layout, NULL);
if (V.pipe) vkDestroyPipeline(V.dev, V.pipe, NULL);
if (V.layout) vkDestroyPipelineLayout(V.dev, V.layout, NULL);
if (V.pass) vkDestroyRenderPass(V.dev, V.pass, NULL);
@@ -369,9 +499,10 @@ static bool vk_available(void) {
static bool vk_render(const Tb3dFrame* f, uint8_t* rgba) { return vk_available() && vk_draw(f, rgba); }
static const char* vk_device(void) { return V.device[0] ? V.device : "?"; }
static const char* vk_error(void) { return V.err; }
static bool vk_shaders(void) { return V.ok && V.shd_ok && shaderc_load(); }
static const Tb3dRenderer s_renderer = {
TB_3D_RENDERER_VERSION, "vulkan", vk_available, vk_render, vk_device, vk_error };
TB_3D_RENDERER_VERSION, "vulkan", vk_available, vk_render, vk_device, vk_error, vk_shaders };
static bool lib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
(void)rt;
@@ -383,6 +514,9 @@ static void lib_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
(void)rt;
lib->lib_userdata = NULL;
vk_cleanup();
if (SC.compiler && SC.release_compiler) SC.release_compiler(SC.compiler);
if (SC.dl) dlclose(SC.dl);
memset(&SC, 0, sizeof(SC));
}
TINYBLOCKS_DEFINE_LIBRARY(vk, "tinyblocks-vk", "1.0.0", lib_init, lib_deinit)
@@ -91,4 +91,57 @@ static const uint32_t s_frag_spv[121] = {
0x00010038,
};
static const uint32_t s_vert_shd_spv[397] = {
0x07230203, 0x00010000, 0x000d000b, 0x00000051, 0x00000000, 0x00020011, 0x00000001, 0x0006000b,
0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001,
0x000a000f, 0x00000000, 0x00000004, 0x6e69616d, 0x00000000, 0x00000015, 0x0000002d, 0x00000032,
0x0000003d, 0x0000004a, 0x00040048, 0x0000000b, 0x00000000, 0x00000005, 0x00050048, 0x0000000b,
0x00000000, 0x00000023, 0x00000000, 0x00050048, 0x0000000b, 0x00000000, 0x00000007, 0x00000010,
0x00040048, 0x0000000b, 0x00000001, 0x00000005, 0x00050048, 0x0000000b, 0x00000001, 0x00000023,
0x00000040, 0x00050048, 0x0000000b, 0x00000001, 0x00000007, 0x00000010, 0x00050048, 0x0000000b,
0x00000002, 0x00000023, 0x00000080, 0x00050048, 0x0000000b, 0x00000003, 0x00000023, 0x00000090,
0x00030047, 0x0000000b, 0x00000002, 0x00040047, 0x00000015, 0x0000001e, 0x00000000, 0x00050048,
0x0000002b, 0x00000000, 0x0000000b, 0x00000000, 0x00050048, 0x0000002b, 0x00000001, 0x0000000b,
0x00000001, 0x00050048, 0x0000002b, 0x00000002, 0x0000000b, 0x00000003, 0x00050048, 0x0000002b,
0x00000003, 0x0000000b, 0x00000004, 0x00030047, 0x0000002b, 0x00000002, 0x00040047, 0x00000032,
0x0000001e, 0x00000000, 0x00040047, 0x0000003d, 0x0000001e, 0x00000001, 0x00040047, 0x0000004a,
0x0000001e, 0x00000001, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, 0x00030016,
0x00000006, 0x00000020, 0x00040017, 0x00000007, 0x00000006, 0x00000004, 0x00040018, 0x0000000a,
0x00000007, 0x00000004, 0x0006001e, 0x0000000b, 0x0000000a, 0x0000000a, 0x00000007, 0x00000007,
0x00040020, 0x0000000c, 0x00000009, 0x0000000b, 0x0004003b, 0x0000000c, 0x0000000d, 0x00000009,
0x00040015, 0x0000000e, 0x00000020, 0x00000001, 0x0004002b, 0x0000000e, 0x0000000f, 0x00000000,
0x00040020, 0x00000010, 0x00000009, 0x0000000a, 0x00040017, 0x00000013, 0x00000006, 0x00000003,
0x00040020, 0x00000014, 0x00000001, 0x00000013, 0x0004003b, 0x00000014, 0x00000015, 0x00000001,
0x0004002b, 0x00000006, 0x00000017, 0x3f800000, 0x00040015, 0x0000001d, 0x00000020, 0x00000000,
0x0004002b, 0x00000006, 0x00000026, 0x3f000000, 0x0004002b, 0x0000001d, 0x00000029, 0x00000001,
0x0004001c, 0x0000002a, 0x00000006, 0x00000029, 0x0006001e, 0x0000002b, 0x00000007, 0x00000006,
0x0000002a, 0x0000002a, 0x00040020, 0x0000002c, 0x00000003, 0x0000002b, 0x0004003b, 0x0000002c,
0x0000002d, 0x00000003, 0x00040020, 0x0000002f, 0x00000003, 0x00000007, 0x00040020, 0x00000031,
0x00000003, 0x00000013, 0x0004003b, 0x00000031, 0x00000032, 0x00000003, 0x0004002b, 0x0000000e,
0x00000033, 0x00000001, 0x0004003b, 0x00000031, 0x0000003d, 0x00000003, 0x00040018, 0x00000040,
0x00000013, 0x00000003, 0x0004003b, 0x00000014, 0x0000004a, 0x00000001, 0x00050036, 0x00000002,
0x00000004, 0x00000000, 0x00000003, 0x000200f8, 0x00000005, 0x00050041, 0x00000010, 0x00000011,
0x0000000d, 0x0000000f, 0x0004003d, 0x0000000a, 0x00000012, 0x00000011, 0x0004003d, 0x00000013,
0x00000016, 0x00000015, 0x00050051, 0x00000006, 0x00000018, 0x00000016, 0x00000000, 0x00050051,
0x00000006, 0x00000019, 0x00000016, 0x00000001, 0x00050051, 0x00000006, 0x0000001a, 0x00000016,
0x00000002, 0x00070050, 0x00000007, 0x0000001b, 0x00000018, 0x00000019, 0x0000001a, 0x00000017,
0x00050091, 0x00000007, 0x0000001c, 0x00000012, 0x0000001b, 0x00050051, 0x00000006, 0x00000021,
0x0000001c, 0x00000002, 0x00050051, 0x00000006, 0x00000024, 0x0000001c, 0x00000003, 0x00050081,
0x00000006, 0x00000025, 0x00000021, 0x00000024, 0x00050085, 0x00000006, 0x00000027, 0x00000025,
0x00000026, 0x00060052, 0x00000007, 0x00000050, 0x00000027, 0x0000001c, 0x00000002, 0x00050041,
0x0000002f, 0x00000030, 0x0000002d, 0x0000000f, 0x0003003e, 0x00000030, 0x00000050, 0x00050041,
0x00000010, 0x00000034, 0x0000000d, 0x00000033, 0x0004003d, 0x0000000a, 0x00000035, 0x00000034,
0x00050091, 0x00000007, 0x0000003b, 0x00000035, 0x0000001b, 0x0008004f, 0x00000013, 0x0000003c,
0x0000003b, 0x0000003b, 0x00000000, 0x00000001, 0x00000002, 0x0003003e, 0x00000032, 0x0000003c,
0x00050051, 0x00000007, 0x00000041, 0x00000035, 0x00000000, 0x0008004f, 0x00000013, 0x00000042,
0x00000041, 0x00000041, 0x00000000, 0x00000001, 0x00000002, 0x00050051, 0x00000007, 0x00000043,
0x00000035, 0x00000001, 0x0008004f, 0x00000013, 0x00000044, 0x00000043, 0x00000043, 0x00000000,
0x00000001, 0x00000002, 0x00050051, 0x00000007, 0x00000045, 0x00000035, 0x00000002, 0x0008004f,
0x00000013, 0x00000046, 0x00000045, 0x00000045, 0x00000000, 0x00000001, 0x00000002, 0x00060050,
0x00000040, 0x00000047, 0x00000042, 0x00000044, 0x00000046, 0x0006000c, 0x00000040, 0x00000048,
0x00000001, 0x00000022, 0x00000047, 0x00040054, 0x00000040, 0x00000049, 0x00000048, 0x0004003d,
0x00000013, 0x0000004b, 0x0000004a, 0x00050091, 0x00000013, 0x0000004c, 0x00000049, 0x0000004b,
0x0003003e, 0x0000003d, 0x0000004c, 0x000100fd, 0x00010038,
};
#endif