Dev ui lesson

From Nebulavenus/forge-gpu · View interactive version

Dev ui lesson is an AI agent skill from the GitHub repository Nebulavenus/forge-gpu. Add a UI lesson — TTF parsing, font rasterization, immediate-mode UI controls, layout

How to use this skill

Skill file

Create a new UI lesson teaching how to build an immediate-mode UI system from

scratch — font parsing, text rasterization, layout, and interactive controls.

UI lessons produce CPU-side data (textures, vertices, indices, UVs) that a

separate GPU lesson will later render. The UI library itself contains **no GPU

code** — it is a pure data-generation layer.

When to use this skill:

developer tools (property editors, debug overlays)

Smart behavior:

index buffers, not rendered pixels

diagram assets (matplotlib), not GPU rendering

structs) where the concept appears in practice

Arguments

The user (or you) can provide:

If any are missing, infer from context or ask.

Steps

1. Analyze what's needed

2. Create the lesson directory

lessons/ui/NN-topic-name/

3. Create a demo program (`main.c`)

A focused C program that demonstrates the UI concept by producing data and

verifying it. UI lesson programs must write BMP images as their primary

visual output. These images are committed to assets/ and embedded in the

README so readers see results immediately. Programs typically:

Requirements:

#include "ui/forge_ui.h" for UI types (once the library exists)

Template structure:

/*
 * UI Lesson NN — Topic Name
 *
 * Demonstrates: [what this shows]
 *
 * SPDX-License-Identifier: Zlib
 */

#include <SDL3/SDL.h>
#include "math/forge_math.h"

int main(int argc, char *argv[])
{
    (void)argc;
    (void)argv;

    if (!SDL_Init(0)) {
        SDL_Log("SDL_Init failed: %s", SDL_GetError());
        return 1;
    }

    /* Demonstrate the UI concept here */

    SDL_Quit();
    return 0;
}

Console output formatting:

on Windows Terminal

Windows)

4. Create `CMakeLists.txt`

add_executable(NN-topic-name main.c)
target_include_directories(NN-topic-name PRIVATE ${FORGE_COMMON_DIR})
target_link_libraries(NN-topic-name PRIVATE SDL3::SDL3)

if(TARGET SDL3::SDL3-shared)
    add_custom_command(TARGET NN-topic-name POST_BUILD
        COMMAND ${CMAKE_COMMAND} -E copy_if_different
            $<TARGET_FILE:SDL3::SDL3-shared>
            $<TARGET_FILE_DIR:NN-topic-name>
    )
endif()

Adapt as needed: Later lessons may link against a shared UI library

(common/ui/) once it exists.

5. Create `README.md`

Structure:

# UI Lesson NN — Topic Name

[Brief subtitle explaining what this teaches]

## What you'll learn

[Bullet list of UI concepts covered]

## Why this matters

[1-2 paragraphs connecting this topic to real game/tool UI development.
Explain when and why a developer will need this.]

## Result

[Brief description of what the example program produces]

[Embed PNG images generated by the program. The program writes BMP files
(no libpng dependency needed in C), so convert them to PNG before committing.
Copy the PNGs to the lesson's `assets/` directory and reference them with
`![alt text](assets/file.png)`. Use tables to show multiple images side by
side:]

| Glyph 1 | Glyph 2 | Glyph 3 |
|---------|---------|---------|
| ![desc](assets/glyph_1.png) | ![desc](assets/glyph_2.png) | ![desc](assets/glyph_3.png) |

**Important:** Build and run the program first to generate the BMP files,
then convert to PNG (`python3 -c "from PIL import Image; Image.open('file.bmp').save('file.png')"`)
and copy them to `assets/`. Never commit BMP files — they are uncompressed
and bloat the repository.

## Key concepts

[Bullet list of core takeaways:]
- **Concept 1** — Brief explanation
- **Concept 2** — Brief explanation

## The Details

[Main explanation of the topic, broken into subsections]

### [Subtopic 1]

[Explanation with code examples and diagrams where appropriate]

### [Subtopic 2]

[Explanation with code examples and diagrams where appropriate]

