nano-ui-rgfw-0.2.0.0: cbits/nano_ui_gl.c
/* OpenGL 3.2 core renderer for the RGFW host.
*
* Geometry is the core's shared draw buffer uploaded as-is (32-byte vertices:
* position, RGBA, UV; 32-bit indices) and drawn per command under a scissor.
* Image-atlas commands sample it tinted by vertex colour; other geometry is
* flat. Text is pre-clipped glyph quads in physical pixels, sampled from an
* R8 coverage atlas.
*
* Frames draw into a retained offscreen framebuffer, which keeps the pixels
* outside a frame's damage, and every present copies it to the window: the
* window's back buffer is undefined after a swap, the retained one is not.
*
* GL entry points are resolved through RGFW's loader, so this file needs no
* GL headers and adds no link dependencies. */
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef void (*rgfw_proc)(void);
extern rgfw_proc RGFW_getProcAddress_OpenGL(const char* procname);
#if defined(_WIN32)
#define NGL_API __stdcall
#else
#define NGL_API
#endif
typedef uint32_t GLenum;
typedef uint32_t GLuint;
typedef uint32_t GLbitfield;
typedef int32_t GLint;
typedef int32_t GLsizei;
typedef float GLfloat;
typedef uint8_t GLboolean;
typedef char GLchar;
typedef intptr_t GLsizeiptr;
#define GL_FALSE 0
#define GL_ONE 1
#define GL_TRIANGLES 0x0004
#define GL_SRC_ALPHA 0x0302
#define GL_ONE_MINUS_SRC_ALPHA 0x0303
#define GL_CULL_FACE 0x0B44
#define GL_DEPTH_TEST 0x0B71
#define GL_BLEND 0x0BE2
#define GL_SCISSOR_TEST 0x0C11
#define GL_UNPACK_ROW_LENGTH 0x0CF2
#define GL_UNPACK_ALIGNMENT 0x0CF5
#define GL_PACK_ALIGNMENT 0x0D05
#define GL_TEXTURE_2D 0x0DE1
#define GL_UNSIGNED_BYTE 0x1401
#define GL_UNSIGNED_INT 0x1405
#define GL_FLOAT 0x1406
#define GL_RED 0x1903
#define GL_VERSION 0x1F02
#define GL_NEAREST 0x2600
#define GL_LINEAR 0x2601
#define GL_TEXTURE_MAG_FILTER 0x2800
#define GL_TEXTURE_MIN_FILTER 0x2801
#define GL_TEXTURE_WRAP_S 0x2802
#define GL_TEXTURE_WRAP_T 0x2803
#define GL_COLOR_BUFFER_BIT 0x4000
#define GL_CLAMP_TO_EDGE 0x812F
#define GL_R8 0x8229
#define GL_RGBA 0x1908
#define GL_RGBA8 0x8058
#define GL_READ_FRAMEBUFFER 0x8CA8
#define GL_DRAW_FRAMEBUFFER 0x8CA9
#define GL_FRAMEBUFFER_COMPLETE 0x8CD5
#define GL_COLOR_ATTACHMENT0 0x8CE0
#define GL_FRAMEBUFFER 0x8D40
#define GL_TEXTURE0 0x84C0
#define GL_TEXTURE1 0x84C1
#define GL_ARRAY_BUFFER 0x8892
#define GL_ELEMENT_ARRAY_BUFFER 0x8893
#define GL_STREAM_DRAW 0x88E0
#define GL_UNIFORM_BUFFER 0x8A11
#define GL_INVALID_INDEX 0xFFFFFFFFu
#define GL_FRAGMENT_SHADER 0x8B30
#define GL_VERTEX_SHADER 0x8B31
#define GL_COMPILE_STATUS 0x8B81
#define GL_LINK_STATUS 0x8B82
#define GL_FRAMEBUFFER_SRGB 0x8DB9
#define NGL_FUNCS \
X(const uint8_t*, GetString, (GLenum)) \
X(void, Viewport, (GLint, GLint, GLsizei, GLsizei)) \
X(void, Scissor, (GLint, GLint, GLsizei, GLsizei)) \
X(void, ClearColor, (GLfloat, GLfloat, GLfloat, GLfloat)) \
X(void, Clear, (GLbitfield)) \
X(void, Enable, (GLenum)) \
X(void, Disable, (GLenum)) \
X(void, BlendFuncSeparate, (GLenum, GLenum, GLenum, GLenum)) \
X(void, PixelStorei, (GLenum, GLint)) \
X(GLuint, CreateShader, (GLenum)) \
X(void, ShaderSource, (GLuint, GLsizei, const GLchar* const*, const GLint*)) \
X(void, CompileShader, (GLuint)) \
X(void, GetShaderiv, (GLuint, GLenum, GLint*)) \
X(void, GetShaderInfoLog, (GLuint, GLsizei, GLsizei*, GLchar*)) \
X(void, DeleteShader, (GLuint)) \
X(GLuint, CreateProgram, (void)) \
X(void, AttachShader, (GLuint, GLuint)) \
X(void, BindAttribLocation, (GLuint, GLuint, const GLchar*)) \
X(void, LinkProgram, (GLuint)) \
X(void, GetProgramiv, (GLuint, GLenum, GLint*)) \
X(void, GetProgramInfoLog, (GLuint, GLsizei, GLsizei*, GLchar*)) \
X(void, DeleteProgram, (GLuint)) \
X(void, UseProgram, (GLuint)) \
X(GLint, GetUniformLocation, (GLuint, const GLchar*)) \
X(GLuint, GetUniformBlockIndex, (GLuint, const GLchar*)) \
X(void, UniformBlockBinding, (GLuint, GLuint, GLuint)) \
X(void, BindBufferBase, (GLenum, GLuint, GLuint)) \
X(void, Uniform1i, (GLint, GLint)) \
X(void, Uniform1f, (GLint, GLfloat)) \
X(void, Uniform2f, (GLint, GLfloat, GLfloat)) \
X(void, GenVertexArrays, (GLsizei, GLuint*)) \
X(void, BindVertexArray, (GLuint)) \
X(void, DeleteVertexArrays, (GLsizei, const GLuint*)) \
X(void, GenBuffers, (GLsizei, GLuint*)) \
X(void, BindBuffer, (GLenum, GLuint)) \
X(void, BufferData, (GLenum, GLsizeiptr, const void*, GLenum)) \
X(void, DeleteBuffers, (GLsizei, const GLuint*)) \
X(void, EnableVertexAttribArray, (GLuint)) \
X(void, VertexAttribPointer, (GLuint, GLint, GLenum, GLboolean, GLsizei, const void*)) \
X(void, DrawElements, (GLenum, GLsizei, GLenum, const void*)) \
X(void, DrawArrays, (GLenum, GLint, GLsizei)) \
X(void, GenTextures, (GLsizei, GLuint*)) \
X(void, BindTexture, (GLenum, GLuint)) \
X(void, ActiveTexture, (GLenum)) \
X(void, TexParameteri, (GLenum, GLenum, GLint)) \
X(void, TexImage2D, (GLenum, GLint, GLint, GLsizei, GLsizei, GLint, GLenum, GLenum, const void*)) \
X(void, TexSubImage2D, (GLenum, GLint, GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, const void*)) \
X(void, DeleteTextures, (GLsizei, const GLuint*)) \
X(void, ReadPixels, (GLint, GLint, GLsizei, GLsizei, GLenum, GLenum, void*)) \
X(void, GenFramebuffers, (GLsizei, GLuint*)) \
X(void, BindFramebuffer, (GLenum, GLuint)) \
X(void, FramebufferTexture2D, (GLenum, GLenum, GLenum, GLuint, GLint)) \
X(GLenum, CheckFramebufferStatus, (GLenum)) \
X(void, DeleteFramebuffers, (GLsizei, const GLuint*)) \
X(void, BlitFramebuffer, (GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLint, GLbitfield, GLenum))
typedef struct ngl_api {
#define X(ret, name, args) ret(NGL_API* name) args;
NGL_FUNCS
#undef X
} ngl_api;
/* Must match the core's vertexSize / indexSize. nano-ui-rgfw-test checks
* them through nano_ui_gl_vertex_bytes and nano_ui_gl_index_bytes. */
enum { NGL_VERTEX_BYTES = 32, NGL_INDEX_BYTES = 4 };
/* One vertex of the core's draw buffer and of the text quads Gl.hs writes
* (writeSpanQuads): position, RGBA from 0 to 1, UV. ngl_vertex_layout points
* the attributes at these fields. */
typedef struct ngl_vertex {
float x, y;
float r, g, b, a;
float u, v;
} ngl_vertex;
_Static_assert(sizeof(ngl_vertex) == NGL_VERTEX_BYTES, "ngl_vertex must be the core's 32-byte vertex");
_Static_assert(offsetof(ngl_vertex, r) == 8, "colour follows the 2-float position");
_Static_assert(offsetof(ngl_vertex, u) == 24, "UV follows the 4-float colour");
_Static_assert(sizeof(uint32_t) == NGL_INDEX_BYTES, "indices are 32-bit");
int32_t nano_ui_gl_vertex_bytes(void) { return NGL_VERTEX_BYTES; }
int32_t nano_ui_gl_index_bytes(void) { return NGL_INDEX_BYTES; }
enum { NGL_MODE_NONE, NGL_MODE_GEOMETRY, NGL_MODE_IMAGE, NGL_MODE_TEXT };
typedef struct ngl_shader_entry {
uint64_t hash;
GLuint program;
GLint uViewport;
GLint uOrigin;
GLint uScale;
GLint uInput;
int failed;
} ngl_shader_entry;
typedef struct ngl_target_slot {
GLuint fbo;
GLuint tex;
int32_t capW;
int32_t capH;
int inUse;
} ngl_target_slot;
typedef struct nano_ui_gl {
ngl_api gl;
GLuint program;
GLint uViewport, uOrigin, uScale, uTextured, uAtlas, uImages;
GLuint geomVao, geomVbo, geomEbo;
GLuint textVao, textVbo;
GLuint effectVao, effectVbo;
GLuint shaderUbo;
ngl_shader_entry* shaders;
int shaderCount, shaderCap;
ngl_target_slot* targets;
int targetCount, targetCap;
GLuint atlas;
GLuint images; /* the core's RGBA image atlas, texture unit 1 */
int32_t imagesW, imagesH;
GLuint retainFbo, retainTex;
int32_t retainCapW, retainCapH; /* texture size, the window rounded up */
int32_t fbW, fbH;
int32_t curW, curH; /* currently bound framebuffer dimensions */
float originX, originY; /* logical origin subtracted for offscreen effect targets */
float scale; /* logical -> physical, for geometry vertices */
int mode;
} nano_ui_gl;
static const char* ngl_vertex_src =
"#version 150\n"
"in vec2 aPos;\n"
"in vec4 aColor;\n"
"in vec2 aUV;\n"
"uniform vec2 uViewport;\n"
"uniform vec2 uOrigin;\n"
"uniform float uScale;\n"
"out vec4 vColor;\n"
"out vec2 vUV;\n"
"void main() {\n"
" vec2 p = (aPos - uOrigin) * uScale;\n"
" gl_Position = vec4(p.x / uViewport.x * 2.0 - 1.0, 1.0 - p.y / uViewport.y * 2.0, 0.0, 1.0);\n"
" vColor = aColor;\n"
" vUV = aUV;\n"
"}\n";
static const char* ngl_fragment_src =
"#version 150\n"
"in vec4 vColor;\n"
"in vec2 vUV;\n"
"uniform sampler2D uAtlas;\n"
"uniform sampler2D uImages;\n"
"uniform float uTextured;\n"
"out vec4 fragColor;\n"
"void main() {\n"
" if (uTextured > 1.5) {\n"
" fragColor = texture(uImages, vUV) * vColor;\n"
" } else {\n"
" float coverage = uTextured > 0.5 ? texture(uAtlas, vUV).r : 1.0;\n"
" fragColor = vec4(vColor.rgb, vColor.a * coverage);\n"
" }\n"
"}\n";
static int ngl_load(ngl_api* gl) {
#define X(ret, name, args) \
gl->name = (ret(NGL_API*) args)RGFW_getProcAddress_OpenGL("gl" #name); \
if (gl->name == NULL) { \
fprintf(stderr, "nano-ui-rgfw: OpenGL entry point gl%s is unavailable\n", #name); \
return 0; \
}
NGL_FUNCS
#undef X
return 1;
}
static GLuint ngl_compile(ngl_api* gl, GLenum type, const char* src) {
GLuint shader = gl->CreateShader(type);
GLint ok = 0;
gl->ShaderSource(shader, 1, &src, NULL);
gl->CompileShader(shader);
gl->GetShaderiv(shader, GL_COMPILE_STATUS, &ok);
if (!ok) {
char log[1024];
gl->GetShaderInfoLog(shader, sizeof log, NULL, log);
fprintf(stderr, "nano-ui-rgfw: shader compile failed: %s\n", log);
gl->DeleteShader(shader);
return 0;
}
return shader;
}
static GLuint ngl_link_program(ngl_api* gl, const char* fragSrc, const char* errPrefix) {
GLuint vs = ngl_compile(gl, GL_VERTEX_SHADER, ngl_vertex_src);
GLuint fs = vs ? ngl_compile(gl, GL_FRAGMENT_SHADER, fragSrc) : 0;
GLint ok = 0;
if (!fs) {
if (vs) gl->DeleteShader(vs);
return 0;
}
GLuint prog = gl->CreateProgram();
gl->AttachShader(prog, vs);
gl->AttachShader(prog, fs);
gl->BindAttribLocation(prog, 0, "aPos");
gl->BindAttribLocation(prog, 1, "aColor");
gl->BindAttribLocation(prog, 2, "aUV");
gl->LinkProgram(prog);
gl->DeleteShader(vs);
gl->DeleteShader(fs);
gl->GetProgramiv(prog, GL_LINK_STATUS, &ok);
if (!ok) {
char log[1024];
gl->GetProgramInfoLog(prog, sizeof log, NULL, log);
fprintf(stderr, "nano-ui-rgfw: %s: %s\n", errPrefix, log);
gl->DeleteProgram(prog);
return 0;
}
return prog;
}
static int ngl_link(nano_ui_gl* r) {
ngl_api* gl = &r->gl;
r->program = ngl_link_program(gl, ngl_fragment_src, "shader link failed");
if (!r->program) return 0;
r->uViewport = gl->GetUniformLocation(r->program, "uViewport");
r->uOrigin = gl->GetUniformLocation(r->program, "uOrigin");
r->uScale = gl->GetUniformLocation(r->program, "uScale");
r->uTextured = gl->GetUniformLocation(r->program, "uTextured");
r->uAtlas = gl->GetUniformLocation(r->program, "uAtlas");
r->uImages = gl->GetUniformLocation(r->program, "uImages");
return 1;
}
static void ngl_vertex_layout(ngl_api* gl) {
gl->EnableVertexAttribArray(0);
gl->VertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, NGL_VERTEX_BYTES, (const void*)offsetof(ngl_vertex, x));
gl->EnableVertexAttribArray(1);
gl->VertexAttribPointer(1, 4, GL_FLOAT, GL_FALSE, NGL_VERTEX_BYTES, (const void*)offsetof(ngl_vertex, r));
gl->EnableVertexAttribArray(2);
gl->VertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, NGL_VERTEX_BYTES, (const void*)offsetof(ngl_vertex, u));
}
static int ngl_major_version(const uint8_t* version) {
int major = 0;
if (version == NULL) return 0;
for (; *version >= '0' && *version <= '9'; version++) major = major * 10 + (*version - '0');
return major;
}
void nano_ui_gl_destroy(nano_ui_gl* r);
/* Requires the target context to be current. Returns NULL (after logging the
* reason to stderr) when the context cannot run the renderer. */
nano_ui_gl* nano_ui_gl_create(void) {
nano_ui_gl* r = (nano_ui_gl*)calloc(1, sizeof *r);
if (r == NULL) return NULL;
ngl_api* gl = &r->gl;
if (!ngl_load(gl)) {
free(r);
return NULL;
}
const uint8_t* version = gl->GetString(GL_VERSION);
if (ngl_major_version(version) < 3) {
fprintf(stderr, "nano-ui-rgfw: OpenGL 3.2 required, context reports %s\n",
version ? (const char*)version : "no version");
free(r);
return NULL;
}
if (!ngl_link(r)) {
nano_ui_gl_destroy(r);
return NULL;
}
gl->GenVertexArrays(1, &r->geomVao);
gl->GenBuffers(1, &r->geomVbo);
gl->GenBuffers(1, &r->geomEbo);
gl->BindVertexArray(r->geomVao);
gl->BindBuffer(GL_ARRAY_BUFFER, r->geomVbo);
gl->BindBuffer(GL_ELEMENT_ARRAY_BUFFER, r->geomEbo);
ngl_vertex_layout(gl);
gl->GenVertexArrays(1, &r->textVao);
gl->GenBuffers(1, &r->textVbo);
gl->BindVertexArray(r->textVao);
gl->BindBuffer(GL_ARRAY_BUFFER, r->textVbo);
ngl_vertex_layout(gl);
gl->GenVertexArrays(1, &r->effectVao);
gl->GenBuffers(1, &r->effectVbo);
gl->BindVertexArray(r->effectVao);
gl->BindBuffer(GL_ARRAY_BUFFER, r->effectVbo);
ngl_vertex_layout(gl);
gl->BindVertexArray(0);
gl->GenBuffers(1, &r->shaderUbo);
gl->GenTextures(1, &r->atlas);
gl->BindTexture(GL_TEXTURE_2D, r->atlas);
gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
gl->UseProgram(r->program);
gl->Uniform1i(r->uAtlas, 0);
gl->Uniform1i(r->uImages, 1);
return r;
}
void nano_ui_gl_destroy(nano_ui_gl* r) {
if (r == NULL) return;
ngl_api* gl = &r->gl;
if (r->shaders) {
for (int i = 0; i < r->shaderCount; i++) {
if (r->shaders[i].program) gl->DeleteProgram(r->shaders[i].program);
}
free(r->shaders);
}
if (r->targets) {
for (int i = 0; i < r->targetCount; i++) {
if (r->targets[i].fbo) gl->DeleteFramebuffers(1, &r->targets[i].fbo);
if (r->targets[i].tex) gl->DeleteTextures(1, &r->targets[i].tex);
}
free(r->targets);
}
if (r->shaderUbo) gl->DeleteBuffers(1, &r->shaderUbo);
if (r->effectVbo) gl->DeleteBuffers(1, &r->effectVbo);
if (r->effectVao) gl->DeleteVertexArrays(1, &r->effectVao);
if (r->retainFbo) gl->DeleteFramebuffers(1, &r->retainFbo);
if (r->retainTex) gl->DeleteTextures(1, &r->retainTex);
if (r->atlas) gl->DeleteTextures(1, &r->atlas);
if (r->images) gl->DeleteTextures(1, &r->images);
if (r->textVbo) gl->DeleteBuffers(1, &r->textVbo);
if (r->textVao) gl->DeleteVertexArrays(1, &r->textVao);
if (r->geomEbo) gl->DeleteBuffers(1, &r->geomEbo);
if (r->geomVbo) gl->DeleteBuffers(1, &r->geomVbo);
if (r->geomVao) gl->DeleteVertexArrays(1, &r->geomVao);
if (r->program) gl->DeleteProgram(r->program);
free(r);
}
/* Replace the glyph atlas. Pixels are the software blitter's white-on-black
* bake; the low byte of each pixel is its coverage. Returns 0 on allocation
* failure. */
int32_t nano_ui_gl_upload_atlas(nano_ui_gl* r, const uint32_t* pixels, int32_t w, int32_t h) {
ngl_api* gl = &r->gl;
size_t n = (size_t)w * (size_t)h;
uint8_t* coverage = (uint8_t*)malloc(n > 0 ? n : 1);
if (coverage == NULL) return 0;
for (size_t i = 0; i < n; i++) coverage[i] = (uint8_t)(pixels[i] & 0xFF);
gl->BindTexture(GL_TEXTURE_2D, r->atlas);
gl->PixelStorei(GL_UNPACK_ALIGNMENT, 1);
gl->TexImage2D(GL_TEXTURE_2D, 0, GL_R8, w, h, 0, GL_RED, GL_UNSIGNED_BYTE, coverage);
free(coverage);
return 1;
}
/* Sync the image texture with the core's atlasW x atlasH RGBA image atlas.
* With whole set, reallocate the texture at that size and upload everything;
* otherwise upload only the x, y, w, h rect. Returns 0 if a rect upload finds
* no texture of the atlas's size. */
int32_t nano_ui_gl_upload_images(nano_ui_gl* r, const uint8_t* pixels, int32_t atlasW, int32_t atlasH,
int32_t x, int32_t y, int32_t w, int32_t h, int32_t whole) {
ngl_api* gl = &r->gl;
if (!whole && (r->images == 0 || r->imagesW != atlasW || r->imagesH != atlasH)) return 0;
if (r->images == 0) {
gl->GenTextures(1, &r->images);
gl->ActiveTexture(GL_TEXTURE1);
gl->BindTexture(GL_TEXTURE_2D, r->images);
gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
} else {
gl->ActiveTexture(GL_TEXTURE1);
gl->BindTexture(GL_TEXTURE_2D, r->images);
}
gl->PixelStorei(GL_UNPACK_ALIGNMENT, 1);
if (whole) {
gl->TexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, atlasW, atlasH, 0, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
r->imagesW = atlasW;
r->imagesH = atlasH;
} else {
gl->PixelStorei(GL_UNPACK_ROW_LENGTH, atlasW);
gl->TexSubImage2D(GL_TEXTURE_2D, 0, x, y, w, h, GL_RGBA, GL_UNSIGNED_BYTE,
pixels + ((size_t)y * (size_t)atlasW + (size_t)x) * 4);
gl->PixelStorei(GL_UNPACK_ROW_LENGTH, 0);
}
gl->ActiveTexture(GL_TEXTURE0);
return 1;
}
/* Pixels the retained texture is rounded up to, in each dimension. */
enum { NGL_RETAIN_BLOCK = 256 };
static int32_t ngl_round_up(int32_t n) {
return (n + NGL_RETAIN_BLOCK - 1) / NGL_RETAIN_BLOCK * NGL_RETAIN_BLOCK;
}
/* Make the retained framebuffer hold at least w x h pixels. A texture well
* past the window is given back, but not for a shrink of a block or so, which
* a drag back out would undo. Returns 1 if the texture was replaced, which
* discards its pixels, 0 if it was kept, and -1 on failure. */
static int ngl_ensure_retain(nano_ui_gl* r, int32_t w, int32_t h) {
ngl_api* gl = &r->gl;
int fits = r->retainFbo && w <= r->retainCapW && h <= r->retainCapH;
int roomy = r->retainCapW - w > 2 * NGL_RETAIN_BLOCK || r->retainCapH - h > 2 * NGL_RETAIN_BLOCK;
if (fits && !roomy) return 0;
if (!r->retainFbo) {
gl->GenFramebuffers(1, &r->retainFbo);
gl->GenTextures(1, &r->retainTex);
}
r->retainCapW = ngl_round_up(w);
r->retainCapH = ngl_round_up(h);
gl->BindTexture(GL_TEXTURE_2D, r->retainTex);
gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
gl->TexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, r->retainCapW, r->retainCapH, 0, GL_RGBA,
GL_UNSIGNED_BYTE, NULL);
gl->BindFramebuffer(GL_FRAMEBUFFER, r->retainFbo);
gl->FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, r->retainTex, 0);
if (gl->CheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) {
fprintf(stderr, "nano-ui-rgfw: retained framebuffer is incomplete\n");
gl->BindFramebuffer(GL_FRAMEBUFFER, 0);
r->retainCapW = 0;
r->retainCapH = 0;
return -1;
}
return 1;
}
/* Start a frame on the retained framebuffer: viewport, fixed pipeline state,
* and the logical -> physical scale for this frame's geometry. A full frame
* clears everything; otherwise nothing is cleared, since the frame's own
* backdrop covers what it repaints, and nothing is drawn outside the damage
* box, where the pixels are last frame's; the core has already cut every
* command and span to the damage. A framebuffer replaced for a new size holds
* no last frame and is cleared too, so a caller must paint a frame at a new
* size in full. Returns 0 if the retained framebuffer cannot be made, and 1
* otherwise. */
int32_t nano_ui_gl_begin(nano_ui_gl* r, int32_t fbW, int32_t fbH, float scale, float red,
float green, float blue, int32_t full) {
ngl_api* gl = &r->gl;
r->fbW = fbW > 0 ? fbW : 1;
r->fbH = fbH > 0 ? fbH : 1;
r->curW = r->fbW;
r->curH = r->fbH;
r->originX = 0.0f;
r->originY = 0.0f;
r->scale = scale;
r->mode = NGL_MODE_NONE;
int replaced = ngl_ensure_retain(r, r->fbW, r->fbH);
if (replaced < 0) return 0;
gl->BindFramebuffer(GL_FRAMEBUFFER, r->retainFbo);
gl->Viewport(0, 0, r->fbW, r->fbH);
gl->Disable(GL_DEPTH_TEST);
gl->Disable(GL_CULL_FACE);
gl->Disable(GL_FRAMEBUFFER_SRGB);
gl->Disable(GL_SCISSOR_TEST);
if (full || replaced) {
gl->ClearColor(red, green, blue, 1.0f);
gl->Clear(GL_COLOR_BUFFER_BIT);
}
gl->Enable(GL_BLEND);
gl->BlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
gl->UseProgram(r->program);
gl->Uniform2f(r->uViewport, (GLfloat)r->fbW, (GLfloat)r->fbH);
gl->Uniform2f(r->uOrigin, 0.0f, 0.0f);
gl->ActiveTexture(GL_TEXTURE1);
gl->BindTexture(GL_TEXTURE_2D, r->images);
gl->ActiveTexture(GL_TEXTURE0);
gl->BindTexture(GL_TEXTURE_2D, r->atlas);
return 1;
}
/* Read the bottom-left w x h of the retained frame as RGBA rows, bottom row
* first, into out, which holds w * h * 4 bytes. Pixels past the last frame's
* size are undefined. */
void nano_ui_gl_read_retained(nano_ui_gl* r, int32_t w, int32_t h, uint8_t* out) {
ngl_api* gl = &r->gl;
gl->BindFramebuffer(GL_READ_FRAMEBUFFER, r->retainFbo);
gl->PixelStorei(GL_PACK_ALIGNMENT, 1);
gl->ReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, out);
gl->BindFramebuffer(GL_FRAMEBUFFER, 0);
}
/* Read the window's back buffer after present and before the swap, which
* leaves it undefined, as nano_ui_gl_read_retained does. Used by tests of
* the present. */
void nano_ui_gl_read_window(nano_ui_gl* r, int32_t w, int32_t h, uint8_t* out) {
ngl_api* gl = &r->gl;
gl->BindFramebuffer(GL_READ_FRAMEBUFFER, 0);
gl->PixelStorei(GL_PACK_ALIGNMENT, 1);
gl->ReadPixels(0, 0, w, h, GL_RGBA, GL_UNSIGNED_BYTE, out);
gl->BindFramebuffer(GL_FRAMEBUFFER, 0);
}
/* Copy the retained frame to the window's back buffer. The caller swaps. */
void nano_ui_gl_present(nano_ui_gl* r) {
ngl_api* gl = &r->gl;
gl->Disable(GL_SCISSOR_TEST);
gl->BindFramebuffer(GL_READ_FRAMEBUFFER, r->retainFbo);
gl->BindFramebuffer(GL_DRAW_FRAMEBUFFER, 0);
gl->BlitFramebuffer(0, 0, r->fbW, r->fbH, 0, 0, r->fbW, r->fbH, GL_COLOR_BUFFER_BIT, GL_NEAREST);
gl->BindFramebuffer(GL_FRAMEBUFFER, 0);
r->mode = NGL_MODE_NONE;
}
void nano_ui_gl_upload_geometry(nano_ui_gl* r, const void* vertices, int32_t vertexCount,
const void* indices, int32_t indexCount) {
ngl_api* gl = &r->gl;
r->mode = NGL_MODE_NONE;
gl->BindVertexArray(r->geomVao);
gl->BindBuffer(GL_ARRAY_BUFFER, r->geomVbo);
gl->BufferData(GL_ARRAY_BUFFER, (GLsizeiptr)vertexCount * NGL_VERTEX_BYTES,
vertexCount > 0 ? vertices : NULL, GL_STREAM_DRAW);
gl->BufferData(GL_ELEMENT_ARRAY_BUFFER, (GLsizeiptr)indexCount * NGL_INDEX_BYTES,
indexCount > 0 ? indices : NULL, GL_STREAM_DRAW);
}
void nano_ui_gl_upload_text(nano_ui_gl* r, const void* vertices, int32_t vertexCount) {
ngl_api* gl = &r->gl;
r->mode = NGL_MODE_NONE;
gl->BindVertexArray(r->textVao);
gl->BindBuffer(GL_ARRAY_BUFFER, r->textVbo);
gl->BufferData(GL_ARRAY_BUFFER, (GLsizeiptr)vertexCount * NGL_VERTEX_BYTES,
vertexCount > 0 ? vertices : NULL, GL_STREAM_DRAW);
}
/* Draw one command's index range, sampling the image texture if image is
* set. The clip is in top-left physical pixels, already intersected with the
* framebuffer; vertices are logical and scaled in the vertex shader by the
* frame's scale. */
void nano_ui_gl_draw_geometry(nano_ui_gl* r, int32_t x0, int32_t y0, int32_t x1, int32_t y1,
uint32_t firstIndex, uint32_t indexCount, int32_t image) {
ngl_api* gl = &r->gl;
int mode = image && r->images ? NGL_MODE_IMAGE : NGL_MODE_GEOMETRY;
if (r->mode != mode) {
if (r->mode != NGL_MODE_GEOMETRY && r->mode != NGL_MODE_IMAGE) {
gl->BindVertexArray(r->geomVao);
gl->Uniform1f(r->uScale, r->scale);
gl->Uniform2f(r->uOrigin, r->originX, r->originY);
gl->Enable(GL_SCISSOR_TEST);
}
gl->Uniform1f(r->uTextured, mode == NGL_MODE_IMAGE ? 2.0f : 0.0f);
r->mode = mode;
}
gl->Scissor(x0, r->curH - y1, x1 - x0, y1 - y0);
gl->DrawElements(GL_TRIANGLES, (GLsizei)indexCount, GL_UNSIGNED_INT,
(const void*)((uintptr_t)firstIndex * NGL_INDEX_BYTES));
}
/* Look up or compile and link a cached fragment shader keyed by its 64-bit
* program hash. Failed compilations are cached so broken shaders never spam
* error logs on every frame. */
static ngl_shader_entry* ngl_get_shader(nano_ui_gl* r, uint64_t hash, const char* fragSrc, int32_t fragLen) {
for (int i = 0; i < r->shaderCount; i++) {
if (r->shaders[i].hash == hash) return &r->shaders[i];
}
if (r->shaderCount == r->shaderCap) {
int newCap = r->shaderCap > 0 ? r->shaderCap * 2 : 16;
ngl_shader_entry* grown = (ngl_shader_entry*)realloc(r->shaders, (size_t)newCap * sizeof *grown);
if (grown == NULL) return NULL;
r->shaders = grown;
r->shaderCap = newCap;
}
ngl_shader_entry* entry = &r->shaders[r->shaderCount++];
memset(entry, 0, sizeof *entry);
entry->hash = hash;
entry->uViewport = -1;
entry->uOrigin = -1;
entry->uScale = -1;
entry->uInput = -1;
if (fragSrc == NULL || fragLen <= 0) {
entry->failed = 1;
return entry;
}
char* srcCopy = (char*)malloc((size_t)fragLen + 1);
if (srcCopy == NULL) {
entry->failed = 1;
return entry;
}
memcpy(srcCopy, fragSrc, (size_t)fragLen);
srcCopy[fragLen] = '\0';
ngl_api* gl = &r->gl;
GLuint prog = ngl_link_program(gl, srcCopy, "custom shader link failed");
free(srcCopy);
if (!prog) {
entry->failed = 1;
return entry;
}
GLuint blk = gl->GetUniformBlockIndex(prog, "NanoShaderBlock");
if (blk != GL_INVALID_INDEX) {
gl->UniformBlockBinding(prog, blk, 0);
}
entry->program = prog;
entry->uViewport = gl->GetUniformLocation(prog, "uViewport");
entry->uOrigin = gl->GetUniformLocation(prog, "uOrigin");
entry->uScale = gl->GetUniformLocation(prog, "uScale");
entry->uInput = gl->GetUniformLocation(prog, "uInput");
return entry;
}
static void ngl_bind_shader_uniforms(
nano_ui_gl* r, ngl_shader_entry* entry, float ox, float oy, float scale,
const void* uniformBytes, int32_t uniformLen) {
ngl_api* gl = &r->gl;
gl->UseProgram(entry->program);
if (entry->uViewport >= 0) gl->Uniform2f(entry->uViewport, (GLfloat)r->curW, (GLfloat)r->curH);
if (entry->uOrigin >= 0) gl->Uniform2f(entry->uOrigin, ox, oy);
if (entry->uScale >= 0) gl->Uniform1f(entry->uScale, scale);
if (entry->uInput >= 0) gl->Uniform1i(entry->uInput, 0);
if (uniformLen > 0 && uniformBytes != NULL) {
gl->BindBuffer(GL_UNIFORM_BUFFER, r->shaderUbo);
gl->BufferData(GL_UNIFORM_BUFFER, (GLsizeiptr)uniformLen, uniformBytes, GL_STREAM_DRAW);
gl->BindBufferBase(GL_UNIFORM_BUFFER, 0, r->shaderUbo);
}
}
static void ngl_restore_default(nano_ui_gl* r) {
ngl_api* gl = &r->gl;
gl->UseProgram(r->program);
gl->Uniform2f(r->uViewport, (GLfloat)r->curW, (GLfloat)r->curH);
gl->Uniform2f(r->uOrigin, r->originX, r->originY);
r->mode = NGL_MODE_NONE;
}
/* Draw one shader-backed geometry command with its std140 uniform block bound
* at UBO binding 0, then restore the default renderer program. */
int32_t nano_ui_gl_draw_shader(nano_ui_gl* r, int32_t x0, int32_t y0, int32_t x1, int32_t y1,
uint32_t firstIndex, uint32_t indexCount, uint64_t hash,
const char* fragSrc, int32_t fragLen, const void* uniformBytes,
int32_t uniformLen) {
ngl_shader_entry* entry = ngl_get_shader(r, hash, fragSrc, fragLen);
if (entry == NULL || entry->failed || entry->program == 0) return 0;
ngl_api* gl = &r->gl;
ngl_bind_shader_uniforms(r, entry, r->originX, r->originY, r->scale, uniformBytes, uniformLen);
gl->BindVertexArray(r->geomVao);
gl->Enable(GL_SCISSOR_TEST);
gl->Scissor(x0, r->curH - y1, x1 - x0, y1 - y0);
gl->DrawElements(GL_TRIANGLES, (GLsizei)indexCount, GL_UNSIGNED_INT,
(const void*)((uintptr_t)firstIndex * NGL_INDEX_BYTES));
ngl_restore_default(r);
return 1;
}
/* Draw a range of the uploaded glyph vertices (physical pixels, pre-clipped). */
void nano_ui_gl_draw_text(nano_ui_gl* r, int32_t firstVertex, int32_t vertexCount) {
ngl_api* gl = &r->gl;
if (vertexCount <= 0) return;
if (r->mode != NGL_MODE_TEXT) {
gl->BindVertexArray(r->textVao);
gl->Uniform1f(r->uTextured, 1.0f);
gl->Uniform1f(r->uScale, 1.0f);
gl->Uniform2f(r->uOrigin, r->originX * r->scale, r->originY * r->scale);
gl->Disable(GL_SCISSOR_TEST);
r->mode = NGL_MODE_TEXT;
}
gl->DrawArrays(GL_TRIANGLES, firstVertex, vertexCount);
}
/* Acquire a 64px-bucketed pooled RGBA8 offscreen framebuffer for Tier 2
* subtree effects. Returns a non-negative slot index or -1 on failure. */
int32_t nano_ui_gl_acquire_target(nano_ui_gl* r, int32_t minW, int32_t minH,
int32_t* outCapW, int32_t* outCapH) {
if (r == NULL) return -1;
int32_t needW = minW > 0 ? ((minW + 63) & ~63) : 64;
int32_t needH = minH > 0 ? ((minH + 63) & ~63) : 64;
int best = -1;
for (int i = 0; i < r->targetCount; i++) {
ngl_target_slot* s = &r->targets[i];
if (!s->inUse && s->fbo && s->tex &&
s->capW >= needW && s->capH >= needH &&
s->capW <= needW * 2 && s->capH <= needH * 2) {
best = i;
break;
}
}
if (best < 0) {
if (r->targetCount == r->targetCap) {
int newCap = r->targetCap > 0 ? r->targetCap * 2 : 8;
ngl_target_slot* grown = (ngl_target_slot*)realloc(r->targets, (size_t)newCap * sizeof *grown);
if (grown == NULL) return -1;
r->targets = grown;
r->targetCap = newCap;
}
ngl_api* gl = &r->gl;
GLuint fbo = 0, tex = 0;
gl->GenFramebuffers(1, &fbo);
gl->GenTextures(1, &tex);
gl->ActiveTexture(GL_TEXTURE0);
gl->BindTexture(GL_TEXTURE_2D, tex);
gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
gl->TexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
gl->TexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, needW, needH, 0, GL_RGBA, GL_UNSIGNED_BYTE, NULL);
gl->BindFramebuffer(GL_FRAMEBUFFER, fbo);
gl->FramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex, 0);
GLenum status = gl->CheckFramebufferStatus(GL_FRAMEBUFFER);
gl->BindTexture(GL_TEXTURE_2D, r->atlas);
if (status != GL_FRAMEBUFFER_COMPLETE) {
gl->DeleteFramebuffers(1, &fbo);
gl->DeleteTextures(1, &tex);
return -1;
}
best = r->targetCount++;
r->targets[best].fbo = fbo;
r->targets[best].tex = tex;
r->targets[best].capW = needW;
r->targets[best].capH = needH;
}
r->targets[best].inUse = 1;
if (outCapW) *outCapW = r->targets[best].capW;
if (outCapH) *outCapH = r->targets[best].capH;
return (int32_t)best;
}
void nano_ui_gl_release_target(nano_ui_gl* r, int32_t slot) {
if (r != NULL && slot >= 0 && slot < r->targetCount) {
r->targets[slot].inUse = 0;
}
}
/* Bind pooled offscreen target slot (>= 0), or the retained framebuffer when
* slot < 0. Updates viewport, active target dimensions, and logical origin. */
int32_t nano_ui_gl_bind_target(nano_ui_gl* r, int32_t slot, int32_t clearTransparent,
float ox, float oy) {
if (r == NULL) return 0;
ngl_api* gl = &r->gl;
if (slot >= 0 && slot < r->targetCount) {
ngl_target_slot* s = &r->targets[slot];
gl->BindFramebuffer(GL_FRAMEBUFFER, s->fbo);
r->curW = s->capW;
r->curH = s->capH;
} else {
gl->BindFramebuffer(GL_FRAMEBUFFER, r->retainFbo);
r->curW = r->fbW;
r->curH = r->fbH;
}
r->originX = ox;
r->originY = oy;
gl->Viewport(0, 0, r->curW, r->curH);
gl->Disable(GL_SCISSOR_TEST);
if (clearTransparent) {
gl->ClearColor(0.0f, 0.0f, 0.0f, 0.0f);
gl->Clear(GL_COLOR_BUFFER_BIT);
}
gl->ActiveTexture(GL_TEXTURE0);
gl->BindTexture(GL_TEXTURE_2D, r->atlas);
ngl_restore_default(r);
return 1;
}
/* Composite pooled source target srcSlot onto the currently bound target at
* physical pixel rect (dx, dy, dw, dh) with UVs (u0, v0)..(u1, v1) through a
* cached GLSL 150 fragment shader. */
int32_t nano_ui_gl_composite_effect(
nano_ui_gl* r, int32_t srcSlot,
float dx, float dy, float dw, float dh,
float u0, float v0, float u1, float v1,
int32_t hasScissor, int32_t sx0, int32_t sy0, int32_t sx1, int32_t sy1,
int32_t blendCopy,
uint64_t hash, const char* fragSrc, int32_t fragLen,
const void* uniformBytes, int32_t uniformLen) {
if (r == NULL || srcSlot < 0 || srcSlot >= r->targetCount || !r->targets[srcSlot].tex) {
return 0;
}
(void)blendCopy;
ngl_shader_entry* entry = ngl_get_shader(r, hash, fragSrc, fragLen);
ngl_api* gl = &r->gl;
const ngl_vertex quad[6] = {
{ dx, dy, 1.f, 1.f, 1.f, 1.f, u0, v0 },
{ dx + dw, dy, 1.f, 1.f, 1.f, 1.f, u1, v0 },
{ dx + dw, dy + dh, 1.f, 1.f, 1.f, 1.f, u1, v1 },
{ dx, dy, 1.f, 1.f, 1.f, 1.f, u0, v0 },
{ dx + dw, dy + dh, 1.f, 1.f, 1.f, 1.f, u1, v1 },
{ dx, dy + dh, 1.f, 1.f, 1.f, 1.f, u0, v1 },
};
if (hasScissor) {
gl->Enable(GL_SCISSOR_TEST);
gl->Scissor(sx0, r->curH - sy1, sx1 - sx0, sy1 - sy0);
} else {
gl->Disable(GL_SCISSOR_TEST);
}
gl->Enable(GL_BLEND);
if (entry == NULL || entry->failed || entry->program == 0) {
/* Fallback: blit the offscreen premultiplied target unshaded so the
* wrapped subtree stays visible if shader compilation fails. */
gl->UseProgram(r->program);
gl->Uniform2f(r->uViewport, (GLfloat)r->curW, (GLfloat)r->curH);
gl->Uniform2f(r->uOrigin, 0.0f, 0.0f);
gl->Uniform1f(r->uScale, 1.0f);
gl->Uniform1f(r->uTextured, 2.0f);
gl->ActiveTexture(GL_TEXTURE1);
gl->BindTexture(GL_TEXTURE_2D, r->targets[srcSlot].tex);
gl->BlendFuncSeparate(GL_ONE, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
gl->BindVertexArray(r->effectVao);
gl->BindBuffer(GL_ARRAY_BUFFER, r->effectVbo);
gl->BufferData(GL_ARRAY_BUFFER, (GLsizeiptr)sizeof(quad), quad, GL_STREAM_DRAW);
gl->DrawArrays(GL_TRIANGLES, 0, 6);
gl->BindTexture(GL_TEXTURE_2D, r->images);
gl->ActiveTexture(GL_TEXTURE0);
gl->BlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
gl->Disable(GL_SCISSOR_TEST);
gl->Uniform1f(r->uScale, r->scale);
ngl_restore_default(r);
return 1;
}
ngl_bind_shader_uniforms(r, entry, 0.0f, 0.0f, 1.0f, uniformBytes, uniformLen);
gl->ActiveTexture(GL_TEXTURE0);
gl->BindTexture(GL_TEXTURE_2D, r->targets[srcSlot].tex);
/* Always blend with straight-alpha-to-premultiplied (SRC_ALPHA, 1-SRC_ALPHA,
* ONE, 1-SRC_ALPHA) so both intermediate cleared targets and the final
* composite share premultiplied offscreen representation. */
gl->BlendFuncSeparate(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA, GL_ONE, GL_ONE_MINUS_SRC_ALPHA);
gl->BindVertexArray(r->effectVao);
gl->BindBuffer(GL_ARRAY_BUFFER, r->effectVbo);
gl->BufferData(GL_ARRAY_BUFFER, (GLsizeiptr)sizeof(quad), quad, GL_STREAM_DRAW);
gl->DrawArrays(GL_TRIANGLES, 0, 6);
gl->Enable(GL_BLEND);
gl->Disable(GL_SCISSOR_TEST);
gl->BindTexture(GL_TEXTURE_2D, r->atlas);
ngl_restore_default(r);
return 1;
}