Commit pending scene, input, export and asset work

- GPU scene renderer: moved, turned or scaled nodes re-send only their own
  triangles instead of rebuilding the scene; per-node matrices are reused;
  FreezeGeometry skips geometry comparisons; lights carry projected
  textures (LightCookie) in the CPU and GLES renderers.
- One ordered per-session key and text delivery path across Desktop,
  Canvas and Raylib.
- Context-menu rows show accelerator labels and checked state.
- Bundle apps keep extracted assets that already match instead of
  rewriting and syncing all of them on every open.
- Image and PDF export modules, hosted box tests, brand assets, plans,
  and the ZX changelog entry.
This commit is contained in:
waozi committed 2026-11-14 16:27:22 -03:00
1 parent 0678895719
commit 7baf863221
39 files changed
+1813 -202

No files matched your search

+2 -2
View File
@@ -59,8 +59,8 @@ and portable loader must never recognize Kryon widget names specially. An
application that does not import Kryon needs no Kryon code or graphical host.
Keep app-specific screens, assets, copy, workflows, and state in the app repo.
One widget concept has one public implementation. `Text(TextProps)` and
`Image(ImageProps)` are the intended text and image widget surfaces. Do not
One widget concept has one public implementation. `Text.Draw(Text.Props)` and
`Image.Draw(Image.Props)` are the intended text and image widget surfaces. Do not
add parallel wrappers or expose raw texture draw calls as app widget APIs.
## Testing and desktop safety
+36
View File
@@ -2,10 +2,36 @@
## Unreleased
- ZX apps run on Ziran's one executable format everywhere. Players and hosted
apps call `InstantiateBundle` on every target, including the browser; the
`--vm` option of `zx` and `ziran run` is gone, and the web, Raylib and
Android runtimes build `libziran` with its instruction engine instead of the
bootstrap subset.
- Opening a bundle app no longer rewrites all of its assets. `BundleWriteAssets`
keeps every extracted file that already holds its asset (`AppFileSame`
compares in place) and writes a changed one without waiting for the disk
(`AppFileWrite(..., durable = false)`): the files are a copy of the bundle,
checked again on the next open. Before, every open synced each asset and its
directories; for an app with 557 assets that was about a third of a second
on every open, measured. `AppFileRead` sizes its buffer once instead of
growing it byte by byte.
- GTK style queries notice a new default display. The style cache answered
from the previous display's settings after `gdk_display_manager_set_default_display`,
so theme values and the style generation went stale.
- The native GPU scene renderer (`kryon/scene_gpu`) no longer rebuilds and
re-uploads a whole scene when one node moves, turns, or scales. It now
re-makes and sends only the moved nodes' triangles, so an animated door or
leaf in a large scene costs a fraction of a millisecond per frame instead
of a full rebuild (about 9 ms for an 88,000-vertex room, measured). The
rebuild path also leaked its per-node matrices on every rebuild; they are
now kept and reused. `SceneGpuResources.geometry_vertices` counts the
vertices sent, so tests can tell a partial update from a full one.
- `FreezeGeometry(scene)` promises that a scene's meshes, materials and
vertices stay as they are, so the GPU renderer stops comparing them with
what it last drew on every frame; nodes may still move, show and hide. Any
Scene call that adds or changes geometry takes the promise back.
- Native Linux apps can drag data out to other applications. The optional
`kryon/DragSourceLinux` module is an XDND version 5 drag source on its own
X connection: it follows the pointer while the toolkit keeps its implicit
@@ -15,6 +41,11 @@
- `GtkStyleIndicatorRaster` and GtkPainter kinds 9–11 draw the GTK theme's own
check box, radio option and submenu arrow, so native menus can show check,
radio and submenu rows exactly as GTK draws them.
- Scene lights can carry a projected texture: `LightCookie` sends a scene
texture through a light's beam over its shadow box, multiplying direct
irradiance in linear light, identically in the CPU and GLES renderers, for
dappled sun through leaves and similar patterns. The GLES host now needs 15
texture units.
- The semantic DOM backend is removed: the `dom` profile, `dom_host`,
`dom_tree`, `dom_paint`, `dom_run` and `dom_app_run`, their tests and
`docs/dom.md`. No project used it. The `web` template now builds a Canvas2D
@@ -97,6 +128,11 @@
- Raylib keys keep a Control, Alt or Super press that was released again
within the same poll, so the quickest Control+C tap still reaches the app as
Control+C instead of a lost plain C.
- Context-menu rows can show right-aligned accelerator labels and checked state,
with aligned check columns and portable hosted-widget fields.
- Replace host-global key/text reads with one shared ordered per-session
delivery path across Desktop, Canvas and Raylib, preserving layout-aware
shortcuts, repeats, IME text, gamepad navigation and focus-loss handling.
- Reuse identical GTK cell measurements, retain native raster caches across
unrelated GLib events, and composite clipped opaque pixels efficiently.
- Detect unchanged GTK painter surfaces by exact byte comparison instead of
Binary file not shown.

After

Width:  |  Height:  |  Size: 847 KiB

+91
View File
@@ -0,0 +1,91 @@
{
"project": "Kryon",
"request": "One original friendly full-body dragon mascot for the Kryon UI toolkit, in the Ziran capybara's flat warm illustration feel, followed by a pastel-only color revision that preserves the accepted character.",
"pastel_follow_up_request": "okay but the colors should be more pastel — for the mascot",
"generation_mode": "built-in image_gen",
"generation_calls_planned": 1,
"conditional_retry_allowed": 1,
"generation_calls_completed": 3,
"attempt_count": 3,
"pastel_edit_calls_planned": 1,
"pastel_edit_calls_completed": 1,
"retry_reason": "The first attempt had extra body shading and tighter margins, a clear style/composition mismatch; the one permitted retry fixed the flat-ink direction.",
"proposals": [
{
"id": "01-dragon-v1",
"version": "v1",
"attempt_count": 2,
"animal": "Dragon",
"direction": "Rounded approachable full-body dragon in three-quarter view, facing right, with a calm warm personality and strong small-icon silhouette.",
"prompt": "Use case: logo-brand\nAsset type: final original mascot bitmap for Kryon, a UI toolkit and Ziran sister project; exactly one finished character.\nPrimary request: Create one entirely original friendly cartoon dragon mascot for Kryon. KDE inspiration is limited only to the broad idea of a rounded, approachable open-source cartoon dragon body and shape. This must not copy or trace Konqi and must not reuse Konqi's exact face, anatomy, pose, or proportions.\nScene/backdrop: None. A genuinely transparent square canvas with no background pixels, ground, shadow, border, or decoration.\nSubject: One full-body dragon in three-quarter view, facing right, standing in a relaxed welcoming pose. Big friendly head, short rounded snout, small rounded horns, small wings, a soft row of rounded back spines, four simple grounded feet without claws, and one clear tapering tail. Calm warm expression, small gentle eyes rendered only with earth-brown marks, closed mouth, no teeth. Nothing in its hands.\nStyle/medium: Confident hand-drawn flat illustration in the same visual family as Ziran's capybara mascot: bold deep earth-brown outline of consistent apparent weight, large quiet solid color areas, minimal interior marks, slight purposeful hand-drawn irregularity, calm warm character, strong sticker-like silhouette readable as a tiny website icon. Absolutely flat ink fills: no lighting, highlights, shadows, secondary shades, gray, cream, white fill, texture, or tonal modeling.\nComposition/framing: Center the single complete dragon on a 1:1 square canvas. The entire silhouette should occupy about 72–76% of the canvas width and height, leaving a clean 12–15% transparent border on every side. Every horn, wing, spine, foot, and tail is wholly visible and comfortably clear of the edge. Three-quarter view faces right.\nColor palette: Exactly four visual ink colors and no others except edge antialiasing between them and transparency: jade green #63B190 for the entire body and wings; exactly one continuous lake-blue underside/belly plane #77B7EA; deep earth-brown #502511 for every outline, eye, nostril, and minimal interior mark; one restrained muted light-orange #A48B62 used only on the small horn tips. Do not create light and dark variants of any color. Do not use orange on wings or elsewhere.\nText: NONE.\nConstraints: One original approachable rounded dragon; one character only; genuine alpha transparency; strong readable silhouette; generous clear margins; four flat source-family inks only; exactly one lake-blue belly plane; orange limited to horn tips; eyes use brown with no white eye fill.\nAvoid: Konqi likeness, KDE logo, gear, fire, smoke, teeth, aggressive claws, K monogram, letter-shaped body, props, clothing, scenery, borders, frames, solid or patterned background, gradients, glow, glossy 3D, textures, shading, highlights, drop shadows, extra characters, extra limbs, cropped anatomy. Absolutely no text, letters, numbers, labels, signatures, logos, or watermark anywhere.",
"file": null,
"transparent_background": true,
"status": "removed-at-owner-request",
"retained": false,
"actual": {
"dimensions": [1254, 1254],
"mode": "RGBA",
"alpha_extrema": [0, 255],
"content_bbox_alpha_gt_1": [107, 63, 1125, 1197],
"bytes": 877306,
"sha256": "aa041bbfe0fa60b97736fff724be5922f6b178607cfab5514b6cc4a17295da89"
},
"visual_review": {
"no_text_verified": true,
"transparent_background_verified": true,
"not_konqi_copy": true,
"style_matches_ziran": true,
"original_character": true
}
},
{
"id": "02-dragon-v2-pastel",
"version": "v2",
"attempt_count": 1,
"animal": "Dragon",
"direction": "Pastel-only color revision of the accepted v1 dragon, preserving the same friendly character, pose, proportions, framing, linework, expression, wings, spines, and transparent background.",
"prompt": "Use case: precise-object-edit\nAsset type: pastel color revision of the accepted Kryon dragon mascot bitmap.\nInput images: Image 1 is the sole edit target, the accepted v1 Kryon dragon mascot.\nPrimary request: Change ONLY the four flat ink colors of Image 1 to a softer pastel palette. Do not redraw, reinterpret, restyle, simplify, or add anything.\nColor palette: body pastel mint/jade approximately #A9DCC5; the single existing belly/underside plane pastel sky blue approximately #BCDDF6; the existing horn-tip accents pastel peach approximately #F5C7A1; all existing outline, eye, nostril, and interior marks deep earth-brown/warm cocoa approximately #6B4434. Use at most these four flat visual inks plus edge antialiasing and transparency.\nTransparency: Preserve the genuinely transparent background and all current alpha edges. No background pixels, ground, or shadow.\nInvariants: Preserve the exact same original character, pose, anatomy, proportions, framing, silhouette, linework geometry and apparent weight, expression, gaze, wings, rounded back spines, horns, feet, tail, belly-plane shape, detail placement, canvas dimensions, and transparent margins. Change only colors. Keep every existing element in the exact same position and size. No added or removed details.\nAvoid: gradients, extra shades, texture, highlights, shadows, glow, glossy rendering, new marks, altered outlines, altered anatomy, text, letters, numbers, logos, signatures, or watermark. Do not introduce a Konqi likeness, KDE logo, gear, props, clothing, scenery, border, fire, teeth, or claws.",
"file": "mascot-dragon.png",
"transparent_background": true,
"status": "complete",
"actual": {
"dimensions": [1254, 1254],
"mode": "RGBA",
"alpha_extrema": [0, 255],
"content_bbox_alpha_gt_1": [107, 64, 1127, 1197],
"bytes": 867648,
"sha256": "9537921d73713caccd9c991b4998224207f5ad21a079dcebc2f57cfc111daae4"
},
"target_palette": {
"body_pastel_mint_jade": "#A9DCC5",
"belly_pastel_sky_blue": "#BCDDF6",
"horn_tips_pastel_peach": "#F5C7A1",
"outline_warm_cocoa": "#6B4434"
},
"visual_review": {
"exact_character_preserved": true,
"pixel_identical_to_v1": false,
"transparent_background_verified": true,
"no_text_verified": true,
"not_konqi_copy": true,
"style_matches_ziran": true,
"pastel_palette_verified": true,
"at_most_four_visual_inks": true,
"original_character": true,
"notes": "The same accepted character, pose, anatomy, expression, linework design, and framing are preserved. Built-in image editing re-antialiased some edge pixels: the alpha>128 silhouette IoU is 99.53710%, ink-region agreement is 99.69063%, and the content bounding box moved by at most two pixels; v2 is therefore not claimed to be pixel-identical to v1."
}
}
],
"validation": {
"local_tests": "passed",
"tests": [
"The retained pastel mascot is a decodable 1254x1254 8-bit RGBA PNG with alpha extrema [0, 255].",
"The retained pastel mascot SHA-256 is 9537921d73713caccd9c991b4998224207f5ad21a079dcebc2f57cfc111daae4 and matches its proposal record.",
"Visible content above alpha 1 has bounding box [107, 64, 1127, 1197], wholly inside the canvas with transparent clearance on every side.",
"OCR returned no text; visual review found no text, letters, numbers, labels, signatures, or watermark.",
"Visual and palette review confirmed the same accepted original dragon, no Konqi copy, the Ziran flat warm style, and the requested pastel mint, sky-blue, peach, and warm-cocoa direction."
],
"scope": "Local validation of the sole retained asset assets/brand/mascot-dragon.png and assets/brand/prompts.json.",
"notes": "The earlier darker bitmap was removed at the owner's request; its prompt and digest remain as provenance only. The retained pastel mascot used one built-in image_gen edit call and its generated binary was copied without retouching."
}
}
+91 -28
View File
@@ -1007,19 +1007,22 @@ four bytes guarantees progress. `tree_input.TypedCodepointPeek(session)` reads
the next scalar without consuming it, and `TypedCodepointCapacity(session)`
reports free slots in the bounded 32-scalar session queue.
Custom SDL desktop hosts can call `DesktopInputEnable()` after `OpenDesktop()`
to use ordered key/text delivery. Call `PollDesktop()` every frame, including
while session text remains unread, then `DesktopInputTake(session)` to transfer
one editing action or a printable-key/text run. Its `(key, modifiers)` result
uses portable key and modifier codes. The bounded 256-record delivery queue
backpressures SDL input; unread text delays later editing actions. Return can
commit a text run delivered in the same call, while window
lifecycle events continue to be pumped. Both standard desktop hosts use this
path. Raw `DesktopPressedKey()` (last key), `DesktopNextKey()` (all keys),
`DesktopTypedCodepoint()` and frame snapshots remain independent observations
of the current poll; the ordered queue owns durable delivery. Run
Every graphical host owns an ordered key/text queue and exposes one session
delivery call: `DesktopInputTake(session)`, `CanvasInputTake(session)`, or
`RaylibInputTake(session)`. Poll the host every frame, including while session
text remains unread, then call its take once before composition. The take
transfers one editing action or a printable-key/text run into that session and
returns `(key, modifiers)` using portable key and modifier codes. Unread text
delays later editing actions; Return can commit a text run delivered in the
same call. Focus loss cancels queued keys so an old shortcut cannot fire after
focus returns, while text already committed by the platform remains ordered.
Desktop's bounded 256-record delivery queue backpressures SDL key and text
events without blocking window lifecycle events. Run
`build-queue -- make test-focus TEST=desktop_input_backpressure` for the native
SDL source and saved-IR regression.
Raylib fills its ordered queue from the platform key, repeat and text streams
during `PollRaylib()`, applying the active keyboard layout before delivery.
A Raylib app that has nothing to animate can call
`RaylibWaitForActivity(descriptors, milliseconds)` between frames instead of
drawing: it returns `RaylibActivityDescriptor`, `RaylibActivityInput` or
@@ -1028,16 +1031,16 @@ drawing. After `RaylibActivityInput` draw two frames, since a frame uses input
the previous one read. `RaylibPrepareGlyphs(text)` readies many characters at
once, so drawing them one at a time does not rebuild a font for each.
Canvas and DOM app hosts retain unread key presses and repeats across drawing
frames, taking one application key per frame. Pressed/released snapshot flags
still expire at the frame boundary; delivery does not replay those flags.
Focus loss and host reset cancel unread keys. Each queued press or repeat
retains its DOM event's Shift, Control/Meta and Alt modifiers. Custom Canvas
loops read `CanvasPressedKeyModifiers()` immediately after `CanvasPressedKey()`
and submit those bits with `KeyboardModifiersSend(session, modifiers)`.
An empty key take reports current held modifiers. `CanvasModifiers()` and
`CaptureFrameInput(session).modifiers` still report held state at their own
sampling time; consuming a shortcut never changes held keys or snapshot flags.
The Canvas app host retains unread key presses, repeats, IME commits and
gamepad navigation across drawing frames. Pressed/released snapshot flags still
expire at the frame boundary; delivery does not replay them. Each queued press
or repeat retains its browser event's Shift, Control/Meta and Alt modifiers.
Custom loops call `CanvasInputTake(session)`; an empty take reports current held
modifiers. `CanvasModifiers()` and `CaptureFrameInput(session).modifiers` still
report held state at their own sampling time, so consuming a shortcut never
changes held keys or snapshot flags. Canvas keeps raylib-named
`GetKeyPressed`/`GetCharPressed` program exports only for raylib applications
compiled for the browser; they are frame observations, not Kryon session input.
Application code owns its product state and calls widgets within `Frame`.
The complete manifest and build commands are in [PROJECTS.md](PROJECTS.md).
@@ -1144,6 +1147,7 @@ Other platform services an application may import:
| Module | Surface |
| --- | --- |
| [`file_export`](../src/backend/file_export.zi) | `ExportBytes` and `ExportFile`: hand a finished file to the user as a browser download or through Android's share sheet |
| [`pdf_export`](../src/backend/pdf_export.zi) | `PdfOpen`, `PdfImage`, `PdfText`, `PdfPage` and `PdfClose`: compose Linux-native PDF pages from full-resolution images and searchable UTF-8 text |
| [`file_picker`](../src/backend/file_picker.zi) | `PickFile(FilePickerProps, output)`: zenity on Linux and BSD, Windows' common dialog, and the browser's chooser, which copies the file into the page's file system |
| [`window_close`](../src/backend/window_close.zi) | `WindowCloseWatch(window)` and `WindowCloseTake()`: close requests for the application's own SDL or Win32 window, so it can ask first or hide to a tray |
| [`idle_time`](../src/backend/idle_time.zi) | `IdleMilliseconds()` from the session's idle service over D-Bus, and `IsWaylandSession()` |
@@ -1775,8 +1779,8 @@ drawing. `SceneFree` never frees borrowed programs, uniforms or sampler pixels.
`ShaderSampler.{width,height,pixels,repeat}` samples straight linear RGBA bytes,
top row first. UV V=0 selects the bottom row. Sampling uses nearest-neighbor
clamp-to-edge by default, or repeat including negative coordinates. Supply
linear data when loading an sRGB image for a custom sampler. The standard
`SceneMaterial.texture` path continues to decode sRGB automatically.
linear data when loading an sRGB image for a custom sampler. `ImageMaterial`
is the standard sRGB image path described below.
Shader output replaces base RGBA before standard lighting and tone mapping.
Use `UnlitMaterial` for direct colour, or `LitMaterial` for procedural surfaces
@@ -1914,7 +1918,7 @@ renders the existing `Scene`, materials and `SceneCamera` into a reusable
Keep one `SceneGpuContext` at a stable address on its owning thread.
`SceneGpuProbe(context)` reports availability, diagnostic, renderer labels,
texture limits and MSAA support. The host requires highp fragment precision,
14 texture units, four MSAA samples and bilinear depth comparisons; it reports
15 texture units, four MSAA samples and bilinear depth comparisons; it reports
unavailability when those requirements cannot be met.
`SceneGpuRender(context, scene, camera, image)` preserves the requested image
dimensions and returns `SceneGpuFrame` with `ok`, `accelerated`, `diagnostic`
@@ -1956,7 +1960,16 @@ claim that unchanged image pixels changed.
Geometry, material programs, textures and render targets retain storage across
frames. Scene and binding data are borrowed during the call; mutate them only
on the owner between calls. `SceneGpuMemoryUsage` reports retained CPU/GPU
on the owner between calls. When only nodes move, turn or scale between
frames, the renderer re-makes and sends just those nodes' triangles; adding,
removing, showing, hiding or re-parenting nodes, or changing meshes or
vertices, uploads the scene again. `SceneGpuResources.geometry_uploads` counts
both kinds of upload and `geometry_vertices` the vertices they sent.
`FreezeGeometry(scene)` (in `kryon/scene`) promises that meshes, materials and
vertices stay as they are, so the renderer stops comparing them with its last
upload on every frame and compares only the nodes. Scene calls that add or
change geometry take the promise back; after writing into the scene's vertex
arrays directly, clear `scene.geometry_frozen` yourself. `SceneGpuMemoryUsage` reports retained CPU/GPU
storage estimates, object counts, upload counts and completed GPU frames; this
is separate from process RSS and presentation-host storage.
The resource report includes live fences/pending frames, accepted submissions
@@ -1979,9 +1992,59 @@ a separate package consumer in native and portable forms without linking EGL.
`ImageValid(*image)`; missing, invalid or unsupported files return an empty image.
The caller owns `image.pixels` and releases it with `VecFree(image.pixels)`.
Pixels are tightly packed, top-down, straight RGBA in the source's sRGB encoding.
Use `AddTexture(scene, image.pixels[:], image.width, image.height)` for scene
texture color decoding. Shader samplers accept linear RGBA; convert sRGB first
when using those bindings.
Use the single public scene-image surface:
```zi
wood := LoadImagePixels("assets/wood.png")
options: SceneTextureOptions = .{
projection=.SceneTextureBox,
filter=.SceneTextureLinear,
wrap=.SceneTextureRepeat,
scale=.{3.0,3.0},
}
material := ImageMaterial(*scene, *wood,
LitMaterial(.{255,255,255,255}, 0.72, 0.0), options)
VecFree(wood.pixels)
unused RoundedBox(*scene, 1.8, 0.08, 0.32, 0.01, material)
```
`ImageMaterial(scene, image, base, options) -> SceneMaterial` validates and
copies a complete `std/image.Image`; the source can be freed immediately.
Equal images, including equal explicitly prepared mip levels, share one owned
scene texture. The scene releases logical storage in `SceneClear`/`SceneFree`.
Native GPU contexts upload the immutable copy once, reuse it without scanning
the image every frame, and release/recreate the upload with context lifecycle.
`SceneTextureOptions` contains `projection`, `filter`, `wrap`, `scale`, `offset`
and `mip_level`. Projection is `SceneTextureUV` or `SceneTextureBox`; box mapping
chooses a face from the dominant object-space normal, so moving, rotating or
scaling a bookshelf part does not make its grain swim. Filtering is
`SceneTextureNearest` or `SceneTextureLinear`, and wrapping is
`SceneTextureClamp` or `SceneTextureRepeat`. A zero scale component defaults to
1. `mip_level` is an explicit nonnegative level prepared once with a box filter;
its fixed selection makes native CPU and GPU results deterministic. Both
renderers filter sRGB texels in linear light and use the same clamp/repeat and
top-row/V-bottom rules. `SceneTextureCoordinate` exposes the exact object-space
coordinate transform for procedural geometry and tests.
`ImageMaterial` replaces the old raw-pixel texture attachment API. Shader
samplers remain the separate programmable linear-RGBA surface; convert sRGB
first when using those bindings.
### Light cookies
`LightCookie(scene, light, texture, scale, offset)` projects a scene texture
through a light's beam, like a gobo: dappled sun through leaves, window bars or
stained glass. `texture` is an existing scene texture index, usually
`ImageMaterial(...).texture`. The texel's linear RGB multiplies the light's
direct irradiance on every lit surface, receiver or not; the hemisphere light,
unlit and exact-colour materials are unaffected. The texture spans the light's
shadow box from `CastLightShadow` `scale` times, shifted by `offset` (in
repetitions), with bilinear filtering and repeat wrapping in linear light, so
the CPU and GPU renderers agree. A light needs a shadow box to carry a cookie;
`shadow_size` may be zero when no depth map is wanted. Only the first light
with a cookie projects one. Change `SceneLight.cookie_offset` between renders
to drift the pattern without rebuilding anything.
Linux uses the existing system image loader and packaged WebP/AVIF adapters,
copying the original straight pixels before Cairo premultiplies them. The
Binary file not shown.