## Data output

[Describe the data structures this lesson produces — vertex layouts, texture
formats, index buffers. This section bridges UI lessons to the GPU lesson
that will render the data.]

- **Vertices**: [format — position, UV, color]
- **Indices**: [format — triangle list, winding order]
- **Textures**: [format — RGBA, single-channel alpha, atlas dimensions]

## Where it's used

In forge-gpu lessons:
- [Link to GPU lesson] renders this data with [technique]
- [Link to math lesson] provides [math concept] used here
- [Link to engine lesson] explains [engineering concept] used here

## Building

cmake -B build

cmake --build build --config Debug

Windows

build\lessons\ui\NN-topic-name\Debug\NN-topic-name.exe

Linux / macOS

./build/lessons/ui/NN-topic-name/NN-topic-name


## Exercises

1. [Exercise extending the concept]
2. [Exercise applying it differently]
3. [Exercise that produces different output data for the GPU to render]

## Further reading

- [Relevant UI/math/engine lesson that builds on this]
- [External resource — TTF spec, stb_truetype, Dear ImGui, etc.]

6. Update project files

under a "UI Lessons" section (create the section if it doesn't exist yet)

6b. Keep READMEs in sync

Every new UI lesson must update all four of these files:

"UI Lessons (lessons/ui/)" section — follow the same format as the

existing rows

shared library, add them to the API reference sections. Always add the

lesson to the "Where It's Used" list

include the new lesson (and verify it matches the current plan order in

PLAN.md)

7. Cross-reference other lessons

structs), and GPU lessons that will consume UI output

UI Lesson NN for details on [concept]"

8. Build, run, and collect output images

cmake -B build
cmake --build build --config Debug

# Run from repo root so the program finds assets/fonts/
./build/lessons/ui/NN-topic-name/NN-topic-name

# Convert generated BMP files to PNG and copy to assets/
python3 -c "
from PIL import Image
import glob
for bmp in glob.glob('*.bmp'):
    Image.open(bmp).save(bmp.replace('.bmp', '.png'), 'PNG', optimize=True)
"
cp *.png lessons/ui/NN-topic-name/assets/

Verify the demo runs and produces BMP files. Convert them to PNG (much

smaller — typically 97% reduction for UI screenshots) and copy to the

lesson's assets/ directory. Never commit BMP files to the repository.

9. Update the UI library (when applicable)

If this lesson introduces reusable types or functions (font metrics, rect

packing, text shaping), add them to common/ui/ following the same

conventions as common/math/:

10. Verify key topics are fully explained

Before finalizing, launch a verification agent using the Task tool

(subagent_type: "general-purpose"). Give the agent the paths to the lesson's

README.md and main.c and ask it to audit every key topic for completeness.

For each key topic / "What you'll learn" bullet, the agent must check:

  1. Explained in the README — Is the concept described clearly enough that

a reader encountering it for the first time could understand it?

  1. Demonstrated in the example program — Does main.c actually exercise

this concept with code and output?

  1. All referenced terms are defined — Read the exact wording of each key

topic and identify every technical term. For each term, confirm it is

explained somewhere in the lesson.

What to flag:

section in "The Details" or the example program

produce

The lesson is incomplete until every key topic passes all three checks.

11. Run markdown linting

Use the /dev-markdown-lint skill to check all markdown files:

npx markdownlint-cli2 "**/*.md"

If errors are found:

  1. Try auto-fix: npx markdownlint-cli2 --fix "**/*.md"
  2. Manually fix remaining errors (especially MD040 - missing language tags)
  3. Verify: npx markdownlint-cli2 "**/*.md"

MANDATORY: Chunked writes for large files

Task agents have a 32K output token limit per Write call. **Any file over ~800

lines** MUST be written in chunks — split into 3-4 parts (~400-600 lines each),

write each to /tmp/, then concatenate.

Recovery rule — if a writing agent fails with a token limit error:

See CODE0

for the full strategy.

Asset Pipeline Mandate

If this lesson requires textures or 3D assets for any reason, they MUST go

through the asset pipeline. No ad-hoc asset loading.

