diff --git a/Makefile b/Makefile
index 33170f4..87b4298 100644
--- a/Makefile
+++ b/Makefile
@@ -87,10 +87,10 @@ CAT_LDFLAGS := $(foreach l,$(CAT_LIBS),-ltinyblocks-$(l))
CAT_INCS := $(foreach l,$(CAT_LIBS),-I$(LIBDIR)/tinyblocks-$(l)/include)
# Libraries que o editor registra como as de categoria, mas com varios
# fontes e o Makefile proprio (o harness nao as compila junto)
-APP_LIBS := socket ssl http archive tensor ai plot 3d shader gl vk
+APP_LIBS := ppm bmp png image socket ssl http archive tensor ai plot 3d shader gl vk
APP_A := $(foreach l,$(APP_LIBS),$(LIBDIR)/tinyblocks-$(l)/build/libtinyblocks-$(l).a)
APP_INCS := $(foreach l,$(APP_LIBS),-I$(LIBDIR)/tinyblocks-$(l)/include)
-APP_LDLIBS := -lssl -lcrypto -lz -lpthread -lEGL -lOpenGL -lvulkan -ldl
+APP_LDLIBS := -lssl -lcrypto -lz -lpng -lpthread -lEGL -lOpenGL -lvulkan -ldl
ED_A := $(ED_DIR)/build/libtinyblocks-editor.a
GX_A := $(GX_DIR)/build/libtinyblocks-graphics.a
SD_A := $(SD_DIR)/build/libtinyblocks-sdl2.a
diff --git a/docs/blocos.md b/docs/blocos.md
index a5c1265..57f2d97 100644
--- a/docs/blocos.md
+++ b/docs/blocos.md
@@ -23,7 +23,7 @@ ver [referencia-api.md](referencia-api.md)).
Para regerar: [ferramentas/README.md](ferramentas/README.md).
-Total: 438 tipos em 40 libraries.
+Total: 445 tipos em 40 libraries.
## Índice
@@ -48,8 +48,8 @@ Total: 438 tipos em 40 libraries.
- [tinyblocks-tensor](#tinyblocks-tensor) (categoria "Tensores") - 51 blocos
- [tinyblocks-ai](#tinyblocks-ai) (categoria "IA") - 39 blocos
- [tinyblocks-plot](#tinyblocks-plot) (categoria "Gráficos") - 19 blocos
-- [tinyblocks-3d](#tinyblocks-3d) (categoria "3D") - 39 blocos
-- [tinyblocks-shader](#tinyblocks-shader) (categoria "Shader") - 24 blocos
+- [tinyblocks-3d](#tinyblocks-3d) (categoria "3D") - 45 blocos
+- [tinyblocks-shader](#tinyblocks-shader) (categoria "Shader") - 25 blocos
- [tinyblocks-toml](#tinyblocks-toml) (categoria "TOML") - 1 bloco
- [tinyblocks-json](#tinyblocks-json) (categoria "JSON") - 2 blocos
- [tinyblocks-xml](#tinyblocks-xml) (categoria "XML") - 2 blocos
@@ -534,6 +534,12 @@ Categoria na paleta: **3D**.
| `3D.MeshUV` | na malha (a) adicione a texcoord u (b) v (c)
padrões: `minha malha\|0\|0` | comando | `a` (texto), `b` (real), `c` (real) | - | Empilha a coordenada de textura (0 a 1) de um vértice |
| `3D.MeshTri` | na malha (a) adicione o triângulo (b) (c) (d)
padrões: `minha malha\|1\|2\|3` | comando | `a` (texto), `b` (inteiro), `c` (inteiro), `d` (inteiro) | - | Um triângulo pelos números dos vértices (1 = o primeiro) |
| `3D.MeshFinish` | finalize a malha (a)
padrões: `minha malha` | comando | `a` (texto) | - | Monta a malha (com as normais que faltam) e a deixa pronta para desenhar |
+| `3D.Texture` | crie a textura (a) da imagem (b)
padrões: `telha\|` | comando | `a` (texto), `b` (imagem) | - | Guarda uma textura com esse nome a partir de uma imagem |
+| `3D.Material` | crie o material (a)
padrões: `meu material` | comando | `a` (texto) | - | Começa um material (cor + texturas) |
+| `3D.MaterialAlbedo` | no material (a) use a textura (b) como albedo
padrões: `meu material\|telha` | comando | `a` (texto), `b` (texto) | - | A textura que dá a cor do material |
+| `3D.MaterialNormal` | no material (a) use a textura (b) como normal
padrões: `meu material\|relevo` | comando | `a` (texto), `b` (texto) | - | A textura de relevo (normal map) do material (usada depois) |
+| `3D.MaterialColor` | no material (a) use a cor (b)
padrões: `meu material\|branco` | comando | `a` (texto), `b` (texto) | - | A cor que multiplica a textura (padrão branco) |
+| `3D.MaterialUse` | use o material (a) no objeto (b)
padrões: `meu material\|jogador` | comando | `a` (texto), `b` (texto) | - | O objeto passa a usar o material (textura e cor) |
| `3D.MoveTo` | mova (a) para x (b) y (c) z (d)
padrões: `jogador\|0\|0.5\|0` | comando | `a` (texto), `b` (real), `c` (real), `d` (real) | - | Põe o objeto nessa posição |
| `3D.MoveBy` | mova (a) por x (b) y (c) z (d)
padrões: `jogador\|0\|0\|0.1` | comando | `a` (texto), `b` (real), `c` (real), `d` (real) | - | Soma à posição do objeto |
| `3D.RotateTo` | gire (a) para x (b) y (c) z (d) graus
padrões: `jogador\|0\|45\|0` | comando | `a` (texto), `b` (real), `c` (real), `d` (real) | - | Rotação nos eixos x, y e z (em graus) |
@@ -585,6 +591,7 @@ Categoria na paleta: **Shader**.
| `Shader.VZ` | z do vértice | repórter | - | `valor` (qualquer) | Posição z do vértice antes de mover o objeto |
| `Shader.U` | u do uv | repórter | - | `valor` (qualquer) | Coordenada de textura u do ponto (0 a 1) |
| `Shader.V` | v do uv | repórter | - | `valor` (qualquer) | Coordenada de textura v do ponto (0 a 1) |
+| `Shader.Texture` | textura do pixel | repórter | - | `valor` (qualquer) | A cor da textura de albedo do material neste ponto (branco se o objeto não tem textura) |
| `Shader.Rgb` | cor r (a) g (b) b (c)
padrões: `1\|0.5\|0` | repórter | `a` (qualquer), `b` (qualquer), `c` (qualquer) | `valor` (qualquer) | Uma cor pelos canais, de 0 a 1 |
| `Shader.Color` | cor (a)
padrões: `azul` | repórter | `a` (qualquer) | `valor` (qualquer) | Uma cor pelo nome (azul, dourado...) ou #rrggbb |
| `Shader.Mix` | misture (a) com (b) por (c)
padrões: `\|\|0.5` | repórter | `a` (qualquer), `b` (qualquer), `c` (qualquer) | `valor` (qualquer) | Mistura duas cores (ou números): 0 = a primeira, 1 = a segunda |
diff --git a/docs/libraries.md b/docs/libraries.md
index 2c2df29..1392c41 100644
--- a/docs/libraries.md
+++ b/docs/libraries.md
@@ -269,8 +269,8 @@ vocabulário (blocos que, fora de um shader, dão erro), e o compilador da 3d
"compile o shader [pilha]" (repórter da 3d; a pilha vem como código JSON)
-> d3_shader_compile: nós com tipo (número, cor, condição) e o estágio
("cor do pixel" = fragmento; "mude a posição do vértice" = vértice)
- |-> GLSL "vec3 tb_shade(P, N, L, UV, base, light, time)" (fragmento)
- | ou "vec3 tb_vert(P, N, L, UV, base, light, time)" (vértice)
+ |-> GLSL "vec3 tb_shade(P, N, L, UV, base, tex, light, time)" (fragmento)
+ | ou "vec3 tb_vert(P, N, L, UV, base, tex, light, time)" (vértice)
| -> Tb3dRenderer.compile de cada backend disponível (com o estágio):
| vk: monta o shader 450 e gera SPIR-V (libshaderc, dlopen);
| no vértice junta com um fragmento padrão ao desenhar
@@ -289,6 +289,18 @@ libshaderc ou com menos de 160 bytes de push constants) fica de fora do
quadro que tem objeto com shader. O `test-3d` compara o xadrez e o degradê
dos três renderizadores.
+### Texturas e materiais
+
+Uma textura nasce de um `TinyBlocks_Image` (`crie a textura [nome] da
+imagem [...]`): a 3d converte para RGBA8 e guarda num cache por nome. Um
+material junta um albedo, um normal map (guardado, ainda sem efeito) e uma
+cor (`tint`) que multiplica o resultado. `use o material [m] no objeto
+[o]` liga o material ao objeto; a `frame_build` da 3d preenche
+`Tb3dDraw.albedo`, o `normaltex` e multiplica `Tb3dDraw.color` pelo tint.
+Os três renderizadores amostram o albedo no `uv` (bilinear, `uv`
+repetido), e a amostra chega ao shader como o `vec3 tex` (o bloco
+`textura do pixel`) e ao caminho padrão como `cor_do_objeto * tex`.
+
### O caminho inverso: renderizadores da 3D
Na `tinyblocks-3d` a direção é a contrária, como no `tinyblocks-graphics`
diff --git a/docs/pendencias.md b/docs/pendencias.md
index cd73b7f..deef89a 100644
--- a/docs/pendencias.md
+++ b/docs/pendencias.md
@@ -119,11 +119,13 @@ de uma palavra (`tecla %1 pressionada?`) funciona. A 3d usa
Os shaders feitos com blocos mudam a cor do pixel (fragmento) e a posição
do vértice (vértice, `mude a posição do vértice`); o estágio sai sozinho do
que a pilha usa. Cada objeto usa um shader (não dá para ter um de vértice e
-um de fragmento no mesmo objeto ao mesmo tempo). Ainda não há texturas,
-materiais nem luz por pixel nos objetos sem shader (estes usam luz por
-vértice). O binário do OpenGL só vale para a mesma placa e driver (o
-projeto salvo não guarda binários: o shader é compilado de novo quando o
-programa roda).
+um de fragmento no mesmo objeto ao mesmo tempo). Texturas de **albedo** e
+materiais já funcionam (textura, cor e o `textura do pixel` nos shaders);
+a textura de **normal map** (`como normal`) já fica guardada no material mas
+ainda não muda a iluminação (falta a fase do relevo). Objetos sem shader
+usam luz por vértice. O binário do OpenGL só vale para a mesma placa e
+driver (o projeto salvo não guarda binários: o shader é compilado de novo
+quando o programa roda).
### Campo de texto de um bloco corta em 63 caracteres
diff --git a/docs/referencia-api.md b/docs/referencia-api.md
index 7dbe846..0d391a2 100644
--- a/docs/referencia-api.md
+++ b/docs/referencia-api.md
@@ -1110,13 +1110,14 @@ OpenGL (clip z em -1..1, y para cima); o Vulkan ajusta por conta propria.
| Declaração | Descrição |
|---|---|
| `#define TB_3D_LIB` = `"tinyblocks-3d"` | TinyBlocks - tb_3d.h Library tinyblocks-3d: uma cena 3D simples feita de blocos (categoria "3D") e o CONTRATO dos renderizadores. A cena tem objetos com nome (cubo, esfera, plano, cilindro), cada um com posicao, rotacao, escala e cor; uma camera; uma luz direcional. O bloco "imagem da cena" desenha tudo numa imagem RGBA, que vai para o palco com "desenhe (imagem da cena ...)". Quem desenha e um Tb3dRenderer. A propria 3d traz um rasterizador em software (sempre disponivel); tinyblocks-vk (Vulkan) e tinyblocks-gl (OpenGL) publicam o deles no lib_userdata, e a 3d procura pelo nome da library no runtime a cada quadro (sem linkar com elas): lib = tb_rt_find_library(rt, "tinyblocks-vk"); const Tb3dRenderer* r = lib ? lib->lib_userdata : NULL; if (r && r->version == TB_3D_RENDERER_VERSION && r->available()) ... A ordem automatica e Vulkan, OpenGL, software ("use o renderizador ..." escolhe um). As matrizes sao 4x4 em colunas (column-major) na convencao do OpenGL (clip z em -1..1, y para cima); o Vulkan ajusta por conta propria. |
-| `#define TB_3D_RENDERER_VERSION` = `5` | Versão do contrato Tb3dRenderer (quem publica confere). |
+| `#define TB_3D_RENDERER_VERSION` = `6` | Versão do contrato Tb3dRenderer (quem publica confere). |
| tipo `struct Tb3dMesh` | 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 monta malhas personalizadas com os blocos "crie a malha", "adicione o vertice/a normal/a texcoord" e "finalize a malha". O renderizador guarda a malha na GPU pelo id; quando o version muda, ele sobe de novo. |
-| `#define TB_3D_STAGE_FRAGMENT` = `0` | 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 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 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) 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` | 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 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 L, vec2 UV, vec3 base, vec3 tex, float light, float time) vec3 tb_vert (vec3 P, vec3 N, vec3 L, vec2 UV, vec3 base, vec3 tex, float light, float time) 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). tex é a textura de albedo amostrada no UV (branco se o objeto não tem material com textura) - o bloco "textura do pixel" devolve isto. 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_VERTEX` = `1` | |
| `#define TB_3D_MAX_BINARIES` = `4` | Quantos binários (renderizadores) um shader compilado guarda. |
| tipo `struct Tb3dBinary` | Binário de um shader para um renderizador (nome dele, dados com malloc, tamanho); o formato só o renderizador conhece. |
| tipo `struct Tb3dShader` | Shader compilado (o valor de "compile o shader"): id único, a função GLSL tb_shade e os binários de cada renderizador. |
+| tipo `struct Tb3dTexture` | Textura: uma imagem RGBA8 (linha 0 no ALTO), a mesma em todos os renderizadores. O id e estavel; o version muda quando os pixels mudam (o renderizador sobe de novo para a GPU). |
| tipo `struct Tb3dDraw` | Um objeto a desenhar |
| tipo `struct Tb3dFrame` | Um quadro: tudo o que o renderizador precisa |
| tipo `struct Tb3dRenderer` | Renderizador. render escreve width*height*4 bytes RGBA, linha 0 no ALTO. |
diff --git a/examples/editor/main.c b/examples/editor/main.c
index 62186c5..1d884ef 100644
--- a/examples/editor/main.c
+++ b/examples/editor/main.c
@@ -57,16 +57,16 @@ void tb_android_boot(void); /* cwd, TINYBLOCKS_APPDIR, fonte e certificados (p
entram no executavel e sao registradas aqui */
# include
# include
-# include
-# include
-# include
-# include
# include
# include
# include
# include
# include
#endif
+#include
+#include
+#include
+#include
/* Registra uma library de categoria: se existir o .so dela no disco, carrega
* por ali (assim "make libs" + hot reload recarrega a lista de blocos na
@@ -115,6 +115,10 @@ int main(int argc, char** argv) {
reg_core(rt, "tinyblocks-variables", tb_variables_get_library);
reg_core(rt, "tinyblocks-vector", tb_vector_get_library);
reg_core(rt, "tinyblocks-appearance", tb_appearance_get_library);
+ reg_core(rt, "tinyblocks-ppm", tb_ppm_get_library);
+ reg_core(rt, "tinyblocks-bmp", tb_bmp_get_library);
+ reg_core(rt, "tinyblocks-png", tb_png_get_library);
+ reg_core(rt, "tinyblocks-image", tb_imglib_get_library);
reg_core(rt, "tinyblocks-pen", tb_pen_get_library);
reg_core(rt, "tinyblocks-fs", tb_fs_get_library);
reg_core(rt, "tinyblocks-os", tb_os_get_library);
@@ -136,7 +140,6 @@ int main(int argc, char** argv) {
#ifdef TB_STATIC_EXTRAS
{
const TinyBlocks_LibraryDescriptor* (*extras[])(void) = {
- tb_ppm_get_library, tb_bmp_get_library, tb_png_get_library, tb_imglib_get_library,
tb_base64_get_library, tb_curves_get_library, tb_vg_get_library, tb_svg_get_library,
tb_regex_get_library, tb_markdown_get_library, tb_opentype_get_library };
for (size_t i = 0; i < sizeof(extras) / sizeof(extras[0]); i++) tb_library_register(rt, extras[i]());
diff --git a/examples/jogo-3d/README.md b/examples/jogo-3d/README.md
index 16f9571..25b6bd0 100644
--- a/examples/jogo-3d/README.md
+++ b/examples/jogo-3d/README.md
@@ -112,3 +112,27 @@ campo: `v` é vértice, `vt` é texcoord, `vn` é normal e `f` é triângulo.
Os números do `f` no `.obj` começam em 1 (iguais aos do bloco "adicione o
triângulo"); quando o índice vier no formato `v/vt/vn` (com barras),
divida o campo por `/` e use só o primeiro número.
+
+## Textura e material (`textura.sb`)
+
+Uma textura sai de uma imagem (categoria **Imagem**/**PNG**, com `carregue o PNG
+[tijolo.png]` ou uma imagem feita com os blocos de desenho):
+
+```
+crie a textura [pedra] da imagem [pedra.png]
+crie o material [rocha]
+no material [rocha] use a textura [pedra] como albedo
+no material [rocha] use a cor [branco]
+use o material [rocha] no objeto [chão]
+```
+
+O **albedo** é a cor da superfície: o renderizador amostra a textura no
+`u/v` de cada vértice (malha personalizada, cubo, esfera e cilindro já
+trazem o `uv`). A amostra chega ao shader com o bloco `textura do pixel`,
+então quem usa `cor do pixel` pode misturar a textura com a cor e a luz. A
+`cor` do material multiplica a textura (o padrão é branco, que não muda
+nada). A textura se repete fora do `0..1`.
+
+O **normal map** (`no material [rocha] use a textura [relevo] como
+normal`) já fica guardado no material, mas ainda não muda a iluminação:
+entra numa fase seguinte, junto com o resto do relevo.
diff --git a/examples/jogo-3d/textura.sb b/examples/jogo-3d/textura.sb
new file mode 100644
index 0000000..1a03a6e
--- /dev/null
+++ b/examples/jogo-3d/textura.sb
@@ -0,0 +1,14 @@
+when flag clicked
+nova cena 3D
+mude [tijolo v] para (carregue o PNG [tijolo.png])
+crie a textura [pedra] da imagem (tijolo)
+crie o material [rocha]
+no material [rocha] use a textura [pedra] como albedo
+crie cubo [caixa] em x (0) y (0.5) z (0)
+use o material [rocha] no objeto [caixa]
+câmera em x (3) y (3.5) z (5) olhando para x (0) y (0.5) z (0)
+sempre
+ gire [caixa] por x (0) y (1) z (0) graus
+ apague tudo
+ desenhe (imagem da cena de (480) por (360)) em x (0) y (0) escala (1)
+end
diff --git a/examples/jogo-3d/tijolo.png b/examples/jogo-3d/tijolo.png
new file mode 100644
index 0000000..bede101
Binary files /dev/null and b/examples/jogo-3d/tijolo.png differ
diff --git a/libraries/tinyblocks-3d/include/tb_3d.h b/libraries/tinyblocks-3d/include/tb_3d.h
index 72e5359..e0848ac 100644
--- a/libraries/tinyblocks-3d/include/tb_3d.h
+++ b/libraries/tinyblocks-3d/include/tb_3d.h
@@ -29,7 +29,7 @@
#include
#define TB_3D_LIB "tinyblocks-3d"
-#define TB_3D_RENDERER_VERSION 5
+#define TB_3D_RENDERER_VERSION 6
/* 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
@@ -50,13 +50,15 @@ typedef struct Tb3dMesh {
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 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)
+ vec3 tb_shade(vec3 P, vec3 N, vec3 L, vec2 UV, vec3 base, vec3 tex, float light, float time)
+ vec3 tb_vert (vec3 P, vec3 N, vec3 L, vec2 UV, vec3 base, vec3 tex, float light, float time)
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).
+ tex é a textura de albedo amostrada no UV (branco se o objeto não tem
+ material com textura) — o bloco "textura do pixel" devolve isto.
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.
@@ -81,6 +83,16 @@ typedef struct Tb3dShader {
int bin_n;
} Tb3dShader;
+/* Textura: uma imagem RGBA8 (linha 0 no ALTO), a mesma em todos os
+ renderizadores. O id e estavel; o version muda quando os pixels mudam
+ (o renderizador sobe de novo para a GPU). */
+typedef struct Tb3dTexture {
+ int id;
+ unsigned version;
+ const uint8_t* rgba;
+ int width, height;
+} Tb3dTexture;
+
/* Um objeto a desenhar */
typedef struct Tb3dDraw {
const Tb3dMesh* mesh;
@@ -89,7 +101,9 @@ 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) */
+ const Tb3dShader* shader; /* NULL = a luz padrao (lambert por vertice) */
+ const Tb3dTexture* albedo; /* NULL = sem textura (branco) */
+ const Tb3dTexture* normaltex; /* NULL = sem normal map (usado depois) */
} Tb3dDraw;
/* Um quadro: tudo o que o renderizador precisa */
diff --git a/libraries/tinyblocks-3d/src/d3_internal.h b/libraries/tinyblocks-3d/src/d3_internal.h
index 57b60ba..5a5de34 100644
--- a/libraries/tinyblocks-3d/src/d3_internal.h
+++ b/libraries/tinyblocks-3d/src/d3_internal.h
@@ -30,6 +30,7 @@ typedef struct {
float P[3], N[3], L[3]; /* ponto/vertice, normal, vertice local */
float uv[2]; /* coordenada de textura */
float base[3];
+ float tex[3]; /* textura de albedo amostrada no uv */
float light, time;
} D3Pixel;
void d3_shader_run(const D3Program* p, const D3Pixel* in, float out[3]);
diff --git a/libraries/tinyblocks-3d/src/d3_shader.c b/libraries/tinyblocks-3d/src/d3_shader.c
index 2d3d9b0..a8cb709 100644
--- a/libraries/tinyblocks-3d/src/d3_shader.c
+++ b/libraries/tinyblocks-3d/src/d3_shader.c
@@ -29,7 +29,7 @@ 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_L, E_UV, /* canal em k[0] */
+ E_CONST, E_VAR, E_PIX, E_BASE, E_LIGHT, E_TIME, E_P, E_N, E_L, E_UV, E_TEX, /* 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] */
@@ -190,6 +190,7 @@ static int expr(C* c, const TinyBlocks_JsonValue* j) {
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);
+ if (!strcmp(t, "Shader.Texture")) return node(c, E_TEX, TV);
const char* axes[] = { "Shader.X", "Shader.Y", "Shader.Z", "Shader.NX", "Shader.NY", "Shader.NZ",
"Shader.VX", "Shader.VY", "Shader.VZ", "Shader.U", "Shader.V" };
for (int k = 0; k < 11; k++)
@@ -424,6 +425,7 @@ static void gx(const D3Program* p, Str* o, int i) {
case E_N: put(o, "N.%c", ch[(int)x->k[0]]); break;
case E_L: put(o, "L.%c", ch[(int)x->k[0]]); break;
case E_UV: put(o, "UV.%c", ch[(int)x->k[0]]); break;
+ case E_TEX: put(o, "tex"); 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);
@@ -479,10 +481,10 @@ static void gs(const D3Program* p, Str* o, int i, int depth) {
static char* emit_glsl(const D3Program* p) {
Str o = {0};
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 tb_vert(vec3 P, vec3 N, vec3 L, vec2 UV, vec3 base, vec3 tex, 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 tb_shade(vec3 P, vec3 N, vec3 L, vec2 UV, vec3 base, vec3 tex, float light, float time) {\n");
put(&o, " vec3 pix = base * light;\n");
}
for (int i = 0; i < p->nl; i++)
@@ -540,6 +542,7 @@ static void ev(const D3Program* p, Run* r, int i, float o[3]) {
case E_N: o[0] = o[1] = o[2] = r->in->N[(int)x->k[0]]; return;
case E_L: o[0] = o[1] = o[2] = r->in->L[(int)x->k[0]]; return;
case E_UV: o[0] = o[1] = o[2] = r->in->uv[(int)x->k[0]]; return;
+ case E_TEX: memcpy(o, r->in->tex, sizeof(r->in->tex)); 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;
diff --git a/libraries/tinyblocks-3d/src/tb_3d.c b/libraries/tinyblocks-3d/src/tb_3d.c
index 38fb62b..b934189 100644
--- a/libraries/tinyblocks-3d/src/tb_3d.c
+++ b/libraries/tinyblocks-3d/src/tb_3d.c
@@ -201,12 +201,15 @@ typedef struct {
int* f; int fn, fcap; /* 3 indices por triangulo (1-based) */
} MeshBuild;
+typedef struct Mat Mat; /* material (texturas + cor) */
+
typedef struct {
char name[48];
int kind;
float pos[3], rot[3], scale[3], color[4];
bool visible;
struct Shd* shader; /* NULL = luz padrao */
+ Mat* material; /* NULL = sem material (cor pura) */
MeshBuild mb; /* malha personalizada (K_CUSTOM) */
Tb3dMesh mesh; /* a malha finalizada */
float bmin[3], bmax[3]; /* caixa local ("encosta em") */
@@ -239,6 +242,95 @@ static void shd_release(Shd* s) {
free(s);
}
+/* Textura ("crie a textura [nome] da imagem [img]"): guarda a imagem e uma
+ copia RGBA8 (linha 0 no alto) que os renderizadores sobem para a GPU. */
+typedef struct Tex {
+ Tb3dTexture pub; /* primeiro: o renderizador ve so isto */
+ char name[48];
+ TinyBlocks_Image* img;
+ uint8_t* rgba;
+ int refs;
+} Tex;
+struct Mat {
+ char name[48];
+ Tex* albedo;
+ Tex* normal;
+ float tint[3]; /* multiplica a cor do objeto */
+};
+
+static struct { Tex** t; int n, cap; } s_tex;
+static struct { Mat** m; int n, cap; } s_mat;
+static int s_tex_seq; /* ids unicos por textura */
+
+static void tex_release(Tex* t) {
+ if (!t || --t->refs > 0) return;
+ if (t->img) tb_image_release(t->img);
+ free(t->rgba);
+ free(t);
+}
+
+static void textures_clear(void) {
+ for (int i = 0; i < s_tex.n; i++) tex_release(s_tex.t[i]);
+ s_tex.n = 0;
+ for (int i = 0; i < s_mat.n; i++) {
+ tex_release(s_mat.m[i]->albedo);
+ tex_release(s_mat.m[i]->normal);
+ free(s_mat.m[i]);
+ }
+ s_mat.n = 0;
+}
+
+static Mat* mat_get(const char* name, bool create) {
+ for (int i = 0; i < s_mat.n; i++) if (!strcmp(s_mat.m[i]->name, name)) return s_mat.m[i];
+ if (!create) return NULL;
+ if (s_mat.n == s_mat.cap) {
+ int nc = s_mat.cap ? s_mat.cap * 2 : 8;
+ Mat** q = realloc(s_mat.m, (size_t)nc * sizeof(*q));
+ if (!q) return NULL;
+ s_mat.m = q; s_mat.cap = nc;
+ }
+ Mat* m = calloc(1, sizeof(*m));
+ if (!m) return NULL;
+ snprintf(m->name, sizeof(m->name), "%s", name);
+ m->tint[0] = m->tint[1] = m->tint[2] = 1.f;
+ s_mat.m[s_mat.n++] = m;
+ return m;
+}
+
+static Tex* tex_get(const char* name) {
+ for (int i = 0; i < s_tex.n; i++) if (!strcmp(s_tex.t[i]->name, name)) return s_tex.t[i];
+ return NULL;
+}
+
+/* Converte a imagem para RGBA8 (linha 0 no alto), como os renderizadores querem */
+static void tex_from_image(Tex* t, TinyBlocks_Image* img) {
+ if (t->img) tb_image_release(t->img);
+ t->img = NULL;
+ free(t->rgba);
+ t->rgba = NULL;
+ t->pub.rgba = NULL;
+ t->pub.width = t->pub.height = 0;
+ if (!img) return;
+ int w = tb_image_width(img), h = tb_image_height(img);
+ if (w <= 0 || h <= 0) return;
+ uint8_t* p = malloc((size_t)w * h * 4);
+ if (!p) return;
+ for (int y = 0; y < h; y++)
+ for (int x = 0; x < w; x++) {
+ uint8_t r, g, b, a;
+ tb_image_get_pixel(img, x, y, &r, &g, &b, &a);
+ uint8_t* q = p + ((size_t)y * w + x) * 4;
+ q[0] = r; q[1] = g; q[2] = b; q[3] = a;
+ }
+ t->img = img;
+ tb_image_retain(img);
+ t->rgba = p;
+ t->pub.rgba = p;
+ t->pub.width = w;
+ t->pub.height = h;
+ t->pub.version++;
+}
+
static double now_s(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
@@ -259,6 +351,7 @@ static struct {
static void scene_reset(void) {
for (int i = 0; i < S.n; i++) { shd_release(S.o[i].shader); mesh_clear(&S.o[i]); }
S.n = 0;
+ textures_clear();
S.eye[0] = 0; S.eye[1] = 6; S.eye[2] = 10;
S.at[0] = S.at[1] = S.at[2] = 0;
S.fov = 60;
@@ -374,6 +467,10 @@ static bool frame_build(Tb3dFrame* f, int w, int h) {
tb_3d_mat_mul(d->mvp, f->viewproj, d->model);
memcpy(d->color, o->color, sizeof(d->color));
d->shader = o->shader ? &o->shader->pub : NULL;
+ d->albedo = (o->material && o->material->albedo) ? &o->material->albedo->pub : NULL;
+ d->normaltex = (o->material && o->material->normal) ? &o->material->normal->pub : NULL;
+ if (o->material)
+ for (int k = 0; k < 3; k++) d->color[k] = o->color[k] * o->material->tint[k];
}
f->draws = s_draws;
f->draw_count = n;
@@ -389,12 +486,34 @@ 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 Tb3dTexture* s_albedo; /* textura do objeto (ou NULL) */
static const Tb3dFrame* s_frame;
static float s_base[3];
static float* s_zbuf;
static size_t s_zcap;
+/* Amostra a textura (bilinear, uv repetido); sem textura, devolve branco */
+static void sample_tex(const Tb3dTexture* t, float u, float v, float out[3]) {
+ out[0] = out[1] = out[2] = 1.f;
+ if (!t || !t->rgba || t->width <= 0 || t->height <= 0) return;
+ int w = t->width, h = t->height;
+ float fu = u - floorf(u), fv = v - floorf(v);
+ float fx = fu * w - 0.5f, fy = fv * h - 0.5f;
+ int x0 = (int)floorf(fx), y0 = (int)floorf(fy);
+ float tx = fx - x0, ty = fy - y0;
+ int x1 = x0 + 1, y1 = y0 + 1;
+ x0 = ((x0 % w) + w) % w; x1 = ((x1 % w) + w) % w;
+ y0 = ((y0 % h) + h) % h; y1 = ((y1 % h) + h) % h;
+ for (int c = 0; c < 3; c++) {
+ float a0 = t->rgba[((size_t)y0 * w + x0) * 4 + c] / 255.f;
+ float b0 = t->rgba[((size_t)y0 * w + x1) * 4 + c] / 255.f;
+ float a1 = t->rgba[((size_t)y1 * w + x0) * 4 + c] / 255.f;
+ float b1 = t->rgba[((size_t)y1 * w + x1) * 4 + c] / 255.f;
+ out[c] = (a0 * (1 - tx) + b0 * tx) * (1 - ty) + (a1 * (1 - tx) + b1 * tx) * ty;
+ }
+}
+
static void raster_tri(const CV* a, const CV* b, const CV* c, int W, int H, uint8_t* px) {
float ax = (a->x / a->w * 0.5f + 0.5f) * W, ay = (0.5f - a->y / a->w * 0.5f) * H, az = a->z / a->w;
float bx = (b->x / b->w * 0.5f + 0.5f) * W, by = (0.5f - b->y / b->w * 0.5f) * H, bz = b->z / b->w;
@@ -423,17 +542,22 @@ static void raster_tri(const CV* a, const CV* b, const CV* c, int W, int H, uint
*zb = z;
uint8_t* p = px + ((size_t)y * W + x) * 4;
float r, g, bl;
+ float q0 = w0 / a->w, q1 = w1 / b->w, q2 = w2 / c->w, qs = 1.f / (q0 + q1 + q2);
+ float iu = (q0 * a->uv[0] + q1 * b->uv[0] + q2 * c->uv[0]) * qs;
+ float iv = (q0 * a->uv[1] + q1 * b->uv[1] + q2 * c->uv[1]) * qs;
+ float tex[3];
+ sample_tex(s_albedo, iu, iv, tex);
if (s_prog) { /* shader: ponto e normal com perspectiva */
- float q0 = w0 / a->w, q1 = w1 / b->w, q2 = w2 / c->w, qs = 1.f / (q0 + q1 + q2);
D3Pixel in;
for (int k = 0; k < 3; k++) {
in.P[k] = (q0 * a->P[k] + q1 * b->P[k] + q2 * c->P[k]) * qs;
in.N[k] = (q0 * a->N[k] + q1 * b->N[k] + q2 * c->N[k]) * qs;
in.L[k] = (q0 * a->L[k] + q1 * b->L[k] + q2 * c->L[k]) * qs;
in.base[k] = s_base[k];
+ in.tex[k] = tex[k];
}
- in.uv[0] = (q0 * a->uv[0] + q1 * b->uv[0] + q2 * c->uv[0]) * qs;
- in.uv[1] = (q0 * a->uv[1] + q1 * b->uv[1] + q2 * c->uv[1]) * qs;
+ in.uv[0] = iu;
+ in.uv[1] = iv;
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);
@@ -442,9 +566,9 @@ static void raster_tri(const CV* a, const CV* b, const CV* c, int W, int H, uint
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;
+ r = (w0 * a->r + w1 * b->r + w2 * c->r) * tex[0];
+ g = (w0 * a->g + w1 * b->g + w2 * c->g) * tex[1];
+ bl = (w0 * a->b + w1 * b->b + w2 * c->b) * tex[2];
}
p[0] = (uint8_t)(fminf(r, 1.f) * 255.f + .5f);
p[1] = (uint8_t)(fminf(g, 1.f) * 255.f + .5f);
@@ -485,6 +609,7 @@ static void shade(const Tb3dFrame* f, const Tb3dDraw* d, const float* v, CV* o)
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.tex[0] = in.tex[1] = in.tex[2] = 1.f;
in.light = 1.f; in.time = f->time;
d3_shader_run_vertex(s_vprog, &in, lp);
}
@@ -536,6 +661,7 @@ static bool sw_render(const Tb3dFrame* f, uint8_t* px) {
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_albedo = d->albedo;
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]);
@@ -547,6 +673,7 @@ static bool sw_render(const Tb3dFrame* f, uint8_t* px) {
}
free(cv);
s_prog = s_vprog = NULL;
+ s_albedo = NULL;
return true;
}
@@ -998,6 +1125,86 @@ static void eval_shader_glsl(TinyBlocks_Block* self, TinyBlocks* rt) {
tb_block_set_output(self, 0, tb_value_text(sh->pub.glsl));
}
+/* -- Texturas e materiais --- */
+static void eval_texture(TinyBlocks_Block* self, TinyBlocks* rt) {
+ self->dirty = false;
+ const char* name = tb_block_input_text(self, rt, 0);
+ if (!name[0]) { tinyblocks_set_error(rt, "dê um nome à textura"); return; }
+ TinyBlocks_Image* img = tb_value_as_image(tb_block_get_input(self, rt, 1));
+ if (!img) { tinyblocks_set_error(rt, "a textura precisa de uma imagem (\"carregue imagem ...\")"); return; }
+ Tex* t = tex_get(name);
+ if (!t) {
+ t = calloc(1, sizeof(*t));
+ if (!t) { tinyblocks_set_error(rt, "sem memória"); return; }
+ t->refs = 1;
+ t->pub.id = ++s_tex_seq;
+ t->pub.version = 1;
+ snprintf(t->name, sizeof(t->name), "%s", name);
+ if (s_tex.n == s_tex.cap) {
+ int nc = s_tex.cap ? s_tex.cap * 2 : 8;
+ Tex** q = realloc(s_tex.t, (size_t)nc * sizeof(*q));
+ if (!q) { free(t); tinyblocks_set_error(rt, "sem memória"); return; }
+ s_tex.t = q; s_tex.cap = nc;
+ }
+ s_tex.t[s_tex.n++] = t;
+ }
+ tex_from_image(t, img);
+}
+
+static void eval_material(TinyBlocks_Block* self, TinyBlocks* rt) {
+ self->dirty = false;
+ const char* name = tb_block_input_text(self, rt, 0);
+ if (!name[0]) { tinyblocks_set_error(rt, "dê um nome ao material"); return; }
+ if (!mat_get(name, true)) tinyblocks_set_error(rt, "sem memória");
+}
+
+static void eval_material_albedo(TinyBlocks_Block* self, TinyBlocks* rt) {
+ self->dirty = false;
+ const char* mn = tb_block_input_text(self, rt, 0);
+ Mat* m = mat_get(mn, false);
+ if (!m) { tinyblocks_set_error(rt, "não existe o material '%s'", mn); return; }
+ const char* tn = tb_block_input_text(self, rt, 1);
+ Tex* t = tex_get(tn);
+ if (!t) { tinyblocks_set_error(rt, "não existe a textura '%s'", tn); return; }
+ t->refs++;
+ tex_release(m->albedo);
+ m->albedo = t;
+}
+
+static void eval_material_normal(TinyBlocks_Block* self, TinyBlocks* rt) {
+ self->dirty = false;
+ const char* mn = tb_block_input_text(self, rt, 0);
+ Mat* m = mat_get(mn, false);
+ if (!m) { tinyblocks_set_error(rt, "não existe o material '%s'", mn); return; }
+ const char* tn = tb_block_input_text(self, rt, 1);
+ Tex* t = tex_get(tn);
+ if (!t) { tinyblocks_set_error(rt, "não existe a textura '%s'", tn); return; }
+ t->refs++;
+ tex_release(m->normal);
+ m->normal = t;
+}
+
+static void eval_material_color(TinyBlocks_Block* self, TinyBlocks* rt) {
+ self->dirty = false;
+ const char* mn = tb_block_input_text(self, rt, 0);
+ Mat* m = mat_get(mn, false);
+ if (!m) { tinyblocks_set_error(rt, "não existe o material '%s'", mn); return; }
+ const char* cn = tb_block_input_text(self, rt, 1);
+ float c[4];
+ if (!d3_color_of(cn, c)) { tinyblocks_set_error(rt, "cor desconhecida '%s'", cn); return; }
+ m->tint[0] = c[0]; m->tint[1] = c[1]; m->tint[2] = c[2];
+}
+
+static void eval_material_use(TinyBlocks_Block* self, TinyBlocks* rt) {
+ self->dirty = false;
+ const char* mn = tb_block_input_text(self, rt, 0);
+ Mat* m = mat_get(mn, false);
+ if (!m) { tinyblocks_set_error(rt, "não existe o material '%s'", mn); return; }
+ Obj* o = need(self, rt, 1);
+ if (!o) return;
+ o->material = m;
+}
+
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()); }
@@ -1037,6 +1244,12 @@ static const Spec s_specs[] = {
{ "3D.MeshUV", "na malha %1 adicione a texcoord u %2 v %3", "minha malha|0|0", 3, {T,R,R}, O_NONE, -1, S_(eval_mesh_uv), "Empilha a coordenada de textura (0 a 1) de um vértice" },
{ "3D.MeshTri", "na malha %1 adicione o triângulo %2 %3 %4", "minha malha|1|2|3", 4, {T,I,I,I}, O_NONE, -1, S_(eval_mesh_tri), "Um triângulo pelos números dos vértices (1 = o primeiro)" },
{ "3D.MeshFinish", "finalize a malha %1", "minha malha", 1, {T}, O_NONE, -1, S_(eval_mesh_finish), "Monta a malha (com as normais que faltam) e a deixa pronta para desenhar" },
+ { "3D.Texture", "crie a textura %1 da imagem %2", "telha|", 2, {T,TB_VALUE_IMAGE}, O_NONE, -1, S_(eval_texture), "Guarda uma textura com esse nome a partir de uma imagem" },
+ { "3D.Material", "crie o material %1", "meu material", 1, {T}, O_NONE, -1, S_(eval_material), "Começa um material (cor + texturas)" },
+ { "3D.MaterialAlbedo", "no material %1 use a textura %2 como albedo", "meu material|telha", 2, {T,T}, O_NONE, -1, S_(eval_material_albedo), "A textura que dá a cor do material" },
+ { "3D.MaterialNormal", "no material %1 use a textura %2 como normal", "meu material|relevo", 2, {T,T}, O_NONE, -1, S_(eval_material_normal), "A textura de relevo (normal map) do material (usada depois)" },
+ { "3D.MaterialColor", "no material %1 use a cor %2", "meu material|branco", 2, {T,T}, O_NONE, -1, S_(eval_material_color), "A cor que multiplica a textura (padrão branco)" },
+ { "3D.MaterialUse", "use o material %1 no objeto %2", "meu material|jogador", 2, {T,T}, O_NONE, -1, S_(eval_material_use), "O objeto passa a usar o material (textura e cor)" },
{ "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)" },
diff --git a/libraries/tinyblocks-gl/src/tb_gl.c b/libraries/tinyblocks-gl/src/tb_gl.c
index f8b2249..2bf3944 100644
--- a/libraries/tinyblocks-gl/src/tb_gl.c
+++ b/libraries/tinyblocks-gl/src/tb_gl.c
@@ -45,8 +45,14 @@ static size_t s_rows_cap;
typedef struct { GLuint vao, vbo, ebo; int icount; unsigned version; } GpuMesh;
static GpuMesh s_mesh[256]; /* pelo id da malha (1..255) */
+/* Texturas (cache pelo id) e a textura branca de 1x1 que substitui quem
+ nao tem material com albedo */
+typedef struct { GLuint tex; int id; unsigned version; } GpuTex;
+static GpuTex s_tex[128];
+static GLuint s_white;
+
/* Programas dos shaders feitos com blocos: cache pelo id (id % 64) */
-typedef struct { GLuint prog; int id; GLint mvp, model, nrm, color, light, ambient, time; } GpuShader;
+typedef struct { GLuint prog; int id; GLint mvp, model, nrm, color, light, ambient, time, albedo; } GpuShader;
static GpuShader s_shd[64];
static void fail(const char* fmt, const char* a) { snprintf(G.err, sizeof(G.err), fmt, a); }
@@ -62,17 +68,21 @@ static const char* VS =
"uniform vec3 u_light;\n"
"uniform float u_ambient;\n"
"out vec3 v_col;\n"
+ "out vec2 v_uv;\n"
"void main() {\n"
" gl_Position = u_mvp * vec4(a_pos, 1.0);\n"
" vec3 n = normalize(u_nrm * a_nrm);\n"
" float I = u_ambient + (1.0 - u_ambient) * max(dot(n, u_light), 0.0);\n"
" v_col = u_color.rgb * I;\n"
+ " v_uv = a_uv;\n"
"}\n";
static const char* FS =
"#version 330 core\n"
"in vec3 v_col;\n"
+ "in vec2 v_uv;\n"
+ "uniform sampler2D u_albedo;\n"
"out vec4 o_color;\n"
- "void main() { o_color = vec4(min(v_col, vec3(1.0)), 1.0); }\n";
+ "void main() { o_color = vec4(min(v_col * texture(u_albedo, v_uv).rgb, vec3(1.0)), 1.0); }\n";
static const char* VS_VERT_HEAD =
"#version 330 core\n"
@@ -94,7 +104,7 @@ static const char* VS_VERT_MAIN =
"void main() {\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"
+ " vec3 P = tb_vert(a_pos, a_nrm, a_pos, a_uv, u_color.rgb, vec3(1.0), 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"
@@ -102,9 +112,9 @@ static const char* VS_VERT_MAIN =
" 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";
+ "vec3 tb_vert(vec3 P, vec3 N, vec3 L, vec2 UV, vec3 base, vec3 tex, 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";
+ "vec3 tb_shade(vec3 P, vec3 N, vec3 L, vec2 UV, vec3 base, vec3 tex, float light, float time) { return base * light; }\n";
static const char* FS_HEAD =
"#version 330 core\n"
"in vec3 v_pos;\n"
@@ -115,12 +125,14 @@ static const char* FS_HEAD =
"uniform vec3 u_light;\n"
"uniform float u_ambient;\n"
"uniform float u_time;\n"
+ "uniform sampler2D u_albedo;\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, v_local, v_uv, u_color.rgb, light, u_time), 1.0);\n"
+ " vec3 tex = texture(u_albedo, v_uv).rgb;\n"
+ " o_color = vec4(tb_shade(v_pos, N, v_local, v_uv, u_color.rgb, tex, light, u_time), 1.0);\n"
"}\n";
static GLuint shader(GLenum kind, const char* src) {
@@ -228,6 +240,7 @@ static GpuShader* gpu_shader(const Tb3dShader* sh) {
g->light = glGetUniformLocation(g->prog, "u_light");
g->ambient = glGetUniformLocation(g->prog, "u_ambient");
g->time = glGetUniformLocation(g->prog, "u_time");
+ g->albedo = glGetUniformLocation(g->prog, "u_albedo");
return g;
}
@@ -268,6 +281,12 @@ static bool gl_setup(void) {
u_color = glGetUniformLocation(s_prog, "u_color");
u_light = glGetUniformLocation(s_prog, "u_light");
u_ambient = glGetUniformLocation(s_prog, "u_ambient");
+ glGenTextures(1, &s_white);
+ glBindTexture(GL_TEXTURE_2D, s_white);
+ static const uint8_t branco[4] = { 255, 255, 255, 255 };
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, 1, 1, 0, GL_RGBA, GL_UNSIGNED_BYTE, branco);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glGenFramebuffers(1, &s_fbo);
glGenRenderbuffers(1, &s_color);
glGenRenderbuffers(1, &s_depth);
@@ -315,6 +334,24 @@ static GpuMesh* gpu_mesh(const Tb3dMesh* m) {
return g;
}
+/* A textura na GPU (cache pelo id): sobe RGBA8 com filtro linear e uv repetido */
+static GLuint gpu_tex(const Tb3dTexture* t) {
+ if (!t || !t->rgba || t->id <= 0 || t->id >= 128) return s_white;
+ GpuTex* g = &s_tex[t->id];
+ if (g->tex && g->version == t->version) return g->tex;
+ if (!g->tex) glGenTextures(1, &g->tex);
+ glBindTexture(GL_TEXTURE_2D, g->tex);
+ glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
+ glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, t->width, t->height, 0, GL_RGBA, GL_UNSIGNED_BYTE, t->rgba);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
+ glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
+ g->id = t->id;
+ g->version = t->version;
+ return g->tex;
+}
+
static bool draw(const Tb3dFrame* f, uint8_t* out) {
if (!target(f->width, f->height)) return false;
glBindFramebuffer(GL_FRAMEBUFFER, s_fbo);
@@ -328,10 +365,13 @@ static bool draw(const Tb3dFrame* f, uint8_t* out) {
glUseProgram(s_prog);
glUniform3fv(u_light, 1, f->light_dir);
glUniform1f(u_ambient, f->ambient);
+ glActiveTexture(GL_TEXTURE0);
+ glUniform1i(glGetUniformLocation(s_prog, "u_albedo"), 0);
for (int i = 0; i < f->draw_count; i++) {
const Tb3dDraw* d = &f->draws[i];
GpuMesh* g = gpu_mesh(d->mesh);
if (!g) continue;
+ glBindTexture(GL_TEXTURE_2D, gpu_tex(d->albedo));
if (d->shader) { /* shader feito com blocos */
GpuShader* sh = gpu_shader(d->shader);
if (!sh) return false; /* a 3d desenha esse quadro em software */
@@ -343,6 +383,7 @@ static bool draw(const Tb3dFrame* f, uint8_t* out) {
glUniform3fv(sh->light, 1, f->light_dir);
glUniform1f(sh->ambient, f->ambient);
glUniform1f(sh->time, f->time);
+ glUniform1i(sh->albedo, 0);
glBindVertexArray(g->vao);
glDrawElements(GL_TRIANGLES, g->icount, GL_UNSIGNED_INT, (void*)0);
glUseProgram(s_prog);
@@ -377,6 +418,10 @@ static void cleanup(void) {
glDeleteBuffers(1, &s_mesh[i].ebo);
}
memset(s_mesh, 0, sizeof(s_mesh));
+ for (int i = 0; i < 128; i++) if (s_tex[i].tex) glDeleteTextures(1, &s_tex[i].tex);
+ memset(s_tex, 0, sizeof(s_tex));
+ if (s_white) glDeleteTextures(1, &s_white);
+ s_white = 0;
for (int i = 0; i < 64; i++) if (s_shd[i].prog) glDeleteProgram(s_shd[i].prog);
memset(s_shd, 0, sizeof(s_shd));
if (s_prog) glDeleteProgram(s_prog);
diff --git a/libraries/tinyblocks-shader/src/tb_shader.c b/libraries/tinyblocks-shader/src/tb_shader.c
index 7d5bc91..26024b1 100644
--- a/libraries/tinyblocks-shader/src/tb_shader.c
+++ b/libraries/tinyblocks-shader/src/tb_shader.c
@@ -32,6 +32,7 @@ static const Spec s_specs[] = {
{ "Shader.VZ", "z do vértice", "", 0, false, "Posição z do vértice antes de mover o objeto" },
{ "Shader.U", "u do uv", "", 0, false, "Coordenada de textura u do ponto (0 a 1)" },
{ "Shader.V", "v do uv", "", 0, false, "Coordenada de textura v do ponto (0 a 1)" },
+ { "Shader.Texture", "textura do pixel", "", 0, false, "A cor da textura de albedo do material neste ponto (branco se o objeto não tem textura)" },
{ "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" },
diff --git a/libraries/tinyblocks-vk/src/shaders/d3.frag b/libraries/tinyblocks-vk/src/shaders/d3.frag
index e11eff2..568e507 100644
--- a/libraries/tinyblocks-vk/src/shaders/d3.frag
+++ b/libraries/tinyblocks-vk/src/shaders/d3.frag
@@ -1,5 +1,7 @@
#version 450
layout(location = 0) in vec3 v_col;
+layout(location = 1) in vec2 v_uv;
+layout(set = 0, binding = 0) uniform sampler2D u_albedo;
layout(location = 0) out vec4 o_color;
-void main() { o_color = vec4(min(v_col, vec3(1.0)), 1.0); }
+void main() { o_color = vec4(min(v_col * texture(u_albedo, v_uv).rgb, vec3(1.0)), 1.0); }
diff --git a/libraries/tinyblocks-vk/src/shaders/d3.vert b/libraries/tinyblocks-vk/src/shaders/d3.vert
index 0dab540..1063cf1 100644
--- a/libraries/tinyblocks-vk/src/shaders/d3.vert
+++ b/libraries/tinyblocks-vk/src/shaders/d3.vert
@@ -8,6 +8,7 @@ layout(location = 1) in vec3 a_nrm;
layout(location = 2) in vec2 a_uv;
layout(push_constant) uniform PC { mat4 mvp; vec4 n0; vec4 n1; vec4 n2; vec4 color; } pc;
layout(location = 0) out vec3 v_col;
+layout(location = 1) out vec2 v_uv;
void main() {
vec4 p = pc.mvp * vec4(a_pos, 1.0);
@@ -18,4 +19,5 @@ void main() {
vec3 n = normalize(N * a_nrm);
float I = pc.color.a + (1.0 - pc.color.a) * max(dot(n, L), 0.0);
v_col = pc.color.rgb * I;
+ v_uv = a_uv;
}
diff --git a/libraries/tinyblocks-vk/src/tb_vk.c b/libraries/tinyblocks-vk/src/tb_vk.c
index 88f9654..79c73e4 100644
--- a/libraries/tinyblocks-vk/src/tb_vk.c
+++ b/libraries/tinyblocks-vk/src/tb_vk.c
@@ -22,6 +22,9 @@ typedef struct { Buf vb, ib; int icount; unsigned version; } GpuMesh;
/* Pipeline de um shader feito com blocos: cache pelo id (id % 64) */
typedef struct { VkPipeline pipe; int id; } GpuShader;
+/* Textura na GPU (cache pelo id) */
+typedef struct { VkImage img; VkDeviceMemory mem; VkImageView view; int id; unsigned version; } GpuTex;
+
/* -- libshaderc (GLSL -> SPIR-V), carregada por dlopen -------------------- */
/* So as funcoes da API C usadas aqui (estavel; nao precisa do header) */
typedef void* (*ShcInit)(void);
@@ -63,13 +66,15 @@ static const char* FS_HEAD =
"layout(location = 1) in vec3 v_nrm;\n"
"layout(location = 2) in vec3 v_local;\n"
"layout(location = 3) in vec2 v_uv;\n"
+ "layout(set = 0, binding = 0) uniform sampler2D u_albedo;\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, v_local, v_uv, pc.color.rgb, light, pc.light.w), 1.0);\n"
+ " vec3 tex = texture(u_albedo, v_uv).rgb;\n"
+ " o_color = vec4(tb_shade(v_pos, N, v_local, v_uv, pc.color.rgb, tex, light, pc.light.w), 1.0);\n"
"}\n";
/* Estagio de VERTICE: o VS chama tb_vert e sai a interface que o fragmento
@@ -88,7 +93,7 @@ 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"
+ " vec3 P = tb_vert(a_pos, a_nrm, a_pos, a_uv, pc.color.rgb, vec3(1.0), 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"
@@ -99,7 +104,7 @@ static const char* VS_VERT_MAIN =
"}\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";
+ "vec3 tb_shade(vec3 P, vec3 N, vec3 L, vec2 UV, vec3 base, vec3 tex, 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) {
@@ -173,6 +178,13 @@ static struct {
VkShaderModule shd_vert;
bool shd_ok; /* da para usar shaders feitos com blocos */
GpuShader shd[64];
+ /* texturas: layout com um sampler, pool e um descritor */
+ VkDescriptorSetLayout desc_layout;
+ VkDescriptorPool desc_pool;
+ VkDescriptorSet desc_set;
+ VkSampler sampler;
+ GpuTex tex[128];
+ GpuTex white; /* 1x1 branco: quem nao tem albedo */
/* alvo (recriado quando muda o tamanho) */
int w, h;
VkImage color, depth;
@@ -300,6 +312,74 @@ static VkResult build_pipe(VkShaderModule vs, VkShaderModule fs, VkPipelineLayou
return vkCreateGraphicsPipelines(V.dev, VK_NULL_HANDLE, 1, &gp, NULL, out);
}
+/* Cria a imagem (com memoria) e a view, ja em SHADER_READ_ONLY, subindo os
+ pixels por um buffer temporario (um comando proprio, antes do desenho). */
+static bool tex_create(const uint8_t* rgba, int w, int h, GpuTex* g) {
+ VkImageCreateInfo ci = { VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO, NULL, 0, VK_IMAGE_TYPE_2D,
+ VK_FORMAT_R8G8B8A8_UNORM, { (uint32_t)w, (uint32_t)h, 1 }, 1, 1, VK_SAMPLE_COUNT_1_BIT,
+ VK_IMAGE_TILING_OPTIMAL, VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT,
+ VK_SHARING_MODE_EXCLUSIVE, 0, NULL, VK_IMAGE_LAYOUT_UNDEFINED };
+ if (vkCreateImage(V.dev, &ci, NULL, &g->img) != VK_SUCCESS) return false;
+ VkMemoryRequirements req;
+ vkGetImageMemoryRequirements(V.dev, g->img, &req);
+ uint32_t t;
+ if (!mem_type(req.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, &t)) return false;
+ VkMemoryAllocateInfo ai = { VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO, NULL, req.size, t };
+ if (vkAllocateMemory(V.dev, &ai, NULL, &g->mem) != VK_SUCCESS) return false;
+ if (vkBindImageMemory(V.dev, g->img, g->mem, 0) != VK_SUCCESS) return false;
+ Buf st = {0};
+ if (!buf_new(&st, (VkDeviceSize)w * h * 4, VK_BUFFER_USAGE_TRANSFER_SRC_BIT)) return false;
+ memcpy(st.map, rgba, (size_t)w * h * 4);
+ VkCommandBuffer cmd = VK_NULL_HANDLE;
+ VkCommandBufferAllocateInfo cb = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO, NULL, V.pool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, 1 };
+ if (vkAllocateCommandBuffers(V.dev, &cb, &cmd) != VK_SUCCESS) { buf_free(&st); return false; }
+ VkCommandBufferBeginInfo bi = { VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, NULL, VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT, NULL };
+ vkBeginCommandBuffer(cmd, &bi);
+ VkImageMemoryBarrier b1 = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, NULL, 0, VK_ACCESS_TRANSFER_WRITE_BIT,
+ VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED,
+ g->img, { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 } };
+ vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, NULL, 1, &b1);
+ VkBufferImageCopy cp = { 0, 0, 0, { VK_IMAGE_ASPECT_COLOR_BIT, 0, 0, 1 }, {0,0,0}, { (uint32_t)w, (uint32_t)h, 1 } };
+ vkCmdCopyBufferToImage(cmd, st.buf, g->img, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &cp);
+ VkImageMemoryBarrier b2 = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, NULL, VK_ACCESS_TRANSFER_WRITE_BIT, VK_ACCESS_SHADER_READ_BIT,
+ VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_QUEUE_FAMILY_IGNORED, VK_QUEUE_FAMILY_IGNORED,
+ g->img, { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 } };
+ vkCmdPipelineBarrier(cmd, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_FRAGMENT_SHADER_BIT, 0, 0, NULL, 0, NULL, 1, &b2);
+ vkEndCommandBuffer(cmd);
+ VkSubmitInfo si = { VK_STRUCTURE_TYPE_SUBMIT_INFO, NULL, 0, NULL, NULL, 1, &cmd, 0, NULL };
+ vkResetFences(V.dev, 1, &V.fence);
+ vkQueueSubmit(V.queue, 1, &si, V.fence);
+ vkWaitForFences(V.dev, 1, &V.fence, VK_TRUE, 5000000000ull);
+ vkFreeCommandBuffers(V.dev, V.pool, 1, &cmd);
+ buf_free(&st);
+ VkImageViewCreateInfo vi = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, NULL, 0, g->img,
+ VK_IMAGE_VIEW_TYPE_2D, VK_FORMAT_R8G8B8A8_UNORM,
+ { VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY, VK_COMPONENT_SWIZZLE_IDENTITY },
+ { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 } };
+ return vkCreateImageView(V.dev, &vi, NULL, &g->view) == VK_SUCCESS;
+}
+
+static void tex_destroy(GpuTex* g) {
+ if (!g->img && !g->view) return;
+ vkDeviceWaitIdle(V.dev);
+ if (g->view) vkDestroyImageView(V.dev, g->view, NULL);
+ if (g->img) vkDestroyImage(V.dev, g->img, NULL);
+ if (g->mem) vkFreeMemory(V.dev, g->mem, NULL);
+ memset(g, 0, sizeof(*g));
+}
+
+/* A view da textura do objeto (branco se nao tem), subindo para a GPU se mudou */
+static VkImageView gpu_tex(const Tb3dTexture* t) {
+ if (!t || !t->rgba || t->id <= 0 || t->id >= 128) return V.white.view;
+ GpuTex* g = &V.tex[t->id];
+ if (g->view && g->version == t->version) return g->view;
+ tex_destroy(g);
+ if (!tex_create(t->rgba, t->width, t->height, g)) { memset(g, 0, sizeof(*g)); return V.white.view; }
+ g->id = t->id;
+ g->version = t->version;
+ return g->view;
+}
+
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,
@@ -319,8 +399,21 @@ static bool make_pipeline(void) {
VkRenderPassCreateInfo rp = { VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, NULL, 0, 2, att, 1, &sub, 1, &dep };
CK(vkCreateRenderPass(V.dev, &rp, NULL, &V.pass), "vkCreateRenderPass");
+ VkDescriptorSetLayoutBinding b0 = { 0, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1, VK_SHADER_STAGE_FRAGMENT_BIT, NULL };
+ VkDescriptorSetLayoutCreateInfo dl = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO, NULL, 0, 1, &b0 };
+ CK(vkCreateDescriptorSetLayout(V.dev, &dl, NULL, &V.desc_layout), "vkCreateDescriptorSetLayout");
+ VkDescriptorPoolSize ps = { VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, 1 };
+ VkDescriptorPoolCreateInfo dp = { VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO, NULL, 0, 1, 1, &ps };
+ CK(vkCreateDescriptorPool(V.dev, &dp, NULL, &V.desc_pool), "vkCreateDescriptorPool");
+ VkDescriptorSetAllocateInfo da = { VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO, NULL, V.desc_pool, 1, &V.desc_layout };
+ CK(vkAllocateDescriptorSets(V.dev, &da, &V.desc_set), "vkAllocateDescriptorSets");
+ VkSamplerCreateInfo sc = { VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO, NULL, 0,
+ VK_FILTER_LINEAR, VK_FILTER_LINEAR, VK_SAMPLER_MIPMAP_MODE_NEAREST,
+ VK_SAMPLER_ADDRESS_MODE_REPEAT, VK_SAMPLER_ADDRESS_MODE_REPEAT, VK_SAMPLER_ADDRESS_MODE_REPEAT,
+ 0, VK_FALSE, 1.f, VK_FALSE, VK_COMPARE_OP_NEVER, 0, 0, VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE, VK_FALSE };
+ CK(vkCreateSampler(V.dev, &sc, NULL, &V.sampler), "vkCreateSampler");
VkPushConstantRange pcr = { VK_SHADER_STAGE_VERTEX_BIT, 0, 128 };
- VkPipelineLayoutCreateInfo pl = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, NULL, 0, 0, NULL, 1, &pcr };
+ VkPipelineLayoutCreateInfo pl = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, NULL, 0, 1, &V.desc_layout, 1, &pcr };
CK(vkCreatePipelineLayout(V.dev, &pl, NULL, &V.layout), "vkCreatePipelineLayout");
VkShaderModule vs, fs;
@@ -338,11 +431,13 @@ static bool make_pipeline(void) {
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 };
+ VkPipelineLayoutCreateInfo pl2 = { VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO, NULL, 0, 1, &V.desc_layout, 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;
}
+ static const uint8_t branco[4] = { 255, 255, 255, 255 };
+ if (!tex_create(branco, 1, 1, &V.white)) snprintf(V.err, sizeof(V.err), "textura branca falhou");
return true;
}
@@ -491,12 +586,21 @@ static GpuShader* gpu_shader(const Tb3dShader* sh) {
return g;
}
+static void bind_tex(VkCommandBuffer cmd, VkPipelineLayout layout, const Tb3dTexture* t) {
+ VkDescriptorImageInfo di = { V.sampler, gpu_tex(t), VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL };
+ VkWriteDescriptorSet w = { VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, V.desc_set, 0, 0, 1,
+ VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, &di, NULL, NULL };
+ vkUpdateDescriptorSets(V.dev, 1, &w, 0, NULL);
+ vkCmdBindDescriptorSets(cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, layout, 0, 1, &V.desc_set, 0, NULL);
+}
+
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 */
+ /* as malhas e texturas antes de gravar os comandos */
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 */
+ gpu_tex(f->draws[i].albedo);
}
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 };
@@ -523,6 +627,7 @@ static bool vk_draw(const Tb3dFrame* f, uint8_t* out) {
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[(unsigned)d->shader->id % 64u].pipe);
+ bind_tex(V.cmd, V.shd_layout, d->albedo);
vkCmdPushConstants(V.cmd, V.shd_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT,
0, sizeof(pc), pc);
VkDeviceSize off = 0;
@@ -541,6 +646,7 @@ static bool vk_draw(const Tb3dFrame* f, uint8_t* out) {
pc[16 + c * 4 + 3] = f->light_dir[c];
}
pc[28] = d->color[0]; pc[29] = d->color[1]; pc[30] = d->color[2]; pc[31] = f->ambient;
+ bind_tex(V.cmd, V.layout, d->albedo);
vkCmdPushConstants(V.cmd, V.layout, VK_SHADER_STAGE_VERTEX_BIT, 0, sizeof(pc), pc);
VkDeviceSize off = 0;
vkCmdBindVertexBuffers(V.cmd, 0, 1, &g->vb.buf, &off);
@@ -570,6 +676,11 @@ static void vk_cleanup(void) {
for (int i = 0; i < 256; i++) { buf_free(&V.mesh[i].vb); buf_free(&V.mesh[i].ib); }
target_free();
for (int i = 0; i < 64; i++) if (V.shd[i].pipe) vkDestroyPipeline(V.dev, V.shd[i].pipe, NULL);
+ for (int i = 0; i < 128; i++) tex_destroy(&V.tex[i]);
+ tex_destroy(&V.white);
+ if (V.sampler) vkDestroySampler(V.dev, V.sampler, NULL);
+ if (V.desc_pool) vkDestroyDescriptorPool(V.dev, V.desc_pool, NULL);
+ if (V.desc_layout) vkDestroyDescriptorSetLayout(V.dev, V.desc_layout, 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);
diff --git a/libraries/tinyblocks-vk/src/tb_vk_shaders.h b/libraries/tinyblocks-vk/src/tb_vk_shaders.h
index 7d88ed4..2dfb995 100644
--- a/libraries/tinyblocks-vk/src/tb_vk_shaders.h
+++ b/libraries/tinyblocks-vk/src/tb_vk_shaders.h
@@ -3,92 +3,105 @@
#define TB_VK_SHADERS_H
#include
-static const uint32_t s_vert_spv[528] = {
- 0x07230203, 0x00010000, 0x000d000b, 0x0000007a, 0x00000000, 0x00020011, 0x00000001, 0x0006000b,
+static const uint32_t s_vert_spv[565] = {
+ 0x07230203, 0x00010000, 0x000d000b, 0x0000007d, 0x00000000, 0x00020011, 0x00000001, 0x0006000b,
0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001,
- 0x0009000f, 0x00000000, 0x00000004, 0x6e69616d, 0x00000000, 0x00000015, 0x0000002d, 0x0000005b,
- 0x0000006d, 0x00040048, 0x0000000b, 0x00000000, 0x00000005, 0x00050048, 0x0000000b, 0x00000000,
- 0x00000023, 0x00000000, 0x00050048, 0x0000000b, 0x00000000, 0x00000007, 0x00000010, 0x00050048,
- 0x0000000b, 0x00000001, 0x00000023, 0x00000040, 0x00050048, 0x0000000b, 0x00000002, 0x00000023,
- 0x00000050, 0x00050048, 0x0000000b, 0x00000003, 0x00000023, 0x00000060, 0x00050048, 0x0000000b,
- 0x00000004, 0x00000023, 0x00000070, 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, 0x0000005b, 0x0000001e, 0x00000001, 0x00040047, 0x0000006d, 0x0000001e,
- 0x00000000, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, 0x00030016, 0x00000006,
- 0x00000020, 0x00040017, 0x00000007, 0x00000006, 0x00000004, 0x00040018, 0x0000000a, 0x00000007,
- 0x00000004, 0x0007001e, 0x0000000b, 0x0000000a, 0x00000007, 0x00000007, 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, 0x0000001d, 0x00000022, 0x00000003, 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, 0x00040018, 0x00000031, 0x00000013, 0x00000003, 0x0004002b, 0x0000000e,
- 0x00000034, 0x00000001, 0x00040020, 0x00000035, 0x00000009, 0x00000007, 0x0004002b, 0x0000000e,
- 0x00000039, 0x00000002, 0x0004002b, 0x0000000e, 0x0000003d, 0x00000003, 0x0004002b, 0x00000006,
- 0x00000041, 0x00000000, 0x00040020, 0x00000051, 0x00000009, 0x00000006, 0x0004003b, 0x00000014,
- 0x0000005b, 0x00000001, 0x0004002b, 0x0000000e, 0x00000060, 0x00000004, 0x00040020, 0x0000006c,
- 0x00000003, 0x00000013, 0x0004003b, 0x0000006c, 0x0000006d, 0x00000003, 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, 0x00000079, 0x00000027, 0x0000001c, 0x00000002, 0x00050041,
- 0x0000002f, 0x00000030, 0x0000002d, 0x0000000f, 0x0003003e, 0x00000030, 0x00000079, 0x00050041,
- 0x00000035, 0x00000036, 0x0000000d, 0x00000034, 0x0004003d, 0x00000007, 0x00000037, 0x00000036,
- 0x00050041, 0x00000035, 0x0000003a, 0x0000000d, 0x00000039, 0x0004003d, 0x00000007, 0x0000003b,
- 0x0000003a, 0x00050041, 0x00000035, 0x0000003e, 0x0000000d, 0x0000003d, 0x0004003d, 0x00000007,
- 0x0000003f, 0x0000003e, 0x00050051, 0x00000006, 0x00000042, 0x00000037, 0x00000000, 0x00050051,
- 0x00000006, 0x00000043, 0x00000037, 0x00000001, 0x00050051, 0x00000006, 0x00000044, 0x00000037,
- 0x00000002, 0x00050051, 0x00000006, 0x00000045, 0x0000003b, 0x00000000, 0x00050051, 0x00000006,
- 0x00000046, 0x0000003b, 0x00000001, 0x00050051, 0x00000006, 0x00000047, 0x0000003b, 0x00000002,
- 0x00050051, 0x00000006, 0x00000048, 0x0000003f, 0x00000000, 0x00050051, 0x00000006, 0x00000049,
- 0x0000003f, 0x00000001, 0x00050051, 0x00000006, 0x0000004a, 0x0000003f, 0x00000002, 0x00060050,
- 0x00000013, 0x0000004b, 0x00000042, 0x00000043, 0x00000044, 0x00060050, 0x00000013, 0x0000004c,
- 0x00000045, 0x00000046, 0x00000047, 0x00060050, 0x00000013, 0x0000004d, 0x00000048, 0x00000049,
- 0x0000004a, 0x00060050, 0x00000031, 0x0000004e, 0x0000004b, 0x0000004c, 0x0000004d, 0x00060041,
- 0x00000051, 0x00000052, 0x0000000d, 0x00000034, 0x00000022, 0x0004003d, 0x00000006, 0x00000053,
- 0x00000052, 0x00060041, 0x00000051, 0x00000054, 0x0000000d, 0x00000039, 0x00000022, 0x0004003d,
- 0x00000006, 0x00000055, 0x00000054, 0x00060041, 0x00000051, 0x00000056, 0x0000000d, 0x0000003d,
- 0x00000022, 0x0004003d, 0x00000006, 0x00000057, 0x00000056, 0x00060050, 0x00000013, 0x00000058,
- 0x00000053, 0x00000055, 0x00000057, 0x0004003d, 0x00000013, 0x0000005c, 0x0000005b, 0x00050091,
- 0x00000013, 0x0000005d, 0x0000004e, 0x0000005c, 0x0006000c, 0x00000013, 0x0000005e, 0x00000001,
- 0x00000045, 0x0000005d, 0x00060041, 0x00000051, 0x00000061, 0x0000000d, 0x00000060, 0x00000022,
- 0x0004003d, 0x00000006, 0x00000062, 0x00000061, 0x00050083, 0x00000006, 0x00000065, 0x00000017,
- 0x00000062, 0x00050094, 0x00000006, 0x00000068, 0x0000005e, 0x00000058, 0x0007000c, 0x00000006,
- 0x00000069, 0x00000001, 0x00000028, 0x00000068, 0x00000041, 0x0008000c, 0x00000006, 0x0000006b,
- 0x00000001, 0x00000032, 0x00000065, 0x00000069, 0x00000062, 0x00050041, 0x00000035, 0x0000006e,
- 0x0000000d, 0x00000060, 0x0004003d, 0x00000007, 0x0000006f, 0x0000006e, 0x0008004f, 0x00000013,
- 0x00000070, 0x0000006f, 0x0000006f, 0x00000000, 0x00000001, 0x00000002, 0x0005008e, 0x00000013,
- 0x00000072, 0x00000070, 0x0000006b, 0x0003003e, 0x0000006d, 0x00000072, 0x000100fd, 0x00010038,
+ 0x000b000f, 0x00000000, 0x00000004, 0x6e69616d, 0x00000000, 0x00000015, 0x0000002d, 0x0000005b,
+ 0x0000006d, 0x00000075, 0x00000077, 0x00040048, 0x0000000b, 0x00000000, 0x00000005, 0x00050048,
+ 0x0000000b, 0x00000000, 0x00000023, 0x00000000, 0x00050048, 0x0000000b, 0x00000000, 0x00000007,
+ 0x00000010, 0x00050048, 0x0000000b, 0x00000001, 0x00000023, 0x00000040, 0x00050048, 0x0000000b,
+ 0x00000002, 0x00000023, 0x00000050, 0x00050048, 0x0000000b, 0x00000003, 0x00000023, 0x00000060,
+ 0x00050048, 0x0000000b, 0x00000004, 0x00000023, 0x00000070, 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, 0x0000005b, 0x0000001e, 0x00000001, 0x00040047,
+ 0x0000006d, 0x0000001e, 0x00000000, 0x00040047, 0x00000075, 0x0000001e, 0x00000001, 0x00040047,
+ 0x00000077, 0x0000001e, 0x00000002, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002,
+ 0x00030016, 0x00000006, 0x00000020, 0x00040017, 0x00000007, 0x00000006, 0x00000004, 0x00040018,
+ 0x0000000a, 0x00000007, 0x00000004, 0x0007001e, 0x0000000b, 0x0000000a, 0x00000007, 0x00000007,
+ 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, 0x0000001d, 0x00000022, 0x00000003, 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, 0x00040018, 0x00000031, 0x00000013, 0x00000003,
+ 0x0004002b, 0x0000000e, 0x00000034, 0x00000001, 0x00040020, 0x00000035, 0x00000009, 0x00000007,
+ 0x0004002b, 0x0000000e, 0x00000039, 0x00000002, 0x0004002b, 0x0000000e, 0x0000003d, 0x00000003,
+ 0x0004002b, 0x00000006, 0x00000041, 0x00000000, 0x00040020, 0x00000051, 0x00000009, 0x00000006,
+ 0x0004003b, 0x00000014, 0x0000005b, 0x00000001, 0x0004002b, 0x0000000e, 0x00000060, 0x00000004,
+ 0x00040020, 0x0000006c, 0x00000003, 0x00000013, 0x0004003b, 0x0000006c, 0x0000006d, 0x00000003,
+ 0x00040017, 0x00000073, 0x00000006, 0x00000002, 0x00040020, 0x00000074, 0x00000003, 0x00000073,
+ 0x0004003b, 0x00000074, 0x00000075, 0x00000003, 0x00040020, 0x00000076, 0x00000001, 0x00000073,
+ 0x0004003b, 0x00000076, 0x00000077, 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, 0x0000007c, 0x00000027, 0x0000001c, 0x00000002, 0x00050041, 0x0000002f, 0x00000030,
+ 0x0000002d, 0x0000000f, 0x0003003e, 0x00000030, 0x0000007c, 0x00050041, 0x00000035, 0x00000036,
+ 0x0000000d, 0x00000034, 0x0004003d, 0x00000007, 0x00000037, 0x00000036, 0x00050041, 0x00000035,
+ 0x0000003a, 0x0000000d, 0x00000039, 0x0004003d, 0x00000007, 0x0000003b, 0x0000003a, 0x00050041,
+ 0x00000035, 0x0000003e, 0x0000000d, 0x0000003d, 0x0004003d, 0x00000007, 0x0000003f, 0x0000003e,
+ 0x00050051, 0x00000006, 0x00000042, 0x00000037, 0x00000000, 0x00050051, 0x00000006, 0x00000043,
+ 0x00000037, 0x00000001, 0x00050051, 0x00000006, 0x00000044, 0x00000037, 0x00000002, 0x00050051,
+ 0x00000006, 0x00000045, 0x0000003b, 0x00000000, 0x00050051, 0x00000006, 0x00000046, 0x0000003b,
+ 0x00000001, 0x00050051, 0x00000006, 0x00000047, 0x0000003b, 0x00000002, 0x00050051, 0x00000006,
+ 0x00000048, 0x0000003f, 0x00000000, 0x00050051, 0x00000006, 0x00000049, 0x0000003f, 0x00000001,
+ 0x00050051, 0x00000006, 0x0000004a, 0x0000003f, 0x00000002, 0x00060050, 0x00000013, 0x0000004b,
+ 0x00000042, 0x00000043, 0x00000044, 0x00060050, 0x00000013, 0x0000004c, 0x00000045, 0x00000046,
+ 0x00000047, 0x00060050, 0x00000013, 0x0000004d, 0x00000048, 0x00000049, 0x0000004a, 0x00060050,
+ 0x00000031, 0x0000004e, 0x0000004b, 0x0000004c, 0x0000004d, 0x00060041, 0x00000051, 0x00000052,
+ 0x0000000d, 0x00000034, 0x00000022, 0x0004003d, 0x00000006, 0x00000053, 0x00000052, 0x00060041,
+ 0x00000051, 0x00000054, 0x0000000d, 0x00000039, 0x00000022, 0x0004003d, 0x00000006, 0x00000055,
+ 0x00000054, 0x00060041, 0x00000051, 0x00000056, 0x0000000d, 0x0000003d, 0x00000022, 0x0004003d,
+ 0x00000006, 0x00000057, 0x00000056, 0x00060050, 0x00000013, 0x00000058, 0x00000053, 0x00000055,
+ 0x00000057, 0x0004003d, 0x00000013, 0x0000005c, 0x0000005b, 0x00050091, 0x00000013, 0x0000005d,
+ 0x0000004e, 0x0000005c, 0x0006000c, 0x00000013, 0x0000005e, 0x00000001, 0x00000045, 0x0000005d,
+ 0x00060041, 0x00000051, 0x00000061, 0x0000000d, 0x00000060, 0x00000022, 0x0004003d, 0x00000006,
+ 0x00000062, 0x00000061, 0x00050083, 0x00000006, 0x00000065, 0x00000017, 0x00000062, 0x00050094,
+ 0x00000006, 0x00000068, 0x0000005e, 0x00000058, 0x0007000c, 0x00000006, 0x00000069, 0x00000001,
+ 0x00000028, 0x00000068, 0x00000041, 0x0008000c, 0x00000006, 0x0000006b, 0x00000001, 0x00000032,
+ 0x00000065, 0x00000069, 0x00000062, 0x00050041, 0x00000035, 0x0000006e, 0x0000000d, 0x00000060,
+ 0x0004003d, 0x00000007, 0x0000006f, 0x0000006e, 0x0008004f, 0x00000013, 0x00000070, 0x0000006f,
+ 0x0000006f, 0x00000000, 0x00000001, 0x00000002, 0x0005008e, 0x00000013, 0x00000072, 0x00000070,
+ 0x0000006b, 0x0003003e, 0x0000006d, 0x00000072, 0x0004003d, 0x00000073, 0x00000078, 0x00000077,
+ 0x0003003e, 0x00000075, 0x00000078, 0x000100fd, 0x00010038,
};
-static const uint32_t s_frag_spv[121] = {
- 0x07230203, 0x00010000, 0x000d000b, 0x00000015, 0x00000000, 0x00020011, 0x00000001, 0x0006000b,
+static const uint32_t s_frag_spv[192] = {
+ 0x07230203, 0x00010000, 0x000d000b, 0x00000021, 0x00000000, 0x00020011, 0x00000001, 0x0006000b,
0x00000001, 0x4c534c47, 0x6474732e, 0x3035342e, 0x00000000, 0x0003000e, 0x00000000, 0x00000001,
- 0x0007000f, 0x00000004, 0x00000004, 0x6e69616d, 0x00000000, 0x00000009, 0x0000000c, 0x00030010,
- 0x00000004, 0x00000007, 0x00040047, 0x00000009, 0x0000001e, 0x00000000, 0x00040047, 0x0000000c,
- 0x0000001e, 0x00000000, 0x00020013, 0x00000002, 0x00030021, 0x00000003, 0x00000002, 0x00030016,
- 0x00000006, 0x00000020, 0x00040017, 0x00000007, 0x00000006, 0x00000004, 0x00040020, 0x00000008,
- 0x00000003, 0x00000007, 0x0004003b, 0x00000008, 0x00000009, 0x00000003, 0x00040017, 0x0000000a,
- 0x00000006, 0x00000003, 0x00040020, 0x0000000b, 0x00000001, 0x0000000a, 0x0004003b, 0x0000000b,
- 0x0000000c, 0x00000001, 0x0004002b, 0x00000006, 0x0000000e, 0x3f800000, 0x0006002c, 0x0000000a,
- 0x0000000f, 0x0000000e, 0x0000000e, 0x0000000e, 0x00050036, 0x00000002, 0x00000004, 0x00000000,
- 0x00000003, 0x000200f8, 0x00000005, 0x0004003d, 0x0000000a, 0x0000000d, 0x0000000c, 0x0007000c,
- 0x0000000a, 0x00000010, 0x00000001, 0x00000025, 0x0000000d, 0x0000000f, 0x00050051, 0x00000006,
- 0x00000011, 0x00000010, 0x00000000, 0x00050051, 0x00000006, 0x00000012, 0x00000010, 0x00000001,
- 0x00050051, 0x00000006, 0x00000013, 0x00000010, 0x00000002, 0x00070050, 0x00000007, 0x00000014,
- 0x00000011, 0x00000012, 0x00000013, 0x0000000e, 0x0003003e, 0x00000009, 0x00000014, 0x000100fd,
- 0x00010038,
+ 0x0008000f, 0x00000004, 0x00000004, 0x6e69616d, 0x00000000, 0x00000009, 0x0000000c, 0x00000015,
+ 0x00030010, 0x00000004, 0x00000007, 0x00040047, 0x00000009, 0x0000001e, 0x00000000, 0x00040047,
+ 0x0000000c, 0x0000001e, 0x00000000, 0x00040047, 0x00000011, 0x00000022, 0x00000000, 0x00040047,
+ 0x00000011, 0x00000021, 0x00000000, 0x00040047, 0x00000015, 0x0000001e, 0x00000001, 0x00020013,
+ 0x00000002, 0x00030021, 0x00000003, 0x00000002, 0x00030016, 0x00000006, 0x00000020, 0x00040017,
+ 0x00000007, 0x00000006, 0x00000004, 0x00040020, 0x00000008, 0x00000003, 0x00000007, 0x0004003b,
+ 0x00000008, 0x00000009, 0x00000003, 0x00040017, 0x0000000a, 0x00000006, 0x00000003, 0x00040020,
+ 0x0000000b, 0x00000001, 0x0000000a, 0x0004003b, 0x0000000b, 0x0000000c, 0x00000001, 0x00090019,
+ 0x0000000e, 0x00000006, 0x00000001, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0x00000000,
+ 0x0003001b, 0x0000000f, 0x0000000e, 0x00040020, 0x00000010, 0x00000000, 0x0000000f, 0x0004003b,
+ 0x00000010, 0x00000011, 0x00000000, 0x00040017, 0x00000013, 0x00000006, 0x00000002, 0x00040020,
+ 0x00000014, 0x00000001, 0x00000013, 0x0004003b, 0x00000014, 0x00000015, 0x00000001, 0x0004002b,
+ 0x00000006, 0x0000001a, 0x3f800000, 0x0006002c, 0x0000000a, 0x0000001b, 0x0000001a, 0x0000001a,
+ 0x0000001a, 0x00050036, 0x00000002, 0x00000004, 0x00000000, 0x00000003, 0x000200f8, 0x00000005,
+ 0x0004003d, 0x0000000a, 0x0000000d, 0x0000000c, 0x0004003d, 0x0000000f, 0x00000012, 0x00000011,
+ 0x0004003d, 0x00000013, 0x00000016, 0x00000015, 0x00050057, 0x00000007, 0x00000017, 0x00000012,
+ 0x00000016, 0x0008004f, 0x0000000a, 0x00000018, 0x00000017, 0x00000017, 0x00000000, 0x00000001,
+ 0x00000002, 0x00050085, 0x0000000a, 0x00000019, 0x0000000d, 0x00000018, 0x0007000c, 0x0000000a,
+ 0x0000001c, 0x00000001, 0x00000025, 0x00000019, 0x0000001b, 0x00050051, 0x00000006, 0x0000001d,
+ 0x0000001c, 0x00000000, 0x00050051, 0x00000006, 0x0000001e, 0x0000001c, 0x00000001, 0x00050051,
+ 0x00000006, 0x0000001f, 0x0000001c, 0x00000002, 0x00070050, 0x00000007, 0x00000020, 0x0000001d,
+ 0x0000001e, 0x0000001f, 0x0000001a, 0x0003003e, 0x00000009, 0x00000020, 0x000100fd, 0x00010038,
};
static const uint32_t s_vert_shd_spv[446] = {
diff --git a/tests/d3_test.c b/tests/d3_test.c
index 6f644ec..fb5f504 100644
--- a/tests/d3_test.c
+++ b/tests/d3_test.c
@@ -300,6 +300,75 @@ int main(void) {
tb_image_release(vi);
}
}
+
+ /* -- textura + material: um quad pintado por uma imagem 2x2 -- */
+ {
+ TinyBlocks_Image* tex = tb_image_new(2, 2, 4);
+ for (int y = 0; y < 2; y++) {
+ tb_image_set_pixel(tex, 0, y, 255, 0, 0, 255); /* esquerda: vermelho */
+ tb_image_set_pixel(tex, 1, y, 0, 0, 255, 255); /* direita: azul */
+ }
+ RUN("3D.Scene", NULL);
+ RUN("3D.MeshCreate", "quad");
+ const char* vx[4][3] = { {"-1","-1","0"}, {"1","-1","0"}, {"1","1","0"}, {"-1","1","0"} };
+ const char* tx[4][2] = { {"0","0"}, {"1","0"}, {"1","1"}, {"0","1"} };
+ for (int i = 0; i < 4; i++) {
+ RUN("3D.MeshVertex", "quad", vx[i][0], vx[i][1], vx[i][2]);
+ RUN("3D.MeshUV", "quad", tx[i][0], tx[i][1]);
+ }
+ RUN("3D.MeshTri", "quad", "1", "2", "3");
+ RUN("3D.MeshTri", "quad", "1", "3", "4");
+ RUN("3D.MeshFinish", "quad");
+ RUN("3D.Camera", "0", "0", "4", "0", "0", "0");
+
+ TinyBlocks_Block* tb = tb_block_create(rt, tb_type_block_find(rt, "3D.Texture"));
+ TinyBlocks_Value nm = tb_value_text("cores");
+ tb_block_set_default(tb, 0, nm); tb_value_free(&nm);
+ TinyBlocks_Value iv = tb_value_image(tex);
+ tb_block_set_default(tb, 1, iv); tb_value_free(&iv);
+ tb_block_eval(tb, rt);
+ CHECK(!tinyblocks_last_error(rt)[0], "3D.Texture: cria a textura a partir de uma imagem");
+ RUN("3D.Material", "mat");
+ RUN("3D.MaterialAlbedo", "mat", "cores");
+ RUN("3D.MaterialUse", "mat", "quad");
+ CHECK(!tinyblocks_last_error(rt)[0], "3D.Material + albedo + use: sem erro");
+ const char* tsh = "[" BLK("Shader.Pixel", BLK0("Shader.Texture")) "]";
+ TinyBlocks_Block* st = compile_shader(tsh);
+ CHECK(st != NULL, "shader com \"textura do pixel\" compila");
+ if (st) {
+ TinyBlocks_Block* g = run_with_shader("3D.ShaderGlsl", st, NULL);
+ CHECK(g->outputs[0].kind == TB_VALUE_TEXT && strstr(g->outputs[0].as.text, "tex"),
+ "o GLSL gerado usa a textura do pixel");
+ }
+ tb_image_release(tex);
+
+ TinyBlocks_Image* ti = render_with("software");
+ CHECK(ti != NULL, "o objeto com textura desenha");
+ if (ti) {
+ uint8_t l[4], r[4];
+ tb_image_get_pixel(ti, 125, 120, &l[0], &l[1], &l[2], &l[3]);
+ tb_image_get_pixel(ti, 195, 120, &r[0], &r[1], &r[2], &r[3]);
+ printf(" textura: esquerda rgb=(%d,%d,%d) direita rgb=(%d,%d,%d)\n", l[0], l[1], l[2], r[0], r[1], r[2]);
+ CHECK(l[0] > 80 && l[0] > 2 * l[2] && r[2] > 80 && r[2] > 2 * r[0],
+ "o albedo pinta a esquerda de vermelho e a direita de azul");
+ for (int i = 0; i < 2; i++) {
+ const char* lib = i ? "tinyblocks-vk" : "tinyblocks-gl";
+ if (!tb_rt_find_library(rt, lib)) continue;
+ TinyBlocks_Image* gi = render_with(gpu[i]);
+ TinyBlocks_Block* gr = RUN("3D.Renderer", NULL);
+ const char* used = gr->outputs[0].kind == TB_VALUE_TEXT ? gr->outputs[0].as.text : "";
+ if (strncmp(used, gpu[i], strlen(gpu[i])) != 0) { tb_image_release(gi); continue; }
+ double mean = 0, bad = 1;
+ if (gi) compare(ti, gi, &mean, &bad);
+ printf(" textura %s x software: diferença média %.3f, pixels muito diferentes %.2f%%\n", gpu[i], mean, bad * 100);
+ char m[96];
+ snprintf(m, sizeof(m), "a textura desenha igual no %s", gpu[i]);
+ CHECK(gi && mean < 4.0 && bad < 0.02, m);
+ tb_image_release(gi);
+ }
+ }
+ tb_image_release(ti);
+ }
tb_image_release(sw);
tinyblocks_deinit(&rt);
if (fails) printf("\n%d FALHA(S)\n", fails);