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>
This commit is contained in:
1 parent
1e171411f7
commit
d5c16a5237
14 files changed
+667
-85
No files matched your search
@@ -29,7 +29,7 @@
|
||||
#include <tinyblocks/tinyblocks.h>
|
||||
|
||||
#define TB_3D_LIB "tinyblocks-3d"
|
||||
#define TB_3D_RENDERER_VERSION 4
|
||||
#define TB_3D_RENDERER_VERSION 5
|
||||
|
||||
/* Malha: triangulos com posicao, normal e uv (8 floats por vertice). Alem
|
||||
das malhas fixas (cubo, esfera, plano e cilindro de tamanho 1), o usuario
|
||||
@@ -47,18 +47,24 @@ typedef struct Tb3dMesh {
|
||||
|
||||
/* Shader compilado: o valor que o repórter "compile o shader [pilha]"
|
||||
devolve (um bloco-handle; guarde numa variável) e que "use o shader" põe
|
||||
num objeto. A 3d compila os blocos para o corpo de uma funcao GLSL (330
|
||||
e 450) e pede a cada renderizador disponivel o BINARIO dele
|
||||
(Tb3dRenderer.compile); o formato do binario so o renderizador conhece.
|
||||
num objeto. A pilha é de VÉRTICE ou de FRAGMENTO, e o "compile o shader"
|
||||
descobre sozinho pelo que a pilha usa:
|
||||
|
||||
vec3 tb_shade(vec3 P, vec3 N, vec3 base, float light, float time)
|
||||
vec3 tb_shade(vec3 P, vec3 N, vec3 L, vec2 UV, vec3 base, float light, float time)
|
||||
vec3 tb_vert (vec3 P, vec3 N, vec3 L, vec2 UV, 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).
|
||||
No fragmento (estágio 0) P/N são o ponto e a normal no mundo e o shader
|
||||
devolve a COR do pixel (0..1); no vértice (estágio 1) P/N são a posição e
|
||||
a normal no espaço do objeto e o shader devolve a POSIÇÃO do vértice
|
||||
(ainda no espaço do objeto: a câmera e o mova/gire aplicam por cima).
|
||||
A 3d compila os blocos para o corpo da função GLSL (330 e 450) e pede a
|
||||
cada renderizador disponível o BINÁRIO dele (Tb3dRenderer.compile).
|
||||
light = ambiente + (1 - ambiente) * max(N . luz, 0); time = segundos.
|
||||
|
||||
id e unico por compilacao (o renderizador guarda o programa da placa por
|
||||
ele) e vale enquanto alguem usar o shader. */
|
||||
#define TB_3D_STAGE_FRAGMENT 0
|
||||
#define TB_3D_STAGE_VERTEX 1
|
||||
#define TB_3D_MAX_BINARIES 4
|
||||
typedef struct Tb3dBinary {
|
||||
char renderer[16]; /* Tb3dRenderer.name de quem compilou */
|
||||
@@ -69,6 +75,7 @@ typedef struct Tb3dBinary {
|
||||
typedef struct Tb3dShader {
|
||||
int id;
|
||||
int version; /* sempre 1 (cada compilacao tem outro id) */
|
||||
int stage; /* TB_3D_STAGE_FRAGMENT ou _VERTEX */
|
||||
const char* glsl;
|
||||
Tb3dBinary bin[TB_3D_MAX_BINARIES];
|
||||
int bin_n;
|
||||
@@ -112,7 +119,7 @@ typedef struct Tb3dRenderer {
|
||||
/* Binario do shader para esta placa, a partir do GLSL (tb_shade). data
|
||||
com malloc (a 3d libera com free). NULL = o renderizador nao guarda
|
||||
binario (compila na hora de desenhar). */
|
||||
bool (*compile)(const char* glsl, void** data, size_t* size, char* err, size_t cap);
|
||||
bool (*compile)(const char* glsl, int stage, void** data, size_t* size, char* err, size_t cap);
|
||||
} Tb3dRenderer;
|
||||
|
||||
TB_API const TinyBlocks_LibraryDescriptor* tb_3d_get_library(void);
|
||||
|
||||
@@ -12,20 +12,28 @@
|
||||
|
||||
typedef struct D3Program D3Program; /* o shader compilado (opaco) */
|
||||
|
||||
/* Estagio do shader: o "compile o shader" descobre sozinho (tem
|
||||
"mude a posicao do vertice" = vertice; "cor do pixel" = fragmento). */
|
||||
enum { D3_STAGE_NONE, D3_STAGE_FRAGMENT, D3_STAGE_VERTEX };
|
||||
|
||||
/* 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 */
|
||||
const char* d3_shader_glsl(const D3Program* p); /* tb_shade ou tb_vert */
|
||||
int d3_shader_stage(const D3Program* p); /* D3_STAGE_* */
|
||||
|
||||
/* Entradas de um pixel e a cor que sai (o interpretador do software) */
|
||||
/* Entradas de um pixel/vertice e a cor que sai (interpretador do software).
|
||||
No fragmento P/N sao o ponto e a normal no mundo; no vertice, P e a
|
||||
posicao local (a que o shader de vertice devolve) e N a normal do objeto. */
|
||||
typedef struct {
|
||||
float P[3], N[3], L[3]; /* ponto no mundo, normal, vertice local */
|
||||
float P[3], N[3], L[3]; /* ponto/vertice, normal, vertice local */
|
||||
float uv[2]; /* coordenada de textura */
|
||||
float base[3];
|
||||
float light, time;
|
||||
} D3Pixel;
|
||||
void d3_shader_run(const D3Program* p, const D3Pixel* in, float out[3]);
|
||||
void d3_shader_run_vertex(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]);
|
||||
|
||||
@@ -5,8 +5,10 @@
|
||||
* 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 GLSL da funcao tb_shade (fragmento) ou tb_vert (vertice), e
|
||||
* - o interpretador usado pelo renderizador em software.
|
||||
* O estagio sai sozinho: a pilha que usa "cor do pixel" e de fragmento; a
|
||||
* que usa "mude a posicao do vertice" e de vertice.
|
||||
*
|
||||
* 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
|
||||
@@ -33,7 +35,7 @@ enum {
|
||||
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,
|
||||
S_PIXEL, S_VPOS, S_SET, S_IF,
|
||||
};
|
||||
|
||||
typedef struct {
|
||||
@@ -49,6 +51,7 @@ struct D3Program {
|
||||
Node* n;
|
||||
int nn, cap;
|
||||
int first; /* primeiro comando */
|
||||
int stage; /* D3_STAGE_* */
|
||||
char local[MAX_LOCALS][32];
|
||||
int ltype[MAX_LOCALS];
|
||||
int nl;
|
||||
@@ -313,6 +316,8 @@ static int set_var(C* c, const TinyBlocks_JsonValue* j, bool change) {
|
||||
static int stmt(C* c, const TinyBlocks_JsonValue* j) {
|
||||
const char* t = jtype(j);
|
||||
if (!strcmp(t, "Shader.Pixel")) {
|
||||
if (c->p->stage == D3_STAGE_VERTEX) { fail(c, "\"cor do pixel\" não vale num shader de vértice"); return -1; }
|
||||
c->p->stage = D3_STAGE_FRAGMENT;
|
||||
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; }
|
||||
@@ -320,6 +325,22 @@ static int stmt(C* c, const TinyBlocks_JsonValue* j) {
|
||||
if (n >= 0) c->p->n[n].a = e;
|
||||
return n;
|
||||
}
|
||||
if (!strcmp(t, "Shader.Vertex")) {
|
||||
if (c->p->stage == D3_STAGE_FRAGMENT) { fail(c, "\"mude a posição do vértice\" não vale num shader de fragmento"); return -1; }
|
||||
c->p->stage = D3_STAGE_VERTEX;
|
||||
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, "\"mude a posição do vértice\" recebe três números");
|
||||
return -1;
|
||||
}
|
||||
int e = node(c, E_RGB, TV);
|
||||
if (e < 0) return -1;
|
||||
c->p->n[e].a = a; c->p->n[e].b = b; c->p->n[e].c = d;
|
||||
int n = node(c, S_VPOS, -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")) {
|
||||
@@ -443,6 +464,7 @@ static void gs(const D3Program* p, Str* o, int i, int depth) {
|
||||
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_VPOS) { put(o, "vpos = "); 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");
|
||||
@@ -456,12 +478,17 @@ static void gs(const D3Program* p, Str* o, int i, int depth) {
|
||||
|
||||
static char* emit_glsl(const D3Program* p) {
|
||||
Str o = {0};
|
||||
put(&o, "vec3 tb_shade(vec3 P, vec3 N, vec3 L, vec2 UV, vec3 base, float light, float time) {\n");
|
||||
put(&o, " vec3 pix = base * light;\n");
|
||||
if (p->stage == D3_STAGE_VERTEX) {
|
||||
put(&o, "vec3 tb_vert(vec3 P, vec3 N, vec3 L, vec2 UV, vec3 base, float light, float time) {\n");
|
||||
put(&o, " vec3 vpos = P;\n");
|
||||
} else {
|
||||
put(&o, "vec3 tb_shade(vec3 P, vec3 N, vec3 L, vec2 UV, 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");
|
||||
put(&o, p->stage == D3_STAGE_VERTEX ? " return vpos;\n}\n" : " return clamp(pix, 0.0, 1.0);\n}\n");
|
||||
return o.s;
|
||||
}
|
||||
|
||||
@@ -473,7 +500,8 @@ D3Program* d3_shader_compile(const TinyBlocks_JsonValue* stack, char* err, size_
|
||||
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->stage == D3_STAGE_NONE)
|
||||
fail(&c, "o shader está vazio (use \"cor do pixel = ...\" ou \"mude a posição do vértice para ...\")");
|
||||
if (!c.failed) {
|
||||
p->glsl = emit_glsl(p);
|
||||
if (!p->glsl) fail(&c, "sem memória");
|
||||
@@ -490,9 +518,10 @@ void d3_shader_free(D3Program* p) {
|
||||
}
|
||||
|
||||
const char* d3_shader_glsl(const D3Program* p) { return p ? p->glsl : ""; }
|
||||
int d3_shader_stage(const D3Program* p) { return p ? p->stage : D3_STAGE_NONE; }
|
||||
|
||||
/* == Interpretador (software): cada valor e um float[3] ================ */
|
||||
typedef struct { const D3Pixel* in; float pix[3]; float loc[MAX_LOCALS][3]; } Run;
|
||||
typedef struct { const D3Pixel* in; float pix[3]; float vpos[3]; float loc[MAX_LOCALS][3]; } Run;
|
||||
|
||||
static float fmod_glsl(float a, float b) { return b == 0 ? 0 : a - b * floorf(a / b); }
|
||||
|
||||
@@ -558,6 +587,7 @@ 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_VPOS) ev(p, r, x->a, r->vpos);
|
||||
else if (x->op == S_SET) ev(p, r, x->a, r->loc[x->var]);
|
||||
else if (x->op == S_IF) {
|
||||
float c[3];
|
||||
@@ -575,3 +605,13 @@ void d3_shader_run(const D3Program* p, const D3Pixel* in, float out[3]) {
|
||||
ex(p, &r, p->first);
|
||||
for (int k = 0; k < 3; k++) out[k] = fminf(fmaxf(r.pix[k], 0.f), 1.f);
|
||||
}
|
||||
|
||||
void d3_shader_run_vertex(const D3Program* p, const D3Pixel* in, float out[3]) {
|
||||
Run r;
|
||||
r.in = in;
|
||||
memcpy(r.vpos, in->P, sizeof(r.vpos));
|
||||
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);
|
||||
memcpy(out, r.vpos, sizeof(r.vpos));
|
||||
}
|
||||
@@ -388,6 +388,7 @@ typedef struct { float x, y, z, w, r, g, b, P[3], N[3], L[3], uv[2]; } CV;
|
||||
|
||||
/* 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];
|
||||
|
||||
@@ -476,7 +477,18 @@ static void clip_and_raster(const CV in[3], int W, int H, uint8_t* 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 p[4] = { v[0], v[1], v[2], 1 }, c[4] = { 0 };
|
||||
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 };
|
||||
@@ -485,9 +497,9 @@ static void shade(const Tb3dFrame* f, const Tb3dDraw* d, const float* v, CV* o)
|
||||
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];
|
||||
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] = v[i]; /* vertice local (shader) */
|
||||
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);
|
||||
@@ -521,10 +533,12 @@ static bool sw_render(const Tb3dFrame* f, uint8_t* px) {
|
||||
if (!p) { free(cv); return false; }
|
||||
cv = p; cv_cap = m->vcount;
|
||||
}
|
||||
for (int i = 0; i < m->vcount; i++) shade(f, d, m->verts + (size_t)i * 8, &cv[i]);
|
||||
s_prog = d->shader ? ((const Shd*)d->shader)->prog : NULL; /* pub e o 1o campo */
|
||||
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;
|
||||
@@ -532,7 +546,7 @@ static bool sw_render(const Tb3dFrame* f, uint8_t* px) {
|
||||
}
|
||||
}
|
||||
free(cv);
|
||||
s_prog = NULL;
|
||||
s_prog = s_vprog = NULL;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -922,7 +936,7 @@ static void shd_binaries(TinyBlocks* rt, Shd* sh) {
|
||||
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, &b->data, &b->size, err, sizeof(err))) {
|
||||
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;
|
||||
}
|
||||
@@ -946,6 +960,7 @@ static void eval_shader(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
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;
|
||||
|
||||
@@ -27,6 +27,7 @@ static struct {
|
||||
const Tb3dFrame* job;
|
||||
uint8_t* out;
|
||||
const char* glsl; /* != NULL: compilar */
|
||||
int stage; /* estagio do shader a compilar */
|
||||
void** bin;
|
||||
size_t* bin_size;
|
||||
bool busy, ok;
|
||||
@@ -73,7 +74,7 @@ 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 =
|
||||
static const char* VS_VERT_HEAD =
|
||||
"#version 330 core\n"
|
||||
"layout(location = 0) in vec3 a_pos;\n"
|
||||
"layout(location = 1) in vec3 a_nrm;\n"
|
||||
@@ -81,17 +82,29 @@ static const char* VS_SHADER =
|
||||
"uniform mat4 u_mvp;\n"
|
||||
"uniform mat4 u_model;\n"
|
||||
"uniform mat3 u_nrm;\n"
|
||||
"uniform vec4 u_color;\n"
|
||||
"uniform vec3 u_light;\n"
|
||||
"uniform float u_ambient;\n"
|
||||
"uniform float u_time;\n"
|
||||
"out vec3 v_pos;\n"
|
||||
"out vec3 v_nrm;\n"
|
||||
"out vec3 v_local;\n"
|
||||
"out vec2 v_uv;\n"
|
||||
"out vec2 v_uv;\n";
|
||||
static const char* VS_VERT_MAIN =
|
||||
"void main() {\n"
|
||||
" gl_Position = u_mvp * vec4(a_pos, 1.0);\n"
|
||||
" v_pos = (u_model * vec4(a_pos, 1.0)).xyz;\n"
|
||||
" vec3 n = normalize(u_nrm * a_nrm);\n"
|
||||
" float light = u_ambient + (1.0 - u_ambient) * max(dot(n, u_light), 0.0);\n"
|
||||
" vec3 P = tb_vert(a_pos, a_nrm, a_pos, a_uv, u_color.rgb, light, u_time);\n"
|
||||
" gl_Position = u_mvp * vec4(P, 1.0);\n"
|
||||
" v_pos = (u_model * vec4(P, 1.0)).xyz;\n"
|
||||
" v_nrm = u_nrm * a_nrm;\n"
|
||||
" v_local = a_pos;\n"
|
||||
" v_local = P;\n"
|
||||
" v_uv = a_uv;\n"
|
||||
"}\n";
|
||||
static const char* DEFAULT_VERT =
|
||||
"vec3 tb_vert(vec3 P, vec3 N, vec3 L, vec2 UV, vec3 base, float light, float time) { return P; }\n";
|
||||
static const char* DEFAULT_FRAG =
|
||||
"vec3 tb_shade(vec3 P, vec3 N, vec3 L, vec2 UV, vec3 base, float light, float time) { return base * light; }\n";
|
||||
static const char* FS_HEAD =
|
||||
"#version 330 core\n"
|
||||
"in vec3 v_pos;\n"
|
||||
@@ -141,13 +154,21 @@ static GLuint link_hint(GLuint vs, GLuint fs, bool retrievable) {
|
||||
return p;
|
||||
}
|
||||
|
||||
/* O programa do shader feito com blocos, compilado do GLSL */
|
||||
static GLuint program_from_glsl(const char* glsl, bool retrievable) {
|
||||
size_t n = strlen(FS_HEAD) + strlen(glsl) + strlen(FS_MAIN) + 1;
|
||||
char* fs = malloc(n);
|
||||
if (!fs) return 0;
|
||||
snprintf(fs, n, "%s%s%s", FS_HEAD, glsl, FS_MAIN);
|
||||
GLuint p = link_hint(shader(GL_VERTEX_SHADER, VS_SHADER), shader(GL_FRAGMENT_SHADER, fs), retrievable);
|
||||
/* O programa do shader feito com blocos, compilado do GLSL. O estagio diz
|
||||
qual funcao o GLSL traz (tb_vert ou tb_shade); o outro estagio usa o
|
||||
padrao (posicao intacta / cor do objeto com luz). */
|
||||
static GLuint program_from_glsl(const char* glsl, int stage, bool retrievable) {
|
||||
bool vert = stage == TB_3D_STAGE_VERTEX;
|
||||
const char* vb = vert ? glsl : DEFAULT_VERT;
|
||||
const char* fb = vert ? DEFAULT_FRAG : glsl;
|
||||
size_t nv = strlen(VS_VERT_HEAD) + strlen(vb) + strlen(VS_VERT_MAIN) + 1;
|
||||
size_t nf = strlen(FS_HEAD) + strlen(fb) + strlen(FS_MAIN) + 1;
|
||||
char* vs = malloc(nv), *fs = malloc(nf);
|
||||
if (!vs || !fs) { free(vs); free(fs); return 0; }
|
||||
snprintf(vs, nv, "%s%s%s", VS_VERT_HEAD, vb, VS_VERT_MAIN);
|
||||
snprintf(fs, nf, "%s%s%s", FS_HEAD, fb, FS_MAIN);
|
||||
GLuint p = link_hint(shader(GL_VERTEX_SHADER, vs), shader(GL_FRAGMENT_SHADER, fs), retrievable);
|
||||
free(vs);
|
||||
free(fs);
|
||||
return p;
|
||||
}
|
||||
@@ -155,12 +176,12 @@ static GLuint program_from_glsl(const char* glsl, bool retrievable) {
|
||||
/* O binario do OpenGL e o programa ja ligado, como o driver o devolve
|
||||
(glGetProgramBinary): 4 bytes com o formato e os bytes do driver. So
|
||||
serve para a mesma placa e driver; se o driver o recusar, recompila. */
|
||||
static bool binary_compile(const char* glsl, void** data, size_t* size) {
|
||||
static bool binary_compile(const char* glsl, int stage, void** data, size_t* size) {
|
||||
*data = NULL; *size = 0;
|
||||
GLint nfmt = 0;
|
||||
glGetIntegerv(GL_NUM_PROGRAM_BINARY_FORMATS, &nfmt);
|
||||
if (nfmt < 1) { fail("%s", "o driver não devolve binários de programa"); return false; }
|
||||
GLuint p = program_from_glsl(glsl, true);
|
||||
GLuint p = program_from_glsl(glsl, stage, true);
|
||||
if (!p) return false;
|
||||
GLint len = 0;
|
||||
glGetProgramiv(p, GL_PROGRAM_BINARY_LENGTH, &len);
|
||||
@@ -197,7 +218,7 @@ static GpuShader* gpu_shader(const Tb3dShader* sh) {
|
||||
memset(g, 0, sizeof(*g));
|
||||
for (int i = 0; i < sh->bin_n && !g->prog; i++)
|
||||
if (!strcmp(sh->bin[i].renderer, "opengl")) g->prog = program_from_binary(sh->bin[i].data, sh->bin[i].size);
|
||||
if (!g->prog) g->prog = program_from_glsl(sh->glsl, false);
|
||||
if (!g->prog) g->prog = program_from_glsl(sh->glsl, sh->stage, false);
|
||||
if (!g->prog) return NULL;
|
||||
g->id = sh->id;
|
||||
g->mvp = glGetUniformLocation(g->prog, "u_mvp");
|
||||
@@ -384,7 +405,7 @@ static void* gl_thread(void* arg) {
|
||||
uint8_t* out = G.out;
|
||||
const char* glsl = G.glsl;
|
||||
pthread_mutex_unlock(&G.mu);
|
||||
bool r = glsl ? binary_compile(glsl, G.bin, G.bin_size) : draw(f, out);
|
||||
bool r = glsl ? binary_compile(glsl, G.stage, G.bin, G.bin_size) : draw(f, out);
|
||||
pthread_mutex_lock(&G.mu);
|
||||
G.ok = r;
|
||||
G.busy = false;
|
||||
@@ -424,10 +445,10 @@ static const char* gl_error(void) { return G.err; }
|
||||
static bool gl_shaders(void) { return true; }
|
||||
|
||||
/* Tb3dRenderer.compile: pede o binario a thread do OpenGL */
|
||||
static bool gl_compile(const char* glsl, void** data, size_t* size, char* err, size_t cap) {
|
||||
static bool gl_compile(const char* glsl, int stage, void** data, size_t* size, char* err, size_t cap) {
|
||||
if (!gl_available()) { snprintf(err, cap, "%s", G.err); return false; }
|
||||
pthread_mutex_lock(&G.mu);
|
||||
G.glsl = glsl; G.bin = data; G.bin_size = size; G.busy = true;
|
||||
G.glsl = glsl; G.stage = stage; G.bin = data; G.bin_size = size; G.busy = true;
|
||||
pthread_cond_broadcast(&G.cv);
|
||||
while (G.busy) pthread_cond_wait(&G.cv, &G.mu);
|
||||
bool ok = G.ok;
|
||||
|
||||
@@ -15,7 +15,8 @@ static void eval_outside(TinyBlocks_Block* self, TinyBlocks* rt) {
|
||||
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.Pixel", "cor do pixel = %1", "", 1, true, "Muda a cor do pixel (uma cor, ou um número para cinza). Faz o shader ser de FRAGMENTO" },
|
||||
{ "Shader.Vertex", "mude a posição do vértice para x %1 y %2 z %3", "|0|0", 3, true, "A posição do vértice no espaço do objeto (a câmera e o mova/gire aplicam por cima). Faz o shader ser de VÉRTICE" },
|
||||
{ "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" },
|
||||
|
||||
@@ -72,18 +72,49 @@ static const char* FS_MAIN =
|
||||
" o_color = vec4(tb_shade(v_pos, N, v_local, v_uv, pc.color.rgb, light, pc.light.w), 1.0);\n"
|
||||
"}\n";
|
||||
|
||||
/* Tb3dRenderer.compile: o binario do shader para o Vulkan e o SPIR-V do
|
||||
fragment inteiro (a interface com o vertice fixo esta em FS_HEAD) */
|
||||
static uint32_t* spirv_fragment(const char* glsl, size_t* words, char* err, size_t cap) {
|
||||
/* Estagio de VERTICE: o VS chama tb_vert e sai a interface que o fragmento
|
||||
espera (posicao no mundo, normal, vertice local e uv). */
|
||||
static const char* VS_VERT_HEAD =
|
||||
"#version 450\n"
|
||||
"layout(location = 0) in vec3 a_pos;\n"
|
||||
"layout(location = 1) in vec3 a_nrm;\n"
|
||||
"layout(location = 2) in vec2 a_uv;\n"
|
||||
"layout(push_constant) uniform PC { mat4 mvp; mat4 model; vec4 color; vec4 light; } pc;\n"
|
||||
"layout(location = 0) out vec3 v_pos;\n"
|
||||
"layout(location = 1) out vec3 v_nrm;\n"
|
||||
"layout(location = 2) out vec3 v_local;\n"
|
||||
"layout(location = 3) out vec2 v_uv;\n";
|
||||
static const char* VS_VERT_MAIN =
|
||||
"void main() {\n"
|
||||
" vec3 n = normalize(transpose(inverse(mat3(pc.model))) * a_nrm);\n"
|
||||
" float light = pc.color.a + (1.0 - pc.color.a) * max(dot(n, pc.light.xyz), 0.0);\n"
|
||||
" vec3 P = tb_vert(a_pos, a_nrm, a_pos, a_uv, pc.color.rgb, light, pc.light.w);\n"
|
||||
" vec4 p = pc.mvp * vec4(P, 1.0);\n"
|
||||
" p.z = (p.z + p.w) * 0.5;\n"
|
||||
" gl_Position = p;\n"
|
||||
" v_pos = (pc.model * vec4(P, 1.0)).xyz;\n"
|
||||
" v_nrm = transpose(inverse(mat3(pc.model))) * a_nrm;\n"
|
||||
" v_local = P;\n"
|
||||
" v_uv = a_uv;\n"
|
||||
"}\n";
|
||||
/* Fragmento padrao de quem so tem shader de vertice (cor do objeto com luz) */
|
||||
static const char* DEFAULT_FRAG =
|
||||
"vec3 tb_shade(vec3 P, vec3 N, vec3 L, vec2 UV, vec3 base, float light, float time) { return base * light; }\n";
|
||||
|
||||
/* Monta o fonte completo de um estagio (o corpo GLSL vem dos blocos) */
|
||||
static char* wrap(const char* head, const char* body, const char* tail, const char* fallback) {
|
||||
const char* b = body ? body : fallback;
|
||||
size_t n = strlen(head) + strlen(b) + strlen(tail) + 1;
|
||||
char* s = malloc(n);
|
||||
if (s) snprintf(s, n, "%s%s%s", head, b, tail);
|
||||
return s;
|
||||
}
|
||||
|
||||
static uint32_t* spirv_stage(const char* src, int stage, size_t* words, char* err, size_t cap) {
|
||||
*words = 0;
|
||||
if (err && cap) err[0] = 0;
|
||||
if (!shaderc_load()) { snprintf(err, cap, "sem a libshaderc: shaders feitos com blocos não rodam no Vulkan"); return NULL; }
|
||||
size_t n = strlen(FS_HEAD) + strlen(glsl) + strlen(FS_MAIN) + 1;
|
||||
char* src = malloc(n);
|
||||
if (!src) return NULL;
|
||||
snprintf(src, n, "%s%s%s", FS_HEAD, glsl, FS_MAIN);
|
||||
void* res = SC.compile(SC.compiler, src, strlen(src), 1 /* fragment */, "shader.frag", "main", NULL);
|
||||
free(src);
|
||||
void* res = SC.compile(SC.compiler, src, strlen(src), stage, stage == 0 ? "shader.vert" : "shader.frag", "main", NULL);
|
||||
if (!res || SC.status(res) != 0) {
|
||||
snprintf(err, cap, "shaderc: %.200s", res ? SC.error(res) : "falhou");
|
||||
if (res) SC.release_result(res);
|
||||
@@ -96,10 +127,27 @@ static uint32_t* spirv_fragment(const char* glsl, size_t* words, char* err, size
|
||||
return spv;
|
||||
}
|
||||
|
||||
/* Tb3dRenderer.compile: o binario do shader para o Vulkan e o SPIR-V do
|
||||
estagio inteiro (vertice: junta com o fragmento padrao ao desenhar;
|
||||
fragmento: a interface com o vertice fixo esta em FS_HEAD) */
|
||||
static uint32_t* spirv_shader(const char* glsl, int stage, size_t* words, char* err, size_t cap) {
|
||||
if (stage == TB_3D_STAGE_VERTEX) {
|
||||
char* src = wrap(VS_VERT_HEAD, glsl, VS_VERT_MAIN, NULL);
|
||||
if (!src) { snprintf(err, cap, "sem memória"); return NULL; }
|
||||
uint32_t* spv = spirv_stage(src, 0, words, err, cap);
|
||||
free(src);
|
||||
return spv;
|
||||
}
|
||||
char* src = wrap(FS_HEAD, glsl, FS_MAIN, NULL);
|
||||
if (!src) { snprintf(err, cap, "sem memória"); return NULL; }
|
||||
uint32_t* spv = spirv_stage(src, 1, words, err, cap);
|
||||
free(src);
|
||||
return spv;
|
||||
}
|
||||
|
||||
static bool vk_compile(const char* glsl, void** data, size_t* size, char* err, size_t cap) {
|
||||
static bool vk_compile(const char* glsl, int stage, void** data, size_t* size, char* err, size_t cap) {
|
||||
size_t words = 0;
|
||||
uint32_t* spv = spirv_fragment(glsl, &words, err, cap);
|
||||
uint32_t* spv = spirv_shader(glsl, stage, &words, err, cap);
|
||||
*data = spv;
|
||||
*size = words * 4;
|
||||
return spv != NULL;
|
||||
@@ -395,6 +443,7 @@ static GpuMesh* gpu_mesh(const Tb3dMesh* m) {
|
||||
static GpuShader* gpu_shader(const Tb3dShader* sh) {
|
||||
GpuShader* g = &V.shd[(unsigned)sh->id % 64u];
|
||||
if (g->pipe && g->id == sh->id) return g;
|
||||
bool vert = sh->stage == TB_3D_STAGE_VERTEX;
|
||||
/* o binario que veio no shader ("compile o shader"); sem ele, compila agora */
|
||||
const void* code = NULL;
|
||||
size_t size = 0;
|
||||
@@ -402,19 +451,41 @@ static GpuShader* gpu_shader(const Tb3dShader* sh) {
|
||||
for (int i = 0; i < sh->bin_n; i++)
|
||||
if (!strcmp(sh->bin[i].renderer, "vulkan")) { code = sh->bin[i].data; size = sh->bin[i].size; }
|
||||
if (!code) {
|
||||
if (!vk_compile(sh->glsl, &own, &size, V.err, sizeof(V.err))) return NULL;
|
||||
if (!vk_compile(sh->glsl, sh->stage, &own, &size, V.err, sizeof(V.err))) return NULL;
|
||||
code = own;
|
||||
}
|
||||
VkShaderModuleCreateInfo sm = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, NULL, 0, size, code };
|
||||
VkShaderModule fs;
|
||||
VkResult r = vkCreateShaderModule(V.dev, &sm, NULL, &fs);
|
||||
VkShaderModule mod;
|
||||
VkResult r = vkCreateShaderModule(V.dev, &sm, NULL, &mod);
|
||||
free(own);
|
||||
if (r != VK_SUCCESS) { snprintf(V.err, sizeof(V.err), "binário do shader recusado (%d)", (int)r); return NULL; }
|
||||
VkShaderModule vs, fs;
|
||||
if (vert) { /* vertice: junta com o fragmento padrao */
|
||||
vs = mod;
|
||||
void* def = NULL;
|
||||
size_t dsz = 0;
|
||||
if (!vk_compile(DEFAULT_FRAG, TB_3D_STAGE_FRAGMENT, &def, &dsz, V.err, sizeof(V.err))) {
|
||||
vkDestroyShaderModule(V.dev, vs, NULL);
|
||||
return NULL;
|
||||
}
|
||||
VkShaderModuleCreateInfo sf = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, NULL, 0, dsz, def };
|
||||
VkResult r2 = vkCreateShaderModule(V.dev, &sf, NULL, &fs);
|
||||
free(def);
|
||||
if (r2 != VK_SUCCESS) {
|
||||
vkDestroyShaderModule(V.dev, vs, NULL);
|
||||
snprintf(V.err, sizeof(V.err), "binário do fragmento padrão recusado (%d)", (int)r2);
|
||||
return NULL;
|
||||
}
|
||||
} else {
|
||||
fs = mod;
|
||||
vs = V.shd_vert;
|
||||
}
|
||||
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);
|
||||
r = build_pipe(vs, fs, V.shd_layout, &g->pipe);
|
||||
if (vert) vkDestroyShaderModule(V.dev, fs, NULL);
|
||||
vkDestroyShaderModule(V.dev, mod, NULL);
|
||||
if (r != VK_SUCCESS) { snprintf(V.err, sizeof(V.err), "pipeline do shader recusado (%d)", (int)r); return NULL; }
|
||||
g->id = sh->id;
|
||||
return g;
|
||||
|
||||
Reference in new issue
Block a user