UI Lesson Conventions

Scope

UI lessons cover building an immediate-mode UI system from the ground up:

UI lessons do not cover:

Data-first approach

Every UI lesson should clearly document what data it produces:

This data contract is what connects UI lessons to the GPU lesson that

renders them.

Tone

UI lessons should be practical and visual. Font parsing and text layout are

domains with deep history and real complexity — treat the material with

respect while keeping it accessible.

pack into an atlas?)

missing kerning

Theming

All generated UI code must use ctx->theme color slots for widget rendering.

Never hardcode color float literals (e.g. 0.878f, 0.878f, 0.941f, 1.0f) —

use the appropriate theme field instead (e.g. ctx->theme.text). The

forge_ui_theme_validate() contrast check is run as part of the test suite

and new themes or color changes must pass all contrast pairs.

Code style

Follow the same conventions as all forge-gpu code:

Diagrams and Formulas

**Find opportunities to create compelling diagrams and visualizations via the

matplotlib scripts** — they increase reader engagement and help learners

understand the topics being taught. Use the /dev-create-diagram skill to add

diagrams following the project's visual identity and quality standards.

Matplotlib diagrams

For visual diagrams (glyph anatomy, atlas packing, text metrics, layout

boxes, widget trees), add a diagram function to

scripts/forge_diagrams/ui/lesson_NN.py (create the file if it doesn't exist):

  1. Write a function following the existing pattern (shared setup_axes,

draw_vector, save helpers from _common.py)

  1. Re-export from scripts/forge_diagrams/ui/__init__.py
  2. Import and register in the DIAGRAMS dict in __main__.py with the lesson key
  3. Run python scripts/forge_diagrams --lesson ui/NN to generate the PNG
  4. Reference in the README: ![Description](assets/diagram_name.png)

Output goes to each lesson's assets/ directory at 200 DPI (PNG only).

Mermaid diagrams

For flow/pipeline diagrams (TTF parsing pipeline, UI layout pass, data

flow from CPU to GPU), use inline mermaid blocks:

flowchart LR

A[TTF File] -->|parse| B[Glyph Outlines] -->|rasterize| C[Bitmap Atlas]

KaTeX math

For formulas (Bezier curves, atlas packing ratios, font scaling), use

inline $...$ and display $$...$$ math notation:

$$
B(t) = (1-t)^2 P_0 + 2(1-t)t P_1 + t^2 P_2
$$

Example: TTF Parsing Lesson

Scenario: Learners want to understand how fonts work before rendering text.

  1. Scope: TTF file structure, table directory, glyph outlines, font metrics
  2. Create: lessons/ui/01-ttf-parsing/
  3. Program: Parse a TTF file, extract glyph outlines, print metrics
  4. README: Explain TTF tables, coordinate systems, compound glyphs
  5. Data output: Glyph contours (point arrays), advance widths, bounding boxes
  6. Cross-reference: Math Lesson 01 (vectors for glyph points), Engine

Lesson 04 (memory layout for TTF tables)

Example: Font Atlas Lesson

Scenario: A learner has parsed glyphs and wants to pack them into a texture.

  1. Scope: Rectangle packing, atlas generation, UV coordinate calculation
  2. Create: lessons/ui/03-font-atlas/
  3. Program: Pack glyphs into an atlas, output the atlas image and UV table
  4. README: Explain packing algorithms, padding, power-of-two textures
  5. Data output: Atlas texture (RGBA), per-glyph UV rects, atlas dimensions
  6. Cross-reference: GPU lesson that samples the atlas texture

When NOT to Create a UI Lesson

In these cases, update existing documentation or plan for later.

Tips

writing code. The data contract is the bridge to the GPU.

of glyphs, atlases, and layouts alongside console metrics.

relevant sections when explaining file formats.

Don't combine font parsing and atlas packing in one lesson.

cross-platform compatibility.

not console text output. Build and run the program (which writes BMP), convert

to PNG, copy to assets/, and embed with ![alt](assets/file.png). Never

commit BMP files — they are uncompressed and bloat the repository.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.