After

Width:  |  Height:  |  Size: 847 KiB

+154
View File
@@ -0,0 +1,154 @@
# Kryon package imports
Status: approved for full migration on 2026-11-12.
## Target
Kryon applications use named, package-qualified Ziran imports:
```zi
Text :: #import "kryon/text"
Text.Draw(session, Text.Props.{
.key = cast(u64)2,
.bounds = Rectangle.{24.0, 48.0, 272.0, 64.0},
.text = "Hello, world!",
})
```
This keeps Ziran's Jai-inspired `::` declarations and `#import` syntax while
making a library name and its origin visible at every use. Go is only the
clarity model. An ordinary flat import is convenient inside one package, but
it is confusing at a library boundary because `Text`, `Props`, or `Draw` no
longer says which package supplied it. Kryon examples and consumers therefore
use named imports, without `using`.
Each widget package owns:
- `Props` for its primary input record;
- `Draw` for its primary retained-widget call;
- short package-local names for closely related records and enums when the
old name repeats the package name;
- descriptive names for additional operations when one package contains more
than one widget.
There are no public `*_props` packages, `WidgetProps` names, `Widget.Widget`
calls, compatibility aliases, or legacy import spellings after the migration.
Internal schema files may remain separate only where codec generation or
import-cycle boundaries require them; the widget package re-exports their
public declarations and users never import them.
Ziran already has the required language support: package-qualified imports,
named imports, and public `using` import re-exports. No UI-specific compiler
feature is planned.
## Widget inventory and rename groups
The current split input modules are:
`box`, `breadcrumb`, `button`, `card`, `checkbox`, `collapsible`,
`colorpicker`, `commandpalette`, `confirmpopover`, `dropdown`, `fieldset`,
`gridmulti`, `guidedtour`, `hovercard`, `image`, `layout`, `link`, `listbox`,
`menu`, `modal`, `navigation`, `overlay`, `page`, `panedview`, `press`,
`progress`, `radio`, `reorder`, `scroll`, `segmented`, `selectable`,
`separator`, `shape`, `sheet`, `slider`, `spinbox`, `svgicon`, `swiperow`,
`tabs`, `text`, `timepicker`, `titlebar`, `toast`, `toggle`, `toolbar`, and
`tooltip`.
Shared/core input records (`control`, `drawing`, `input`, `text_input`,
`accessibility`, `canvas`, `grid`, `router`, `scene_tree`, and `swipe`) remain
in explicitly named core packages rather than pretending to be widgets.
The mechanical rename is `WidgetProps` to `Props` and `Widget` to `Draw`
inside the widget's named package. Related types lose the redundant package
prefix where qualification already provides it, for example
`Text.Wrap`/`Text.Range`, `Dropdown.Option`/`Dropdown.Result`, and
`TabBar.Tab`/`TabBar.Result`. Multi-widget modules are split or keep
unambiguous operation names so a package never exposes names such as
`Modal.ModalFrameProps`.
Codec functions retain wire-schema names where those names are part of the
host protocol; their generated source imports the owning widget package and
refers to `Package.Props`. Wire field names and serialized compatibility are
not changed merely for source spelling.
## Consumer inventory
The source search under `/mnt/storage/Projects` found these consumer groups.
Repository ownership and active sessions are checked before editing each one:
- `kryonlabs/kryon`: core, examples, templates, docs, tests, website demo;
- `harness/harmony`, `harness/music`;
- `kryonlabs/browser`, `explorer`, `github`, `rill`, `taskmgr`, `terminal`,
`workbook`;
- `kryonlabs/packages/{css,data-views,game2d,plot}`;
- `waozixyz/apps/{breeze,photos,werk}`;
- `waozixyz/atr`;
- `waozixyz/catalog/retro/{scraper,site}`;
- `waozixyz/games/{apple,arcade,choano,katalis,shark,shovey,wurm,zoombinis}`;
- `waozixyz/learning/jungle`;
- `waozixyz/modules/{apps,auth,dew,entity,gamekit}`;
- `ziranlang/ziran-vscode` fixtures that classify Kryon hello programs.
Generated output, `build/`, `vendor/`, `backup/`, archives, and package caches
are not migration sources. Downstream vendor copies are never edited.
## Order
1. [ ] Establish widget package exports, `Props`/`Draw` names, and focused
source/saved-IR/package-resolution tests in Kryon.
2. [ ] Update codec generation and regenerate `widget_codec.zi`, preserving
concurrent pointer-validation work.
3. [ ] Convert Kryon core call sites, examples, templates, tests, API docs, and
the website demo to named package imports.
4. [ ] Replace the old hello module/host pair with one runnable
`examples/hello.zi`; remove its automated screenshot path and keep other
capture examples unchanged.
5. [ ] Migrate each external consumer with a local Kryon override and run its
own focused and full local test targets through `build-queue`.
6. [ ] Run Kryon's focused tests, `make test`, and `make push-check` through
`build-queue`; run the hello window only on a private scrubbed Xvfb.
7. [ ] Reduce the auto-discovered Ziran behavior suite by about 20% (223 to
178 scripts), removing redundant or shallow cases while retaining the
clearer integration, regression, backend, and button-behavior coverage.
8. [ ] Commit each verified repository once. Push the complete compatible set
together; do not release or bump versions.
9. [ ] Add the portable lowercase `kryon/app` application boundary:
`App.Window`, `App.Frame`, and `App.Run(window, draw)`. Application source
imports only `kryon/app` and widget packages; the app package selects its
host from the build target and diagnoses targets without a host clearly.
10. [ ] Put platform hosts behind lowercase `kryon/host/desktop`,
`kryon/host/web`, `kryon/host/android`, and `kryon/host/terminal` package
names. Keep platform-only code such as Linux GIO accessibility inside its
host so other targets never parse its C ABI.
11. [ ] Remove public names that differ only by case or stutter:
`Desktop`/`desktop`, `desktop_run`, `*_widget`, and `*_props`. Keep one
lowercase package name per thing and no compatibility aliases.
12. [ ] Keep `examples/hello.zi` human-readable: a multi-line `main` declares
`App.Window`, then a void `Draw(App.Frame)` submits only `Text.Draw` with
`Text.Props.{.text = "Hello, world!", .size = 32}`. The frame supplies the
session and default bounds; no explicit widget key or status return.
13. [ ] Add `examples/window.zi`, the smallest program that calls
`App.Run(window)` with no draw callback, and verify that native window on a
private scrubbed Xvfb.
## Risks
- Public `using` re-export behavior must remain identical in source, saved IR,
native C, Go, and portable bundles.
- Renaming records affects generated codec symbols and host bindings; source
spelling must change without accidentally changing the wire contract.
- Some modules contain several related widgets and need deliberate package
boundaries instead of a blind prefix removal.
- Concurrent dirty work exists in Kryon and several consumers. Overlapping
files are serialized with their owning task, and only migration hunks are
staged.
- Package-qualified imports require project builds or an explicit
`--module-path kryon=...`; standalone example and editor commands must carry
that mapping.
- `kryon/app` is portable but its hosts are target-specific. Native C selects
the SDL/Cairo desktop host, Wasm selects the Canvas host, Android selects its
activity host, and other targets either select an explicit host or stop with
a named `kryon/app` diagnostic. Linux GIO and other C-only declarations must
never be reachable from Go, Wasm, or ZX checking.
+128
View File
@@ -0,0 +1,128 @@
# Why an empty window generates 64 C files, and how to shrink it
Owner, 2026-11-13: "why does a simple window in kryon have so many c files
genared tresehakngi semes ocmpletyl borkne analyze and improve ti"
Status, 2026-11-14: steps 1 and 3 done and pushed; step 2 reverted; step 4 stays.
| | Files | C | Executable |
| --- | --- | --- | --- |
| Before | 64 | 748 KB | 346 KB |
| Now (Kryon 1be70904) | 62 | 545 KB | 265 KB |
- Done: text editing. `text_request` calls a boundary procedure that
`src/ui/text_boundary.zi` registers from a module initializer, and only the
editing widgets import it. `std/grapheme` is gone from an empty window.
- Done: test driver. `src/backend/test_driver.zi` is a 1.6 KB wrapper; the
engine (`test_driver_engine`) is built only with `--define KRYON_TEST_DRIVER`
or `KRYON_TEST_DRIVER` set for `ziran tool kryon build`.
`tests/program_entry_project_test.py` checks both.
- Reverted: images. A `cursor_picture` split moved the decoders out, but its
host capability broke the Go backend ("Go global startup cannot call a host
before binding") and builds that link the hosted widget host. It came out in
797d7317. An empty window still carries `image_decode_linux`, `avif_decode`
and `lanczos_cache` (37 KB of C). Doing it again needs registration that does
not reach a host from global startup.
- Accessibility stays (63 KB), as planned.
Ziran module initializers exist and are documented ("Module initializers" in
Ziran's `docs/USAGE.md`, test `tests/module_registration.sh`), so the
"does not work today" note below is out of date.
## Measurement
`examples/window.zi` is five lines: an `App.Window` and `App.Run(window)`.
```sh
ziran build --target=c --project --root examples --exe --entry window:main \
-o build/extension-window-test examples/window.zi
ls build/extension-window-test/*.c | wc -l # 64
cat build/extension-window-test/*.c | wc -c # 748 KB
stat -c %s build/extension-window-test/window # 346 KB executable
```
| Share | Size | Files | What it is |
| --- | --- | --- | --- |
| 22% | 168 KB | 17 | Desktop host, painting and the window itself |
| 22% | 163 KB | 21 | Image decoding, WebP, AVIF and Lanczos scaling |
| 20% | 146 KB | 6 | Unicode grapheme tables and text editing |
| 15% | 109 KB | 12 | Widget tree, input and session |
| 11% | 81 KB | 1 | UI test driver |
| 9% | 69 KB | 2 | Accessibility (AT-SPI) |
| 1% | 11 KB | 5 | Standard library |
## Finding
Ziran's pruning works. `--entry` keeps only reachable procedures: for example
27 of `test_driver`'s 52 procedures, 32 of `accessibility_linux`'s 73 and none
of `video_linux`'s 47 are emitted.
The output is large because Kryon's desktop host calls every optional feature
directly, so all of it is reachable for every program:
- `desktop_loop.zi` imports `test_driver` and calls `TestDriverPointer`,
`TestDriverWheel` and `TestDriverFrame` every frame. Whether a test drives
the process is decided at run time by `KRYON_TEST_DRIVER`, so the compiler
must keep the driver.
- `desktop_loop.zi` imports `accessibility_linux` and publishes the tree each
frame; it is enabled at run time.
- `cairo_raster.zi` imports `image_decode_linux` and `lanczos_cache`, which
pull in the WebP and AVIF packages, because the paint queue's image
operation is handled in the rasterizer whether or not the program draws an
image.
- `text_request.zi` imports `std/grapheme` (134 KB of tables) for text
editing, which the session's input path reaches for every program.
About 62% of the generated C (460 KB, 30 files) is feature code an empty window
never runs: images, text editing, the test driver and accessibility.
## Plan, by size of win
Each step makes a feature reachable only from the module a program imports to
use it, so the existing pruning drops it from programs that do not.
The first idea, a procedure slot that the feature's module fills in a module
initializer, does not work today: Ziran has no documented module initializer
that runs registration code at startup for the C target. The mechanism
therefore differs per feature.
1. **Text editing (20%)**: doable in Kryon alone. Files:
`src/ui/text_request.zi`, `src/ui/tree_input.zi`, the text field and text
area widgets. An editing widget passes its grapheme-boundary procedure when
it registers its editable text for the frame, and `text_request` calls
through that value. A program with no editing widget then has no reference
to `std/grapheme`. Risk: text requests cross the portable host protocol, so
the Canvas, raylib, Android and ZX hosts and their text tests are affected.
Test: a program with no editable text generates no `std_grapheme_data.c`,
and every host's text input test passes.
2. **Images (22%)**: needs a decision first. The rasterizer replays paint
operations after the widget call, so the image operation must name a
desktop draw procedure that the portable `kryon/image` module cannot
reference. Two ways:
- Ziran gains module initializers (or link-time registration), and the
image module registers the desktop decoder. A compiler change.
- Desktop builds save targeted IR (`--target=c`), `kryon/image` selects the
Cairo image module with `#if TARGET == .C && OS == .LINUX`, and the paint
operation carries that module's draw procedure. Today only program
entries save targeted IR; frame applications save portable IR.
Files either way: `src/backend/cairo_raster.zi` (its image cache, decode
and Lanczos part moves to its own module), `src/backend/paint_queue.zi`,
`src/ui/image/`.
3. **UI test driver (11%)**: a build-time choice. Files: the ten host files
that call `TestDriver*` (desktop, Canvas, raylib, Android),
`src/backend/test_driver.zi`, `mk/ziran-project.mk`, and the 13 tests that
set `KRYON_TEST_DRIVER`. The driver becomes a module a test build adds
through a profile option, not part of every program. Several of those host
files carry other tasks' uncommitted edits on 2026-11-13.
4. **Accessibility (9%)**: stays. It is the one feature a user benefits from
without the program asking, so it is not removed by default.
Target after steps 1 to 3: about 36 files and 360 KB for `examples/window.zi`,
roughly half of today.
## Ziran's part
Pruning itself needs no change. Module initializers would make step 2 simple
and give Kryon one registration mechanism for every optional feature. A
separate possible improvement is emitting one C file per program instead of
one per module, which changes the file count but not the amount of code.
+48 -7
View File
@@ -22,6 +22,7 @@ AppFiles :: struct {
libc :: #system_library "libc";
AppFreeBytes :: (bytes: *u8) #foreign libc "free";
AppCompareBytes :: (first: *void, second: *void, bytes: usize) -> s32 #foreign libc "memcmp";
AppFileFree :: (value: string) {
if value.count > 0 {
@@ -209,11 +210,11 @@ AppFileRead :: (files: *AppFiles, name: string) -> string {
if size < 0 || size > APP_DOCUMENT_LIMIT {
return ""
}
// Sized once: a large document is read without growing byte by byte.
bytes: Vec(u8)
for index: 0..size - 1 {
if !VecPush(bytes, cast(u8)0) {
return ""
}
if !VecResize(bytes, size) {
VecFree(bytes)
return ""
}
read: s64
{
@@ -228,7 +229,47 @@ AppFileRead :: (files: *AppFiles, name: string) -> string {
return BuilderFinish(bytes)
}
AppFileWrite :: (files: *AppFiles, name: string, value: string) -> bool {
// Does NAME already hold exactly VALUE? Compared in place, a piece at a time,
// without copying the file.
AppFileSame :: (files: *AppFiles, name: string, value: string) -> bool {
if !AppFilesAvailable(files) {
return false
}
path := AppFilePath(files, name, false)
defer { AppFileFree(path) }
if path == "" {
return false
}
file := OpenRead(path)
if !file.valid {
return false
}
defer { unused CloseFile(file) }
if FileSize(file) != value.count {
return false
}
piece: [8192]u8
offset: s64 = 0
while offset < value.count {
count := value.count - offset
if count > 8192 {
count = 8192
}
part := value[offset:offset + count]
expected := cast(*TextDescriptor)(*part)
if ReadAt(file, piece[:count], offset) != count ||
AppCompareBytes(cast(*void)(*piece[0]), cast(*void)expected.data, cast(usize)count) != 0 {
return false
}
offset += count
}
return true
}
// Replace NAME with VALUE atomically. A DURABLE write (documents) also reaches
// the disk before it returns; a copy that can be made again, such as a
// bundle's extracted assets, need not wait for that.
AppFileWrite :: (files: *AppFiles, name: string, value: string, durable: bool = true) -> bool {
if !AppFilesAvailable(files) || value.count > APP_DOCUMENT_LIMIT || name == ".lock" {
return false
}
@@ -261,7 +302,7 @@ AppFileWrite :: (files: *AppFiles, name: string, value: string) -> bool {
}
ok := WriteTextAt(file, value, 0) == value.count
#if !#defined(PLATFORM_WEB) {
ok = ok && SyncFile(file)
ok = ok && (!durable || SyncFile(file))
}
// Browser hosts flush their mounted filesystem as a batch. Emscripten's
// fsync synchronizes the entire IndexedDB mount, so doing it for each
@@ -287,7 +328,7 @@ AppFileWrite :: (files: *AppFiles, name: string, value: string) -> bool {
// Persist the rename and any newly created ancestors, leaf first, down
// to the root itself. AppPrivateDirectory persisted the root's own entry.
index := path.count - 1
while index >= files.root.count {
while durable && index >= files.root.count {
if path[index] == cast(u8)47 && !AppSyncDirectory(path[:index]) {
return false
}
+4 -1
View File
@@ -1,5 +1,8 @@
// Extract only the resources carried by the opened bundle, into a private
// host-owned directory. The same paths work in native and browser filesystems.
// The files are a copy of the bundle, not documents: one that already holds
// its asset is kept, so reopening an app writes nothing, and a new copy is not
// forced to disk, since the next open compares it again.
#import "std/bundle_host"
#import "std/byte_text_linux"
#import "app_files"
@@ -10,7 +13,7 @@ BundleWriteAssets :: (bundle: *void, files: *AppFiles) -> bool {
name := TextFromCString(BundleAssetPath(bundle, index))
data := TextFromBytes(BytesFromPointer(BundleAssetBytes(bundle, index),
BundleAssetLength(bundle, index)))
if !AppFileWrite(files, name, data) { return false }
if !AppFileSame(files, name, data) && !AppFileWrite(files, name, data, false) { return false }
index += 1
}
return true
+1 -8
View File
@@ -376,14 +376,7 @@ PollCanvas :: () -> bool {
return false
}
CanvasGamepadPoll()
// Gamepad navigation and test input join the page's keys in order.
if canvas_focused && !canvas_snapshot_focus_lost {
navigation := GamepadNavigationTake(*canvas_gamepad_navigation)
while navigation != 0 {
InputDeliveryKey(*canvas_input, navigation, 0, false)
navigation = GamepadNavigationTake(*canvas_gamepad_navigation)
}
}
// A test driver types through the same ordered delivery.
TestDriverInput(*canvas_input)
canvas_pointer.x = cast(float32)GetMouseX()
canvas_pointer.y = cast(float32)GetMouseY()
+12
View File
@@ -1,6 +1,7 @@
#import "gamepad_navigation"
#import "canvas_types"
#import "canvas_events"
#import "input_delivery"
#import "c_string"
#import "geometry"
#import "drawing_props"
@@ -25,6 +26,17 @@
cast(float32)PageGamepadAxis(pad, 1))
}
GamepadNavigationPoll(*canvas_gamepad_navigation, buttons, canvas_focused, canvas_snapshot_focus_lost)
CanvasGamepadDeliver()
}
// Navigation presses join the page's keys in order while it has focus.
CanvasGamepadDeliver :: () {
if !canvas_focused || canvas_snapshot_focus_lost { return }
key := GamepadNavigationTake(*canvas_gamepad_navigation)
while key != 0 {
InputDeliveryKey(*canvas_input, key, 0, false)
key = GamepadNavigationTake(*canvas_gamepad_navigation)
}
}
canvas_gamepad_names: [512]u8;
+21
View File
@@ -0,0 +1,21 @@
// Decode encoded image bytes with Kryon's native image pipeline and export
// them in the format selected by the destination path.
#import "raylib_image_decode"
#import "c_string"
image_export_raylib :: #system_library "raylib";
ImageExportNative :: (image: RaylibGlyphImage, path: *u8) -> bool #foreign image_export_raylib "ExportImage";
#program_export
EncodedImageExport :: (data: string, file_type: string, path: string) -> bool {
path_bytes: [4096]u8
if data.count == 0 || !CopyCString(path, path_bytes[:]) {
return false
}
image := RaylibDecodePixels(data, file_type)
if image.data == null {
return false
}
defer { RaylibImageRelease(image) }
return ImageExportNative(image, *path_bytes[0])
}
+196
View File
@@ -0,0 +1,196 @@
// Native PDF pages with searchable UTF-8 text and full-resolution images.
// Applications own their page design; this module owns Cairo/Pango resource
// lifetimes and the conversion from Kryon's straight RGBA image pixels.
#import "std/c_string"
#import "std/byte_text_linux"
Utf8 :: #import "std/utf8";
#import "std/vec"
ImagePixels :: #import "image_pixels";
PdfBounds :: struct { x: float64; y: float64; width: float64; height: float64; }
PdfDocument :: struct { surface: *void; paint: *void; width: float64; height: float64; }
cairo :: #system_library "cairo";
pango :: #system_library "pangocairo-1.0";
objects :: #system_library "gobject-2.0";
PdfSurfaceCreate :: (path: *u8, width: float64, height: float64) -> *void #foreign cairo "cairo_pdf_surface_create";
PdfSurfaceStatus :: (surface: *void) -> s32 #foreign cairo "cairo_surface_status";
PdfSurfaceFinish :: (surface: *void) #foreign cairo "cairo_surface_finish";
PdfSurfaceDestroy :: (surface: *void) #foreign cairo "cairo_surface_destroy";
PdfCreate :: (surface: *void) -> *void #foreign cairo "cairo_create";
PdfDestroy :: (paint: *void) #foreign cairo "cairo_destroy";
PdfStatus :: (paint: *void) -> s32 #foreign cairo "cairo_status";
PdfShowPageNative :: (paint: *void) #foreign cairo "cairo_show_page";
PdfSave :: (paint: *void) #foreign cairo "cairo_save";
PdfRestore :: (paint: *void) #foreign cairo "cairo_restore";
PdfRectangle :: (paint: *void, x: float64, y: float64, width: float64, height: float64) #foreign cairo "cairo_rectangle";
PdfClip :: (paint: *void) #foreign cairo "cairo_clip";
PdfSetSourceRGBA :: (paint: *void, red: float64, green: float64, blue: float64, alpha: float64) #foreign cairo "cairo_set_source_rgba";
PdfFill :: (paint: *void) #foreign cairo "cairo_fill";
PdfTranslate :: (paint: *void, x: float64, y: float64) #foreign cairo "cairo_translate";
PdfScale :: (paint: *void, x: float64, y: float64) #foreign cairo "cairo_scale";
PdfImageSurface :: (bytes: *u8, format: s32, width: s32, height: s32, stride: s32) -> *void #foreign cairo "cairo_image_surface_create_for_data";
PdfSetSourceSurface :: (paint: *void, surface: *void, x: float64, y: float64) #foreign cairo "cairo_set_source_surface";
PdfGetSource :: (paint: *void) -> *void #foreign cairo "cairo_get_source";
PdfPatternFilter :: (pattern: *void, filter: s32) #foreign cairo "cairo_pattern_set_filter";
PdfPaint :: (paint: *void) #foreign cairo "cairo_paint";
PdfMoveTo :: (paint: *void, x: float64, y: float64) #foreign cairo "cairo_move_to";
PdfLayoutNew :: (paint: *void) -> *void #foreign pango "pango_cairo_create_layout";
PdfLayoutText :: (layout: *void, text: *u8, count: s32) #foreign pango "pango_layout_set_text";
PdfLayoutWidth :: (layout: *void, width: s32) #foreign pango "pango_layout_set_width";
PdfLayoutHeight :: (layout: *void, height: s32) #foreign pango "pango_layout_set_height";
PdfLayoutWrap :: (layout: *void, wrap: s32) #foreign pango "pango_layout_set_wrap";
PdfLayoutAlign :: (layout: *void, align: s32) #foreign pango "pango_layout_set_alignment";
PdfLayoutFont :: (layout: *void, description: *void) #foreign pango "pango_layout_set_font_description";
PdfLayoutSize :: (layout: *void, width: *s32, height: *s32) #foreign pango "pango_layout_get_pixel_size";
PdfLayoutShow :: (paint: *void, layout: *void) #foreign pango "pango_cairo_show_layout";
PdfFontNew :: () -> *void #foreign pango "pango_font_description_new";
PdfFontFree :: (description: *void) #foreign pango "pango_font_description_free";
PdfFontFamily :: (description: *void, family: *u8) #foreign pango "pango_font_description_set_family";
PdfFontSize :: (description: *void, size: float64) #foreign pango "pango_font_description_set_absolute_size";
PdfFontWeight :: (description: *void, weight: s32) #foreign pango "pango_font_description_set_weight";
PdfObjectFree :: (object: *void) #foreign objects "g_object_unref";
PdfOpen :: (document: *PdfDocument, path: string, width: float64 = 612.0, height: float64 = 792.0) -> bool {
if document.surface != null || path.count == 0 || width <= 0.0 || height <= 0.0 { return false }
name: [4096]u8
if !CopyCString(path, name[:]) { return false }
document.surface = PdfSurfaceCreate(*name[0], width, height)
if document.surface == null || PdfSurfaceStatus(document.surface) != 0 {
if document.surface != null { PdfSurfaceDestroy(document.surface) }
document.* = PdfDocument.{}
return false
}
document.paint = PdfCreate(document.surface)
if document.paint == null || PdfStatus(document.paint) != 0 {
if document.paint != null { PdfDestroy(document.paint) }
PdfSurfaceDestroy(document.surface)
document.* = PdfDocument.{}
return false
}
document.width = width; document.height = height
return true
}
PdfPageColor :: (document: *PdfDocument, color: u32) -> bool {
if document.paint == null { return false }
PdfSetSourceRGBA(document.paint, cast(float64)(color >> 24) / 255.0,
cast(float64)((color >> 16) & cast(u32)255) / 255.0,
cast(float64)((color >> 8) & cast(u32)255) / 255.0,
cast(float64)(color & cast(u32)255) / 255.0)
PdfRectangle(document.paint, 0.0, 0.0, document.width, document.height)
PdfFill(document.paint)
return PdfStatus(document.paint) == 0
}
// Draws every source pixel, contained inside bounds. Transparent assets keep
// their alpha and can be layered over another full-resolution image.
PdfImage :: (document: *PdfDocument, path: string, bounds: PdfBounds) -> bool {
if document.paint == null || path.count == 0 || bounds.width <= 0.0 || bounds.height <= 0.0 { return false }
image := ImagePixels.LoadImagePixels(path)
defer VecFree(image.pixels)
count := cast(s64)image.width * image.height
if image.width <= 0 || image.height <= 0 || count <= 0 || image.pixels.count != count * 4 { return false }
converted: Vec(u8)
defer VecFree(converted)
if !VecResize(converted, count * 4) { return false }
for at: cast(s64)0..count - 1 {
source := at * 4
alpha := cast(u32)image.pixels[source + 3]
red := (cast(u32)image.pixels[source] * alpha + 127) / 255
green := (cast(u32)image.pixels[source + 1] * alpha + 127) / 255
blue := (cast(u32)image.pixels[source + 2] * alpha + 127) / 255
// Cairo ARGB32 is native-endian; Linux's little-endian bytes are BGRA.
converted[at * 4] = cast(u8)blue
converted[at * 4 + 1] = cast(u8)green
converted[at * 4 + 2] = cast(u8)red
converted[at * 4 + 3] = cast(u8)alpha
}
surface := PdfImageSurface(*converted[0], 0, image.width, image.height, image.width * 4)
if surface == null || PdfSurfaceStatus(surface) != 0 {
if surface != null { PdfSurfaceDestroy(surface) }
return false
}
scale := bounds.width / cast(float64)image.width
if bounds.height / cast(float64)image.height < scale { scale = bounds.height / cast(float64)image.height }
width := cast(float64)image.width * scale
height := cast(float64)image.height * scale
PdfSave(document.paint)
PdfRectangle(document.paint, bounds.x, bounds.y, bounds.width, bounds.height)
PdfClip(document.paint)
PdfTranslate(document.paint, bounds.x + (bounds.width - width) / 2.0,
bounds.y + (bounds.height - height) / 2.0)
PdfScale(document.paint, scale, scale)
PdfSetSourceSurface(document.paint, surface, 0.0, 0.0)
PdfPatternFilter(PdfGetSource(document.paint), 4)
PdfPaint(document.paint)
PdfRestore(document.paint)
PdfSurfaceDestroy(surface)
return PdfStatus(document.paint) == 0
}
PdfStringData :: (value: string) -> *u8 {
descriptor := cast(*TextDescriptor)(*value)
return descriptor.data
}
// Text remains text in the PDF (including fallback fonts for CJK), so it can
// be selected, searched and extracted. Pango wraps words inside bounds.
PdfText :: (document: *PdfDocument, value: string, bounds: PdfBounds, size: float64,
color: u32 = 0x3e332aff, centered: bool = true, bold: bool = false) -> bool {
if document.paint == null || value.count == 0 || value.count > 2147483647 ||
!Utf8.Valid(value) || bounds.width <= 0.0 || bounds.height <= 0.0 || size <= 0.0 { return false }
layout := PdfLayoutNew(document.paint)
description := PdfFontNew()
if layout == null || description == null {
if layout != null { PdfObjectFree(layout) }
if description != null { PdfFontFree(description) }
return false
}
defer PdfObjectFree(layout)
defer PdfFontFree(description)
family: [32]u8
unused CopyCString("Noto Sans", family[:])
PdfFontFamily(description, *family[0])
PdfFontSize(description, size * 1024.0)
if bold { PdfFontWeight(description, 700) }
PdfLayoutFont(layout, description)
PdfLayoutText(layout, PdfStringData(value), cast(s32)value.count)
PdfLayoutWidth(layout, cast(s32)(bounds.width * 1024.0))
PdfLayoutHeight(layout, cast(s32)(bounds.height * 1024.0))
PdfLayoutWrap(layout, 2)
PdfLayoutAlign(layout, ifx centered then 1 else 0)
text_width: s32; text_height: s32
PdfLayoutSize(layout, *text_width, *text_height)
y := bounds.y
if cast(float64)text_height < bounds.height { y += (bounds.height - cast(float64)text_height) / 2.0 }
PdfSetSourceRGBA(document.paint, cast(float64)(color >> 24) / 255.0,
cast(float64)((color >> 16) & cast(u32)255) / 255.0,
cast(float64)((color >> 8) & cast(u32)255) / 255.0,
cast(float64)(color & cast(u32)255) / 255.0)
PdfMoveTo(document.paint, bounds.x, y)
PdfLayoutShow(document.paint, layout)
return PdfStatus(document.paint) == 0
}
PdfPage :: (document: *PdfDocument) -> bool {
if document.paint == null { return false }
PdfShowPageNative(document.paint)
return PdfStatus(document.paint) == 0
}
PdfClose :: (document: *PdfDocument) -> bool {
if document.surface == null { return false }
status: s32 = 0
if document.paint != null {
status = PdfStatus(document.paint)
PdfDestroy(document.paint)
}
PdfSurfaceFinish(document.surface)
if status == 0 { status = PdfSurfaceStatus(document.surface) }
PdfSurfaceDestroy(document.surface)
document.* = PdfDocument.{}
return status == 0
}
+171 -47
View File
@@ -38,6 +38,8 @@ SceneGpuResources :: struct {
gpu_bytes: s64; cpu_bytes: s64
buffers: s32; textures: s32; programs: s32; framebuffers: s32; renderbuffers: s32
geometry_uploads: s64; texture_uploads: s64; frames: s64; shadow_renders: s64
// Vertices sent to the GPU so far. A node that only moves sends its own.
geometry_vertices: s64
fences: s32; pending_frames: s32; submitted_frames: s64; cancelled_frames: s64
}
// ok means a valid nonblocking operation; queued/completed distinguish progress.
@@ -56,12 +58,13 @@ GpuVertex :: struct { p: [3]float32; n: [3]float32; c: [3]float32; uv: [2]float3
GpuDraw :: struct { first: s32; count: s32; mesh: s32; node: s32; receive: bool; cast_shadow: bool; shown: bool; origin: Vector3 }
GpuLocations :: struct {
vp: s32; view: s32; base: s32; glow: s32; material: s32; flags: s32; settings: s32; transparent: s32
albedo_size: s32; albedo: s32; dfg: s32; sky: s32; ground: s32; up: s32; light_count: s32; uniforms: s32
albedo_size: s32; albedo_sampling: s32; albedo: s32; dfg: s32; sky: s32; ground: s32; up: s32; light_count: s32; uniforms: s32
shadow: [4]s32; shadow_settings: [4]s32; light_color: [4]s32; light_direction: [4]s32; shadow_matrix: [4]s32
cookie: s32; cookie_matrix: s32; cookie_transform: s32; cookie_size: s32; cookie_light: s32
sampler: [8]s32; sampler_size: [8]s32; sampler_repeat: [8]s32
}
GpuProgram :: struct { features: s32; key: *ShaderProgram; saved: ShaderProgram; id: u32; used: bool; locations: GpuLocations }
GpuTexture :: struct { key: *u8; width: s32; height: s32; id: u32; used: bool; bytes: Vec(u8) }
GpuTexture :: struct { key: *u8; cache_key: u64; width: s32; height: s32; id: u32; used: bool; bytes: Vec(u8) }
GpuShadow :: struct { texture: u32; framebuffer: u32; size: s32; source: SceneLight }
GpuBindingCheck :: struct {program: *ShaderProgram; uniforms: *ShaderValue; uniform_count: s64; samplers: *ShaderSampler; sampler_count: s64}
SceneGpuContext :: struct {
@@ -71,6 +74,9 @@ SceneGpuContext :: struct {
framebuffer: u32; color: u32; depth: u32; resolve: u32; resolved: u32
buffer: u32; shadow_program: u32; dfg: u32
vertices: Vec(GpuVertex); draws: Vec(GpuDraw)
// Where each node's triangles lie in VERTICES and where the node stood when
// they were made, so a node that only moves replaces just its own.
node_first: Vec(s32); node_count: Vec(s32); node_world: Vec(M.GpuMatrix); node_shown: Vec(bool)
snapshot: Vec(u8); readback: Vec(u8); order: Vec(s32); keys: Vec(float64)
programs: Vec(GpuProgram); textures: Vec(GpuTexture); shadows: [4]GpuShadow
bindings: Vec(GpuBindingCheck)
@@ -78,6 +84,8 @@ SceneGpuContext :: struct {
transfers: [2]GpuTransfer; last_request: u64
shadow_geometry: s64
geometry_valid: bool
// The snapshot was taken of a scene whose geometry was frozen.
snapshot_frozen: bool
snapshot_counts: [8]s64
log: [2048]u8
}
@@ -109,8 +117,8 @@ SceneGpuProbe :: (gpu: *SceneGpuContext)->SceneGpuCapabilities {
maximum: s32;G.GetInteger(0x8d57,*maximum)
range: [2]s32;precision: s32;G.GetPrecision(0x8b30,0x8df2,*range[0],*precision)
gpu.capabilities.max_samples=maximum;gpu.capabilities.highp_bits=precision;gpu.capabilities.highp_range=range[1]
gpu.capabilities.diagnostic="fragment highp, 14 texture units and full 4x MSAA required"
if maximum<4||precision<23||range[1]<127||gpu.capabilities.texture_units<14 { return gpu.capabilities }
gpu.capabilities.diagnostic="fragment highp, 15 texture units and full 4x MSAA required"
if maximum<4||precision<23||range[1]<127||gpu.capabilities.texture_units<15 { return gpu.capabilities }
if !Resize(gpu,4,4) { return gpu.capabilities }
gpu.capabilities.diagnostic="bilinear depth comparison required for full PCF"
if !ProbePCF(gpu) {return gpu.capabilities}
@@ -350,6 +358,7 @@ SceneGpuRelease :: (gpu: *SceneGpuContext) {
// EGLDisplay is process-shared, including with foreign hosts. eglTerminate
// invalidates their contexts too; release only the context/objects we own.
VecFree(gpu.vertices);VecFree(gpu.draws);VecFree(gpu.snapshot);VecFree(gpu.readback)
VecFree(gpu.node_first);VecFree(gpu.node_count);VecFree(gpu.node_world);VecFree(gpu.node_shown)
VecFree(gpu.order);VecFree(gpu.keys);VecFree(gpu.programs);VecFree(gpu.textures)
VecFree(gpu.bindings)
gpu.capabilities=SceneGpuCapabilities.{};gpu.resources=SceneGpuResources.{}
@@ -534,7 +543,7 @@ SnapshotPart :: (gpu: *SceneGpuContext,offset: *s64,data: *void,bytes: s64,write
GeometrySnapshot :: (gpu: *SceneGpuContext,scene: *Scene,write: bool)->bool {
counts: [8]s64=.[scene.nodes.count,scene.meshes.count,scene.positions.count,scene.normals.count,scene.colors.count,scene.uvs.count,scene.indices.count,0]
if !write {for at:0..7 {if counts[at]!=gpu.snapshot_counts[at] {return false}}}
else {gpu.snapshot_counts=counts}
else {gpu.snapshot_counts=counts;gpu.snapshot_frozen=scene.geometry_frozen}
total:=(scene.nodes.count*cast(s64)size_of(SceneNode)+scene.meshes.count*cast(s64)size_of(SceneMesh)+
(scene.positions.count+scene.normals.count+scene.colors.count)*cast(s64)size_of(Vector3)+
scene.uvs.count*cast(s64)size_of(ShapePoint)+scene.indices.count*4)
@@ -559,51 +568,133 @@ MaterialEqual :: (a: SceneMaterial,b: SceneMaterial)->bool {
if a.kind!=b.kind||!ColorEqual(a.color,b.color)||a.roughness!=b.roughness||a.metalness!=b.metalness||
!ColorEqual(a.glow,b.glow)||a.glow_strength!=b.glow_strength||a.opacity!=b.opacity||
a.transparent!=b.transparent||a.double_sided!=b.double_sided||a.flat!=b.flat||a.vertex_colors!=b.vertex_colors||
a.texture!=b.texture||a.alpha_test!=b.alpha_test||a.exact_color!=b.exact_color||a.shader!=b.shader||
a.texture!=b.texture||a.texture_projection!=b.texture_projection||a.texture_filter!=b.texture_filter||
a.texture_wrap!=b.texture_wrap||a.texture_scale.x!=b.texture_scale.x||a.texture_scale.y!=b.texture_scale.y||
a.texture_offset.x!=b.texture_offset.x||a.texture_offset.y!=b.texture_offset.y||
a.alpha_test!=b.alpha_test||a.exact_color!=b.exact_color||a.shader!=b.shader||
a.shader_uniforms.count!=b.shader_uniforms.count||a.shader_samplers.count!=b.shader_samplers.count {return false}
if a.shader_uniforms.count>0&&*a.shader_uniforms[0]!=*b.shader_uniforms[0] {return false}
if a.shader_samplers.count>0&&*a.shader_samplers[0]!=*b.shader_samplers[0] {return false}
return true
}
// One node's triangles in world space, written into gpu.vertices from FIRST
// on (appended where FIRST is past the end). Returns how many vertices, or -1.
BakeNode :: (gpu: *SceneGpuContext,scene: *Scene,node: SceneNode,matrix: M.GpuMatrix,first: s32)->s32 {
if node.mesh<0||node.mesh>=scene.meshes.count {return -1}
mesh:=scene.meshes[node.mesh];normal:=M.NormalMatrix(matrix)
count:=ifx mesh.index_count>0 then mesh.index_count else mesh.vertex_count
if count<0||mesh.first_vertex<0||mesh.vertex_count<0||mesh.first_vertex+mesh.vertex_count>scene.positions.count {return -1}
if scene.normals.count!=scene.positions.count||scene.colors.count!=scene.positions.count||scene.uvs.count!=scene.positions.count {return -1}
if mesh.index_count>0&&(mesh.first_index<0||mesh.first_index+count>scene.indices.count) {return -1}
mirrored:=M.Determinant3(matrix)<0.0
write:=cast(s64)first
corner: s32
while corner+2<count {
p: [3]Vector3;n: [3]Vector3;c: [3]Vector3;uv: [3]ShapePoint
for lane: 0..2 {
index:=mesh.first_vertex+corner+cast(s32)lane
if mesh.index_count>0 {index=mesh.first_vertex+scene.indices[mesh.first_index+corner+lane]}
if index<mesh.first_vertex||index>=mesh.first_vertex+mesh.vertex_count {return -1}
p[lane]=M.Point(matrix,scene.positions[index]);n[lane]=M.Normalize(M.Direction(normal,scene.normals[index]))
c[lane]=scene.colors[index]
uv[lane]=SceneTextureCoordinate(mesh.material,scene.positions[index],scene.normals[index],scene.uvs[index])
}
face:=M.Normalize(M.Cross(M.Sub(p[1],p[0]),M.Sub(p[2],p[0])))
for lane: 0..2 {
at0:=ifx mirrored&&lane>0 then 3-lane else lane
vertex: GpuVertex=.{V3(p[at0]),V3(n[at0]),V3(c[at0]),float32.[cast(float32)uv[at0].x,cast(float32)uv[at0].y],V3(face)}
if write<gpu.vertices.count {gpu.vertices[write]=vertex}
else if !VecPush(gpu.vertices,vertex) {return -1}
write+=1
}
corner+=3
}
return cast(s32)(write-cast(s64)first)
}
MatrixSame :: (a: M.GpuMatrix,b: M.GpuMatrix)->bool {
for at: 0..15 {if a.m[at]!=b.m[at] {return false}}
return true
}
// How the scene differs from the uploaded geometry: 0 not at all, 1 only in
// its node records, 2 in its meshes or vertices too. A scene whose geometry
// is frozen, and was when uploaded, has only its nodes compared.
GeometryChange :: (gpu: *SceneGpuContext,scene: *Scene)->s32 {
counts: [8]s64=.[scene.nodes.count,scene.meshes.count,scene.positions.count,scene.normals.count,scene.colors.count,scene.uvs.count,scene.indices.count,0]
for at:0..7 {if counts[at]!=gpu.snapshot_counts[at] {return 2}}
offset: s64
nodes:=ifx SnapshotPart(gpu,*offset,(ifx scene.nodes.count>0 then cast(*void)*scene.nodes[0] else null),scene.nodes.count*cast(s64)size_of(SceneNode),false) then 0 else 1
if gpu.snapshot_frozen&&scene.geometry_frozen {return cast(s32)nodes}
same:=true
if !SnapshotPart(gpu,*offset,(ifx scene.meshes.count>0 then cast(*void)*scene.meshes[0] else null),scene.meshes.count*cast(s64)size_of(SceneMesh),false) {same=false}
if !SnapshotPart(gpu,*offset,(ifx scene.positions.count>0 then cast(*void)*scene.positions[0] else null),scene.positions.count*cast(s64)size_of(Vector3),false) {same=false}
if !SnapshotPart(gpu,*offset,(ifx scene.normals.count>0 then cast(*void)*scene.normals[0] else null),scene.normals.count*cast(s64)size_of(Vector3),false) {same=false}
if !SnapshotPart(gpu,*offset,(ifx scene.colors.count>0 then cast(*void)*scene.colors[0] else null),scene.colors.count*cast(s64)size_of(Vector3),false) {same=false}
if !SnapshotPart(gpu,*offset,(ifx scene.uvs.count>0 then cast(*void)*scene.uvs[0] else null),scene.uvs.count*cast(s64)size_of(ShapePoint),false) {same=false}
if !SnapshotPart(gpu,*offset,(ifx scene.indices.count>0 then cast(*void)*scene.indices[0] else null),scene.indices.count*4,false) {same=false}
return ifx same then cast(s32)nodes else 2
}
// The changed node records only moved nodes: every node keeps its parent, its
// mesh, whether it is shown and how it takes part in shadows, so the batches
// made from them still hold.
OnlyMoved :: (gpu: *SceneGpuContext,scene: *Scene)->bool {
if gpu.node_first.count!=scene.nodes.count||gpu.node_world.count!=scene.nodes.count||gpu.node_shown.count!=scene.nodes.count {return false}
kept:=cast(*SceneNode)cast(*void)*gpu.snapshot[0]
for at: 0..scene.nodes.count-1 {
node:=scene.nodes[at];before:=kept[at]
if node.parent>=at||node.parent!=before.parent||node.mesh!=before.mesh||node.cast_shadow!=before.cast_shadow||
node.receive_shadow!=before.receive_shadow||node.visible!=before.visible {return false}
}
return true
}
// Re-makes and sends only the triangles of nodes that moved.
UpdateMoved :: (gpu: *SceneGpuContext,scene: *Scene)->bool {
G.BindBuffer(0x8892,gpu.buffer)
size:=cast(s64)size_of(GpuVertex)
for at: 0..scene.nodes.count-1 {
node:=scene.nodes[at];matrix:=M.Compose(node.position,node.rotation,node.scale)
if node.parent>=0 {matrix=M.Multiply(gpu.node_world[node.parent],matrix)}
if MatrixSame(matrix,gpu.node_world[at]) {continue}
gpu.node_world[at]=matrix
if node.mesh<0 {continue}
first:=gpu.node_first[at]
if BakeNode(gpu,scene,node,matrix,first)!=gpu.node_count[at] {return false}
if gpu.node_count[at]>0 {
G.BufferSubData(0x8892,cast(s64)first*size,cast(s64)gpu.node_count[at]*size,cast(*void)*gpu.vertices[first])
gpu.resources.geometry_vertices+=gpu.node_count[at]
}
// A blended mesh is sorted by where its node stands.
for d: 0..gpu.draws.count-1 {if gpu.draws[d].node==cast(s32)at {gpu.draws[d].origin=M.Point(matrix,.{})}}
}
if G.GetError()!=0 {return false}
if scene.nodes.count>0 {unused G.CopyMemory(cast(*void)*gpu.snapshot[0],cast(*void)*scene.nodes[0],cast(usize)(scene.nodes.count*cast(s64)size_of(SceneNode)))}
gpu.resources.geometry_uploads+=1
return true
}
PrepareGeometry :: (gpu: *SceneGpuContext,scene: *Scene)->bool {
if gpu.geometry_valid&&GeometrySnapshot(gpu,scene,false) {return true}
if gpu.geometry_valid {
change:=GeometryChange(gpu,scene)
if change==0 {return true}
// Most frames that change anything only move a node: a door swings, a leaf
// sways. Those replace the moved nodes' triangles and nothing else.
if change==1&&OnlyMoved(gpu,scene)&&UpdateMoved(gpu,scene) {return true}
}
gpu.geometry_valid=false
VecClear(gpu.vertices);VecClear(gpu.draws)
world: Vec(M.GpuMatrix);shown: Vec(bool)
VecClear(gpu.node_first);VecClear(gpu.node_count);VecClear(gpu.node_world);VecClear(gpu.node_shown)
for at: 0..scene.nodes.count-1 {
node:=scene.nodes[at];matrix:=M.Compose(node.position,node.rotation,node.scale);visible:=node.visible
if node.parent>=0 {
if node.parent>=at {return false}
matrix=M.Multiply(world[node.parent],matrix);visible=visible&&shown[node.parent]
matrix=M.Multiply(gpu.node_world[node.parent],matrix);visible=visible&&gpu.node_shown[node.parent]
}
if !VecPush(world,matrix)||!VecPush(shown,visible) {return false}
if node.mesh<0 {continue}
if node.mesh>=scene.meshes.count {return false}
mesh:=scene.meshes[node.mesh];normal:=M.NormalMatrix(matrix)
count:=ifx mesh.index_count>0 then mesh.index_count else mesh.vertex_count
if count<0||mesh.first_vertex<0||mesh.vertex_count<0||mesh.first_vertex+mesh.vertex_count>scene.positions.count {return false}
if scene.normals.count!=scene.positions.count||scene.colors.count!=scene.positions.count||scene.uvs.count!=scene.positions.count {return false}
if mesh.index_count>0&&(mesh.first_index<0||mesh.first_index+count>scene.indices.count) {return false}
first:=cast(s32)gpu.vertices.count
corner: s32
while corner+2<count {
p: [3]Vector3;n: [3]Vector3;c: [3]Vector3;uv: [3]ShapePoint
for lane: 0..2 {
index:=mesh.first_vertex+corner+cast(s32)lane
if mesh.index_count>0 {index=mesh.first_vertex+scene.indices[mesh.first_index+corner+lane]}
if index<mesh.first_vertex||index>=mesh.first_vertex+mesh.vertex_count {return false}
p[lane]=M.Point(matrix,scene.positions[index]);n[lane]=M.Normalize(M.Direction(normal,scene.normals[index]))
c[lane]=scene.colors[index];uv[lane]=scene.uvs[index]
}
face:=M.Normalize(M.Cross(M.Sub(p[1],p[0]),M.Sub(p[2],p[0])))
for lane: 0..2 {
at0:=ifx M.Determinant3(matrix)<0.0&&lane>0 then 3-lane else lane
vertex: GpuVertex=.{V3(p[at0]),V3(n[at0]),V3(c[at0]),float32.[cast(float32)uv[at0].x,cast(float32)uv[at0].y],V3(face)}
if !VecPush(gpu.vertices,vertex) {return false}
}
corner+=3
}
draw: GpuDraw=.{first,cast(s32)gpu.vertices.count-first,node.mesh,cast(s32)at,node.receive_shadow,node.cast_shadow,visible,M.Point(matrix,.{})}
if !VecPush(gpu.node_world,matrix)||!VecPush(gpu.node_shown,visible)||!VecPush(gpu.node_first,first)||!VecPush(gpu.node_count,0) {return false}
if node.mesh<0 {continue}
count:=BakeNode(gpu,scene,node,matrix,first)
if count<0 {return false}
gpu.node_count[at]=count
mesh:=scene.meshes[node.mesh]
draw: GpuDraw=.{first,count,node.mesh,cast(s32)at,node.receive_shadow,node.cast_shadow,visible,M.Point(matrix,.{})}
merged:=false
if gpu.draws.count>0&&!mesh.material.transparent {
last:=*gpu.draws[gpu.draws.count-1];other:=scene.meshes[last.mesh].material
@@ -615,9 +706,10 @@ PrepareGeometry :: (gpu: *SceneGpuContext,scene: *Scene)->bool {
if !merged&&!VecPush(gpu.draws,draw) {return false}
}
G.BindBuffer(0x8892,gpu.buffer)
G.BufferData(0x8892,gpu.vertices.count*cast(s64)size_of(GpuVertex),(ifx gpu.vertices.count>0 then cast(*void)*gpu.vertices[0] else null),0x88e4)
G.BufferData(0x8892,gpu.vertices.count*cast(s64)size_of(GpuVertex),(ifx gpu.vertices.count>0 then cast(*void)*gpu.vertices[0] else null),0x88e8)
if G.GetError()!=0||!GeometrySnapshot(gpu,scene,true) {return false}
gpu.resources.geometry_uploads+=1
gpu.resources.geometry_vertices+=gpu.vertices.count
gpu.geometry_valid=true
return true
}
@@ -675,7 +767,7 @@ ProgramFor :: (gpu: *SceneGpuContext,key: *ShaderProgram,features: s32)->u32 {
else if !VecPush(gpu.programs,value) {G.DeleteProgram(id);return 0}
return id
}
TextureFor :: (gpu: *SceneGpuContext,pixels: *u8,width: s32,height: s32)->u32 {
TextureFor :: (gpu: *SceneGpuContext,pixels: *u8,width: s32,height: s32,cache_key: u64=0)->u32 {
if width<=0||height<=0||width>gpu.capabilities.max_texture_size||height>gpu.capabilities.max_texture_size {return 0}
bytes:=cast(s64)width*height*4;slot: s64=-1
for at: 0..gpu.textures.count-1 {
@@ -684,17 +776,22 @@ TextureFor :: (gpu: *SceneGpuContext,pixels: *u8,width: s32,height: s32)->u32 {
if t.key==pixels&&t.width==width&&t.height==height {
if t.used {return t.id}
t.used=true
if cache_key!=0&&t.cache_key==cache_key {return t.id}
if t.bytes.count==bytes&&G.CompareMemory((ifx t.bytes.count>0 then cast(*void)*t.bytes[0] else null),cast(*void)pixels,cast(usize)bytes)==0 {return t.id}
G.BindTexture(0x0de1,t.id);G.TexImage(0x0de1,0,0x8058,width,height,0,0x1908,0x1401,cast(*void)pixels)
if !VecResize(t.bytes,bytes) {return 0}
unused G.CopyMemory((ifx t.bytes.count>0 then cast(*void)*t.bytes[0] else null),cast(*void)pixels,cast(usize)bytes)
gpu.resources.texture_uploads+=1;return t.id
if cache_key==0 {
if !VecResize(t.bytes,bytes) {return 0}
unused G.CopyMemory((ifx t.bytes.count>0 then cast(*void)*t.bytes[0] else null),cast(*void)pixels,cast(usize)bytes)
} else {VecFree(t.bytes)}
t.cache_key=cache_key;gpu.resources.texture_uploads+=1;return t.id
}
}
if slot<0 {empty: GpuTexture;if !VecPush(gpu.textures,empty) {return 0};slot=gpu.textures.count-1}
value:=*gpu.textures[slot];value.key=pixels;value.width=width;value.height=height;value.used=true
if !VecResize(value.bytes,bytes) {return 0}
unused G.CopyMemory(cast(*void)*value.bytes[0],cast(*void)pixels,cast(usize)bytes)
value:=*gpu.textures[slot];value.key=pixels;value.cache_key=cache_key;value.width=width;value.height=height;value.used=true
if cache_key==0 {
if !VecResize(value.bytes,bytes) {return 0}
unused G.CopyMemory(cast(*void)*value.bytes[0],cast(*void)pixels,cast(usize)bytes)
} else {VecFree(value.bytes)}
value.id=G.Texture(width,height,0x8058,0x1908,0x1401,cast(*void)pixels)
id:=value.id
gpu.resources.texture_uploads+=1
@@ -721,9 +818,12 @@ CacheLocations :: (id: u32)->GpuLocations {
l: GpuLocations
l.vp=G.Location(id,"vp");l.view=G.Location(id,"view");l.base=G.Location(id,"base");l.glow=G.Location(id,"glow")
l.material=G.Location(id,"material");l.flags=G.Location(id,"flags");l.settings=G.Location(id,"settings")
l.transparent=G.Location(id,"transparent");l.albedo_size=G.Location(id,"albedoSize");l.albedo=G.Location(id,"albedo")
l.transparent=G.Location(id,"transparent");l.albedo_size=G.Location(id,"albedoSize")
l.albedo_sampling=G.Location(id,"albedoSampling");l.albedo=G.Location(id,"albedo")
l.dfg=G.Location(id,"dfg");l.sky=G.Location(id,"sky");l.ground=G.Location(id,"ground");l.up=G.Location(id,"up")
l.light_count=G.Location(id,"lightCount");l.uniforms=G.Location(id,"kryonUniforms[0]")
l.cookie=G.Location(id,"cookie");l.cookie_matrix=G.Location(id,"cookieMatrix");l.cookie_transform=G.Location(id,"cookieTransform")
l.cookie_size=G.Location(id,"cookieSize");l.cookie_light=G.Location(id,"cookieLight")
for at:0..3 {
shadow: Text=Name("shadow%",at);l.shadow[at]=G.Location(id,TextView(shadow))
settings: Text=Name("shadowSettings[%]",at);l.shadow_settings[at]=G.Location(id,TextView(settings))
@@ -751,12 +851,13 @@ Draw :: (gpu: *SceneGpuContext,scene: *Scene,d: GpuDraw,view: M.GpuMatrix,vp: M.
G.Uniform4f(locations.settings,ifx scene.tone_mapping then 1.0 else 0.0,ifx m.exact_color then 1.0 else 0.0,cast(float32)scene.exposure,ifx perspective then 1.0 else 0.0)
G.Uniform1i(locations.transparent,ifx m.transparent then 1 else 0)
if m.double_sided {G.Disable(0x0b44)} else {G.Enable(0x0b44)}
G.Uniform2f(locations.albedo_size,0.0,0.0);G.Uniform1i(locations.albedo,0)
G.Uniform2f(locations.albedo_size,0.0,0.0);G.Uniform2f(locations.albedo_sampling,0.0,0.0);G.Uniform1i(locations.albedo,0)
if m.texture>=0&&m.texture<scene.textures.count {
t:=scene.textures[m.texture];bytes:=cast(s64)t.width*t.height*4
if t.first_texel<0||t.first_texel+bytes>scene.texels.count {return false}
texture:=TextureFor(gpu,*scene.texels[t.first_texel],t.width,t.height);if texture==0 {return false}
texture:=TextureFor(gpu,*scene.texels[t.first_texel],t.width,t.height,t.cache_key);if texture==0 {return false}
BindTexture(0,texture);G.Uniform2f(locations.albedo_size,cast(float32)t.width,cast(float32)t.height)
G.Uniform2f(locations.albedo_sampling,cast(float32)cast(s32)m.texture_filter,cast(float32)cast(s32)m.texture_wrap)
}
BindTexture(1,gpu.dfg);G.Uniform1i(locations.dfg,1)
VectorAt(locations.sky,M.Times(LinearColor(scene.sky),scene.hemisphere));VectorAt(locations.ground,M.Times(LinearColor(scene.ground),scene.hemisphere))
@@ -778,6 +879,7 @@ Draw :: (gpu: *SceneGpuContext,scene: *Scene,d: GpuDraw,view: M.GpuMatrix,vp: M.
G.Uniform4f(locations.shadow_settings[at],1.0,cast(float32)l.shadow_bias,cast(float32)l.shadow_normal_bias,cast(float32)(l.shadow_radius/cast(float64)l.shadow_size))
}
}
if !BindCookie(gpu,scene,locations,count) {return false}
if m.shader!=null {
uniforms: [64]float32
for slot: 0..m.shader.uniform_count-1 {
@@ -795,6 +897,28 @@ Draw :: (gpu: *SceneGpuContext,scene: *Scene,d: GpuDraw,view: M.GpuMatrix,vp: M.
G.DrawArrays(4,d.first,d.count)
return true
}
// The first light whose cookie can project binds it to unit 14, after the
// albedo, DFG, four shadow and eight shader-sampler units.
BindCookie :: (gpu: *SceneGpuContext,scene: *Scene,locations: *GpuLocations,count: s32)->bool {
G.Uniform1i(locations.cookie,14);G.Uniform1i(locations.cookie_light,-1)
for at: 0..count-1 {
l:=scene.lights[at]
if !l.cookie {continue}
if l.cookie_texture<0||l.cookie_texture>=scene.textures.count||l.shadow_half_width<=0.0||l.shadow_half_height<=0.0||l.shadow_far==l.shadow_near {continue}
t:=scene.textures[l.cookie_texture];bytes:=cast(s64)t.width*t.height*4
if t.width<=0||t.height<=0||t.first_texel<0||t.first_texel+bytes>scene.texels.count {continue}
texture:=TextureFor(gpu,*scene.texels[t.first_texel],t.width,t.height,t.cache_key);if texture==0 {return false}
BindTexture(14,texture)
bias:=M.Identity()
bias.m[0]=0.5;bias.m[3]=0.5;bias.m[5]=0.5;bias.m[7]=0.5;bias.m[10]=0.5;bias.m[11]=0.5
MatrixAt(locations.cookie_matrix,M.Multiply(bias,ShadowVP(l)))
G.Uniform4f(locations.cookie_transform,cast(float32)l.cookie_scale.x,cast(float32)l.cookie_scale.y,cast(float32)l.cookie_offset.x,cast(float32)l.cookie_offset.y)
G.Uniform2f(locations.cookie_size,cast(float32)t.width,cast(float32)t.height)
G.Uniform1i(locations.cookie_light,cast(s32)at)
return true
}
return true
}
ShadowVP :: (l: SceneLight)->M.GpuMatrix {return M.Multiply(M.Orthographic(-l.shadow_half_width,l.shadow_half_width,l.shadow_half_height,-l.shadow_half_height,l.shadow_near,l.shadow_far),M.LookAt(l.position,l.target,.{0,1,0}))}
ShadowSpaceEqual :: (a: SceneLight,b: SceneLight)->bool {
// Radiometry and receiver bias/filter parameters do not change caster depth.
+2
View File
@@ -49,6 +49,7 @@ RawGenBuffers :: (count: s32, ids: *u32) #foreign gl "glGenBuffers";
RawDeleteBuffers :: (count: s32, ids: *u32) #foreign gl "glDeleteBuffers";
RawBindBuffer :: (target: u32, id: u32) #foreign gl "glBindBuffer";
RawBufferData :: (target: u32, bytes: s64, data: *void, usage: u32) #foreign gl "glBufferData";
RawBufferSubData :: (target: u32, offset: s64, bytes: s64, data: *void) #foreign gl "glBufferSubData";
RawMapBufferRange :: (target: u32,offset: s64,bytes: s64,access: u32)->*void #foreign gl "glMapBufferRange";
RawUnmapBuffer :: (target: u32)->u8 #foreign gl "glUnmapBuffer";
RawFenceSync :: (condition: u32,flags: u32)->*void #foreign gl "glFenceSync";
@@ -140,6 +141,7 @@ GenBuffers :: (count: s32, ids: *u32) {RawGenBuffers(count,ids)}
DeleteBuffers :: (count: s32, ids: *u32) {RawDeleteBuffers(count,ids)}
BindBuffer :: (target: u32, id: u32) {RawBindBuffer(target,id)}
BufferData :: (target: u32, bytes: s64, data: *void, usage: u32) {RawBufferData(target,bytes,data,usage)}
BufferSubData :: (target: u32, offset: s64, bytes: s64, data: *void) {RawBufferSubData(target,offset,bytes,data)}
EnableAttribute :: (index: u32) {RawEnableAttribute(index)}
AttributePointer :: (index: u32, count: s32, kind: u32, normalized: u8, stride: s32, offset: *void) {RawAttributePointer(index,count,kind,normalized,stride,offset)}
CreateShader :: (kind: u32) ->u32 {return RawCreateShader(kind)}
+35 -4
View File
@@ -64,6 +64,7 @@ uniform vec4 material; // roughness, metalness, alpha_test, kind
uniform vec4 flags; // vertex colors, flat, double sided, receive
uniform vec4 settings; // tone mapping, exact color, exposure, perspective
uniform vec2 albedoSize;
uniform vec2 albedoSampling; // filter (nearest/linear), wrap (clamp/repeat)
uniform sampler2D albedo;
uniform sampler2D dfg;
uniform sampler2DShadow shadow0;
@@ -74,6 +75,11 @@ uniform mat4 shadowMatrix[4];
uniform vec4 shadowSettings[4]; // enabled, bias, normal bias, radius/size
uniform vec3 lightColor[4];
uniform vec3 lightDirection[4];
uniform sampler2D cookie;
uniform mat4 cookieMatrix;
uniform vec4 cookieTransform; // scale xy, offset zw
uniform vec2 cookieSize;
uniform int cookieLight; // the one light whose beam carries the cookie, or -1
uniform vec3 sky;
uniform vec3 ground;
uniform vec3 up;
@@ -82,6 +88,21 @@ uniform int transparent;
float sat(float a){return clamp(a,0.0,1.0);}
vec3 unit(vec3 a){float n=length(a);return n>0.0?a/n: vec3(0.0);}
vec3 linearColor(vec3 c){return mix(c/12.92,pow((c+0.055)/1.055,vec3(2.4)),step(vec3(0.04045),c));}
ivec2 albedoCoordinate(ivec2 p){
ivec2 size=ivec2(albedoSize);
if(albedoSampling.y>0.5){return ivec2((p.x%size.x+size.x)%size.x,(p.y%size.y+size.y)%size.y);}
return clamp(p,ivec2(0),size-1);
}
vec4 albedoTexel(ivec2 p){
p=albedoCoordinate(p);p.y=int(albedoSize.y)-1-p.y;
vec4 t=texelFetch(albedo,p,0);return vec4(linearColor(t.rgb),t.a);
}
vec4 albedoAt(vec2 uv){
if(albedoSampling.x<0.5){return albedoTexel(ivec2(floor(uv*albedoSize)));}
vec2 p=uv*albedoSize-0.5;ivec2 a=ivec2(floor(p)),b=a+1;vec2 f=fract(p);
return mix(mix(albedoTexel(a),albedoTexel(ivec2(b.x,a.y)),f.x),
mix(albedoTexel(ivec2(a.x,b.y)),albedoTexel(b),f.x),f.y);
}
vec3 encode(vec3 c){c=clamp(c,0.0,1.0);return mix(c*12.92,1.055*pow(c,vec3(0.41666))-0.055,step(vec3(0.0031308),c));}
vec3 neutral(vec3 c){
c*=settings.z;float x=min(c.r,min(c.g,c.b));
@@ -120,6 +141,18 @@ float lightShadow(int i){
if(i==2)return shadowAt(shadow2,2);
return shadowAt(shadow3,3);
}
vec3 cookieTexel(ivec2 p){
ivec2 size=ivec2(cookieSize);
p=ivec2((p.x%size.x+size.x)%size.x,(p.y%size.y+size.y)%size.y);p.y=size.y-1-p.y;
return linearColor(texelFetch(cookie,p,0).rgb);
}
vec3 lightCookie(int i){
if(i!=cookieLight)return vec3(1.0);
vec2 uv=(cookieMatrix*vec4(world,1.0)).xy*cookieTransform.xy+cookieTransform.zw;
vec2 p=uv*cookieSize-0.5;ivec2 a=ivec2(floor(p)),b=a+1;vec2 f=fract(p);
return mix(mix(cookieTexel(a),cookieTexel(ivec2(b.x,a.y)),f.x),
mix(cookieTexel(ivec2(a.x,b.y)),cookieTexel(b),f.x),f.y);
}
GLSL
GpuFragmentMain :: #string GLSL
void main(){
@@ -133,9 +166,7 @@ void main(){
vec4 color=base;
if(KRYON_VERTEX>0.5)color.rgb*=vertexColor;
if(albedoSize.x>0.0){
vec2 p=clamp(floor(texcoord*albedoSize),vec2(0),albedoSize-1.0);
vec4 t=texture(albedo,vec2(p.x+0.5,albedoSize.y-p.y-0.5)/albedoSize);
color*=vec4(linearColor(t.rgb),t.a);
color*=albedoAt(texcoord);
}
if(KRYON_KIND<1.5)color=kryonMaterial(color,vec4(world,1.0),vec4(unit(worldNormal),0.0),vec4(texcoord,0.0,0.0));
if(KRYON_KIND>1.5){
@@ -162,7 +193,7 @@ void main(){
vec3 direction=lightDirection[i].xyz;
float nl=sat(dot(n,direction));
if(nl==0.0&&bounded&&all(lessThanEqual(abs(direction),vec3(1.001)))&&all(lessThanEqual(abs(lightColor[i]),vec3(1e20))))continue;
vec3 irradiance=lightColor[i].rgb*nl*lightShadow(i);
vec3 irradiance=lightColor[i].rgb*nl*lightShadow(i)*lightCookie(i);
vec3 halfVector=unit(direction+eye);float nh=sat(dot(n,halfVector)),vh=sat(dot(eye,halfVector));
float fresnel=exp2((-5.55473*vh-6.98316)*vh);
vec3 f=mix(spec,vec3(1.0),fresnel);
+189 -10
View File
@@ -16,6 +16,7 @@
#import "std/math"
#import "std/vec"
#import "std/option"
#import "std/image"
#import "drawing_props"
#import "shader"
@@ -30,6 +31,34 @@ MaterialKind :: enum {
MaterialShadow :: 2 // only the shadows falling on it, like ShadowMaterial
}
SceneTextureProjection :: enum {
SceneTextureUV :: 0
SceneTextureBox :: 1
}
SceneTextureFilter :: enum {
SceneTextureNearest :: 0
SceneTextureLinear :: 1
}
SceneTextureWrap :: enum {
SceneTextureClamp :: 0
SceneTextureRepeat :: 1
}
// Image material mapping. A zero scale component means one texture repeat per
// mesh unit, which also makes the zero value a useful default. MIP_LEVEL is an
// explicit, deterministic box-filtered level prepared once when the material
// is made; CPU and GPU render the same selected image.
SceneTextureOptions :: struct {
projection: SceneTextureProjection
filter: SceneTextureFilter
wrap: SceneTextureWrap
scale: ShapePoint
offset: ShapePoint
mip_level: s32
}
SceneMaterial :: struct {
kind: MaterialKind
color: Color // sRGB; its alpha is ignored
@@ -42,7 +71,12 @@ SceneMaterial :: struct {
double_sided: bool
flat: bool // one normal per face
vertex_colors: bool // multiply by each vertex's linear colour
texture: s32 // AddTexture's number, or -1
texture: s32 // ImageMaterial's owned scene resource, or -1
texture_projection: SceneTextureProjection
texture_filter: SceneTextureFilter
texture_wrap: SceneTextureWrap
texture_scale: ShapePoint
texture_offset: ShapePoint
alpha_test: float64 // texels below this alpha are not drawn
exact_color: bool // written without tone mapping
shader: *ShaderProgram // borrowed; null uses the standard material
@@ -69,7 +103,14 @@ SceneMesh :: struct {
material: SceneMaterial
}
SceneTexture :: struct { width: s32; height: s32; first_texel: s64; }
SceneTexture :: struct {
width: s32
height: s32
first_texel: s64
// Nonzero only for immutable ImageMaterial storage. The native renderer
// can then reuse an upload without rescanning every texel each frame.
cache_key: u64
}
SceneLight :: struct {
color: Color
@@ -85,6 +126,10 @@ SceneLight :: struct {
shadow_bias: float64
shadow_normal_bias: float64
shadow_radius: float64
cookie: bool // LightCookie projects cookie_texture
cookie_texture: s32 // a scene texture, such as an ImageMaterial's
cookie_scale: ShapePoint // repeats across the shadow box
cookie_offset: ShapePoint
}
Scene :: struct {
@@ -106,6 +151,10 @@ Scene :: struct {
exposure: float64
tone_mapping: bool // three.js's neutral tone mapping
failed: bool
// FreezeGeometry's promise: meshes and vertices stay as they are, so a
// renderer need not look for changes in them on every frame. Nodes may
// still move, show and hide. Calls that change geometry take it back.
geometry_frozen: bool
}
// A flat outline drawn with moves, lines, curves and arcs, as three.js's
@@ -154,6 +203,16 @@ SceneClear :: (scene: *Scene) {
scene.exposure = 1.0
scene.tone_mapping = false
scene.failed = false
scene.geometry_frozen = false
}
// Promises that meshes, materials and vertices stay as they are from now on,
// so renderers stop comparing them with what they last drew. Nodes may still
// move, turn, scale, show and hide. Any Scene call that adds or changes
// geometry takes the promise back; after writing into the scene's vertex
// arrays directly, clear scene.geometry_frozen yourself.
FreezeGeometry :: (scene: *Scene) {
scene.geometry_frozen = true
}
SceneFree :: (scene: *Scene) {
@@ -187,15 +246,72 @@ ShadowMaterial :: (color: Color, opacity: float64) -> SceneMaterial {
transparent = true, texture = -1}
}
// Copies straight-alpha RGBA8 pixels for materials to use.
AddTexture :: (scene: *Scene, pixels: []u8, width: s32, height: s32) -> s32 {
if width <= 0 || height <= 0 || pixels.count < cast(s64)width * height * 4 { scene.failed = true; return -1 }
texture: SceneTexture = .{width, height, scene.texels.count}
for at: 0..cast(s64)width * height * 4 - 1 {
if !VecPush(scene.texels, pixels[at]) { scene.failed = true; return -1 }
// Copies IMAGE into SCENE once and returns BASE with an image-backed texture.
// Equal prepared images share one scene resource. IMAGE may be released as
// soon as this returns. Use SceneTextureBox + SceneTextureRepeat for stable
// object-space wood grain on boxes without authoring mesh UVs.
ImageMaterial :: (scene: *Scene, image: *Image, base: SceneMaterial,
options: SceneTextureOptions = .{}) -> SceneMaterial {
material := base
material.texture = -1
if scene == null || !ImageValid(image) || options.mip_level < 0 ||
!Finite64(options.scale.x) || !Finite64(options.scale.y) ||
!Finite64(options.offset.x) || !Finite64(options.offset.y) ||
cast(s32)options.projection < 0 || cast(s32)options.projection > 1 ||
cast(s32)options.filter < 0 || cast(s32)options.filter > 1 ||
cast(s32)options.wrap < 0 || cast(s32)options.wrap > 1 {
if scene != null { scene.failed = true }
return material
}
if !VecPush(scene.textures, texture) { scene.failed = true; return -1 }
return cast(s32)(scene.textures.count - 1)
material.texture_projection = options.projection
material.texture_filter = options.filter
material.texture_wrap = options.wrap
material.texture_scale = .{
ifx options.scale.x == 0.0 then 1.0 else options.scale.x,
ifx options.scale.y == 0.0 then 1.0 else options.scale.y,
}
material.texture_offset = options.offset
width := image.width
height := image.height
level := options.mip_level
while level > 0 {
if width > 1 { width = (width + 1) / 2 }
if height > 1 { height = (height + 1) / 2 }
level -= 1
}
if width != image.width || height != image.height {
prepared := ResizeBox(image, width, height)
if !ImageValid(*prepared) {
VecFree(prepared.pixels)
scene.failed = true
return material
}
material.texture = AddImageTexture(scene, *prepared)
VecFree(prepared.pixels)
return material
}
material.texture = AddImageTexture(scene, image)
return material
}
// The exact coordinate transform used by both native renderers. Box mapping
// uses the dominant object-space normal, so transforms never make the texture
// swim and every generated box face has one stable planar projection.
SceneTextureCoordinate :: (material: SceneMaterial, position: Vector3,
normal: Vector3, uv: ShapePoint) -> ShapePoint {
coordinate := uv
if material.texture_projection == .SceneTextureBox {
ax := ifx normal.x < 0.0 then -normal.x else normal.x
ay := ifx normal.y < 0.0 then -normal.y else normal.y
az := ifx normal.z < 0.0 then -normal.z else normal.z
if ax >= ay && ax >= az { coordinate = .{position.z, position.y} }
else if ay >= az { coordinate = .{position.x, position.z} }
else { coordinate = .{position.x, position.y} }
}
sx := ifx material.texture_scale.x == 0.0 then 1.0 else material.texture_scale.x
sy := ifx material.texture_scale.y == 0.0 then 1.0 else material.texture_scale.y
return .{coordinate.x * sx + material.texture_offset.x,
coordinate.y * sy + material.texture_offset.y}
}
// ---------------------------------------------------------------- lights
@@ -233,6 +349,25 @@ CastLightShadow :: (scene: *Scene, light: s32, half_width: float64, half_height:
kept.shadow_radius = radius
}
// LIGHT carries TEXTURE through its beam like a gobo: the texel's linear RGB
// scales the light's direct irradiance on every lit surface, whether or not
// it receives shadows. The texture spans the light's shadow box (set by
// CastLightShadow) SCALE times, shifted by OFFSET, filtered bilinearly and
// repeated. Only the first light with a cookie projects one.
LightCookie :: (scene: *Scene, light: s32, texture: s32, scale: ShapePoint, offset: ShapePoint) {
if light < 0 || light >= cast(s32)scene.lights.count || texture < 0 ||
texture >= cast(s32)scene.textures.count || !Finite64(scale.x) || !Finite64(scale.y) ||
!Finite64(offset.x) || !Finite64(offset.y) {
scene.failed = true
return
}
kept := *scene.lights[light]
kept.cookie = true
kept.cookie_texture = texture
kept.cookie_scale = scale
kept.cookie_offset = offset
}
// ---------------------------------------------------------------- nodes
BeginGroup :: (scene: *Scene) -> s32 {
@@ -310,6 +445,7 @@ NodeScale :: (scene: *Scene, node: s32) -> Vector3 {
// Changes the material of every mesh at or below NODE.
SetMaterial :: (scene: *Scene, node: s32, material: SceneMaterial) -> s32 {
scene.geometry_frozen = false
if !ValidNode(scene, node) { return node }
for at: 0..scene.nodes.count - 1 {
if scene.nodes[at].mesh >= 0 && Descends(scene, cast(s32)at, node) {
@@ -339,12 +475,14 @@ VertexPosition :: (scene: *Scene, node: s32, vertex: s32) -> Vector3 {
}
SetVertexPosition :: (scene: *Scene, node: s32, vertex: s32, position: Vector3) {
scene.geometry_frozen = false
at := VertexAt(scene, node, vertex)
if at >= 0 { scene.positions[at] = position }
}
// A linear colour, used by materials with vertex_colors.
SetVertexColor :: (scene: *Scene, node: s32, vertex: s32, color: Vector3) {
scene.geometry_frozen = false
at := VertexAt(scene, node, vertex)
if at >= 0 { scene.colors[at] = color }
}
@@ -352,6 +490,7 @@ SetVertexColor :: (scene: *Scene, node: s32, vertex: s32, color: Vector3) {
// Normals from the faces, as three.js's computeVertexNormals: shared by
// the faces meeting at an indexed vertex, one per face otherwise.
ComputeNormals :: (scene: *Scene, node: s32) {
scene.geometry_frozen = false
if !ValidNode(scene, node) || scene.nodes[node].mesh < 0 { return }
mesh := scene.meshes[scene.nodes[node].mesh]
first := mesh.first_vertex
@@ -734,6 +873,45 @@ Extrude :: (scene: *Scene, shape: *Shape, depth: float64, material: SceneMateria
#scope_file
ImageFingerprint :: (image: *Image) -> u64 {
hash: u64 = 1469598103934665603
hash = (hash ^ cast(u64)cast(u32)image.width) * 1099511628211
hash = (hash ^ cast(u64)cast(u32)image.height) * 1099511628211
for at: 0..image.pixels.count - 1 {
hash = (hash ^ cast(u64)image.pixels[at]) * 1099511628211
}
return ifx hash == 0 then 1 else hash
}
AddImageTexture :: (scene: *Scene, image: *Image) -> s32 {
key := ImageFingerprint(image)
bytes := cast(s64)image.width * image.height * 4
for at: 0..scene.textures.count - 1 {
texture := scene.textures[at]
if texture.cache_key != key || texture.width != image.width || texture.height != image.height { continue }
same := true
for byte: 0..bytes - 1 {
if scene.texels[texture.first_texel + byte] != image.pixels[byte] { same = false; break }
}
if same { return cast(s32)at }
}
texture: SceneTexture = .{image.width, image.height, scene.texels.count, key}
first := scene.texels.count
for at: 0..bytes - 1 {
if !VecPush(scene.texels, image.pixels[at]) {
scene.failed = true
while scene.texels.count > first { unused VecPop(scene.texels) }
return -1
}
}
if !VecPush(scene.textures, texture) {
scene.failed = true
while scene.texels.count > first { unused VecPop(scene.texels) }
return -1
}
return cast(s32)(scene.textures.count - 1)
}
SCENE_PI :: 3.141592653589793
SCENE_TAU :: 6.283185307179586
@@ -814,6 +992,7 @@ FinishMesh :: (scene: *Scene, first: s32, first_index: s32, indexed: bool, mater
mesh: SceneMesh = .{first_vertex = first, vertex_count = cast(s32)scene.positions.count - first,
first_index = first_index, material = material}
if indexed { mesh.index_count = cast(s32)scene.indices.count - first_index }
scene.geometry_frozen = false
if !VecPush(scene.meshes, mesh) { scene.failed = true; return -1 }
return AddNode(scene, cast(s32)(scene.meshes.count - 1))
}
+103 -12
View File
@@ -216,6 +216,11 @@ RenderLight :: struct {
radius: float64
size: s32
first_texel: s64
cookie: bool
cookie_matrix: Matrix // world to cookie coordinates over the shadow box
cookie_texture: SceneTexture
cookie_scale: ShapePoint
cookie_offset: ShapePoint
}
RenderVertex :: struct {
@@ -608,20 +613,24 @@ PrepareLights :: (work: *Renderer, scene: *Scene) {
work.up = Normalize(Direction(work.view, .{0.0, 1.0, 0.0}))
work.light_count = 0
VecClear(work.shadow_depth)
cookie_used := false
for at: 0..scene.lights.count - 1 {
if work.light_count >= MAX_LIGHTS { break }
source := scene.lights[at]
light: RenderLight
light.color = Times(LinearColor(source.color), source.intensity)
light.direction = Normalize(Direction(work.view, Sub(source.position, source.target)))
if source.cookie && !cookie_used && LightCookieValid(scene, source) {
cookie_used = true
light.cookie = true
light.cookie_matrix = LightBoxMatrix(source)
light.cookie_texture = scene.textures[source.cookie_texture]
light.cookie_scale = source.cookie_scale
light.cookie_offset = source.cookie_offset
}
if source.shadow && source.shadow_size > 0 {
eye := LookAt(source.position, source.target, .{0.0, 1.0, 0.0})
lens := Orthographic(-source.shadow_half_width, source.shadow_half_width,
source.shadow_half_height, -source.shadow_half_height, source.shadow_near, source.shadow_far)
bias := Identity()
bias.m[0] = 0.5; bias.m[3] = 0.5; bias.m[5] = 0.5; bias.m[7] = 0.5; bias.m[10] = 0.5; bias.m[11] = 0.5
light.shadow = true
light.shadow_matrix = Multiply(bias, Multiply(lens, eye))
light.shadow_matrix = LightBoxMatrix(source)
light.bias = source.shadow_bias
light.normal_bias = source.shadow_normal_bias
light.radius = source.shadow_radius
@@ -634,6 +643,50 @@ PrepareLights :: (work: *Renderer, scene: *Scene) {
}
}
// World to 0..1 coordinates across the light's shadow box, depth in Z.
LightBoxMatrix :: (source: SceneLight) -> Matrix {
eye := LookAt(source.position, source.target, .{0.0, 1.0, 0.0})
lens := Orthographic(-source.shadow_half_width, source.shadow_half_width,
source.shadow_half_height, -source.shadow_half_height, source.shadow_near, source.shadow_far)
bias := Identity()
bias.m[0] = 0.5; bias.m[3] = 0.5; bias.m[5] = 0.5; bias.m[7] = 0.5; bias.m[10] = 0.5; bias.m[11] = 0.5
return Multiply(bias, Multiply(lens, eye))
}
// A cookie needs a shadow box and a complete scene texture.
LightCookieValid :: (scene: *Scene, source: SceneLight) -> bool {
if source.cookie_texture < 0 || source.cookie_texture >= cast(s32)scene.textures.count { return false }
if source.shadow_half_width <= 0.0 || source.shadow_half_height <= 0.0 || source.shadow_far == source.shadow_near { return false }
texture := scene.textures[source.cookie_texture]
bytes := cast(s64)texture.width * texture.height * 4
return texture.width > 0 && texture.height > 0 && texture.first_texel >= 0 &&
texture.first_texel + bytes <= scene.texels.count
}
// The cookie's linear RGB at WORLD: bilinear, repeating, top row first.
CookieAt :: (scene: *Scene, light: RenderLight, world: Vector3) -> Vector3 {
coord := Point(light.cookie_matrix, world)
texture := light.cookie_texture
x := (coord.x * light.cookie_scale.x + light.cookie_offset.x) * cast(float64)texture.width - 0.5
y := (coord.y * light.cookie_scale.y + light.cookie_offset.y) * cast(float64)texture.height - 0.5
x0 := cast(s32)Floor(x); y0 := cast(s32)Floor(y)
fx := x - Floor(x); fy := y - Floor(y)
ax := TextureCoordinate(x0, texture.width, .SceneTextureRepeat)
bx := TextureCoordinate(x0 + 1, texture.width, .SceneTextureRepeat)
ay := TextureCoordinate(y0, texture.height, .SceneTextureRepeat)
by := TextureCoordinate(y0 + 1, texture.height, .SceneTextureRepeat)
a := CookieTexel(scene, texture, ax, ay); b := CookieTexel(scene, texture, bx, ay)
c := CookieTexel(scene, texture, ax, by); d := CookieTexel(scene, texture, bx, by)
low := Add(a, Times(Sub(b, a), fx))
high := Add(c, Times(Sub(d, c), fx))
return Add(low, Times(Sub(high, low), fy))
}
CookieTexel :: (scene: *Scene, texture: SceneTexture, tx: s32, ty: s32) -> Vector3 {
at := texture.first_texel + (cast(s64)(texture.height - 1 - ty) * texture.width + tx) * 4
return .{Linear(scene.texels[at]), Linear(scene.texels[at + 1]), Linear(scene.texels[at + 2])}
}
MeshDrawn :: (work: *Renderer, scene: *Scene, node: s32) -> bool {
return scene.nodes[node].mesh >= 0 && work.shown[node]
}
@@ -799,7 +852,8 @@ DrawMesh :: (work: *Renderer, scene: *Scene, node: s32) {
vertex.world = Point(world, scene.positions[source])
vertex.world_normal = Normalize(BackDirection(work.view, vertex.normal))
vertex.color = scene.colors[source]
vertex.uv = scene.uvs[source]
vertex.uv = SceneTextureCoordinate(mesh.material, scene.positions[source],
scene.normals[source], scene.uvs[source])
if !PushRenderVertex(work, vertex) { work.failed = true; return }
}
corners := Corners(mesh)
@@ -1260,8 +1314,14 @@ Shade :: (work: *Renderer, state: *DrawState, a: *RenderVertex, b: *RenderVertex
if material.kind == .MaterialUnlit { return Output(work, state, diffuse, alpha) }
view := Add(Add(Times(a.view, la), Times(b.view, lb)), Times(c.view, lc))
shadow: [MAX_LIGHTS]float64
cookie: [MAX_LIGHTS]Vector3
for light: 0..work.light_count - 1 {
shadow[light] = 1.0
cookie[light] = .{1.0, 1.0, 1.0}
if work.lights[light].cookie && material.kind != .MaterialShadow {
world := Add(Add(Times(a.world, la), Times(b.world, lb)), Times(c.world, lc))
cookie[light] = CookieAt(state.scene, work.lights[light], world)
}
if work.lights[light].shadow && state.receive {
world := Add(Add(Times(a.world, la), Times(b.world, lb)), Times(c.world, lc))
world_normal := Add(Add(Times(a.world_normal, la), Times(b.world_normal, lb)), Times(c.world_normal, lc))
@@ -1294,7 +1354,7 @@ Shade :: (work: *Renderer, state: *DrawState, a: *RenderVertex, b: *RenderVertex
for light: 0..work.light_count - 1 {
source := work.lights[light]
dot_nl := Saturate(Dot(normal, source.direction))
irradiance := Times(source.color, dot_nl * shadow[light])
irradiance := Mul(Times(source.color, dot_nl * shadow[light]), cookie[light])
half := Normalize(Add(source.direction, eye))
dot_nh := Saturate(Dot(normal, half))
dot_vh := Saturate(Dot(eye, half))
@@ -1330,10 +1390,41 @@ Output :: (work: *Renderer, state: *DrawState, color: Vector3, alpha: float64) -
Texel :: (work: *Renderer, state: *DrawState, u: float64, v: float64) -> Fragment {
texture := state.texture
tx := cast(s32)Floor(u * cast(float64)texture.width)
ty := cast(s32)Floor(v * cast(float64)texture.height)
tx = ifx tx < 0 then 0 else ifx tx >= texture.width then texture.width - 1 else tx
ty = ifx ty < 0 then 0 else ifx ty >= texture.height then texture.height - 1 else ty
if state.material.texture_filter == .SceneTextureNearest {
tx := TextureCoordinate(cast(s32)Floor(u * cast(float64)texture.width),
texture.width, state.material.texture_wrap)
ty := TextureCoordinate(cast(s32)Floor(v * cast(float64)texture.height),
texture.height, state.material.texture_wrap)
return TextureTexel(state, tx, ty)
}
x := u * cast(float64)texture.width - 0.5
y := v * cast(float64)texture.height - 0.5
x0 := cast(s32)Floor(x); y0 := cast(s32)Floor(y)
fx := x - Floor(x); fy := y - Floor(y)
ax := TextureCoordinate(x0, texture.width, state.material.texture_wrap)
bx := TextureCoordinate(x0 + 1, texture.width, state.material.texture_wrap)
ay := TextureCoordinate(y0, texture.height, state.material.texture_wrap)
by := TextureCoordinate(y0 + 1, texture.height, state.material.texture_wrap)
a := TextureTexel(state, ax, ay); b := TextureTexel(state, bx, ay)
c := TextureTexel(state, ax, by); d := TextureTexel(state, bx, by)
low: Fragment = .{a.r + (b.r-a.r)*fx, a.g + (b.g-a.g)*fx,
a.b + (b.b-a.b)*fx, a.a + (b.a-a.a)*fx, false}
high: Fragment = .{c.r + (d.r-c.r)*fx, c.g + (d.g-c.g)*fx,
c.b + (d.b-c.b)*fx, c.a + (d.a-c.a)*fx, false}
return .{low.r + (high.r-low.r)*fy, low.g + (high.g-low.g)*fy,
low.b + (high.b-low.b)*fy, low.a + (high.a-low.a)*fy, false}
}
TextureCoordinate :: (coordinate: s32, size: s32, wrap: SceneTextureWrap) -> s32 {
if wrap == .SceneTextureRepeat {
result := coordinate % size
return ifx result < 0 then result + size else result
}
return ifx coordinate < 0 then 0 else ifx coordinate >= size then size - 1 else coordinate
}
TextureTexel :: (state: *DrawState, tx: s32, ty: s32) -> Fragment {
texture := state.texture
// Pictures are kept top row first; texture rows count from the bottom.
at := texture.first_texel + (cast(s64)(texture.height - 1 - ty) * texture.width + tx) * 4
scene := state.scene
+22
View File
@@ -87,6 +87,16 @@ SyncScope :: (base: string) -> s32 {
value := AppFileRead(*files, "file.json")
if value != "three" { return 38 }
AppFileFree(value)
// A copy that can be made again (a bundle's extracted asset) is replaced
// atomically but never waits for the disk: neither the file nor any
// directory is synced, so a failing sync cannot stop it.
Watch(root, true)
if !AppFileWrite(*files, "copy/asset.avif", "asset", false) || watched_hits != 0 { return 39 }
Watch(Under(root, "copy/asset.avif.new"), true)
if !AppFileWrite(*files, "copy/asset.avif", "again", false) || watched_hits != 0 { return 43 }
value = AppFileRead(*files, "copy/asset.avif")
if value != "again" { return 44 }
AppFileFree(value)
Watch("", false)
AppFilesClose(*files)
return 0
@@ -139,6 +149,18 @@ main :: (argc: s32, argv: **u8) -> s32 {
value = AppFileRead(*files, "documents/day.json")
if value != text || files.status != DOCUMENT_READY { return 8 }
AppFileFree(value)
// Compared in pieces: a match across several pieces, a difference in the
// very last byte, another length and a missing file.
if !AppFileSame(*files, "documents/day.json", text) { return 12 }
other_end: Vec(u8)
for index: 0..131070 { unused VecPush(other_end, cast(u8)97) }
unused VecPush(other_end, cast(u8)98)
changed := BuilderFinish(other_end)
if AppFileSame(*files, "documents/day.json", changed) ||
AppFileSame(*files, "documents/day.json", "a") ||
AppFileSame(*files, "documents/missing.json", "") { return 13 }
if !AppFileSame(*files, "empty.json", "") { return 14 }
AppFileFree(changed)
AppFileFree(text)
if AppFileWrite(*files, "../outside", "wrong") ||
AppFileWrite(*files, "escape", "wrong") || AppFileWrite(*files, ".lock", "wrong") { return 9 }
+97 -51
View File
@@ -21,68 +21,96 @@ SOURCE = '''#import "page_core"
#import "canvas_events"
#import "page_input"
#import "canvas_input"
#import "input_delivery"
#import "key_input"
#import "tree_input"
#import "session"
app_session: Session;
Take :: () -> (key: s32, modifiers: s32) {
key, modifiers := InputDeliveryTake(*canvas_input, app_session, CanvasHeldModifiers())
return key, modifiers
}
main :: () -> s32 {
CanvasEventsReset()
session := SessionOpen()
app_session = SessionOpen()
if !SessionValid(app_session) { return 40 }
if KeyF3 != 292 { return 32 }
unused CanvasKeyDown("F3", "F3", false, 0)
key := CanvasAppKeyTake()
unused KeyboardSend(session, key)
if key != KeyF3 || KeyboardTake(session) != KeyF3 || KeyboardTake(session) != 0 { return 33 }
key, modifiers := Take()
unused KeyboardSend(app_session, key)
if key != KeyF3 || KeyboardTake(app_session) != KeyF3 || KeyboardTake(app_session) != 0 { return 33 }
unused CanvasKeyUp("F3", "F3")
unused SessionClose(session)
CanvasEventsReset()
unused CanvasKeyDown("Home", "Home", false, 0)
unused CanvasKeyUp("Home", "Home")
unused CanvasKeyDown("Digit4", "4", false, 0)
unused CanvasKeyUp("Digit4", "4")
// CanvasAppMainLoop takes one AppKey before CanvasAppFrame begins drawing.
first := CanvasAppKeyTake()
// The app loop takes its input before the frame begins drawing.
key, modifiers = Take()
CanvasEventsBeginFrame()
if first != 268 { return 1 }
if key != 268 { return 1 }
if !IsKeyPressed(52) { return 2 }
CanvasEventsEndFrame()
if canvas_keys_pressed_count != 0 || canvas_keys_released_count != 0 { return 3 }
second := CanvasAppKeyTake()
key, modifiers = Take()
CanvasEventsBeginFrame()
if second != 52 { return 4 }
if key != 52 { return 4 }
// Delivering an unread event must not replay its pressed/released flags.
if canvas_keys_pressed_count != 0 || canvas_keys_released_count != 0 { return 5 }
CanvasEventsEndFrame()
if CanvasAppKeyTake() != 0 { return 6 }
key, modifiers = Take()
if key != 0 { return 6 }
// Events arriving while drawing yields survive cleanup, with no duplication.
unused CanvasKeyDown("KeyA", "a", false, 0)
CanvasEventsBeginFrame()
if CanvasAppKeyTake() != 65 { return 7 }
key, modifiers = Take()
if key != 65 { return 7 }
unused CanvasKeyDown("KeyB", "b", false, 0)
CanvasEventsEndFrame()
if !CanvasQueueHas(*canvas_keys_pressed[0], canvas_keys_pressed_count, 66) { return 8 }
if CanvasAppKeyTake() != 66 { return 9 }
key, modifiers = Take()
if key != 66 { return 9 }
CanvasEventsBeginFrame()
CanvasEventsEndFrame()
if CanvasAppKeyTake() != 0 || canvas_keys_pressed_count != 0 { return 10 }
key, modifiers = Take()
if key != 0 || canvas_keys_pressed_count != 0 { return 10 }
// Raylib's GetKeyPressed reads this frame's presses beside session delivery.
unused CanvasKeyDown("KeyC", "c", false, 0)
if GetKeyPressed() != 67 || CanvasAppKeyTake() != 0 { return 16 }
if GetKeyPressed() != 67 || GetKeyPressed() != 0 { return 16 }
key, modifiers = Take()
if key != 67 { return 17 }
CanvasEventsBeginFrame()
CanvasEventsEndFrame()
// Repeats also survive frames and retain the existing fresh-key priority.
unused CanvasKeyDown("KeyA", "a", true, 0)
unused CanvasKeyDown("KeyB", "b", true, 0)
if CanvasAppKeyTake() != 65 { return 11 }
if GetKeyPressed() != 0 { return 18 }
CanvasEventsReset()
// Repeats keep their place after the fresh press, edit by edit.
unused CanvasKeyDown("ArrowLeft", "ArrowLeft", false, 0)
unused CanvasKeyDown("ArrowRight", "ArrowRight", false, 0)
unused CanvasKeyDown("ArrowLeft", "ArrowLeft", true, 1)
expected: [3]s32 = .[263, 262, 263]
expected_modifiers: [3]s32 = .[0, 0, 1]
for index: 0..2 {
key, modifiers = Take()
if key != expected[index] || modifiers != expected_modifiers[index] { return 11 }
}
CanvasEventsBeginFrame()
CanvasEventsEndFrame()
if canvas_keys_repeated_count != 0 { return 12 }
if CanvasAppKeyTake() != 66 || CanvasAppKeyTake() != 0 { return 13 }
key, modifiers = Take()
if key != 0 { return 13 }
unused CanvasKeyDown("KeyC", "c", false, 0)
CanvasEventsReset()
if CanvasAppKeyTake() != 0 { return 14 }
// A focus change cancels pending shortcuts instead of replaying them later.
unused CanvasKeyDown("KeyD", "d", false, 0)
key, modifiers = Take()
if key != 0 { return 14 }
// A focus change cancels pending shortcuts and keeps typed text.
unused CanvasKeyDown("KeyD", "d", false, 2)
CanvasTyped(100)
unused CanvasEvent(CanvasEventBlur, 0, 0, 0.0, 0.0, null, null)
if CanvasAppKeyTake() != 0 { return 15 }
key, modifiers = Take()
if key != 0 || TypedCodepointTake(app_session) != 100 { return 15 }
// Complete shortcuts retain event flags after every physical key is up.
CanvasEventsReset()
unused CanvasKeyDown("ControlLeft", "Control", false, 2)
@@ -91,15 +119,13 @@ main :: () -> s32 {
unused CanvasKeyUp("ControlLeft", "Control")
unused CanvasKeyDown("KeyB", "b", false, 0)
unused CanvasKeyUp("KeyB", "b")
if CanvasHeldModifiers() != 0 || IsKeyDown(341) { return 17 }
if CanvasAppKeyTake() != 341 || canvas_key_event.modifiers != 2 { return 18 }
CanvasEventsBeginFrame()
CanvasEventsEndFrame()
if CanvasAppKeyTake() != 65 || canvas_key_event.modifiers != 2 { return 19 }
if CanvasHeldModifiers() != 0 { return 20 }
// The same fresh queue backs the legacy GetKeyPressed consumer.
if GetKeyPressed() != 66 || canvas_key_event.modifiers != 0 { return 21 }
if CanvasAppKeyTake() != 0 || canvas_key_event.modifiers != 0 { return 22 }
if CanvasHeldModifiers() != 0 || IsKeyDown(341) { return 19 }
key, modifiers = Take()
if key != 65 || modifiers != 2 || !TextFieldInputFor(key, modifiers, "").select_all { return 20 }
key, modifiers = Take()
if key != 66 || modifiers != 0 { return 21 }
key, modifiers = Take()
if key != 0 || modifiers != 0 { return 22 }
// Repeats carry their own flags, even when the modifier changes while held.
CanvasEventsReset()
unused CanvasKeyDown("KeyA", "a", false, 2)
@@ -110,27 +136,47 @@ main :: () -> s32 {
unused CanvasKeyUp("KeyA", "a")
unused CanvasKeyUp("KeyB", "b")
CanvasEventsEndFrame()
if CanvasAppKeyTake() != 65 || canvas_key_event.modifiers != 2 { return 23 }
if CanvasAppKeyTake() != 66 || canvas_key_event.modifiers != 4 { return 24 }
if CanvasAppKeyTake() != 65 || canvas_key_event.modifiers != 3 { return 25 }
if CanvasAppKeyTake() != 65 || canvas_key_event.modifiers != 0 { return 26 }
if CanvasAppKeyTake() != 0 || canvas_key_event.modifiers != 0 { return 27 }
// Bounded queues drop a whole event, never just its key or modifiers.
for at: cast(s32)0..CANVAS_QUEUE_LIMIT {
unused CanvasKeyDown("KeyC", "c", false, at % 8)
unused CanvasKeyUp("KeyC", "c")
keys: [5]s32 = .[65, 65, 65, 66, 0]
flags: [5]s32 = .[2, 3, 0, 4, 0]
for index: cast(s32)0..4 {
key, modifiers = Take()
if key != keys[index] || modifiers != flags[index] { return 23 + index }
}
for at: cast(s32)0..CANVAS_QUEUE_LIMIT - 1 {
if CanvasAppKeyTake() != 67 || canvas_key_event.modifiers != at % 8 { return 28 }
}
if CanvasAppKeyTake() != 0 { return 29 }
unused CanvasKeyDown("KeyA", "a", false, 7)
// Typed text and the Enter after it commit together; Space types a space.
CanvasEventsReset()
if canvas_key_event.modifiers != 0 || CanvasAppKeyTake() != 0 { return 30 }
CanvasTyped(104)
unused CanvasKeyDown("Space", " ", false, 0)
unused CanvasKeyDown("Enter", "Enter", false, 0)
key, modifiers = Take()
bytes: [8]u8
if key != KeyEnter || TypedTextTake(app_session, bytes[:]) != "h " { return 34 }
// Raylib's GetCharPressed takes this frame's characters; later ones survive.
if GetCharPressed() != 104 || GetCharPressed() != 32 || GetCharPressed() != 0 { return 35 }
CanvasTyped(120)
CanvasEventsBeginFrame()
CanvasTyped(121)
CanvasEventsEndFrame()
if GetCharPressed() != 121 || GetCharPressed() != 0 { return 36 }
while TypedCodepointTake(app_session) != 0 {}
// A bounded queue drops whole events, never just a key or its modifiers.
CanvasEventsReset()
for at: cast(s32)0..INPUT_DELIVERY_CAPACITY {
unused CanvasKeyDown("ArrowUp", "ArrowUp", false, at % 8)
unused CanvasKeyUp("ArrowUp", "ArrowUp")
}
if canvas_input.count != INPUT_DELIVERY_CAPACITY { return 28 }
for at: cast(s32)0..INPUT_DELIVERY_CAPACITY - 1 {
key, modifiers = Take()
if key != 265 || modifiers != at % 8 { return 29 }
}
key, modifiers = Take()
if key != 0 { return 30 }
unused CanvasKeyDown("KeyA", "a", false, 7)
unused CanvasAppKeyTake()
unused CanvasEvent(CanvasEventBlur, 0, 0, 0.0, 0.0, null, null)
if canvas_key_event.modifiers != 0 || CanvasAppKeyTake() != 0 { return 31 }
key, modifiers = Take()
if key != 0 || modifiers != 0 { return 31 }
TreeInputReset(app_session)
unused SessionClose(app_session)
return 0
}
'''
@@ -162,7 +208,7 @@ def main():
run([ZIRAN, 'build', '--target=c', '--exe', '--entry', 'app_keys:main',
*modules, *target, *define, '-o', WORK / 'native', source])
run([WORK / 'native/app_keys'])
print(f'{form}: native Canvas AppKey delivery passed', flush=True)
print(f'{form}: native Canvas ordered key delivery passed', flush=True)
if __name__ == '__main__':
+18 -4
View File
@@ -1,20 +1,34 @@
// Link the real Canvas host entry and its existing standard-key delegate.
// Link the real Canvas host entry and its ordered gamepad delivery.
// Page gamepad sampling is covered independently by canvas_gamepad_test.
#import "canvas_host"
#import "canvas_events"
#import "canvas_input"
#import "gamepad_navigation"
#import "session"
#import "tree_input"
Take :: (session: Session) -> s32 {
key, modifiers := CanvasInputTake(session)
return key
}
#program_export
main :: () -> s32 {
CanvasEventsReset()
session := SessionOpen()
if !SessionValid(session) { return 4 }
defer { TreeInputReset(session); unused SessionClose(session) }
buttons: [4]u32
GamepadNavigationPoll(*canvas_gamepad_navigation, buttons, true)
buttons[0] = cast(u32)1
GamepadNavigationPoll(*canvas_gamepad_navigation, buttons, true)
if CanvasPressedKey() != 257 || CanvasPressedKey() != 0 { return 1 }
CanvasGamepadDeliver()
if Take(session) != 257 || Take(session) != 0 { return 1 }
GamepadNavigationPoll(*canvas_gamepad_navigation, buttons, true)
if CanvasPressedKey() != 0 { return 2 }
CanvasGamepadDeliver()
if Take(session) != 0 { return 2 }
GamepadNavigationBlur(*canvas_gamepad_navigation)
if CanvasPressedKey() != 0 { return 3 }
CanvasGamepadDeliver()
if Take(session) != 0 { return 3 }
return 0
}
+1 -1
View File
@@ -61,7 +61,7 @@ def main():
run([ZIRAN, 'build', '--target=c', '--exe', '--entry', 'canvas_gamepad_test:main',
*modules, *target, *define, '-o', WORK / 'native', entry])
run([WORK / 'native/canvas_gamepad_test'])
# Link the real CanvasPressedKey entry against its production module
# Link the real CanvasInputTake entry against its production module
# graph as native code too; do not mistake this for WASM execution.
host_paths = ['--root', ROOT / 'tests', '--module-path', ROOT / 'src/backend',
*UI_MODULE_ARGS, '--module-path', ZIRAN_ROOT / 'std']
+10 -1
View File
@@ -3,15 +3,24 @@
#import "canvas_events"
#import "canvas_input"
#import "gamepad_navigation"
#import "session"
#import "input_delivery"
#import "tree_input"
Step :: () { CanvasGamepadPoll() }
Take :: () -> s32 { return CanvasAppKeyTake() }
gamepad_session: Session;
Take :: () -> s32 {
key, modifiers := InputDeliveryTake(*canvas_input, gamepad_session, CanvasHeldModifiers())
return key
}
Focus :: (focused: bool) {
unused CanvasEvent(ifx focused then CanvasEventFocus else CanvasEventBlur, 0, 0, 0.0, 0.0, null, null)
}
#program_export
main :: () -> s32 {
CanvasEventsReset()
gamepad_session = SessionOpen()
if !SessionValid(gamepad_session) { return 2 }
available[0] = true
Step()
if Take() != 0 { return 1 }
+4 -2
View File
@@ -166,13 +166,15 @@ RunProbe :: () -> s32 {
if !Focus(false) || !Step(session, cast(u8)4, false) { return 115 + Probe.failure }
if !Step(session, cast(u8)0, false) { return 130 + Probe.failure }
if !Focus(true) || !Key(true) || !Step(session, cast(u8)1, true, 65) { return 145 + Probe.failure }
// Shared named codes and modifier observations survive the widget drain.
// Shared named codes and modifier observations survive ordered delivery.
for code: cast(s32)0..2 {
named: s32 = ifx code == 0 then 263 else ifx code == 1 then 340 else 327
Probe.expected_named_code = named
Probe.expected_named_flags = cast(u8)3
Probe.expected_modifiers = ifx named == 340 then 1 else 0
if !NamedKey(named, true) || !Step(session, cast(u8)1, true, named) { return 150 + Probe.failure }
// A modifier key is an observation, never a delivered widget key.
delivered: s32 = ifx named == 340 then 0 else named
if !NamedKey(named, true) || !Step(session, cast(u8)1, true, delivered) { return 150 + Probe.failure }
Probe.expected_named_flags = cast(u8)4
Probe.expected_modifiers = 0
if !NamedKey(named, false) || !Step(session, cast(u8)1) { return 151 + Probe.failure }
+17
View File
@@ -0,0 +1,17 @@
#import "kryon/session"
Box :: #import "kryon/box";
test_host :: #system_library "host_api";
TestSessionHost :: () -> Session #foreign test_host;
#program_export
main :: () -> s32 {
session := TestSessionHost()
unused Box.Draw(session, Box.Props.{
.key = cast(u64)17,
.bounds = .{4.0, 6.0, 40.0, 24.0},
.fill = .{32, 64, 96, 255},
.radius = 3.0,
})
return 0
}
+54
View File
@@ -0,0 +1,54 @@
#import "std/bundle_host"
#import "std/byte_text_linux"
#import "std/file"
#import "hosted_app"
#import "hosted_values"
#import "widget_codec"
#import "widget_host"
#import "session"
app: HostedApp;
session_codec: WidgetSessionCodec;
box_codec: WidgetBoxPropsCodec;
Allows :: (context: *void, module: string, function: string) -> bool {
unused context
return function == "TestSessionHost" || WidgetHostSupports(module, function)
}
Call :: (context: *void, module: *u8, function: *u8,
arguments: *HostValue, count: s32, result: *HostValue) -> s32 {
unused context
owner := TextFromCString(module)
name := TextFromCString(function)
if name == "TestSessionHost" && count == 0 {
result.* = WidgetEncodeSession(Session.{.slot = 4, .epoch = cast(u64)12}, *session_codec)
return 1
}
if WidgetHostSupports(owner, name) && name == "BoxHostedHost" && count == 2 &&
WidgetValidSession(arguments[0]) && WidgetValidBoxProps(arguments[1]) {
props := WidgetDecodeBoxProps(arguments[1], *box_codec)
if props.key != cast(u64)17 || props.bounds.width != 40.0 ||
props.fill.b != cast(u8)96 || props.radius != 3.0 {
return 0
}
result.* = HostScalar("s32", 0)
return 1
}
return 0
}
#program_export
main :: () -> s32 {
bytes, read := ReadEntireFile("hosted-box.zx")
if !read || !HostedAppOpen(*app, bytes) ||
!HostedAppStart(*app, Allows, Call, null) {
return 1
}
answer: s64
if !HostedAppRun(*app, *answer) || answer != 0 {
return 2
}
HostedAppClose(*app)
return 0
}
+22
View File
@@ -1,5 +1,6 @@
// CPU job ownership and completion without a graphics library or display.
Pixels :: #import "raylib_image_decode";
Exporter :: #import "image_export";
#import "std/byte_text_linux"
#import "webp_codec_stub"
c :: #system_library "c";
@@ -24,10 +25,16 @@ failed: bool;
file_reads: s32;
file_frees: s32;
pixel_frees: s32;
exports: s32;
#program_export
LoadImageFromMemory :: (extension: *u8, bytes: *u8, count: s32) -> Pixels.RaylibGlyphImage {
unused extension
if count == 4 && bytes[0] == 9 {
pixels := Allocate(4)
for index: 0..3 { pixels[index] = bytes[index] }
return Pixels.RaylibGlyphImage.{cast(*void)pixels, 1, 1, 1, 7}
}
if Self() == owner { failed = true }
unused Lock(cast(*void)*mutex[0])
started = true
@@ -42,6 +49,16 @@ LoadImageFromMemory :: (extension: *u8, bytes: *u8, count: s32) -> Pixels.Raylib
#program_export
UnloadImage :: (image: Pixels.RaylibGlyphImage) { Free(cast(*u8)image.data); pixel_frees += 1 }
#program_export
ExportImage :: (image: Pixels.RaylibGlyphImage, path: *u8) -> bool {
if image.data == null || image.width != 1 || image.height != 1 ||
TextFromCString(path) != "tray-icon.png" {
failed = true
return false
}
exports += 1
return true
}
#program_export
LoadFileData :: (path: *u8, count: *s32) -> *u8 {
unused path
if Self() != owner { failed = true }
@@ -110,6 +127,11 @@ Check :: () -> s32 {
Pixels.RaylibImageClose(*job)
Pixels.RaylibImageClose(*job)
if failed || file_reads != 1 || file_frees != 1 || pixel_frees != 2 { return 7 }
export_bytes: [4]u8 = .[9, 8, 7, 6]
if !Exporter.EncodedImageExport(TextFromBytes(export_bytes[:]), ".png", "tray-icon.png") ||
exports != 1 || pixel_frees != 3 || failed {
return 11
}
if Pixels.RaylibImageStart(*job, "empty.png", "") { return 8 }
unused ConditionDestroy(cast(*void)*condition[0])
unused MutexDestroy(cast(*void)*mutex[0])
+51 -2
View File
@@ -89,6 +89,55 @@ Lighting :: () -> s32 {
return failures
}
main :: () -> s32 {
return Shapes() + Lighting()
Near :: (a: s32, b: s32) -> s32 { return ifx a > b then a - b else b - a }
// A floor seen from above under a sun whose beam carries a two-colour
// cookie: the left half of the shadow box is dark, the right half bright,
// and unlit materials ignore it.
Cookie :: () -> s32 {
scene: Scene
SceneInit(*scene)
sun := AddDirectionalLight(*scene, .{255, 255, 255, 255}, 2.0, .{0.0, 6.0, 0.5})
scene.lights[sun].target = .{0.0, 0.0, 0.0}
CastLightShadow(*scene, sun, 1.0, 1.0, 0.1, 20.0, 0, 0.0, 0.0, 1.0)
pixels := NewImage(2, 1)
pixels.pixels[0] = 10; pixels.pixels[1] = 10; pixels.pixels[2] = 10; pixels.pixels[3] = 255
pixels.pixels[4] = 255; pixels.pixels[5] = 230; pixels.pixels[6] = 160; pixels.pixels[7] = 255
holder := ImageMaterial(*scene, *pixels, UnlitMaterial(.{255, 255, 255, 255}))
VecFree(pixels.pixels)
floor := SetRotation(*scene, Plane(*scene, 2.0, 2.0, LitMaterial(.{200, 200, 200, 255})), -1.5707963267948966, 0.0, 0.0)
camera := OrthographicCamera(-1.0, 1.0, 1.0, -1.0, 0.1, 20.0)
camera.position = .{0.0, 10.0, 0.0}
camera.target = .{0.0, 0.0, 0.0}
camera.up = .{0.0, 0.0, -1.0}
image: Image
image.width = 32
image.height = 32
failures: s32 = 0
failures += Check(RenderScene(*scene, camera, *image), "render without cookie")
plain_left := Pixel(*image, 4, 16, 0); plain_right := Pixel(*image, 27, 16, 0)
failures += Check(plain_left == plain_right, "uniform floor without a cookie")
LightCookie(*scene, sun, holder.texture, .{1.0, 1.0}, .{0.0, 0.0})
failures += Check(!scene.failed && scene.lights[sun].cookie, "cookie attached")
failures += Check(RenderScene(*scene, camera, *image), "render with cookie")
left := Pixel(*image, 4, 16, 0); right := Pixel(*image, 27, 16, 0)
bright: s32 = ifx right > left then 27 else 4
failures += Check(Near(left, right) > 60, "cookie halves differ")
failures += Check(Pixel(*image, bright, 16, 2) + 20 < Pixel(*image, bright, 16, 0), "cookie colour warms the light")
failures += Check(Near(Pixel(*image, 4, 4, 0), left) <= 2 && Near(Pixel(*image, 4, 28, 0), left) <= 2, "cookie spans the shadow box")
// Half a repeat of offset swaps the halves.
scene.lights[sun].cookie_offset = .{0.5, 0.0}
failures += Check(RenderScene(*scene, camera, *image), "render shifted cookie")
failures += Check(Near(Pixel(*image, 4, 16, 0), right) <= 2 && Near(Pixel(*image, 27, 16, 0), left) <= 2, "offset shifts the cookie")
scene.meshes[scene.nodes[floor].mesh].material = UnlitMaterial(.{200, 200, 200, 255})
failures += Check(RenderScene(*scene, camera, *image), "render unlit")
failures += Check(Pixel(*image, 4, 16, 0) == Pixel(*image, 27, 16, 0), "unlit ignores the cookie")
LightCookie(*scene, sun, 99, .{1.0, 1.0}, .{0.0, 0.0})
failures += Check(scene.failed, "missing cookie texture fails the scene")
SceneFree(*scene)
return failures
}
main :: () -> s32 {
return Shapes() + Lighting() + Cookie()
}
+8 -3
View File
@@ -15,6 +15,11 @@ AsyncHash :: (image: *Image)->u64 {
for at:0..image.pixels.count-1 {h=(h^cast(u64)image.pixels[at])*cast(u64)1099511628211}
return h
}
AsyncImage :: (pixels: []u8,width: s32,height: s32)->Image {
image:=NewImage(width,height)
for at:0..image.pixels.count-1 {image.pixels[at]=pixels[at]}
return image
}
AsyncWait :: (gpu: *SceneGpuContext,image: *Image)->SceneGpuAsyncResult {
for at:0..4999 {
result:=SceneGpuPoll(gpu,image)
@@ -36,7 +41,8 @@ AsyncTests :: ()->bool {
uniforms: [1]ShaderValue=.[.{0.7,0.4,0.1,1}]
material:=UnlitMaterial(.{255,255,255,255});material.shader=*program;material.shader_uniforms=uniforms[:]
texels: [16]u8=.[255,100,40,255,80,220,100,255,50,100,230,255,190,140,70,255]
material.texture=AddTexture(*scene,texels[:],2,2)
texture:=AsyncImage(texels[:],2,2);defer VecFree(texture.pixels)
material=ImageMaterial(*scene,*texture,material)
a:=RoundedBox(*scene,0.9,0.9,0.4,0.05,material);SetPosition(*scene,a,-0.3,0,0)
material.transparent=true;material.color.a=110
unused RoundedBox(*scene,0.8,0.8,0.5,0.05,material)
@@ -54,7 +60,6 @@ AsyncTests :: ()->bool {
cameras[slot]=camera
uniforms[0].x=0.1+cast(float64)(batch*2+slot)*0.02
program.code[2].a=ifx slot==0 then 5 else 4
scene.texels[0]=cast(u8)(100+batch*5+slot*20)
SetPosition(*scene,a,-0.3+cast(float64)slot*0.1,0,0)
scene.meshes[0].material.double_sided=slot==0
if !SceneGpuRender(*reference,*scene,camera,*expected).ok {return false}
@@ -134,7 +139,7 @@ AsyncTests :: ()->bool {
if !SceneGpuProbe(*gpu).available {return false}
gpu.capabilities.async_available=false;gpu.capabilities.async_diagnostic="test lacks PBO mapping"
if SceneGpuSubmit(*gpu,*scene,camera,80,50,1).ok||!SceneGpuRender(*gpu,*scene,camera,*image).ok {return false}
print("Async exact camera/material/geometry/texture/program frames, sync interleave, two-slot backpressure, cancellation, loss, fallback and 24 releases passed; unready polls %\n",unready)
print("Async exact camera/material/geometry/owned-texture/program frames, sync interleave, two-slot backpressure, cancellation, loss, fallback and 24 releases passed; unready polls %\n",unready)
return true
}
#program_export
+23 -3
View File
@@ -2,6 +2,7 @@
#import, file "../src/backend/scene_gpu.zi";
G :: #import, file "../src/backend/scene_gpu_gl.zi";
#import "std/image"
#import "std/vec"
#import "std/text_tools"
#import "kryon/scene"
#import "kryon/scene_render"
@@ -46,13 +47,32 @@ main :: ()->s32 {
print("Private GLX host renderer %\n",TextView(label[:]))
if !Check(display,context,drawable) {return 6}
scene: Scene;SceneInit(*scene);defer SceneFree(*scene)
unused RoundedBox(*scene,1,1,1,0.1,UnlitMaterial(.{150,80,40,255}))
source:=NewImage(4,4)
for y:0..3 {for x:0..3 {
at:=(y*4+x)*4;source.pixels[at]=cast(u8)(60+x*50);source.pixels[at+1]=cast(u8)(25+y*35)
source.pixels[at+2]=cast(u8)(10+(x+y)*20);source.pixels[at+3]=255
}}
options: SceneTextureOptions=.{projection=.SceneTextureBox,filter=.SceneTextureLinear,
wrap=.SceneTextureRepeat,scale=.{2.5,2.5}}
material:=ImageMaterial(*scene,*source,UnlitMaterial(.{255,255,255,255}),options)
VecFree(source.pixels)
unused RoundedBox(*scene,1,1,1,0.1,material)
camera:=PerspectiveCamera(45,1,0.1,20);camera.position=.{0,0,3}
image:=NewImage(128,128)
image:=NewImage(128,128);reference:=NewImage(128,128)
defer VecFree(image.pixels);defer VecFree(reference.pixels);defer RenderSceneRelease()
gpu: SceneGpuContext;caps:=SceneGpuProbe(*gpu);defer SceneGpuRelease(*gpu)
if !caps.available {print("GPU probe %\n",caps.diagnostic);return 7}
if !Check(display,context,drawable) {return 8}
if !SceneGpuRender(*gpu,*scene,camera,*image).ok||!Check(display,context,drawable) {return 9}
if !RenderScene(*scene,camera,*reference) {return 18}
error: s64
for at:0..image.pixels.count-1 {
d:=cast(s32)image.pixels[at]-cast(s32)reference.pixels[at]
error+=ifx d<0 then -d else d
}
if error>image.pixels.count*2 {return 19}
uploads:=gpu.resources.texture_uploads
if !SceneGpuRender(*gpu,*scene,camera,*image).ok||gpu.resources.texture_uploads!=uploads||!Check(display,context,drawable) {return 20}
if !SceneGpuSubmit(*gpu,*scene,camera,128,128,1).queued||!Check(display,context,drawable) {return 14}
if !SceneGpuSubmit(*gpu,*scene,camera,128,128,2).queued||!Check(display,context,drawable) {return 15}
if !SceneGpuRender(*gpu,*scene,camera,*image).ok||!Check(display,context,drawable) {return 16}
@@ -63,7 +83,7 @@ main :: ()->s32 {
if !Check(display,context,drawable) {return 11}
if !SceneGpuRender(*gpu,*scene,camera,*image).ok||!Check(display,context,drawable) {return 12}
SceneGpuRelease(*gpu)
print("Foreign GLX context, draw/read pbuffers and pixels preserved through probe/render/async/sync-interleave/resize/release/recreate\n")
print("Private-Xvfb image material CPU/GPU parity and foreign GLX context lifecycle passed\n")
unused G.GLXMakeCurrent(display,0,0,null)
return 0
}
+5
View File
@@ -17,6 +17,11 @@ MaterialFillPadding :: (material: *SceneMaterial,pattern: u8) {
material.flat=saved.flat
material.vertex_colors=saved.vertex_colors
material.texture=saved.texture
material.texture_projection=saved.texture_projection
material.texture_filter=saved.texture_filter
material.texture_wrap=saved.texture_wrap
material.texture_scale=saved.texture_scale
material.texture_offset=saved.texture_offset
material.alpha_test=saved.alpha_test
material.exact_color=saved.exact_color
material.shader=saved.shader
+61 -13
View File
@@ -11,13 +11,16 @@ G :: #import, file "../src/backend/scene_gpu_gl.zi";
libc :: #system_library "c";
Flush :: (stream: *void)->s32 #foreign libc "fflush";
Pause :: (microseconds: u32)->s32 #foreign libc "usleep";
TestImage :: (pixels: []u8,width: s32,height: s32)->Image {
image:=NewImage(width,height)
for at:0..image.pixels.count-1 {image.pixels[at]=pixels[at]}
return image
}
ReleaseCycles :: ()->bool {
scene: Scene;SceneInit(*scene);defer SceneFree(*scene)
pixels: Vec(u8)
if !VecResize(pixels,1024*1024*4) {return false}
for at:0..pixels.count-1 {pixels[at]=255}
texture:=NewImage(1024,1024,255,255,255,255);defer VecFree(texture.pixels)
material:=UnlitMaterial(.{120,80,30,255})
material.texture=AddTexture(*scene,pixels[:],1024,1024)
material=ImageMaterial(*scene,*texture,material)
unused RoundedBox(*scene,1,1,1,0.1,material)
camera:=PerspectiveCamera(45,1,0.1,20);camera.position=.{0,0,3}
image:=NewImage(64,64)
@@ -117,7 +120,8 @@ FeatureVariants :: ()->bool {
material:=LitMaterial(.{180,100,40,255},0.65)
material.shader=*program;material.shader_uniforms=uniforms[:]
pixels: [8]u8=.[255,255,255,255,150,220,100,100]
material.texture=AddTexture(*scene,pixels[:],2,1)
texture:=TestImage(pixels[:],2,1);defer VecFree(texture.pixels)
material=ImageMaterial(*scene,*texture,material)
left:=RoundedBox(*scene,0.9,0.9,0.4,0.12,material);SetPosition(*scene,left,-0.55,0,0)
right:=RoundedBox(*scene,0.9,0.9,0.4,0.12,material);SetPosition(*scene,right,0.55,0,0)
for at:0..scene.colors.count-1 {scene.colors[at]=.{0.4,0.8,0.6}}
@@ -260,13 +264,22 @@ Quality :: (kind: s32)->bool {
if kind==1 {material.flat=true}
if kind==2 {material=UnlitMaterial(.{130,220,80,255});material.transparent=true;material.opacity=0.45}
pixels: [16]u8=.[255,30,0,255,0,255,0,180,0,0,255,64,255,255,0,0]
texture:=TestImage(pixels[:],2,2);defer VecFree(texture.pixels)
program: ShaderProgram;samplers: [1]ShaderSampler=.[.{2,2,pixels[:],true}]
code: [2]ShaderInstruction=.[.{op=.ShaderSample,dest=4,a=3,slot=0},.{op=.ShaderOutput,a=4}]
if kind==3 {
if !ShaderCompile(*program,code[:]).ok {return false}
material.shader=*program;material.shader_samplers=samplers[:]
}
if kind==4 {material.texture=AddTexture(*scene,pixels[:],2,2);material.alpha_test=0.3;material.transparent=true}
if kind==4 {
material=ImageMaterial(*scene,*texture,material)
material.alpha_test=0.3;material.transparent=true
}
if kind==13 {
options: SceneTextureOptions=.{projection=.SceneTextureBox,filter=.SceneTextureLinear,
wrap=.SceneTextureRepeat,scale=.{2.3,1.7},offset=.{0.2,-0.1}}
material=ImageMaterial(*scene,*texture,material,options)
}
if kind==6 {
discard_code: [3]ShaderInstruction=.[
.{op=.ShaderLiteral,dest=4,value=.{0.45,0,0,0}},
@@ -276,6 +289,12 @@ Quality :: (kind: s32)->bool {
material.shader=*program
}
if kind==11 {material.exact_color=true}
if kind==14 {
// The sun's beam carries a repeating two-by-two cookie across its box.
holder:=ImageMaterial(*scene,*texture,UnlitMaterial(.{255,255,255,255}))
LightCookie(*scene,sun,holder.texture,.{3.0,2.5},.{0.1,0.2})
if scene.failed||!scene.lights[sun].cookie {return false}
}
node:=RoundedBox(*scene,1,1,0.6,0.1,material)
mesh:=scene.meshes[scene.nodes[node].mesh]
for at:mesh.first_vertex..mesh.first_vertex+mesh.vertex_count-1 {
@@ -311,15 +330,18 @@ Quality :: (kind: s32)->bool {
}
print("quality % mae % fraction_over_16 %\n",kind,cast(float64)error/cast(float64)image.pixels.count,cast(float64)large/cast(float64)image.pixels.count)
if error>image.pixels.count||large>image.pixels.count/200 {return false}
if kind==3||kind==4 {
if kind==13&&(gpu.resources.texture_uploads!=1||gpu.textures.count!=1||gpu.textures[0].bytes.count!=0) {
print("immutable image cache retained duplicate bytes or upload count % % %\n",
gpu.resources.texture_uploads,gpu.textures.count,gpu.textures[0].bytes.count)
return false
}
if kind==3||kind==4||kind==13 {
old:=gpu.resources.texture_uploads;pixels[0]=0;pixels[1]=255
if !SceneGpuRender(*gpu,*scene,camera,*image).ok {return false}
// AddTexture copies its source; custom samplers borrow it.
// ImageMaterial owns an immutable copy; custom samplers borrow their bytes.
if kind==3&&gpu.resources.texture_uploads!=old+1 {return false}
if kind==4 {
scene.texels[0]=0
if !SceneGpuRender(*gpu,*scene,camera,*image).ok||gpu.resources.texture_uploads!=old+1 {return false}
}
if kind==4&&gpu.resources.texture_uploads!=old {return false}
if kind==13&&gpu.resources.texture_uploads!=old {return false}
}
if kind==3 {
code[0]=.{op=.ShaderLiteral,dest=4,value=.{0.1,0.3,0.7,1}}
@@ -371,6 +393,32 @@ main :: ()->s32 {
if !HostCheck(host)||SceneGpuMemoryUsage(*gpu).pending_frames!=0 {return 75}
SetPosition(*scene,node,0.2,0.0,0.0)
if !SceneGpuRender(*gpu,*scene,camera,*image).ok||gpu.resources.geometry_uploads!=2 {return 7}
// A node that only moves sends its own triangles, not the whole scene's:
// a second box joins, then turns.
second:=RoundedBox(*scene,0.4,0.4,0.2,0.0,material)
unused SetPosition(*scene,second,-0.6,0.5,0.0)
if !SceneGpuRender(*gpu,*scene,camera,*image).ok {return 76}
sent:=gpu.resources.geometry_vertices;uploads:=gpu.resources.geometry_uploads
unused SetRotation(*scene,second,0.0,0.0,0.5)
if !SceneGpuRender(*gpu,*scene,camera,*image).ok {return 77}
turned:=gpu.resources.geometry_vertices-sent
if turned<=0||turned>=gpu.vertices.count||gpu.resources.geometry_uploads!=uploads+1 {print("a moved node sent % of % vertices\n",turned,gpu.vertices.count);return 78}
// The picture is the one a fresh upload of the same scene gives.
fresh: SceneGpuContext;again:=NewImage(128,128)
if !SceneGpuRender(*fresh,*scene,camera,*again).ok {return 79}
for at: 0..image.pixels.count-1 {if image.pixels[at]!=again.pixels[at] {print("partial update differs at byte %\n",at);return 80}}
// A frozen scene still follows its nodes; a call that changes geometry takes
// the promise back and the change is drawn.
FreezeGeometry(*scene)
if !SceneGpuRender(*gpu,*scene,camera,*image).ok {return 81}
sent=gpu.resources.geometry_vertices
unused SetPosition(*scene,second,-0.5,0.4,0.0)
if !SceneGpuRender(*gpu,*scene,camera,*image).ok||gpu.resources.geometry_vertices-sent!=turned {return 82}
SetVertexPosition(*scene,second,0,.{-0.3,-0.3,0.2})
if scene.geometry_frozen {return 83}
if !SceneGpuRender(*gpu,*scene,camera,*image).ok||!SceneGpuRender(*fresh,*scene,camera,*again).ok {return 84}
for at: 0..image.pixels.count-1 {if image.pixels[at]!=again.pixels[at] {print("unfrozen change differs at byte %\n",at);return 85}}
SceneGpuRelease(*fresh);VecFree(again.pixels)
// A rejected mutation must not make the previous snapshot appear valid with
// partially rebuilt draw commands.
previous_mesh:=scene.nodes[node].mesh;scene.nodes[node].mesh=99999
@@ -409,7 +457,7 @@ main :: ()->s32 {
for at:0..image.pixels.count-1 {if image.pixels[at]!=reference.pixels[at] {return 43}}
SceneGpuRelease(*gpu);SceneFree(*scene);RenderSceneRelease()
print("Scene GPU lifecycle, mutation, resize, retention and fallback passed\n")
for kind:0..12 {if !Quality(cast(s32)kind) {return 50+cast(s32)kind};if !HostCheck(host) {return 36}}
for kind:0..14 {if !Quality(cast(s32)kind) {return 50+cast(s32)kind};if !HostCheck(host) {return 36}}
if !FeatureVariants()||!HostCheck(host) {return 48}
if !ReleaseCycles()||!HostCheck(host) {return 41}
if !PrecisionFallback()||!HostCheck(host) {return 44}
+17
View File
@@ -0,0 +1,17 @@
#!/bin/sh
set -eu
repo=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
. "$repo/tests/toolchain.sh"
out="$repo/build/scratch/scene-image-material"
mkdir -p "$out"
source="$repo/tests/scene_image_material_test.zi"
"$ziran" ir --project --root "$repo/tests" -o "$out/ir" "$source"
for form in source saved; do
input=$source; root=$repo/tests
if test "$form" = saved; then input=$out/ir/scene_image_material_test.zir; root=$out/ir; fi
"$ziran" build --project --root "$root" --target=c --entry scene_image_material_test:main --exe -o "$out/$form" "$input"
"$out/$form/scene_image_material_test"
"$ziran" bundle --project --root "$root" --entry scene_image_material_test:main -o "$out/$form.zx" "$input"
test "$("$ziran" run "$out/$form.zx")" = 0
done
printf 'Scene image material source/saved native and portable passed\n'
+89
View File
@@ -0,0 +1,89 @@
#import "kryon/scene"
#import "kryon/scene_render"
#import "std/image"
#import "std/vec"
Check :: (condition: bool, message: string) -> s32 {
if condition { return 0 }
print("image material: %\n", message)
return 1
}
ImageHash :: (image: *Image) -> u64 {
hash: u64 = 1469598103934665603
for at: 0..image.pixels.count - 1 {
hash = (hash ^ cast(u64)image.pixels[at]) * 1099511628211
}
return hash
}
ResourceAndProjection :: () -> s32 {
scene: Scene
SceneInit(*scene)
source := NewImage(4, 4)
defer { SceneFree(*scene); RenderSceneRelease() }
for y: 0..3 { for x: 0..3 {
at := (y * 4 + x) * 4
source.pixels[at] = cast(u8)(40 + x * 60)
source.pixels[at + 1] = cast(u8)(20 + y * 50)
source.pixels[at + 2] = cast(u8)(10 + (x + y) * 25)
source.pixels[at + 3] = 255
} }
options: SceneTextureOptions = .{projection=.SceneTextureBox,
filter=.SceneTextureLinear,wrap=.SceneTextureRepeat,
scale=.{2.0,3.0},offset=.{0.25,0.5}}
base := UnlitMaterial(.{255,255,255,255})
first := ImageMaterial(*scene,*source,base,options)
other := options; other.filter=.SceneTextureNearest
second := ImageMaterial(*scene,*source,base,other)
fail := Check(!scene.failed && first.texture == second.texture &&
scene.textures.count == 1 && scene.texels.count == 64,
"equal images with distinct sampling must share one owned scene resource")
mip := options; mip.mip_level=1
reduced := ImageMaterial(*scene,*source,base,mip)
again := ImageMaterial(*scene,*source,base,mip)
fail += Check(reduced.texture == again.texture && reduced.texture != first.texture &&
scene.textures.count == 2 && scene.textures[reduced.texture].width == 2 &&
scene.textures[reduced.texture].height == 2 && scene.texels.count == 80,
"explicit mip preparation must be deterministic and deduplicated")
x := SceneTextureCoordinate(first,.{1.0,2.0,3.0},.{-1.0,0.0,0.0},.{})
y := SceneTextureCoordinate(first,.{1.0,2.0,3.0},.{0.0,1.0,0.0},.{})
z := SceneTextureCoordinate(first,.{1.0,2.0,3.0},.{0.0,0.0,1.0},.{})
fail += Check(x.x==6.25 && x.y==6.5 && y.x==2.25 && y.y==9.5 &&
z.x==2.25 && z.y==6.5,"box projection must use stable object axes")
unused RoundedBox(*scene,1.0,1.0,1.0,0.0,first)
VecFree(source.pixels)
camera:=PerspectiveCamera(45.0,1.0,0.1,20.0);camera.position=.{0.0,0.0,3.0}
output:=NewImage(64,64);defer VecFree(output.pixels)
fail += Check(RenderScene(*scene,camera,*output),"owned image must render after source release")
hash:=ImageHash(*output);retained:=RenderSceneMemoryBytes()
fail += Check(RenderScene(*scene,camera,*output) && ImageHash(*output)==hash &&
RenderSceneMemoryBytes()==retained,"unchanged static geometry must render without retained growth")
SceneClear(*scene)
fail += Check(scene.textures.count==0 && scene.texels.count==0,
"SceneClear must release every logical image resource")
return fail
}
LinearRepeat :: () -> s32 {
scene: Scene;SceneInit(*scene)
source:=NewImage(2,2)
defer {VecFree(source.pixels);SceneFree(*scene);RenderSceneRelease()}
values: [16]u8=.[255,0,0,255, 0,255,0,255, 0,0,255,255, 255,255,255,255]
for at:0..15 {source.pixels[at]=values[at]}
options: SceneTextureOptions=.{filter=.SceneTextureLinear,wrap=.SceneTextureRepeat,
offset=.{1.0,1.0}}
material:=ImageMaterial(*scene,*source,UnlitMaterial(.{255,255,255,255}),options)
unused Plane(*scene,2.0,2.0,material)
camera:=OrthographicCamera(-1.0,1.0,1.0,-1.0,0.1,10.0);camera.position=.{0.0,0.0,3.0}
output:=NewImage(33,33);defer VecFree(output.pixels)
if !RenderScene(*scene,camera,*output) {return 10}
at:=(16*33+16)*4
return Check(output.pixels[at]>175&&output.pixels[at]<200&&
output.pixels[at+1]>175&&output.pixels[at+1]<200&&
output.pixels[at+2]>175&&output.pixels[at+2]<200,
"linear repeat sampling must blend four wrapped sRGB texels in linear light")
}
#program_export
main :: () -> s32 { return ResourceAndProjection()+LinearRepeat() }
+2 -2
View File
@@ -41,11 +41,11 @@ Run :: (width: s32, height: s32, kind: s32, motion: bool = false) -> bool {
texture.pixels[at+3]=255
} }
material:=UnlitMaterial(.{205,177,137,255})
if kind>=2 { material.texture=AddTexture(*scene,texture.pixels[:],1024,1024) }
if kind>=2 { material=ImageMaterial(*scene,*texture,material) }
if kind==3 { material.shader=*program; material.shader_uniforms=uniforms[:] }
if kind>=4 {
material=LitMaterial(.{205,177,137,255})
material.texture=AddTexture(*scene,texture.pixels[:],1024,1024)
material=ImageMaterial(*scene,*texture,material)
AddHemisphereLight(*scene,.{255,245,225,255},.{80,65,55,255},1.0)
light := AddDirectionalLight(*scene,.{255,235,210,255},2.0,.{2.0,4.0,5.0})
if kind==5 {
+4 -1
View File
@@ -337,8 +337,11 @@ VisibilityBuild :: (scene: *Scene, p: *ShaderProgram, extra: bool, variant: s32)
if variant==2 { front.alpha_test=0.5 }
if variant==3 {
texels: [16]u8=.[255,255,255,0, 255,255,255,255, 255,255,255,128, 255,255,255,64]
texture:=NewImage(2,2)
for at:0..15 {texture.pixels[at]=texels[at]}
front.shader=null
front.texture=AddTexture(scene,texels[:],2,2)
front=ImageMaterial(scene,*texture,front)
VecFree(texture.pixels)
front.alpha_test=0.5
}
unused SetPosition(scene,Plane(scene,0.8,0.8,front),0.0,0.0,0.5)
+21
View File
@@ -0,0 +1,21 @@
#!/bin/sh
set -eu
repo=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
. "$repo/tests/toolchain.sh"
unset DISPLAY WAYLAND_DISPLAY XAUTHORITY DBUS_SESSION_BUS_ADDRESS SESSION_MANAGER
export YUE_DESKTOP_RECOVERY=0
work="$repo/build/scratch/hosted-box-host"
mkdir -p "$work" "$work/c"
"$ziran" bundle --root "$repo/tests" $kryon_project_args \
--define KRYON_HOSTED_UI --entry hosted_box_guest:main \
-o "$work/hosted-box.zx" "$repo/tests/hosted_box_guest.zi"
"$ziran" build --target=c --no-main --entry hosted_box_host_test:main \
--root "$repo/tests" $kryon_project_args -o "$work/c" \
"$repo/tests/hosted_box_host_test.zi"
"${CC:-cc}" -O2 -std=c11 -ffunction-sections -fdata-sections \
-I"$work/c" -I"$ziran_root/include" "$work"/c/*.c \
"${ZIRAN_LIB:-$ziran_root/build/libziran.a}" -Wl,--gc-sections \
-lm -lpthread -o "$work/run"
(cd "$work" && ./run)
printf '%s\n' 'Public Box.Draw passed through a real portable HostedApp host capability'
+3
View File
@@ -74,6 +74,8 @@ Cairo = "src/backend/cairo_raster.zi"
Canvas = "src/backend/Canvas/module.zi"
Raylib = "src/backend/raylib_runtime.zi"
raylib_runtime = "src/backend/raylib_runtime.zi"
ImageExport = "src/backend/image_export.zi"
image_export = "src/backend/image_export.zi"
AndroidSurface = "src/backend/android_surface.zi"
http_transfer = "src/backend/http_transfer.zi"
file_download = "src/backend/file_download.zi"
@@ -256,6 +258,7 @@ canvas_window = "src/backend/canvas_window.zi"
dpi = "src/ui/dpi.zi"
dropdown = "src/ui/dropdown/dropdown.zi"
file_export = "src/backend/file_export.zi"
pdf_export = "src/backend/pdf_export.zi"
frame_pacing = "src/ui/frame_pacing.zi"
frame_transition = "src/ui/frame_transition.zi"
grid = "src/ui/grid.zi"