3D: tinyblocks-3d com renderizadores Vulkan (vk) e OpenGL (gl); jogo das moedas

tinyblocks-3d (categoria 3D): cena com objetos com nome (cubo, esfera,
plano, cilindro), posicao/rotacao/escala/cor, colisao por caixas,
distancia, camera, luz direcional, ceu, e o bloco "imagem da cena" que
desenha numa imagem para o palco. Define o contrato Tb3dRenderer e traz um
rasterizador em software (z-buffer, corte no plano de perto, lambert por
vertice).

tinyblocks-gl: OpenGL 3.3 core por EGL sem janela (surfaceless), numa
thread propria dona do contexto (o SDL pode usar GL na thread do editor).
tinyblocks-vk: Vulkan 1.1 sem janela (render pass cor + profundidade,
viewport com altura negativa, z convertido no shader, push constants de 128
bytes, copia para buffer); SPIR-V embutido, gerado pelo glslc (make
shaders). Os dois publicam o renderizador no lib_userdata e nao dependem de
simbolos da 3d (o quadro leva a MVP pronta). Escolha automatica: Vulkan,
OpenGL, software.

test-3d: blocos, colisao e camera; as imagens de Vulkan e OpenGL ficam a
0,001 de diferenca media do software (testado na NVIDIA, na Intel e no
llvmpipe, com a camada de validacao). No Windows a 3d entra so com o
software.

examples/jogo-3d: "Pegue as moedas", todo em blocos.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mguinhosandClaude Opus 5.5 committed 2026-10-27 02:12:03 -03:00
1 parent 8f2c00693d
commit 5bae31edf3
29 files changed
+18420 -5

No files matched your search

