How hugi-r/2d-sdf works
Project type and purpose
• This is a small open-source 2D Signed Distance Function (SDF) software renderer written in C, with two frontends:
• A command-line tool (main.c + render.c/.h) that reads geometry files (.wkt), renders to BMP.
• A WebAssembly/JavaScript demo (webdemo/) exposing the same core via emscripten.
• There is also a standalone Python script (grid.py) for generating .wkt instruction files (not part of the web frontend).
File structure
• Top-level:
• render.c / render.h – the core SDF rendering library (parsing, distance functions, compositing, BMP output).
• main.c – the CLI entrypoint that invokes the render library, handles file I/O and output canvas.
• grid.py – Python utility to generate .wkt geometry (grid pattern) for examples.
• examples/ – sample .wkt instruction files (data.wkt, grid.wkt, bezier.wkt, color_layers.wkt).
• webdemo/ – HTML, C glue code (webdemo.c), and the emscripten build target for the in-browser demo.
README for additional insights
• The README describes how geometries are defined (POINT, SEGMENT, BEZIER, ROUND, LAYER), build commands (gcc for CLI, emcc for web), and usage patterns.
• It highlights the layering model: each layer is independently rendered then blend-composited.
Main components and interactions
a. Components
1. WKT Instruction Files (examples/*.wkt)
2. CLI Frontend (main.c)
3. Core Rendering Engine (render.c / render.h)
– Parser
– SDF Operations & Compositing
– BMP Output Writer
4. Python WKT Generator (grid.py)
5. Web Demo Frontend
– HTML + JavaScript (index.html + generated webdemo.out.js)
– Emscripten glue (webdemo.c)
– Core Rendering Engine compiled to WebAssembly/asm.js
6. External Libraries
– C standard library + libm
– Emscripten runtime (for the web demo)
b. Relationships and data flow
• WKT files → parsed by either the CLI or the WebAssembly module → pass AST/instruction list to the Core Rendering Engine → compute SDF per pixel → output raw image buffer →
– CLI: writes BMP file to disk → user views with an image viewer.
– Web demo: the JavaScript harness copies the buffer into a browser canvas for display.
• grid.py → generates .wkt files as input to the CLI or can be used for other workflows.
c. Architectural patterns and principles
– Separation of concerns: one core library for parsing and rendering, two thin frontends (CLI & Web).
– Adapter pattern in webdemo.c: exposing C functions to JavaScript.
– Data-flow pipeline: parse → compute → composite layers → output.
d. Key technologies and frameworks
– C99, GCC + libm for CLI.
– Emscripten to compile C to WebAssembly/asm.js for the in-browser demo.
– Simple text-based instruction format inspired by WKT.
Key points to capture
• The central, reusable rendering core.
• Two distinct frontends sharing the same engine.
• grid.py’s sole role as a WKT generator (not part of the demo).