diff --git a/docs/blocos.md b/docs/blocos.md
index 3609a63..eb01955 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: 424 tipos em 40 libraries.
+Total: 425 tipos em 40 libraries.
## Índice
@@ -48,7 +48,7 @@ Total: 424 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") - 32 blocos
+- [tinyblocks-3d](#tinyblocks-3d) (categoria "3D") - 33 blocos
- [tinyblocks-shader](#tinyblocks-shader) (categoria "Shader") - 18 blocos
- [tinyblocks-toml](#tinyblocks-toml) (categoria "TOML") - 1 bloco
- [tinyblocks-json](#tinyblocks-json) (categoria "JSON") - 2 blocos
@@ -521,6 +521,7 @@ Categoria na paleta: **3D**.
| Tipo | Rótulo no editor | Forma | Entradas | Saídas | Descrição |
|---|---|---|---|---|---|
+| `3D._Shader` | | comando | - | - | _(escondido)_ |
| `3D.Scene` | nova cena 3D | comando | - | - | Apaga os objetos e volta câmera, luz e céu ao padrão |
| `3D.Cube` | crie cubo (a) em x (b) y (c) z (d)
padrões: `jogador\|0\|0.5\|0` | comando | `a` (texto), `b` (real), `c` (real), `d` (real) | - | Cubo de lado 1 com esse nome (troca se já existir) |
| `3D.Sphere` | crie esfera (a) em x (b) y (c) z (d)
padrões: `bola\|0\|0.5\|0` | comando | `a` (texto), `b` (real), `c` (real), `d` (real) | - | Esfera de diâmetro 1 |
@@ -550,9 +551,9 @@ Categoria na paleta: **3D**.
| `3D.Use` | use o renderizador (a)
padrões: `automático` | comando | `a` (texto) | - | vulkan, opengl, software ou automático |
| `3D.Renderer` | renderizador da cena | repórter | - | `texto` (texto) | Quem desenhou o último quadro (e em qual placa) |
| `3D.Count` | número de objetos 3D | repórter | - | `valor` (inteiro) | Quantos objetos a cena tem |
-| `3D.ShaderCompile` | compile o shader (a) com (b)
padrões: `ondas\|` | comando | `a` (texto), `b` (json) | - | Compila a pilha de blocos de Shader encaixada (não executa: lê os blocos) |
-| `3D.ShaderUse` | use o shader (a) no objeto (b)
padrões: `ondas\|chão` | comando | `a` (texto), `b` (texto) | - | O objeto passa a ser pintado pelo shader ("nenhum" volta ao normal) |
-| `3D.ShaderGlsl` | GLSL do shader (a)
padrões: `ondas` | repórter | `a` (texto) | `texto` (texto) | O código GLSL que o shader virou (para ver ou estudar) |
+| `3D.Shader` | compile o shader (a) | repórter | `a` (json) | `shader` (bloco) | Compila a pilha de blocos de Shader encaixada (não a executa) e devolve o shader compilado, com o binário de cada renderizador |
+| `3D.ShaderUse` | use o shader (a) no objeto (b)
padrões: `\|chão` | comando | `a` (qualquer), `b` (texto) | - | O objeto passa a ser pintado pelo shader (vazio ou "nenhum" volta ao normal) |
+| `3D.ShaderGlsl` | GLSL do shader (a) | repórter | `a` (qualquer) | `texto` (texto) | O código GLSL que o shader virou (para ver ou estudar) |
## tinyblocks-shader
diff --git a/docs/editor.md b/docs/editor.md
index 74ec6ba..843e927 100644
--- a/docs/editor.md
+++ b/docs/editor.md
@@ -314,8 +314,9 @@ Ao arrastar, comandos encaixam no topo de um encaixe de pilha
(`SN_STACK`, também em repórteres) e repórteres não entram nele. O MCP
coloca um comando num encaixe de pilha com `into` + `input`. Na notação do
fórum, o encaixe de pilha de um comando vem nas linhas de baixo, indentado e
-fechado com `end`, como um bloco C (`TB_SB_SLOT_STACK`); um repórter com
-encaixe de pilha dentro de outro bloco não tem notação.
+fechado com `end`, como um bloco C (`TB_SB_SLOT_STACK`); vale também para
+um repórter com encaixe de pilha dentro do bloco da linha (`mude [s v] para
+(compile o shader)` + a pilha + `end`).
Os repórteres "código de (...)" e "código da pilha (...)" (Controle) só
devolvem o que receberam: servem para ver o código como dado.
diff --git a/docs/ferramentas/api_desc.py b/docs/ferramentas/api_desc.py
index 0d96a1f..91eccc5 100644
--- a/docs/ferramentas/api_desc.py
+++ b/docs/ferramentas/api_desc.py
@@ -627,7 +627,7 @@ D = {
# -- encaixes e shaders
"TB_SLOT_CODE": "Encaixe de bloco: a entrada recebe o código (JSON) do bloco encaixado, sem executá-lo.",
"TB_SLOT_STACK": "Encaixe de pilha de comandos (implica CODE): recebe a lista dos comandos.",
-"Tb3dShader": "Shader feito com blocos: id estável, versão (muda a cada compilação) e a função GLSL tb_shade.",
+"Tb3dShader": "Shader compilado (o valor de \"compile o shader\"): id único, a função GLSL tb_shade e os binários de cada renderizador.",
"tb_shader_get_library": "Descritor da tinyblocks-shader (o vocabulário dos shaders).",
"D3Program": "Shader compilado (opaco): nós com tipo, locais e o GLSL gerado.",
"D3Pixel": "Entradas de um pixel para o interpretador: ponto, normal, cor do objeto, luz e tempo.",
@@ -639,4 +639,6 @@ D = {
"TB_SB_SLOT_STACK": "Campo que é um encaixe de pilha: na notação, a pilha vem nas linhas de baixo, até o end.",
"slot_is_code": "O campo i é um encaixe de bloco (TB_SLOT_CODE ou TB_SLOT_STACK)?",
"slot_is_stack": "O campo i é um encaixe de pilha (fica numa faixa abaixo do rótulo)?",
+"Tb3dBinary": "Binário de um shader para um renderizador (nome dele, dados com malloc, tamanho); o formato só o renderizador conhece.",
+"TB_3D_MAX_BINARIES": "Quantos binários (renderizadores) um shader compilado guarda.",
}
diff --git a/docs/libraries.md b/docs/libraries.md
index 8d39919..ace4bf4 100644
--- a/docs/libraries.md
+++ b/docs/libraries.md
@@ -266,18 +266,24 @@ vocabulário (blocos que, fora de um shader, dão erro), e o compilador da 3d
### Shaders feitos com blocos
```
-pilha (JSON) -> d3_shader_compile -> nós com tipo (número, cor, condição)
- |-> GLSL "vec3 tb_shade(P, N, base, light, time)"
- | OpenGL: compila direto (um programa por shader)
- | Vulkan: libshaderc (dlopen) -> SPIR-V -> pipeline
- `-> interpretador (software, pixel a pixel)
+"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)
+ |-> GLSL "vec3 tb_shade(P, N, base, light, time)"
+ | -> Tb3dRenderer.compile de cada backend disponível:
+ | vk: monta o fragment 450 e gera SPIR-V (libshaderc, dlopen)
+ | gl: liga o programa e devolve o binário do driver (glGetProgramBinary)
+ `-> interpretador (o renderizador em software, pixel a pixel)
+ = o shader compilado: um bloco-handle (valor), com referências contadas
```
-O `Tb3dDraw` leva o `Tb3dShader` (id estável, versão e o GLSL); o
-renderizador recompila quando a versão muda. Um renderizador que não aceita
-shaders (`shaders()` falso: Vulkan sem a 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.
+A 3d não sabe o formato de nenhum binário: guarda cada um com o nome do
+renderizador (`Tb3dBinary`) e os entrega no `Tb3dDraw.shader`. Cada
+backend procura o seu; sem ele (o backend apareceu depois, ou o driver
+recusou o binário), compila a partir do GLSL na hora de desenhar. Um
+renderizador que não aceita shaders (`shaders()` falso: Vulkan sem a
+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.
### O caminho inverso: renderizadores da 3D
diff --git a/docs/pendencias.md b/docs/pendencias.md
index 36cda8c..3bf53e7 100644
--- a/docs/pendencias.md
+++ b/docs/pendencias.md
@@ -118,8 +118,9 @@ de uma palavra (`tecla %1 pressionada?`) funciona. A 3d usa
Os shaders feitos com blocos mudam a cor do pixel (fragment); ainda não há
shader de vértice (deformar a malha), texturas nem luz por pixel nos objetos
-sem shader (estes usam luz por vértice). Um repórter com encaixe de pilha
-("código da pilha") dentro de outro bloco não tem notação do fórum.
+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).
### Campo de texto de um bloco corta em 63 caracteres
diff --git a/docs/referencia-api.md b/docs/referencia-api.md
index 0b97e64..bbaab94 100644
--- a/docs/referencia-api.md
+++ b/docs/referencia-api.md
@@ -1093,9 +1093,11 @@ 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` = `2` | Versão do contrato Tb3dRenderer (quem publica confere). |
+| `#define TB_3D_RENDERER_VERSION` = `3` | Versão do contrato Tb3dRenderer (quem publica confere). |
| tipo `struct Tb3dMesh` | Malha: triangulos com posicao e normal (6 floats por vertice). As malhas da cena sao fixas (cubo, esfera, plano e cilindro de tamanho 1): o renderizador pode guarda-las na GPU pelo id. |
-| tipo `struct Tb3dShader` | Shader compilado ("compile o shader [nome] com [pilha]"): o corpo de uma funcao GLSL que o renderizador poe no fragment shader: vec3 tb_shade(vec3 P, vec3 N, vec3 base, float light, float time) P = ponto no mundo, N = normal (normalizada), base = cor do objeto, light = ambiente + (1 - ambiente) * max(N . luz, 0), time = segundos. Devolve a cor do pixel (0..1). id fica igual enquanto o nome existir; version muda a cada compilacao (o renderizador recompila). |
+| `#define TB_3D_MAX_BINARIES` = `4` | 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. vec3 tb_shade(vec3 P, vec3 N, vec3 base, float light, float time) P = ponto no mundo, N = normal (normalizada), base = cor do objeto, light = ambiente + (1 - ambiente) * max(N . luz, 0), time = segundos; devolve a cor do pixel (0..1). id e unico por compilacao (o renderizador guarda o programa da placa por ele) e vale enquanto alguem usar o shader. |
+| 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 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/jogo-3d/README.md b/examples/jogo-3d/README.md
index 8ee4818..c1a7088 100644
--- a/examples/jogo-3d/README.md
+++ b/examples/jogo-3d/README.md
@@ -34,18 +34,27 @@ O segundo exemplo pinta os objetos com **shaders escritos em blocos**:
ondas que andam no chão e listras na bola.
```
-compile o shader [ondas] com
+mude [ondas v] para (compile o shader)
mude [onda v] para (seno de (((x do ponto) * (40)) + ((tempo) * (120))))
cor do pixel = (misture (cor [azul]) com (cor [ciano]) por (((onda) + (1)) / (2)))
cor do pixel = ((cor do pixel) * (luz))
end
-use o shader [ondas] no objeto [chão]
+use o shader (ondas) no objeto [chão]
```
-O "compile o shader" tem um **encaixe de pilha** (a cavidade escura em
-forma de comando): a pilha encaixada não roda; o bloco recebe o código dela
-e o traduz para GLSL (OpenGL e Vulkan) ou para o interpretador do
-renderizador em software. Os blocos da categoria **Shader** (`cor do
-pixel`, `luz`, `tempo`, `x do ponto`, `misture`...) só têm sentido ali; as
-contas, o "se" e as variáveis comuns também valem (as variáveis viram
-locais do shader). O bloco `GLSL do shader [ondas]` mostra o código gerado.
+"compile o shader" é um repórter com um **encaixe de pilha** (a cavidade
+escura em forma de comando): a pilha encaixada não roda; o bloco lê o
+código dela e devolve o **shader compilado**, um valor que se guarda numa
+variável como qualquer outro. O valor leva o binário de cada renderizador
+disponível (Vulkan: SPIR-V; OpenGL: o programa como o driver o devolve) e
+o necessário para o renderizador em software; o monitor mostra, por
+exemplo, "shader compilado (vulkan: 2940 bytes, opengl: 10953 bytes)".
+
+Os blocos da categoria **Shader** (`cor do pixel`, `luz`, `tempo`, `x do
+ponto`, `misture`...) só têm sentido ali; as contas, o "se" e as variáveis
+comuns também valem (as variáveis viram locais do shader). `GLSL do shader
+(ondas)` mostra o código gerado.
+
+Na notação do fórum, a pilha de um encaixe vem nas linhas de baixo,
+indentada e fechada com `end`, mesmo quando o bloco com o encaixe está
+dentro de outro (como o "compile o shader" dentro do "mude").
diff --git a/examples/jogo-3d/shaders.json b/examples/jogo-3d/shaders.json
index 226ff08..648a456 100644
--- a/examples/jogo-3d/shaders.json
+++ b/examples/jogo-3d/shaders.json
@@ -689,12 +689,12 @@
},
{
"i": 7,
- "type": "3D.ShaderCompile",
+ "type": "Variables.Set",
"x": 0,
"y": 0,
"parent": 6,
"prel": 0,
- "next": 26,
+ "next": 27,
"sub": [
-1,
-1,
@@ -740,12 +740,63 @@
},
{
"i": 8,
- "type": "Variables.Set",
+ "type": "3D.Shader",
"x": 0,
"y": 0,
"parent": 7,
"prel": 5,
- "next": 15,
+ "next": -1,
+ "sub": [
+ -1,
+ -1,
+ -1
+ ],
+ "args": [
+ 9,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1
+ ],
+ "in_text": [
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ ""
+ ],
+ "lit": ""
+ },
+ {
+ "i": 9,
+ "type": "Variables.Set",
+ "x": 0,
+ "y": 0,
+ "parent": 8,
+ "prel": 4,
+ "next": 16,
"sub": [
-1,
-1,
@@ -753,7 +804,7 @@
],
"args": [
-1,
- 9,
+ 10,
-1,
-1,
-1,
@@ -790,11 +841,11 @@
"lit": ""
},
{
- "i": 9,
+ "i": 10,
"type": "Number.Sin",
"x": 0,
"y": 0,
- "parent": 8,
+ "parent": 9,
"prel": 5,
"next": -1,
"sub": [
@@ -802,60 +853,9 @@
-1,
-1
],
- "args": [
- 10,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1
- ],
- "in_text": [
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- ""
- ],
- "lit": ""
- },
- {
- "i": 10,
- "type": "Math.Add",
- "x": 0,
- "y": 0,
- "parent": 9,
- "prel": 4,
- "next": -1,
- "sub": [
- -1,
- -1,
- -1
- ],
"args": [
11,
- 13,
+ -1,
-1,
-1,
-1,
@@ -893,7 +893,7 @@
},
{
"i": 11,
- "type": "Math.Mul",
+ "type": "Math.Add",
"x": 0,
"y": 0,
"parent": 10,
@@ -906,6 +906,57 @@
],
"args": [
12,
+ 14,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1
+ ],
+ "in_text": [
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ ""
+ ],
+ "lit": ""
+ },
+ {
+ "i": 12,
+ "type": "Math.Mul",
+ "x": 0,
+ "y": 0,
+ "parent": 11,
+ "prel": 4,
+ "next": -1,
+ "sub": [
+ -1,
+ -1,
+ -1
+ ],
+ "args": [
+ 13,
-1,
-1,
-1,
@@ -943,11 +994,11 @@
"lit": ""
},
{
- "i": 12,
+ "i": 13,
"type": "Shader.X",
"x": 0,
"y": 0,
- "parent": 11,
+ "parent": 12,
"prel": 4,
"next": -1,
"sub": [
@@ -994,11 +1045,11 @@
"lit": ""
},
{
- "i": 13,
+ "i": 14,
"type": "Math.Mul",
"x": 0,
"y": 0,
- "parent": 10,
+ "parent": 11,
"prel": 5,
"next": -1,
"sub": [
@@ -1007,7 +1058,7 @@
-1
],
"args": [
- 14,
+ 15,
-1,
-1,
-1,
@@ -1045,11 +1096,11 @@
"lit": ""
},
{
- "i": 14,
+ "i": 15,
"type": "Shader.Time",
"x": 0,
"y": 0,
- "parent": 13,
+ "parent": 14,
"prel": 4,
"next": -1,
"sub": [
@@ -1095,65 +1146,14 @@
],
"lit": ""
},
- {
- "i": 15,
- "type": "Shader.Pixel",
- "x": 0,
- "y": 0,
- "parent": 8,
- "prel": 0,
- "next": 22,
- "sub": [
- -1,
- -1,
- -1
- ],
- "args": [
- 16,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1
- ],
- "in_text": [
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- ""
- ],
- "lit": ""
- },
{
"i": 16,
- "type": "Shader.Mix",
+ "type": "Shader.Pixel",
"x": 0,
"y": 0,
- "parent": 15,
- "prel": 4,
- "next": -1,
+ "parent": 9,
+ "prel": 0,
+ "next": 23,
"sub": [
-1,
-1,
@@ -1161,8 +1161,8 @@
],
"args": [
17,
- 18,
- 19,
+ -1,
+ -1,
-1,
-1,
-1,
@@ -1199,7 +1199,7 @@
},
{
"i": 17,
- "type": "Shader.Color",
+ "type": "Shader.Mix",
"x": 0,
"y": 0,
"parent": 16,
@@ -1210,6 +1210,57 @@
-1,
-1
],
+ "args": [
+ 18,
+ 19,
+ 20,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1
+ ],
+ "in_text": [
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ ""
+ ],
+ "lit": ""
+ },
+ {
+ "i": 18,
+ "type": "Shader.Color",
+ "x": 0,
+ "y": 0,
+ "parent": 17,
+ "prel": 4,
+ "next": -1,
+ "sub": [
+ -1,
+ -1,
+ -1
+ ],
"args": [
-1,
-1,
@@ -1249,11 +1300,11 @@
"lit": ""
},
{
- "i": 18,
+ "i": 19,
"type": "Shader.Color",
"x": 0,
"y": 0,
- "parent": 16,
+ "parent": 17,
"prel": 5,
"next": -1,
"sub": [
@@ -1300,11 +1351,11 @@
"lit": ""
},
{
- "i": 19,
+ "i": 20,
"type": "Number.Div",
"x": 0,
"y": 0,
- "parent": 16,
+ "parent": 17,
"prel": 6,
"next": -1,
"sub": [
@@ -1313,7 +1364,7 @@
-1
],
"args": [
- 20,
+ 21,
-1,
-1,
-1,
@@ -1351,11 +1402,11 @@
"lit": ""
},
{
- "i": 20,
+ "i": 21,
"type": "Math.Add",
"x": 0,
"y": 0,
- "parent": 19,
+ "parent": 20,
"prel": 4,
"next": -1,
"sub": [
@@ -1364,7 +1415,7 @@
-1
],
"args": [
- 21,
+ 22,
-1,
-1,
-1,
@@ -1402,11 +1453,11 @@
"lit": ""
},
{
- "i": 21,
+ "i": 22,
"type": "Variables.Get",
"x": 0,
"y": 0,
- "parent": 20,
+ "parent": 21,
"prel": 4,
"next": -1,
"sub": [
@@ -1453,11 +1504,11 @@
"lit": ""
},
{
- "i": 22,
+ "i": 23,
"type": "Shader.Pixel",
"x": 0,
"y": 0,
- "parent": 15,
+ "parent": 16,
"prel": 0,
"next": -1,
"sub": [
@@ -1465,60 +1516,9 @@
-1,
-1
],
- "args": [
- 23,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1
- ],
- "in_text": [
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- ""
- ],
- "lit": ""
- },
- {
- "i": 23,
- "type": "Math.Mul",
- "x": 0,
- "y": 0,
- "parent": 22,
- "prel": 4,
- "next": -1,
- "sub": [
- -1,
- -1,
- -1
- ],
"args": [
24,
- 25,
+ -1,
-1,
-1,
-1,
@@ -1556,7 +1556,7 @@
},
{
"i": 24,
- "type": "Shader.PixelColor",
+ "type": "Math.Mul",
"x": 0,
"y": 0,
"parent": 23,
@@ -1568,8 +1568,8 @@
-1
],
"args": [
- -1,
- -1,
+ 25,
+ 26,
-1,
-1,
-1,
@@ -1607,11 +1607,11 @@
},
{
"i": 25,
- "type": "Shader.Light",
+ "type": "Shader.PixelColor",
"x": 0,
"y": 0,
- "parent": 23,
- "prel": 5,
+ "parent": 24,
+ "prel": 4,
"next": -1,
"sub": [
-1,
@@ -1658,12 +1658,12 @@
},
{
"i": 26,
- "type": "3D.ShaderCompile",
+ "type": "Shader.Light",
"x": 0,
"y": 0,
- "parent": 7,
- "prel": 0,
- "next": 40,
+ "parent": 24,
+ "prel": 5,
+ "next": -1,
"sub": [
-1,
-1,
@@ -1671,7 +1671,58 @@
],
"args": [
-1,
- 27,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1
+ ],
+ "in_text": [
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ ""
+ ],
+ "lit": ""
+ },
+ {
+ "i": 27,
+ "type": "Variables.Set",
+ "x": 0,
+ "y": 0,
+ "parent": 7,
+ "prel": 0,
+ "next": 42,
+ "sub": [
+ -1,
+ -1,
+ -1
+ ],
+ "args": [
+ -1,
+ 28,
-1,
-1,
-1,
@@ -1708,20 +1759,20 @@
"lit": ""
},
{
- "i": 27,
- "type": "Control.IfElse",
+ "i": 28,
+ "type": "3D.Shader",
"x": 0,
"y": 0,
- "parent": 26,
+ "parent": 27,
"prel": 5,
"next": -1,
"sub": [
- 32,
- 36,
+ -1,
+ -1,
-1
],
"args": [
- 28,
+ 29,
-1,
-1,
-1,
@@ -1759,11 +1810,62 @@
"lit": ""
},
{
- "i": 28,
+ "i": 29,
+ "type": "Control.IfElse",
+ "x": 0,
+ "y": 0,
+ "parent": 28,
+ "prel": 4,
+ "next": -1,
+ "sub": [
+ 34,
+ 38,
+ -1
+ ],
+ "args": [
+ 30,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1
+ ],
+ "in_text": [
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ ""
+ ],
+ "lit": ""
+ },
+ {
+ "i": 30,
"type": "Operators.Eq",
"x": 0,
"y": 0,
- "parent": 27,
+ "parent": 29,
"prel": 4,
"next": -1,
"sub": [
@@ -1772,7 +1874,7 @@
-1
],
"args": [
- 29,
+ 31,
-1,
-1,
-1,
@@ -1810,11 +1912,11 @@
"lit": ""
},
{
- "i": 29,
+ "i": 31,
"type": "Math.Mod",
"x": 0,
"y": 0,
- "parent": 28,
+ "parent": 30,
"prel": 4,
"next": -1,
"sub": [
@@ -1823,7 +1925,7 @@
-1
],
"args": [
- 30,
+ 32,
-1,
-1,
-1,
@@ -1861,11 +1963,11 @@
"lit": ""
},
{
- "i": 30,
+ "i": 32,
"type": "Number.Floor",
"x": 0,
"y": 0,
- "parent": 29,
+ "parent": 31,
"prel": 4,
"next": -1,
"sub": [
@@ -1873,108 +1975,6 @@
-1,
-1
],
- "args": [
- 31,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1
- ],
- "in_text": [
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- ""
- ],
- "lit": ""
- },
- {
- "i": 31,
- "type": "Shader.Y",
- "x": 0,
- "y": 0,
- "parent": 30,
- "prel": 4,
- "next": -1,
- "sub": [
- -1,
- -1,
- -1
- ],
- "args": [
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1
- ],
- "in_text": [
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- ""
- ],
- "lit": ""
- },
- {
- "i": 32,
- "type": "Shader.Pixel",
- "x": 0,
- "y": 0,
- "parent": 27,
- "prel": 1,
- "next": -1,
- "sub": [
- -1,
- -1,
- -1
- ],
"args": [
33,
-1,
@@ -2015,7 +2015,7 @@
},
{
"i": 33,
- "type": "Math.Mul",
+ "type": "Shader.Y",
"x": 0,
"y": 0,
"parent": 32,
@@ -2027,8 +2027,8 @@
-1
],
"args": [
- 34,
- 35,
+ -1,
+ -1,
-1,
-1,
-1,
@@ -2066,10 +2066,112 @@
},
{
"i": 34,
+ "type": "Shader.Pixel",
+ "x": 0,
+ "y": 0,
+ "parent": 29,
+ "prel": 1,
+ "next": -1,
+ "sub": [
+ -1,
+ -1,
+ -1
+ ],
+ "args": [
+ 35,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1
+ ],
+ "in_text": [
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ ""
+ ],
+ "lit": ""
+ },
+ {
+ "i": 35,
+ "type": "Math.Mul",
+ "x": 0,
+ "y": 0,
+ "parent": 34,
+ "prel": 4,
+ "next": -1,
+ "sub": [
+ -1,
+ -1,
+ -1
+ ],
+ "args": [
+ 36,
+ 37,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1
+ ],
+ "in_text": [
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ ""
+ ],
+ "lit": ""
+ },
+ {
+ "i": 36,
"type": "Shader.Color",
"x": 0,
"y": 0,
- "parent": 33,
+ "parent": 35,
"prel": 4,
"next": -1,
"sub": [
@@ -2116,11 +2218,11 @@
"lit": ""
},
{
- "i": 35,
+ "i": 37,
"type": "Shader.Light",
"x": 0,
"y": 0,
- "parent": 33,
+ "parent": 35,
"prel": 5,
"next": -1,
"sub": [
@@ -2167,11 +2269,11 @@
"lit": ""
},
{
- "i": 36,
+ "i": 38,
"type": "Shader.Pixel",
"x": 0,
"y": 0,
- "parent": 27,
+ "parent": 29,
"prel": 2,
"next": -1,
"sub": [
@@ -2180,58 +2282,6 @@
-1
],
"args": [
- 37,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1,
- -1
- ],
- "in_text": [
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- "",
- ""
- ],
- "lit": ""
- },
- {
- "i": 37,
- "type": "Math.Mul",
- "x": 0,
- "y": 0,
- "parent": 36,
- "prel": 4,
- "next": -1,
- "sub": [
- -1,
- -1,
- -1
- ],
- "args": [
- 38,
39,
-1,
-1,
@@ -2246,6 +2296,7 @@
-1,
-1,
-1,
+ -1,
-1
],
"in_text": [
@@ -2269,11 +2320,62 @@
"lit": ""
},
{
- "i": 38,
+ "i": 39,
+ "type": "Math.Mul",
+ "x": 0,
+ "y": 0,
+ "parent": 38,
+ "prel": 4,
+ "next": -1,
+ "sub": [
+ -1,
+ -1,
+ -1
+ ],
+ "args": [
+ 40,
+ 41,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1
+ ],
+ "in_text": [
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ ""
+ ],
+ "lit": ""
+ },
+ {
+ "i": 40,
"type": "Shader.Color",
"x": 0,
"y": 0,
- "parent": 37,
+ "parent": 39,
"prel": 4,
"next": -1,
"sub": [
@@ -2320,11 +2422,11 @@
"lit": ""
},
{
- "i": 39,
+ "i": 41,
"type": "Shader.Light",
"x": 0,
"y": 0,
- "parent": 37,
+ "parent": 39,
"prel": 5,
"next": -1,
"sub": [
@@ -2371,13 +2473,64 @@
"lit": ""
},
{
- "i": 40,
- "type": "3D.ShaderUse",
+ "i": 42,
+ "type": "IO.Print",
"x": 0,
"y": 0,
- "parent": 26,
+ "parent": 27,
"prel": 0,
- "next": 41,
+ "next": 44,
+ "sub": [
+ -1,
+ -1,
+ -1
+ ],
+ "args": [
+ -1,
+ 43,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1
+ ],
+ "in_text": [
+ "ondas",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ ""
+ ],
+ "lit": ""
+ },
+ {
+ "i": 43,
+ "type": "Variables.Get",
+ "x": 0,
+ "y": 0,
+ "parent": 42,
+ "prel": 5,
+ "next": -1,
"sub": [
-1,
-1,
@@ -2403,6 +2556,57 @@
],
"in_text": [
"ondas",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ ""
+ ],
+ "lit": ""
+ },
+ {
+ "i": 44,
+ "type": "3D.ShaderUse",
+ "x": 0,
+ "y": 0,
+ "parent": 42,
+ "prel": 0,
+ "next": 46,
+ "sub": [
+ -1,
+ -1,
+ -1
+ ],
+ "args": [
+ 45,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1
+ ],
+ "in_text": [
+ "",
"chão",
"",
"",
@@ -2422,13 +2626,115 @@
"lit": ""
},
{
- "i": 41,
+ "i": 45,
+ "type": "Variables.Get",
+ "x": 0,
+ "y": 0,
+ "parent": 44,
+ "prel": 4,
+ "next": -1,
+ "sub": [
+ -1,
+ -1,
+ -1
+ ],
+ "args": [
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1
+ ],
+ "in_text": [
+ "ondas",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ ""
+ ],
+ "lit": ""
+ },
+ {
+ "i": 46,
"type": "3D.ShaderUse",
"x": 0,
"y": 0,
- "parent": 40,
+ "parent": 44,
"prel": 0,
- "next": 42,
+ "next": 48,
+ "sub": [
+ -1,
+ -1,
+ -1
+ ],
+ "args": [
+ 47,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1,
+ -1
+ ],
+ "in_text": [
+ "",
+ "bola",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ "",
+ ""
+ ],
+ "lit": ""
+ },
+ {
+ "i": 47,
+ "type": "Variables.Get",
+ "x": 0,
+ "y": 0,
+ "parent": 46,
+ "prel": 4,
+ "next": -1,
"sub": [
-1,
-1,
@@ -2454,7 +2760,7 @@
],
"in_text": [
"listras",
- "bola",
+ "",
"",
"",
"",
@@ -2473,15 +2779,15 @@
"lit": ""
},
{
- "i": 42,
+ "i": 48,
"type": "Control.Forever",
"x": 0,
"y": 0,
- "parent": 41,
+ "parent": 46,
"prel": 0,
"next": -1,
"sub": [
- 43,
+ 49,
-1,
-1
],
@@ -2524,13 +2830,13 @@
"lit": ""
},
{
- "i": 43,
+ "i": 49,
"type": "3D.RotateBy",
"x": 0,
"y": 0,
- "parent": 42,
+ "parent": 48,
"prel": 1,
- "next": 44,
+ "next": 50,
"sub": [
-1,
-1,
@@ -2575,13 +2881,13 @@
"lit": ""
},
{
- "i": 44,
+ "i": 50,
"type": "Stage.Clear",
"x": 0,
"y": 0,
- "parent": 43,
+ "parent": 49,
"prel": 0,
- "next": 45,
+ "next": 51,
"sub": [
-1,
-1,
@@ -2626,20 +2932,20 @@
"lit": ""
},
{
- "i": 45,
+ "i": 51,
"type": "Stage.Draw",
"x": 0,
"y": 0,
- "parent": 44,
+ "parent": 50,
"prel": 0,
- "next": 47,
+ "next": 53,
"sub": [
-1,
-1,
-1
],
"args": [
- 46,
+ 52,
-1,
-1,
-1,
@@ -2677,11 +2983,11 @@
"lit": ""
},
{
- "i": 46,
+ "i": 52,
"type": "3D.Image",
"x": 0,
"y": 0,
- "parent": 45,
+ "parent": 51,
"prel": 4,
"next": -1,
"sub": [
@@ -2728,11 +3034,11 @@
"lit": ""
},
{
- "i": 47,
+ "i": 53,
"type": "Stage.Text",
"x": 0,
"y": 0,
- "parent": 45,
+ "parent": 51,
"prel": 0,
"next": -1,
"sub": [
@@ -2741,7 +3047,7 @@
-1
],
"args": [
- 48,
+ 54,
-1,
-1,
-1,
@@ -2779,11 +3085,11 @@
"lit": ""
},
{
- "i": 48,
+ "i": 54,
"type": "3D.Renderer",
"x": 0,
"y": 0,
- "parent": 47,
+ "parent": 53,
"prel": 4,
"next": -1,
"sub": [
@@ -2836,5 +3142,18 @@
}
],
"user_blocks": [],
- "variables": []
+ "variables": [
+ {
+ "name": "ondas",
+ "kind": 0,
+ "num": 0,
+ "text": ""
+ },
+ {
+ "name": "listras",
+ "kind": 0,
+ "num": 0,
+ "text": ""
+ }
+ ]
}
diff --git a/examples/jogo-3d/shaders.sb b/examples/jogo-3d/shaders.sb
index cb8b211..cfa10b9 100644
--- a/examples/jogo-3d/shaders.sb
+++ b/examples/jogo-3d/shaders.sb
@@ -5,20 +5,21 @@ mude o tamanho de [chão] para x (20) y (1) z (20)
crie esfera [bola] em x (0) y (1.5) z (0)
mude o tamanho de [bola] para x (3) y (3) z (3)
câmera em x (0) y (6) z (10) olhando para x (0) y (1) z (0)
-compile o shader [ondas] com
+mude [ondas v] para (compile o shader)
mude [onda v] para (seno de (((x do ponto) * (40)) + ((tempo) * (120))))
cor do pixel = (misture (cor [azul]) com (cor [ciano]) por (((onda) + (1)) / (2)))
cor do pixel = ((cor do pixel) * (luz))
end
-compile o shader [listras] com
+mude [listras v] para (compile o shader)
se <(resto de (arredonde (y do ponto) para baixo) por (2)) = (0)> então
cor do pixel = ((cor [vermelho]) * (luz))
senão
cor do pixel = ((cor [branco]) * (luz))
end
end
-use o shader [ondas] no objeto [chão]
-use o shader [listras] no objeto [bola]
+escreva [ondas] (ondas)
+use o shader (ondas) no objeto [chão]
+use o shader (listras) no objeto [bola]
sempre
gire [bola] por x (0) y (2) z (0) graus
apague tudo
diff --git a/libraries/tinyblocks-3d/include/tb_3d.h b/libraries/tinyblocks-3d/include/tb_3d.h
index b9c89b9..f977ba2 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 2
+#define TB_3D_RENDERER_VERSION 3
/* Malha: triangulos com posicao e normal (6 floats por vertice). As malhas
da cena sao fixas (cubo, esfera, plano e cilindro de tamanho 1): o
@@ -42,19 +42,33 @@ typedef struct Tb3dMesh {
int icount;
} Tb3dMesh;
-/* Shader compilado ("compile o shader [nome] com [pilha]"): o corpo de uma
- funcao GLSL que o renderizador poe no fragment shader:
+/* 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.
vec3 tb_shade(vec3 P, vec3 N, vec3 base, float light, float time)
P = ponto no mundo, N = normal (normalizada), base = cor do objeto,
- light = ambiente + (1 - ambiente) * max(N . luz, 0), time = segundos.
- Devolve a cor do pixel (0..1). id fica igual enquanto o nome existir;
- version muda a cada compilacao (o renderizador recompila). */
+ light = ambiente + (1 - ambiente) * max(N . luz, 0), time = segundos;
+ devolve a cor do pixel (0..1).
+
+ id e unico por compilacao (o renderizador guarda o programa da placa por
+ ele) e vale enquanto alguem usar o shader. */
+#define TB_3D_MAX_BINARIES 4
+typedef struct Tb3dBinary {
+ char renderer[16]; /* Tb3dRenderer.name de quem compilou */
+ void* data; /* malloc do renderizador; a 3d da free */
+ size_t size;
+} Tb3dBinary;
+
typedef struct Tb3dShader {
int id;
- int version;
- const char* glsl; /* a funcao tb_shade inteira (GLSL 330/450) */
+ int version; /* sempre 1 (cada compilacao tem outro id) */
+ const char* glsl;
+ Tb3dBinary bin[TB_3D_MAX_BINARIES];
+ int bin_n;
} Tb3dShader;
/* Um objeto a desenhar */
@@ -92,6 +106,10 @@ typedef struct Tb3dRenderer {
const char* (*error)(void); /* ultimo erro */
bool (*shaders)(void); /* desenha Tb3dDraw.shader? (false: a 3d
usa outro renderizador nesse quadro) */
+ /* 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);
} Tb3dRenderer;
TB_API const TinyBlocks_LibraryDescriptor* tb_3d_get_library(void);
diff --git a/libraries/tinyblocks-3d/src/tb_3d.c b/libraries/tinyblocks-3d/src/tb_3d.c
index 443ae03..824b9b8 100644
--- a/libraries/tinyblocks-3d/src/tb_3d.c
+++ b/libraries/tinyblocks-3d/src/tb_3d.c
@@ -196,14 +196,25 @@ typedef struct {
int kind;
float pos[3], rot[3], scale[3], color[4];
bool visible;
- int shader; /* indice em s_shd (-1 = luz padrao) */
+ struct Shd* shader; /* NULL = luz padrao */
} Obj;
-/* Shaders compilados, pelo nome ("compile o shader [nome] com [pilha]") */
-typedef struct { Tb3dShader pub; char name[48]; D3Program* prog; } Shd;
-#define MAX_SHADERS 64
-static Shd s_shd[MAX_SHADERS];
-static int s_shd_n;
+/* Shader compilado ("compile o shader [pilha]"): o valor que viaja num
+ bloco-handle; o handle e cada objeto que o usa guardam uma referencia. */
+typedef struct Shd {
+ Tb3dShader pub; /* primeiro: o renderizador ve so isto */
+ D3Program* prog; /* nos (interpretador do software) */
+ int refs;
+} Shd;
+static int s_shd_seq; /* ids unicos por compilacao */
+
+static Shd* shd_retain(Shd* s) { if (s) s->refs++; return s; }
+static void shd_release(Shd* s) {
+ if (!s || --s->refs > 0) return;
+ d3_shader_free(s->prog);
+ for (int i = 0; i < s->pub.bin_n; i++) free(s->pub.bin[i].data);
+ free(s);
+}
static double now_s(void) {
struct timespec ts;
@@ -223,6 +234,7 @@ static struct {
} S;
static void scene_reset(void) {
+ for (int i = 0; i < S.n; i++) shd_release(S.o[i].shader);
S.n = 0;
S.eye[0] = 0; S.eye[1] = 6; S.eye[2] = 10;
S.at[0] = S.at[1] = S.at[2] = 0;
@@ -318,7 +330,7 @@ static bool frame_build(Tb3dFrame* f, int w, int h) {
obj_matrices(o, d->model, d->normal);
tb_3d_mat_mul(d->mvp, f->viewproj, d->model);
memcpy(d->color, o->color, sizeof(d->color));
- d->shader = o->shader >= 0 && o->shader < s_shd_n && s_shd[o->shader].prog ? &s_shd[o->shader].pub : NULL;
+ d->shader = o->shader ? &o->shader->pub : NULL;
}
f->draws = s_draws;
f->draw_count = n;
@@ -462,7 +474,7 @@ static bool sw_render(const Tb3dFrame* f, uint8_t* px) {
cv = p; cv_cap = m->vcount;
}
for (int i = 0; i < m->vcount; i++) shade(f, d, m->verts + (size_t)i * 6, &cv[i]);
- s_prog = d->shader ? s_shd[d->shader->id - 1].prog : NULL; /* id = indice + 1 */
+ s_prog = d->shader ? ((const Shd*)d->shader)->prog : NULL; /* pub e o 1o campo */
s_frame = f;
memcpy(s_base, d->color, sizeof(s_base));
for (int t = 0; t + 2 < m->icount; t += 3) {
@@ -479,7 +491,8 @@ static bool sw_render(const Tb3dFrame* f, uint8_t* px) {
static bool sw_shaders(void) { return true; }
static const Tb3dRenderer s_software = {
- TB_3D_RENDERER_VERSION, "software", sw_available, sw_render, sw_device, sw_error, sw_shaders };
+ TB_3D_RENDERER_VERSION, "software", sw_available, sw_render, sw_device, sw_error, sw_shaders,
+ NULL /* interpreta os nos do proprio shader: sem binario */ };
const Tb3dRenderer* tb_3d_software_renderer(void) { return &s_software; }
@@ -544,7 +557,8 @@ static void create(TinyBlocks_Block* self, TinyBlocks* rt, int kind) {
if (kind == K_PLANE) { o->scale[0] = o->scale[2] = 10; }
o->color[0] = o->color[1] = o->color[2] = 0.8f; o->color[3] = 1;
o->visible = true;
- o->shader = -1;
+ shd_release(o->shader);
+ o->shader = NULL;
}
static void eval_cube(TinyBlocks_Block* s, TinyBlocks* rt) { create(s, rt, K_CUBE); }
static void eval_sphere(TinyBlocks_Block* s, TinyBlocks* rt) { create(s, rt, K_SPHERE); }
@@ -567,7 +581,12 @@ OBJ_CMD(eval_color, if (!d3_color_of(name_in(self, rt, 1), o->color))
static void eval_delete(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
Obj* o = find(name_in(self, rt, 0));
- if (o) { int i = (int)(o - S.o); memmove(o, o + 1, (size_t)(S.n - i - 1) * sizeof(*o)); S.n--; }
+ if (o) {
+ shd_release(o->shader);
+ int i = (int)(o - S.o);
+ memmove(o, o + 1, (size_t)(S.n - i - 1) * sizeof(*o));
+ S.n--;
+ }
}
static void coord(TinyBlocks_Block* self, TinyBlocks* rt, int axis) {
@@ -668,50 +687,119 @@ static void eval_image(TinyBlocks_Block* self, TinyBlocks* rt) {
tb_image_release(img);
}
-static int shader_find(const char* name) {
- for (int i = 0; i < s_shd_n; i++) if (!strcmp(s_shd[i].name, name)) return i;
- return -1;
+/* -- o bloco-handle do shader compilado --- */
+typedef struct { Shd* s; TinyBlocks_Block* owner; } ShdHandle;
+typedef struct { TinyBlocks_Block* handle; } ShdProducer;
+static TinyBlocks_TypeBlock* s_t_shader;
+
+static void shd_handle_deinit(TinyBlocks_Block* self, TinyBlocks* rt) {
+ (void)rt;
+ ShdHandle* h = self->userdata;
+ if (!h) return;
+ shd_release(h->s);
+ h->s = NULL;
+ if (h->owner && h->owner->userdata && ((ShdProducer*)h->owner->userdata)->handle == self)
+ ((ShdProducer*)h->owner->userdata)->handle = NULL;
}
-static void eval_shader_compile(TinyBlocks_Block* self, TinyBlocks* rt) {
- self->dirty = false;
- const char* nm = name_in(self, rt, 0);
- if (!nm[0]) { tinyblocks_set_error(rt, "dê um nome ao shader"); return; }
- TinyBlocks_Value v = tb_block_get_input(self, rt, 1);
- const TinyBlocks_JsonValue* code = v.kind == TB_VALUE_JSON ? v.as.json : NULL;
- char err[200];
- D3Program* prog = d3_shader_compile(code, err, sizeof(err));
- if (!prog) { tinyblocks_set_error(rt, "shader \"%s\": %s", nm, err); return; }
- int i = shader_find(nm);
- if (i < 0) {
- if (s_shd_n == MAX_SHADERS) { d3_shader_free(prog); tinyblocks_set_error(rt, "shaders demais (máximo %d)", MAX_SHADERS); return; }
- i = s_shd_n++;
- memset(&s_shd[i], 0, sizeof(s_shd[i]));
- snprintf(s_shd[i].name, sizeof(s_shd[i].name), "%s", nm);
- s_shd[i].pub.id = i + 1;
+static size_t shd_handle_text(TinyBlocks_Block* self, char* out, size_t cap) {
+ ShdHandle* h = self->userdata;
+ if (!h || !h->s) return (size_t)snprintf(out, cap, "shader vazio");
+ const Tb3dShader* p = &h->s->pub;
+ if (!p->bin_n) return (size_t)snprintf(out, cap, "shader compilado");
+ char buf[256]; /* o tamanho devolvido e o real, mesmo com cap 0 */
+ size_t n = (size_t)snprintf(buf, sizeof(buf), "shader compilado (");
+ for (int i = 0; i < p->bin_n && n < sizeof(buf); i++)
+ n += (size_t)snprintf(buf + n, sizeof(buf) - n, "%s%s: %zu bytes", i ? ", " : "", p->bin[i].renderer, p->bin[i].size);
+ if (n < sizeof(buf)) snprintf(buf + n, sizeof(buf) - n, ")");
+ return (size_t)snprintf(out, cap, "%s", buf);
+}
+
+static void shd_producer_deinit(TinyBlocks_Block* self, TinyBlocks* rt) {
+ ShdProducer* p = self->userdata;
+ if (p && p->handle) {
+ TinyBlocks_Block* h = p->handle;
+ p->handle = NULL;
+ ((ShdHandle*)h->userdata)->owner = NULL;
+ tb_block_destroy(h, rt);
}
- d3_shader_free(s_shd[i].prog);
- s_shd[i].prog = prog;
- s_shd[i].pub.glsl = d3_shader_glsl(prog);
- s_shd[i].pub.version++;
+}
+
+static Shd* shd_of(TinyBlocks_Value v) {
+ if (v.kind != TB_VALUE_BLOCK || !v.as.block || v.as.block->type != s_t_shader) return NULL;
+ ShdHandle* h = v.as.block->userdata;
+ return h ? h->s : NULL;
+}
+
+/* Pede o binario a cada renderizador disponivel (o formato e dele: a 3d so
+ guarda). Quem nao compila antes desenha a partir do GLSL. */
+static void shd_binaries(TinyBlocks* rt, Shd* sh) {
+ static const char* libs[] = { "tinyblocks-vk", "tinyblocks-gl" };
+ for (int i = 0; i < 2 && sh->pub.bin_n < TB_3D_MAX_BINARIES; i++) {
+ TinyBlocks_LibraryBlock* lib = tb_rt_find_library(rt, libs[i]);
+ const Tb3dRenderer* r = lib ? lib->lib_userdata : NULL;
+ if (!r || r->version != TB_3D_RENDERER_VERSION || !r->compile || !r->available() || !r->shaders()) continue;
+ Tb3dBinary* b = &sh->pub.bin[sh->pub.bin_n];
+ char err[200];
+ if (!r->compile(sh->pub.glsl, &b->data, &b->size, err, sizeof(err))) {
+ snprintf(S.err, sizeof(S.err), "%s: %.140s", r->name, err);
+ continue;
+ }
+ snprintf(b->renderer, sizeof(b->renderer), "%s", r->name);
+ sh->pub.bin_n++;
+ }
+}
+
+/* "compile o shader [pilha]": le o codigo da pilha (nao a executa) e
+ devolve o shader compilado: nos (software), GLSL e o binario de cada
+ renderizador */
+static void eval_shader(TinyBlocks_Block* self, TinyBlocks* rt) {
+ self->dirty = false;
+ TinyBlocks_Value v = tb_block_get_input(self, rt, 0);
+ char err[200];
+ D3Program* prog = d3_shader_compile(v.kind == TB_VALUE_JSON ? v.as.json : NULL, err, sizeof(err));
+ if (!prog) { tinyblocks_set_error(rt, "shader: %s", err); return; }
+ Shd* sh = calloc(1, sizeof(*sh));
+ if (!sh) { d3_shader_free(prog); tinyblocks_set_error(rt, "sem memória"); return; }
+ sh->prog = prog;
+ sh->refs = 1;
+ sh->pub.id = ++s_shd_seq;
+ sh->pub.version = 1;
+ sh->pub.glsl = d3_shader_glsl(prog);
+ shd_binaries(rt, sh);
+ ShdProducer* p = self->userdata;
+ if (!p->handle) { /* um handle por bloco: muda o conteudo */
+ p->handle = tb_block_create(rt, s_t_shader);
+ if (!p->handle) { shd_release(sh); return; }
+ ((ShdHandle*)p->handle->userdata)->owner = self;
+ }
+ ShdHandle* h = p->handle->userdata;
+ shd_release(h->s);
+ h->s = sh;
+ tb_block_set_output(self, 0, tb_value_block(p->handle));
}
static void eval_shader_use(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
Obj* o = need(self, rt, 1);
if (!o) return;
- const char* nm = name_in(self, rt, 0);
- if (!nm[0] || !strcasecmp(nm, "nenhum")) { o->shader = -1; return; }
- int i = shader_find(nm);
- if (i < 0) { tinyblocks_set_error(rt, "não existe o shader '%s' (compile antes)", nm); return; }
- o->shader = i;
+ TinyBlocks_Value v = tb_block_get_input(self, rt, 0);
+ Shd* sh = shd_of(v);
+ if (!sh) {
+ char* t = tb_value_to_string(v);
+ bool none = !t || !t[0] || !strcasecmp(t, "nenhum");
+ free(t);
+ if (!none) { tinyblocks_set_error(rt, "encaixe um shader compilado (\"compile o shader\" ou uma variável com ele)"); return; }
+ }
+ shd_release(o->shader);
+ o->shader = shd_retain(sh);
}
static void eval_shader_glsl(TinyBlocks_Block* self, TinyBlocks* rt) {
self->dirty = false;
- int i = shader_find(name_in(self, rt, 0));
- if (i < 0) { tinyblocks_set_error(rt, "não existe o shader '%s'", name_in(self, rt, 0)); return; }
- tb_block_set_output(self, 0, tb_value_text(s_shd[i].pub.glsl));
+ Shd* sh = shd_of(tb_block_get_input(self, rt, 0));
+ if (!sh) { tinyblocks_set_error(rt, "encaixe um shader compilado"); return; }
+ tb_block_set_output(self, 0, tb_value_text(sh->pub.glsl));
}
static void eval_renderer(TinyBlocks_Block* self, TinyBlocks* rt) {
@@ -726,7 +814,7 @@ static void eval_count(TinyBlocks_Block* self, TinyBlocks* rt) {
}
/* == Registro ========================================================= */
-enum { O_NONE, O_IMAGE, O_REAL, O_BOOL, O_TEXT, O_INT };
+enum { O_NONE, O_IMAGE, O_REAL, O_BOOL, O_TEXT, O_INT, O_SHADER };
typedef struct {
const char* name; const char* label; const char* defs;
@@ -771,11 +859,11 @@ static const Spec s_specs[] = {
{ "3D.Use", "use o renderizador %1", "automático", 1, {T}, O_NONE, -1, S_(eval_use), "vulkan, opengl, software ou automático" },
{ "3D.Renderer", "renderizador da cena", "", 0, {T}, O_TEXT, -1, S_(eval_renderer), "Quem desenhou o último quadro (e em qual placa)" },
{ "3D.Count", "número de objetos 3D", "", 0, {T}, O_INT, -1, S_(eval_count), "Quantos objetos a cena tem" },
- { "3D.ShaderCompile", "compile o shader %1 com %2", "ondas|", 2, {T,TB_VALUE_JSON}, O_NONE, 1, S_(eval_shader_compile),
- "Compila a pilha de blocos de Shader encaixada (não executa: lê os blocos)" },
- { "3D.ShaderUse", "use o shader %1 no objeto %2", "ondas|chão", 2, {T,T}, O_NONE, -1, S_(eval_shader_use),
- "O objeto passa a ser pintado pelo shader (\"nenhum\" volta ao normal)" },
- { "3D.ShaderGlsl", "GLSL do shader %1", "ondas", 1, {T}, O_TEXT, -1, S_(eval_shader_glsl),
+ { "3D.Shader", "compile o shader %1", "", 1, {TB_VALUE_JSON}, O_SHADER, 0, S_(eval_shader),
+ "Compila a pilha de blocos de Shader encaixada (não a executa) e devolve o shader compilado, com o binário de cada renderizador" },
+ { "3D.ShaderUse", "use o shader %1 no objeto %2", "|chão", 2, {TB_VALUE_NONE,T}, O_NONE, -1, S_(eval_shader_use),
+ "O objeto passa a ser pintado pelo shader (vazio ou \"nenhum\" volta ao normal)" },
+ { "3D.ShaderGlsl", "GLSL do shader %1", "", 1, {TB_VALUE_NONE}, O_TEXT, -1, S_(eval_shader_glsl),
"O código GLSL que o shader virou (para ver ou estudar)" },
};
#undef T
@@ -788,6 +876,12 @@ static bool d3_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
meshes_build();
scene_reset();
lib->lib_userdata = (void*)&s_software;
+ s_t_shader = tb_type_block_create(rt, "3D._Shader", NULL, 0, NULL, 0, NULL);
+ if (!s_t_shader) return false;
+ tb_type_block_set_flags(s_t_shader, TB_TYPE_HIDDEN);
+ tb_type_block_set_instance_hooks(s_t_shader, sizeof(ShdHandle), NULL, shd_handle_deinit);
+ tb_type_block_set_value_text(s_t_shader, shd_handle_text);
+ if (!tb_library_add(lib, &s_t_shader->base)) return false;
static const char* names[] = { "a", "b", "c", "d", "e", "f" };
for (size_t i = 0; i < sizeof(s_specs) / sizeof(s_specs[0]); i++) {
const Spec* sp = &s_specs[i];
@@ -799,6 +893,7 @@ static bool d3_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
case O_BOOL: out[0] = (TinyBlocks_SlotDesc){ "sim?", TB_VALUE_INTEGER }; break;
case O_TEXT: out[0] = (TinyBlocks_SlotDesc){ "texto", TB_VALUE_TEXT }; break;
case O_INT: out[0] = (TinyBlocks_SlotDesc){ "valor", TB_VALUE_INTEGER }; break;
+ case O_SHADER: out[0] = (TinyBlocks_SlotDesc){ "shader", TB_VALUE_BLOCK }; break;
default: break;
}
TinyBlocks_TypeBlock* t = tb_type_block_create(rt, sp->name, sp->nin ? in : NULL, (uint32_t)sp->nin,
@@ -806,6 +901,7 @@ static bool d3_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
if (!t) return false;
tb_type_block_set_label(t, sp->label, sp->defs);
if (sp->stack_slot >= 0) tb_type_block_set_input_flags(t, (uint32_t)sp->stack_slot, TB_SLOT_STACK);
+ if (sp->out == O_SHADER) tb_type_block_set_instance_hooks(t, sizeof(ShdProducer), NULL, shd_producer_deinit);
tb_meta_declare(sp->name, sp->fname, __FILE__, sp->doc);
if (!tb_library_add(lib, &t->base)) return false;
}
@@ -815,11 +911,10 @@ static bool d3_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
static void d3_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
(void)rt;
lib->lib_userdata = NULL;
+ for (int i = 0; i < S.n; i++) shd_release(S.o[i].shader);
free(S.o); S.o = NULL; S.n = S.cap = 0;
free(s_draws); s_draws = NULL; s_draws_cap = 0;
free(s_zbuf); s_zbuf = NULL; s_zcap = 0;
- for (int i = 0; i < s_shd_n; i++) d3_shader_free(s_shd[i].prog);
- memset(s_shd, 0, sizeof(s_shd)); s_shd_n = 0;
meshes_free();
}
diff --git a/libraries/tinyblocks-gl/src/tb_gl.c b/libraries/tinyblocks-gl/src/tb_gl.c
index 872a69c..18e4be7 100644
--- a/libraries/tinyblocks-gl/src/tb_gl.c
+++ b/libraries/tinyblocks-gl/src/tb_gl.c
@@ -23,9 +23,12 @@ static struct {
pthread_mutex_t mu;
pthread_cond_t cv;
bool started, ready, failed, quit;
- /* um pedido por vez */
+ /* um pedido por vez: desenhar um quadro, ou compilar o binario de um shader */
const Tb3dFrame* job;
uint8_t* out;
+ const char* glsl; /* != NULL: compilar */
+ void** bin;
+ size_t* bin_size;
bool busy, ok;
char err[256], device[128];
} G = { .mu = PTHREAD_MUTEX_INITIALIZER, .cv = PTHREAD_COND_INITIALIZER };
@@ -41,9 +44,9 @@ static size_t s_rows_cap;
typedef struct { GLuint vao, vbo, ebo; int icount; } GpuMesh;
static GpuMesh s_mesh[32]; /* pelo id da malha */
-/* Programas dos shaders feitos com blocos, pelo id (recompila se a versao muda) */
-typedef struct { GLuint prog; int version; GLint mvp, model, nrm, color, light, ambient, time; } GpuShader;
-static GpuShader s_shd[65];
+/* 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;
+static GpuShader s_shd[64];
static void fail(const char* fmt, const char* a) { snprintf(G.err, sizeof(G.err), fmt, a); }
@@ -115,11 +118,12 @@ static GLuint shader(GLenum kind, const char* src) {
return s;
}
-static GLuint link(GLuint vs, GLuint fs) {
+static GLuint link_hint(GLuint vs, GLuint fs, bool retrievable) {
if (!vs || !fs) { if (vs) glDeleteShader(vs); if (fs) glDeleteShader(fs); return 0; }
GLuint p = glCreateProgram();
glAttachShader(p, vs);
glAttachShader(p, fs);
+ if (retrievable) glProgramParameteri(p, GL_PROGRAM_BINARY_RETRIEVABLE_HINT, GL_TRUE);
glLinkProgram(p);
glDeleteShader(vs);
glDeleteShader(fs);
@@ -129,21 +133,65 @@ static GLuint link(GLuint vs, GLuint fs) {
return p;
}
-/* O programa de um shader feito com blocos (compila na 1a vez e a cada versao) */
+/* 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);
+ free(fs);
+ return p;
+}
+
+/* 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) {
+ *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);
+ if (!p) return false;
+ GLint len = 0;
+ glGetProgramiv(p, GL_PROGRAM_BINARY_LENGTH, &len);
+ uint8_t* buf = len > 0 ? malloc((size_t)len + 4) : NULL;
+ GLenum fmt = 0;
+ if (buf) glGetProgramBinary(p, len, &len, &fmt, buf + 4);
+ glDeleteProgram(p);
+ if (!buf || len <= 0) { free(buf); fail("%s", "o driver não devolveu o binário"); return false; }
+ uint32_t f = (uint32_t)fmt;
+ memcpy(buf, &f, 4);
+ *data = buf;
+ *size = (size_t)len + 4;
+ return true;
+}
+
+static GLuint program_from_binary(const void* data, size_t size) {
+ if (size <= 4) return 0;
+ uint32_t f;
+ memcpy(&f, data, 4);
+ GLuint p = glCreateProgram();
+ glProgramBinary(p, (GLenum)f, (const uint8_t*)data + 4, (GLsizei)(size - 4));
+ GLint ok = 0;
+ glGetProgramiv(p, GL_LINK_STATUS, &ok);
+ if (!ok) { glDeleteProgram(p); return 0; }
+ return p;
+}
+
+/* O programa de um shader feito com blocos (na 1a vez que o id aparece):
+ do binario que veio no shader, ou do GLSL */
static GpuShader* gpu_shader(const Tb3dShader* sh) {
- if (sh->id <= 0 || sh->id >= 65) { fail("%s", "id de shader inválido"); return NULL; }
- GpuShader* g = &s_shd[sh->id];
- if (g->prog && g->version == sh->version) return g;
+ GpuShader* g = &s_shd[(unsigned)sh->id % 64u];
+ if (g->prog && g->id == sh->id) return g;
if (g->prog) glDeleteProgram(g->prog);
memset(g, 0, sizeof(*g));
- size_t n = strlen(FS_HEAD) + strlen(sh->glsl) + strlen(FS_MAIN) + 1;
- char* fs = malloc(n);
- if (!fs) return NULL;
- snprintf(fs, n, "%s%s%s", FS_HEAD, sh->glsl, FS_MAIN);
- g->prog = link(shader(GL_VERTEX_SHADER, VS_SHADER), shader(GL_FRAGMENT_SHADER, fs));
- free(fs);
+ 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) return NULL;
- g->version = sh->version;
+ g->id = sh->id;
g->mvp = glGetUniformLocation(g->prog, "u_mvp");
g->model = glGetUniformLocation(g->prog, "u_model");
g->nrm = glGetUniformLocation(g->prog, "u_nrm");
@@ -293,7 +341,7 @@ static void cleanup(void) {
glDeleteBuffers(1, &s_mesh[i].ebo);
}
memset(s_mesh, 0, sizeof(s_mesh));
- for (int i = 0; i < 65; i++) if (s_shd[i].prog) glDeleteProgram(s_shd[i].prog);
+ 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);
if (s_fbo) { glDeleteFramebuffers(1, &s_fbo); glDeleteRenderbuffers(1, &s_color); glDeleteRenderbuffers(1, &s_depth); }
@@ -319,8 +367,9 @@ static void* gl_thread(void* arg) {
if (G.quit) break;
const Tb3dFrame* f = G.job;
uint8_t* out = G.out;
+ const char* glsl = G.glsl;
pthread_mutex_unlock(&G.mu);
- bool r = draw(f, out);
+ bool r = glsl ? binary_compile(glsl, G.bin, G.bin_size) : draw(f, out);
pthread_mutex_lock(&G.mu);
G.ok = r;
G.busy = false;
@@ -347,7 +396,7 @@ static bool gl_available(void) {
static bool gl_render(const Tb3dFrame* f, uint8_t* rgba) {
if (!gl_available()) return false;
pthread_mutex_lock(&G.mu);
- G.job = f; G.out = rgba; G.busy = true;
+ G.job = f; G.out = rgba; G.glsl = NULL; G.busy = true;
pthread_cond_broadcast(&G.cv);
while (G.busy) pthread_cond_wait(&G.cv, &G.mu);
bool ok = G.ok;
@@ -359,8 +408,22 @@ static const char* gl_device(void) { return G.device[0] ? G.device : "?"; }
static const char* gl_error(void) { return G.err; }
static bool gl_shaders(void) { return true; }
+/* 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) {
+ 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;
+ pthread_cond_broadcast(&G.cv);
+ while (G.busy) pthread_cond_wait(&G.cv, &G.mu);
+ bool ok = G.ok;
+ G.glsl = NULL;
+ if (!ok) snprintf(err, cap, "%s", G.err);
+ pthread_mutex_unlock(&G.mu);
+ return ok;
+}
+
static const Tb3dRenderer s_renderer = {
- TB_3D_RENDERER_VERSION, "opengl", gl_available, gl_render, gl_device, gl_error, gl_shaders };
+ TB_3D_RENDERER_VERSION, "opengl", gl_available, gl_render, gl_device, gl_error, gl_shaders, gl_compile };
static bool lib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
(void)rt;
diff --git a/libraries/tinyblocks-scratchblocks/src/tb_scratchblocks.c b/libraries/tinyblocks-scratchblocks/src/tb_scratchblocks.c
index cdc71d6..a9ccaa0 100644
--- a/libraries/tinyblocks-scratchblocks/src/tb_scratchblocks.c
+++ b/libraries/tinyblocks-scratchblocks/src/tb_scratchblocks.c
@@ -331,6 +331,22 @@ static const Model* model_of(const Models* M, const char* type) {
return NULL;
}
+/* O bloco da linha (ou um repórter encaixado nele, em profundidade) que tem
+ encaixe de pilha: a pilha dele vem nas linhas de baixo. -1 = nenhum.
+ Ex.: "mude [s v] para (compile o shader)" + a pilha + "end". */
+static int stack_holder(const Models* M, const TbBpTab* tab, int bi, const Model** md) {
+ if (bi < 0 || bi >= tab->blocks_n || !tab->blocks[bi].used) return -1;
+ const Model* m = model_of(M, tab->blocks[bi].type);
+ if (m) { *md = m; return bi; }
+ for (int s = 0; s < TB_BP_MAX_INPUTS; s++) {
+ int c = tab->blocks[bi].args[s];
+ if (c < 0) continue;
+ int h = stack_holder(M, tab, c, md);
+ if (h >= 0) return h;
+ }
+ return -1;
+}
+
/* "define nome (a) rotulo ": um bloco do usuario achado no texto */
#define PROTO_MAX 64
typedef struct {
@@ -609,9 +625,10 @@ static void render_chain(const Models* M, const TbBpTab* tab, int bi, int depth,
indent(out, depth);
render_block(M, tab, c, out, true);
sb_str(out, "\n");
- const Model* md = model_of(M, b->type);
- if (md && md->stack_slot >= 0 && md->stack_slot < TB_BP_MAX_INPUTS) {
- render_chain(M, tab, b->args[md->stack_slot], depth + 1, out);
+ const Model* md = NULL;
+ int holder = stack_holder(M, tab, c, &md);
+ if (holder >= 0 && md->stack_slot < TB_BP_MAX_INPUTS) {
+ render_chain(M, tab, tab->blocks[holder].args[md->stack_slot], depth + 1, out);
indent(out, depth); sb_str(out, "end\n");
}
if (sh == TB_SB_C1 || sh == TB_SB_C2 || sh == TB_SB_CAP) {
@@ -920,10 +937,11 @@ int tb_scratchblocks_import(const char* text, TbBpTab* out, const TbSbContext* c
else if (depth > 0) tb_blueprint_link(out, L->cblock, TB_BP_REL_SUB0 + L->sub, bi);
L->last = bi;
}
- const Model* md = outer ? NULL : model_of(&M, out->blocks[bi].type);
- if (md && md->stack_slot >= 0 && depth + 1 < LEVEL_MAX) { /* encaixe de pilha: sub < 0 */
+ const Model* md = NULL;
+ int holder = outer ? -1 : stack_holder(&M, out, bi, &md);
+ if (holder >= 0 && depth + 1 < LEVEL_MAX) { /* encaixe de pilha (sub < 0): no bloco ou num repórter dele */
depth++;
- lv[depth].cblock = bi; lv[depth].sub = -1 - md->stack_slot; lv[depth].last = -1;
+ lv[depth].cblock = holder; lv[depth].sub = -1 - md->stack_slot; lv[depth].last = -1;
} else if (!outer && (sh == TB_SB_C1 || sh == TB_SB_C2 || sh == TB_SB_CAP) && depth + 1 < LEVEL_MAX) {
depth++;
lv[depth].cblock = bi; lv[depth].sub = 0; lv[depth].last = -1;
diff --git a/libraries/tinyblocks-vk/src/tb_vk.c b/libraries/tinyblocks-vk/src/tb_vk.c
index ce431d5..1708284 100644
--- a/libraries/tinyblocks-vk/src/tb_vk.c
+++ b/libraries/tinyblocks-vk/src/tb_vk.c
@@ -19,12 +19,11 @@
typedef struct { VkBuffer buf; VkDeviceMemory mem; void* map; VkDeviceSize size; } Buf;
typedef struct { Buf vb, ib; int icount; } GpuMesh;
-/* Pipeline de um shader feito com blocos, pelo id (refeito se a versao muda) */
-typedef struct { VkPipeline pipe; int version; } GpuShader;
+/* Pipeline de um shader feito com blocos: cache pelo id (id % 64) */
+typedef struct { VkPipeline pipe; int id; } GpuShader;
-/* -- libshaderc (GLSL -> SPIR-V em execucao), carregada por dlopen --------
- So as funcoes da API C usadas aqui (a API e estavel; nao precisa do
- header). Sem a biblioteca, a vk so nao desenha shaders feitos com blocos. */
+/* -- libshaderc (GLSL -> SPIR-V), carregada por dlopen -------------------- */
+/* So as funcoes da API C usadas aqui (estavel; nao precisa do header) */
typedef void* (*ShcInit)(void);
typedef void (*ShcRelease)(void*);
typedef void* (*ShcCompile)(void*, const char*, size_t, int, const char*, const char*, const void*);
@@ -37,6 +36,73 @@ static struct {
ShcStatus status; ShcLength length; ShcBytes bytes, error;
} SC;
+static bool shaderc_load(void) {
+ if (SC.tried) return SC.compiler != NULL;
+ SC.tried = true;
+ const char* names[] = { "libshaderc_shared.so.1", "libshaderc.so.1", "libshaderc_shared.so", "libshaderc.so" };
+ for (int i = 0; i < 4 && !SC.dl; i++) SC.dl = dlopen(names[i], RTLD_NOW | RTLD_LOCAL);
+ if (!SC.dl) return false;
+#define SYM(field, name) do { void* p_ = dlsym(SC.dl, name); memcpy(&SC.field, &p_, sizeof(p_)); } while (0)
+ SYM(init, "shaderc_compiler_initialize");
+ SYM(release_compiler, "shaderc_compiler_release");
+ SYM(compile, "shaderc_compile_into_spv");
+ SYM(status, "shaderc_result_get_compilation_status");
+ SYM(length, "shaderc_result_get_length");
+ SYM(bytes, "shaderc_result_get_bytes");
+ SYM(error, "shaderc_result_get_error_message");
+ SYM(release_result, "shaderc_result_release");
+#undef SYM
+ if (SC.init && SC.compile && SC.status && SC.length && SC.bytes && SC.error && SC.release_result)
+ SC.compiler = SC.init();
+ return SC.compiler != NULL;
+}
+
+static const char* FS_HEAD =
+ "#version 450\n"
+ "layout(location = 0) in vec3 v_pos;\n"
+ "layout(location = 1) in vec3 v_nrm;\n"
+ "layout(push_constant) uniform PC { mat4 mvp; mat4 model; vec4 color; vec4 light; } pc;\n"
+ "layout(location = 0) out vec4 o_color;\n";
+static const char* FS_MAIN =
+ "void main() {\n"
+ " vec3 N = normalize(v_nrm);\n"
+ " float light = pc.color.a + (1.0 - pc.color.a) * max(dot(N, pc.light.xyz), 0.0);\n"
+ " o_color = vec4(tb_shade(v_pos, N, pc.color.rgb, light, pc.light.w), 1.0);\n"
+ "}\n";
+
+/* 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) {
+ *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);
+ if (!res || SC.status(res) != 0) {
+ snprintf(err, cap, "shaderc: %.200s", res ? SC.error(res) : "falhou");
+ if (res) SC.release_result(res);
+ return NULL;
+ }
+ size_t len = SC.length(res);
+ uint32_t* spv = malloc(len ? len : 4);
+ if (spv) { memcpy(spv, SC.bytes(res), len); *words = len / 4; }
+ SC.release_result(res);
+ return spv;
+}
+
+
+static bool vk_compile(const char* glsl, void** data, size_t* size, char* err, size_t cap) {
+ size_t words = 0;
+ uint32_t* spv = spirv_fragment(glsl, &words, err, cap);
+ *data = spv;
+ *size = words * 4;
+ return spv != NULL;
+}
+
static struct {
bool tried, ok;
char err[256], device[160];
@@ -56,7 +122,7 @@ static struct {
VkPipelineLayout shd_layout; /* 160 bytes de push constants */
VkShaderModule shd_vert;
bool shd_ok; /* da para usar shaders feitos com blocos */
- GpuShader shd[65];
+ GpuShader shd[64];
/* alvo (recriado quando muda o tamanho) */
int w, h;
VkImage color, depth;
@@ -320,71 +386,32 @@ static GpuMesh* gpu_mesh(const Tb3dMesh* m) {
return g;
}
-static bool shaderc_load(void) {
- if (SC.tried) return SC.compiler != NULL;
- SC.tried = true;
- const char* names[] = { "libshaderc_shared.so.1", "libshaderc.so.1", "libshaderc_shared.so", "libshaderc.so" };
- for (int i = 0; i < 4 && !SC.dl; i++) SC.dl = dlopen(names[i], RTLD_NOW | RTLD_LOCAL);
- if (!SC.dl) { snprintf(V.err, sizeof(V.err), "sem a libshaderc: shaders feitos com blocos não rodam no Vulkan"); return false; }
-#define SYM(field, name) do { void* p_ = dlsym(SC.dl, name); memcpy(&SC.field, &p_, sizeof(p_)); } while (0)
- SYM(init, "shaderc_compiler_initialize");
- SYM(release_compiler, "shaderc_compiler_release");
- SYM(compile, "shaderc_compile_into_spv");
- SYM(status, "shaderc_result_get_compilation_status");
- SYM(length, "shaderc_result_get_length");
- SYM(bytes, "shaderc_result_get_bytes");
- SYM(error, "shaderc_result_get_error_message");
- SYM(release_result, "shaderc_result_release");
-#undef SYM
- if (SC.init && SC.compile && SC.status && SC.length && SC.bytes && SC.error && SC.release_result)
- SC.compiler = SC.init();
- if (!SC.compiler) snprintf(V.err, sizeof(V.err), "a libshaderc não iniciou");
- return SC.compiler != NULL;
-}
-
-static const char* FS_HEAD =
- "#version 450\n"
- "layout(location = 0) in vec3 v_pos;\n"
- "layout(location = 1) in vec3 v_nrm;\n"
- "layout(push_constant) uniform PC { mat4 mvp; mat4 model; vec4 color; vec4 light; } pc;\n"
- "layout(location = 0) out vec4 o_color;\n";
-static const char* FS_MAIN =
- "void main() {\n"
- " vec3 N = normalize(v_nrm);\n"
- " float light = pc.color.a + (1.0 - pc.color.a) * max(dot(N, pc.light.xyz), 0.0);\n"
- " o_color = vec4(tb_shade(v_pos, N, pc.color.rgb, light, pc.light.w), 1.0);\n"
- "}\n";
-
-/* O pipeline de um shader feito com blocos (compila na 1a vez e a cada versao) */
+/* O pipeline de um shader feito com blocos (na 1a vez que o id aparece) */
static GpuShader* gpu_shader(const Tb3dShader* sh) {
- if (sh->id <= 0 || sh->id >= 65) { snprintf(V.err, sizeof(V.err), "id de shader inválido"); return NULL; }
- GpuShader* g = &V.shd[sh->id];
- if (g->pipe && g->version == sh->version) return g;
- if (!shaderc_load()) return NULL;
- size_t n = strlen(FS_HEAD) + strlen(sh->glsl) + strlen(FS_MAIN) + 1;
- char* src = malloc(n);
- if (!src) return NULL;
- snprintf(src, n, "%s%s%s", FS_HEAD, sh->glsl, FS_MAIN);
- void* res = SC.compile(SC.compiler, src, strlen(src), 1 /* fragment */, "shader.frag", "main", NULL);
- free(src);
- if (!res || SC.status(res) != 0) {
- snprintf(V.err, sizeof(V.err), "shaderc: %.200s", res ? SC.error(res) : "falhou");
- if (res) SC.release_result(res);
- return NULL;
+ GpuShader* g = &V.shd[(unsigned)sh->id % 64u];
+ if (g->pipe && g->id == sh->id) return g;
+ /* o binario que veio no shader ("compile o shader"); sem ele, compila agora */
+ const void* code = NULL;
+ size_t size = 0;
+ void* own = NULL;
+ 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;
+ code = own;
}
- VkShaderModuleCreateInfo sm = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, NULL, 0, SC.length(res),
- (const uint32_t*)(const void*)SC.bytes(res) };
+ VkShaderModuleCreateInfo sm = { VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO, NULL, 0, size, code };
VkShaderModule fs;
VkResult r = vkCreateShaderModule(V.dev, &sm, NULL, &fs);
- SC.release_result(res);
- if (r != VK_SUCCESS) { snprintf(V.err, sizeof(V.err), "módulo do shader recusado (%d)", (int)r); return NULL; }
+ free(own);
+ if (r != VK_SUCCESS) { snprintf(V.err, sizeof(V.err), "binário do shader recusado (%d)", (int)r); return NULL; }
vkDeviceWaitIdle(V.dev);
if (g->pipe) vkDestroyPipeline(V.dev, g->pipe, NULL);
g->pipe = VK_NULL_HANDLE;
r = build_pipe(V.shd_vert, fs, V.shd_layout, &g->pipe);
vkDestroyShaderModule(V.dev, fs, NULL);
if (r != VK_SUCCESS) { snprintf(V.err, sizeof(V.err), "pipeline do shader recusado (%d)", (int)r); return NULL; }
- g->version = sh->version;
+ g->id = sh->id;
return g;
}
@@ -419,7 +446,7 @@ static bool vk_draw(const Tb3dFrame* f, uint8_t* out) {
memcpy(pc + 16, d->model, sizeof(d->model));
pc[32] = d->color[0]; pc[33] = d->color[1]; pc[34] = d->color[2]; pc[35] = f->ambient;
pc[36] = f->light_dir[0]; pc[37] = f->light_dir[1]; pc[38] = f->light_dir[2]; pc[39] = f->time;
- vkCmdBindPipeline(V.cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, V.shd[d->shader->id].pipe);
+ vkCmdBindPipeline(V.cmd, VK_PIPELINE_BIND_POINT_GRAPHICS, V.shd[(unsigned)d->shader->id % 64u].pipe);
vkCmdPushConstants(V.cmd, V.shd_layout, VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT,
0, sizeof(pc), pc);
VkDeviceSize off = 0;
@@ -466,7 +493,7 @@ static void vk_cleanup(void) {
vkDeviceWaitIdle(V.dev);
for (int i = 0; i < 32; i++) { buf_free(&V.mesh[i].vb); buf_free(&V.mesh[i].ib); }
target_free();
- for (int i = 0; i < 65; i++) if (V.shd[i].pipe) vkDestroyPipeline(V.dev, V.shd[i].pipe, NULL);
+ for (int i = 0; i < 64; i++) if (V.shd[i].pipe) vkDestroyPipeline(V.dev, V.shd[i].pipe, NULL);
if (V.shd_vert) vkDestroyShaderModule(V.dev, V.shd_vert, NULL);
if (V.shd_layout) vkDestroyPipelineLayout(V.dev, V.shd_layout, NULL);
if (V.pipe) vkDestroyPipeline(V.dev, V.pipe, NULL);
@@ -502,7 +529,7 @@ static const char* vk_error(void) { return V.err; }
static bool vk_shaders(void) { return V.ok && V.shd_ok && shaderc_load(); }
static const Tb3dRenderer s_renderer = {
- TB_3D_RENDERER_VERSION, "vulkan", vk_available, vk_render, vk_device, vk_error, vk_shaders };
+ TB_3D_RENDERER_VERSION, "vulkan", vk_available, vk_render, vk_device, vk_error, vk_shaders, vk_compile };
static bool lib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
(void)rt;
diff --git a/tests/d3_test.c b/tests/d3_test.c
index 7a6f77d..20f7217 100644
--- a/tests/d3_test.c
+++ b/tests/d3_test.c
@@ -35,20 +35,27 @@ static TinyBlocks_Block* run(const char* type, const char* const* args, int n) {
}
#define RUN(type, ...) run(type, (const char* const[]){ __VA_ARGS__ }, (int)(sizeof((const char* const[]){ __VA_ARGS__ }) / sizeof(char*)))
-/* "compile o shader [nome] com [pilha]" com o codigo (JSON) da pilha */
-static bool compile_shader(const char* name, const char* json) {
- TinyBlocks_Block* x = tb_block_create(rt, tb_type_block_find(rt, "3D.ShaderCompile"));
- TinyBlocks_Value nv = tb_value_text(name);
- tb_block_set_default(x, 0, nv);
- tb_value_free(&nv);
+/* "compile o shader [pilha]" com o codigo (JSON) da pilha: o bloco (a saida
+ e o shader compilado), ou NULL em erro */
+static TinyBlocks_Block* compile_shader(const char* json) {
+ TinyBlocks_Block* x = tb_block_create(rt, tb_type_block_find(rt, "3D.Shader"));
TinyBlocks_JsonValue* j = tb_json_parse(json, NULL, 0);
TinyBlocks_Value jv = tb_value_json(j);
- tb_block_set_default(x, 1, jv);
+ tb_block_set_default(x, 0, jv);
tb_value_free(&jv);
tb_json_release(j);
tinyblocks_clear_error(rt);
tb_block_eval(x, rt);
- return !tinyblocks_last_error(rt)[0];
+ return tinyblocks_last_error(rt)[0] ? NULL : x;
+}
+
+/* bloco com o shader (valor) na entrada 0 e um texto na 1 */
+static TinyBlocks_Block* run_with_shader(const char* type, TinyBlocks_Block* sh, const char* obj) {
+ TinyBlocks_Block* x = tb_block_create(rt, tb_type_block_find(rt, type));
+ tb_block_set_default(x, 0, sh->outputs[0]);
+ if (obj) { TinyBlocks_Value t = tb_value_text(obj); tb_block_set_default(x, 1, t); tb_value_free(&t); }
+ tb_block_eval(x, rt);
+ return x;
}
#define BLK(t, ...) "{\"type\":\"" t "\",\"inputs\":[" __VA_ARGS__ "]}"
@@ -147,20 +154,28 @@ int main(void) {
BLK("Number.Floor", BLK0("Shader.Z"))) ",2") ",0")
"],\"mouths\":[[" BLK("Shader.Pixel", BLK("Math.Mul", BLK("Shader.Color", "\"branco\"") "," BLK0("Shader.Light")))
"],[" BLK("Shader.Pixel", BLK("Math.Mul", BLK("Shader.Color", "\"#333333\"") "," BLK0("Shader.Light"))) "]]}]";
- CHECK(compile_shader("xadrez", xadrez), "compila o xadrez (se/senão, resto, arredonde, cor, luz)");
+ TinyBlocks_Block* sx = compile_shader(xadrez);
+ CHECK(sx && sx->outputs[0].kind == TB_VALUE_BLOCK, "compila o xadrez (se/senão, resto, arredonde, cor, luz): um valor");
const char* degrade = "[" BLK("Variables.Set", "\"t\"," BLK("Math.Div", BLK("Math.Add", BLK0("Shader.NY") ",1") ",2"))
"," BLK("Shader.Pixel", BLK("Math.Mul", BLK("Shader.Mix", BLK("Shader.Color", "\"azul\"") ","
BLK("Shader.Color", "\"branco\"") "," BLK("Variables.Get", "\"t\"")) "," BLK0("Shader.Light"))) "]";
- CHECK(compile_shader("degrade", degrade), "compila o degradê (variável local, misture)");
- RUN("3D.ShaderUse", "xadrez", "chão");
- RUN("3D.ShaderUse", "degrade", "bola");
+ TinyBlocks_Block* sd = compile_shader(degrade);
+ CHECK(sd != NULL, "compila o degradê (variável local, misture)");
+ if (!sx || !sd) return 1;
+ char vt[128];
+ tb_value_to_text(sx->outputs[0], vt, sizeof(vt));
+ printf(" valor: %s\n", vt);
+ CHECK(strstr(vt, "vulkan: ") && strstr(vt, "opengl: "),
+ "o shader compilado leva o binário de cada renderizador (Vulkan: SPIR-V; OpenGL: o do driver)");
+ run_with_shader("3D.ShaderUse", sx, "chão");
+ run_with_shader("3D.ShaderUse", sd, "bola");
CHECK(!tinyblocks_last_error(rt)[0], "use o shader no objeto");
- TinyBlocks_Block* g = RUN("3D.ShaderGlsl", "xadrez");
+ TinyBlocks_Block* g = run_with_shader("3D.ShaderGlsl", sx, NULL);
CHECK(g->outputs[0].kind == TB_VALUE_TEXT && strstr(g->outputs[0].as.text, "vec3 tb_shade(") &&
strstr(g->outputs[0].as.text, "mod("), "GLSL gerado");
- CHECK(!compile_shader("ruim", "[" BLK("Shader.Pixel", BLK0("Input.Timer")) "]") &&
+ CHECK(!compile_shader("[" BLK("Shader.Pixel", BLK0("Input.Timer")) "]") &&
strstr(tinyblocks_last_error(rt), "não pode ser usado num shader"), "bloco que não cabe num shader: erro claro");
- CHECK(!compile_shader("ruim", "[{\"type\":\"Control.If\",\"inputs\":[" BLK("Operators.Lt", BLK0("Shader.PixelColor") ",1")
+ CHECK(!compile_shader("[{\"type\":\"Control.If\",\"inputs\":[" BLK("Operators.Lt", BLK0("Shader.PixelColor") ",1")
"],\"mouths\":[[]]}]") && strstr(tinyblocks_last_error(rt), "comparar números"), "comparar cor: erro claro");
tinyblocks_clear_error(rt);
tb_image_release(sw);
diff --git a/tests/editor_harness.c b/tests/editor_harness.c
index 18876b1..8cb2801 100644
--- a/tests/editor_harness.c
+++ b/tests/editor_harness.c
@@ -1439,7 +1439,7 @@ int main(void) {
free(t);
t = mcp("add_scratchblocks", "{\"code\":\"when flag clicked\\n"
"say (join [e=] (código de ((seno de (x)) * (2))))\\n"
- "say (join [p=] (código da pilha))\\n"
+ "say (join [p=] (código da pilha))\\nend\\n"
"say (join [x=] (x))\\n\",\"x\":40,\"y\":40}", &err, NULL);
CHECK(!err, "encaixes: cria o script");
int stk = -1;