+30
View File
@@ -0,0 +1,30 @@
# Makefile da library gl (renderizador OpenGL da 3d)
# Constroi build/libtinyblocks-gl.a e build/libtinyblocks-gl.so
CC := gcc
BUILD := build
CFLAGS := -std=c11 -O2 -Wall -Wextra -pedantic -fvisibility=hidden \
-D_POSIX_C_SOURCE=200809L -I../../include -Iinclude -I../tinyblocks-3d/include
SRCS := src/tb_gl.c
OBJS := $(BUILD)/tb_gl.o
LIB_A := $(BUILD)/libtinyblocks-gl.a
LIB_SO := $(BUILD)/libtinyblocks-gl.so
.PHONY: all static shared clean
all: static shared
static: $(LIB_A)
shared: $(LIB_SO)
$(BUILD)/%.o: src/%.c $(wildcard include/*.h) $(wildcard src/*.h)
@mkdir -p $(BUILD)
$(CC) $(CFLAGS) -fPIC -c $< -o $@
$(LIB_A): $(OBJS)
ar rcs $@ $^
$(LIB_SO): $(OBJS)
$(CC) -shared -o $@ $^ -lEGL -lOpenGL -lpthread -lm
clean:
$(RM) -r $(BUILD)
+20
View File
@@ -0,0 +1,20 @@
/*
* TinyBlocks - tb_gl.h
* Library tinyblocks-gl: renderizador OpenGL da tinyblocks-3d.
*
* Nao tem blocos: publica um Tb3dRenderer ("opengl") no lib_userdata, que a
* 3d acha pelo nome. Desenha sem janela: contexto OpenGL 3.3 core pelo EGL
* (plataforma surfaceless do Mesa, ou o display padrao), num framebuffer
* fora da tela, e le os pixels de volta.
*
* O contexto vive numa thread propria: assim ele nunca e o "corrente" da
* thread do editor, onde o SDL pode estar usando o OpenGL dele.
*/
#ifndef TINYBLOCKS_GL_H
#define TINYBLOCKS_GL_H
#include <tinyblocks/tinyblocks.h>
TB_API const TinyBlocks_LibraryDescriptor* tb_gl_get_library(void);
#endif /* TINYBLOCKS_GL_H */
+15
View File
@@ -0,0 +1,15 @@
# Metadados da library gl. Lido pela UI/build sem recompilar o .so.
[library]
name = "tinyblocks-gl"
version = "1.0.0"
category = "3D"
description = "Renderizador OpenGL 3.3 (EGL, sem janela) para a tinyblocks-3d"
color = [92, 107, 219, 255]
dark = [64, 77, 168, 255]
[build]
sources = ["src/tb_gl.c"]
includes = ["include"]
shared = "build/libtinyblocks-gl.so"
static = "build/libtinyblocks-gl.a"
depends = ["3d"]
+295
View File
@@ -0,0 +1,295 @@
/*
* TinyBlocks - tb_gl.c
* Renderizador OpenGL (EGL sem janela) da tinyblocks-3d.
*/
#define _POSIX_C_SOURCE 200809L
#define GL_GLEXT_PROTOTYPES 1
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <EGL/egl.h>
#include <EGL/eglext.h>
#include <GL/glcorearb.h>
#include <tinyblocks/tinyblocks.h>
#include "tb_3d.h"
#include "tb_gl.h"
/* == Estado da thread do OpenGL ======================================== */
static struct {
pthread_t th;
pthread_mutex_t mu;
pthread_cond_t cv;
bool started, ready, failed, quit;
/* um pedido por vez */
const Tb3dFrame* job;
uint8_t* out;
bool busy, ok;
char err[256], device[128];
} G = { .mu = PTHREAD_MUTEX_INITIALIZER, .cv = PTHREAD_COND_INITIALIZER };
/* So a thread do OpenGL mexe nestes */
static EGLDisplay s_dpy = EGL_NO_DISPLAY;
static EGLContext s_ctx = EGL_NO_CONTEXT;
static GLuint s_prog, s_fbo, s_color, s_depth;
static GLint u_mvp, u_nrm, u_color, u_light, u_ambient;
static int s_w, s_h;
static uint8_t* s_rows; /* leitura (de baixo para cima) */
static size_t s_rows_cap;
typedef struct { GLuint vao, vbo, ebo; int icount; } GpuMesh;
static GpuMesh s_mesh[32]; /* pelo id da malha */
static void fail(const char* fmt, const char* a) { snprintf(G.err, sizeof(G.err), fmt, a); }
static const char* VS =
"#version 330 core\n"
"layout(location = 0) in vec3 a_pos;\n"
"layout(location = 1) in vec3 a_nrm;\n"
"uniform mat4 u_mvp;\n"
"uniform mat3 u_nrm;\n"
"uniform vec4 u_color;\n"
"uniform vec3 u_light;\n"
"uniform float u_ambient;\n"
"out vec3 v_col;\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"
"}\n";
static const char* FS =
"#version 330 core\n"
"in vec3 v_col;\n"
"out vec4 o_color;\n"
"void main() { o_color = vec4(min(v_col, vec3(1.0)), 1.0); }\n";
static GLuint shader(GLenum kind, const char* src) {
GLuint s = glCreateShader(kind);
glShaderSource(s, 1, &src, NULL);
glCompileShader(s);
GLint ok = 0;
glGetShaderiv(s, GL_COMPILE_STATUS, &ok);
if (!ok) {
char log[200];
glGetShaderInfoLog(s, sizeof(log), NULL, log);
fail("shader: %s", log);
glDeleteShader(s);
return 0;
}
return s;
}
static bool gl_setup(void) {
PFNEGLGETPLATFORMDISPLAYEXTPROC get_platform =
(PFNEGLGETPLATFORMDISPLAYEXTPROC)eglGetProcAddress("eglGetPlatformDisplayEXT");
if (get_platform) s_dpy = get_platform(EGL_PLATFORM_SURFACELESS_MESA, EGL_DEFAULT_DISPLAY, NULL);
EGLint maj, min;
if (s_dpy == EGL_NO_DISPLAY || !eglInitialize(s_dpy, &maj, &min)) {
s_dpy = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (s_dpy == EGL_NO_DISPLAY || !eglInitialize(s_dpy, &maj, &min)) { fail("%s", "o EGL não iniciou"); return false; }
}
if (!eglBindAPI(EGL_OPENGL_API)) { fail("%s", "o EGL não oferece OpenGL"); return false; }
static const EGLint cfg_attr[] = { EGL_RENDERABLE_TYPE, EGL_OPENGL_BIT, EGL_SURFACE_TYPE, 0, EGL_NONE };
EGLConfig cfg = NULL;
EGLint n = 0;
if (!eglChooseConfig(s_dpy, cfg_attr, &cfg, 1, &n) || n < 1) cfg = NULL; /* EGL_KHR_no_config_context */
static const EGLint ctx_attr[] = { EGL_CONTEXT_MAJOR_VERSION, 3, EGL_CONTEXT_MINOR_VERSION, 3,
EGL_CONTEXT_OPENGL_PROFILE_MASK, EGL_CONTEXT_OPENGL_CORE_PROFILE_BIT, EGL_NONE };
s_ctx = eglCreateContext(s_dpy, cfg, EGL_NO_CONTEXT, ctx_attr);
if (s_ctx == EGL_NO_CONTEXT) { fail("%s", "não criou um contexto OpenGL 3.3"); return false; }
if (!eglMakeCurrent(s_dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, s_ctx)) { fail("%s", "contexto sem janela recusado"); return false; }
snprintf(G.device, sizeof(G.device), "%s", (const char*)glGetString(GL_RENDERER));
GLuint vs = shader(GL_VERTEX_SHADER, VS), fs = shader(GL_FRAGMENT_SHADER, FS);
if (!vs || !fs) return false;
s_prog = glCreateProgram();
glAttachShader(s_prog, vs);
glAttachShader(s_prog, fs);
glLinkProgram(s_prog);
glDeleteShader(vs);
glDeleteShader(fs);
GLint ok = 0;
glGetProgramiv(s_prog, GL_LINK_STATUS, &ok);
if (!ok) { fail("%s", "o programa de shaders não ligou"); return false; }
u_mvp = glGetUniformLocation(s_prog, "u_mvp");
u_nrm = glGetUniformLocation(s_prog, "u_nrm");
u_color = glGetUniformLocation(s_prog, "u_color");
u_light = glGetUniformLocation(s_prog, "u_light");
u_ambient = glGetUniformLocation(s_prog, "u_ambient");
glGenFramebuffers(1, &s_fbo);
glGenRenderbuffers(1, &s_color);
glGenRenderbuffers(1, &s_depth);
return true;
}
static bool target(int w, int h) {
if (w == s_w && h == s_h) return true;
glBindRenderbuffer(GL_RENDERBUFFER, s_color);
glRenderbufferStorage(GL_RENDERBUFFER, GL_RGBA8, w, h);
glBindRenderbuffer(GL_RENDERBUFFER, s_depth);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, w, h);
glBindFramebuffer(GL_FRAMEBUFFER, s_fbo);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_RENDERBUFFER, s_color);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, s_depth);
if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) { fail("%s", "framebuffer incompleto"); return false; }
s_w = w; s_h = h;
return true;
}
static GpuMesh* gpu_mesh(const Tb3dMesh* m) {
if (m->id <= 0 || m->id >= 32) return NULL;
GpuMesh* g = &s_mesh[m->id];
if (g->vao) return g;
glGenVertexArrays(1, &g->vao);
glGenBuffers(1, &g->vbo);
glGenBuffers(1, &g->ebo);
glBindVertexArray(g->vao);
glBindBuffer(GL_ARRAY_BUFFER, g->vbo);
glBufferData(GL_ARRAY_BUFFER, (GLsizeiptr)m->vcount * 6 * sizeof(float), m->verts, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, g->ebo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)m->icount * sizeof(uint32_t), m->index, GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)0);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * sizeof(float), (void*)(3 * sizeof(float)));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
g->icount = m->icount;
return g;
}
static bool draw(const Tb3dFrame* f, uint8_t* out) {
if (!target(f->width, f->height)) return false;
glBindFramebuffer(GL_FRAMEBUFFER, s_fbo);
glViewport(0, 0, f->width, f->height);
glClearColor(f->sky[0], f->sky[1], f->sky[2], 1.f);
glClearDepth(1.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glDisable(GL_CULL_FACE);
glUseProgram(s_prog);
glUniform3fv(u_light, 1, f->light_dir);
glUniform1f(u_ambient, f->ambient);
for (int i = 0; i < f->draw_count; i++) {
const Tb3dDraw* d = &f->draws[i];
GpuMesh* g = gpu_mesh(d->mesh);
if (!g) continue;
glUniformMatrix4fv(u_mvp, 1, GL_FALSE, d->mvp);
glUniformMatrix3fv(u_nrm, 1, GL_FALSE, d->normal);
glUniform4fv(u_color, 1, d->color);
glBindVertexArray(g->vao);
glDrawElements(GL_TRIANGLES, g->icount, GL_UNSIGNED_INT, (void*)0);
}
size_t row = (size_t)f->width * 4, n = row * (size_t)f->height;
if (n > s_rows_cap) {
uint8_t* p = realloc(s_rows, n);
if (!p) { fail("%s", "sem memória"); return false; }
s_rows = p; s_rows_cap = n;
}
glPixelStorei(GL_PACK_ALIGNMENT, 1);
glReadPixels(0, 0, f->width, f->height, GL_RGBA, GL_UNSIGNED_BYTE, s_rows);
for (int y = 0; y < f->height; y++) /* o GL comeca de baixo */
memcpy(out + (size_t)y * row, s_rows + (size_t)(f->height - 1 - y) * row, row);
GLenum e = glGetError();
if (e != GL_NO_ERROR) { char t[32]; snprintf(t, sizeof(t), "0x%x", e); fail("erro do OpenGL %s", t); return false; }
return true;
}
static void cleanup(void) {
for (int i = 0; i < 32; i++)
if (s_mesh[i].vao) {
glDeleteVertexArrays(1, &s_mesh[i].vao);
glDeleteBuffers(1, &s_mesh[i].vbo);
glDeleteBuffers(1, &s_mesh[i].ebo);
}
memset(s_mesh, 0, sizeof(s_mesh));
if (s_prog) glDeleteProgram(s_prog);
if (s_fbo) { glDeleteFramebuffers(1, &s_fbo); glDeleteRenderbuffers(1, &s_color); glDeleteRenderbuffers(1, &s_depth); }
s_prog = s_fbo = s_color = s_depth = 0;
s_w = s_h = 0;
if (s_dpy != EGL_NO_DISPLAY) {
eglMakeCurrent(s_dpy, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT);
if (s_ctx != EGL_NO_CONTEXT) eglDestroyContext(s_dpy, s_ctx);
eglTerminate(s_dpy);
}
s_dpy = EGL_NO_DISPLAY; s_ctx = EGL_NO_CONTEXT;
free(s_rows); s_rows = NULL; s_rows_cap = 0;
}
static void* gl_thread(void* arg) {
(void)arg;
bool ok = gl_setup();
pthread_mutex_lock(&G.mu);
G.ready = ok; G.failed = !ok;
pthread_cond_broadcast(&G.cv);
while (ok && !G.quit) {
while (!G.busy && !G.quit) pthread_cond_wait(&G.cv, &G.mu);
if (G.quit) break;
const Tb3dFrame* f = G.job;
uint8_t* out = G.out;
pthread_mutex_unlock(&G.mu);
bool r = draw(f, out);
pthread_mutex_lock(&G.mu);
G.ok = r;
G.busy = false;
pthread_cond_broadcast(&G.cv);
}
pthread_mutex_unlock(&G.mu);
cleanup();
return NULL;
}
/* == Tb3dRenderer ===================================================== */
static bool gl_available(void) {
pthread_mutex_lock(&G.mu);
if (!G.started) {
G.started = true;
if (pthread_create(&G.th, NULL, gl_thread, NULL) != 0) { G.failed = true; fail("%s", "sem thread"); }
}
while (!G.ready && !G.failed) pthread_cond_wait(&G.cv, &G.mu);
bool ok = G.ready;
pthread_mutex_unlock(&G.mu);
return ok;
}
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;
pthread_cond_broadcast(&G.cv);
while (G.busy) pthread_cond_wait(&G.cv, &G.mu);
bool ok = G.ok;
pthread_mutex_unlock(&G.mu);
return ok;
}
static const char* gl_device(void) { return G.device[0] ? G.device : "?"; }
static const char* gl_error(void) { return G.err; }
static const Tb3dRenderer s_renderer = {
TB_3D_RENDERER_VERSION, "opengl", gl_available, gl_render, gl_device, gl_error };
static bool lib_init(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
(void)rt;
lib->lib_userdata = (void*)&s_renderer; /* a thread so nasce no 1o uso */
return true;
}
static void lib_deinit(TinyBlocks* rt, TinyBlocks_LibraryBlock* lib) {
(void)rt;
lib->lib_userdata = NULL;
pthread_mutex_lock(&G.mu);
bool started = G.started;
G.quit = true;
pthread_cond_broadcast(&G.cv);
pthread_mutex_unlock(&G.mu);
if (started) pthread_join(G.th, NULL);
G.started = G.ready = G.failed = G.quit = false;
}
TINYBLOCKS_DEFINE_LIBRARY(gl, "tinyblocks-gl", "1.0.0", lib_init, lib_deinit)
const TinyBlocks_LibraryDescriptor* tb_gl_get_library(void) {
return &_tb_lib_desc_gl;
}