48 KiB
Components over platforms: hello-platform and hello-raylib
Source inspection: 2026-11-05, after the migration into the new mj repository.
This describes the current working files, not the initial repository commit
(0ed20b5, which did not contain the sample). Recheck the source before cloning
this design. The original analysis did not build or launch any target. Section 12
records the 2026-11-07 hello-raylib study and its separate validation limits.
1. What is shared, and why
hello/hello-platform is one counter expressed through five application targets:
macOS, iOS, Android, Linux and Windows. It has no graphics-engine dependency.
Dialect owns business state and transitions; the view model exposes presentation
state; the view renders it and emits input events; the platform delegate owns
startup and native integration. The native entry point connects these layers.
The reusable flow is:
native startup -> delegate -> component.setup() -> hpSet(didSetup, true)
button -> hpSet(didClickIncrement, true)
-> controller queue -> should functions -> changed fields
-> countText effect -> view model -> UI observation -> redraw
Do not put counter logic into platform buttons. Do not introduce a second controller in a view model. Do not duplicate source just because a new platform directory exists: link to the existing compatible implementation.
For variables already defined and managed by dialect.yml, that YAML is the only
source of truth. Express their state changes in its rules or effects; handwritten
functions must not assign or reset them independently, including for safety.
View-model copies receive updates through the generated effects. Initial property
defaults do not replace or duplicate the state-transition rules.
2. Ownership and file roles
| Responsibility | Source of truth | Generated? |
|---|---|---|
| Fields, transitions, UI output effect | hello/hello-platform/dialect.yml |
No |
| Swift controller, context, F, setters, rules, registrations | hello/hello-platform/ver-mac/src/dialect.swift |
Yes |
| Kotlin equivalents | hello/hello-platform/ver-android/app/src/main/kotlin/org/opengamestudio/dialect.kt |
Yes |
| Swift component lifetime and setup entry | components/hp/hp.swift |
No |
| Apple observable model | components/hp/hpVM.swift |
No |
| Apple view | components/hp/mac/view/HPView.swift |
No |
| SwiftCrossUI model and view | components/hp/linux/hpVM.swift, linux/view/HPView.swift |
No |
| Kotlin component/model/view | components/hp/android/hp.kt, hpVM.kt, view/HPView.kt |
No |
| Console helpers | components/other/other.swift, other.kt |
No |
| Native window icon helper | components/other/windows/otherWindows.swift |
No |
All four Swift targets compile the same generated engine. iOS/Linux/Windows
src/dialect.swift link directly to ../../ver-mac/src/dialect.swift.
They do not regenerate separate Swift implementations. Sharing these declarations
works because they depend on the names HPComponent and HPVM, rather than a UI
framework. Each target provides its compatible implementation of those names.
3. Dialect's actual execution model
The generated HPContext contains count: Int, countText: String, and Boolean
inputs/latches didClickIncrement, didSetup, didLaunch, plus recentField.
Values initially default to zero, empty string and false. F provides typed-at-
compile-time string constants; field values themselves cross Any/cast APIs.
Incorrect names/types can therefore still fail at runtime.
hpSet routes to HPComponent.singleton!.ctrl in Swift and
HPComponent.ctrl in Kotlin. It creates a context snapshot with one changed
field, queues it and synchronously drains the queue on the caller's thread.
For each queued item, the controller commits only its recentField value to the
canonical context, runs registered should functions, queues their returned
changes, then invokes callbacks for the current canonical event.
Swift value-type contexts provide copies; Kotlin's selfCopy() explicitly
provides the equivalent isolation. Returning recentField = "none" means a
should produced no event. The processing flag prevents recursive drains when
callbacks dispatch more events, while allowing the existing drain to process
them. This is not thread synchronization or automatic main-thread dispatch.
Keep UI-affecting inputs on the UI thread, and marshal future background results
there before changing observable models through effects.
Should functions are registered for count, countText and didLaunch. Branches
within each should are ordered; the first match returns. Each should changes
one field. A generated branch's computed change is queued, not immediately
written wholesale to canonical state. Oneliners are field-filtered callbacks:
countText copies c.countText into HPVM.shared!.countText (Kotlin !!).
Concrete startup sequence:
- Component construction creates its controller and registers effects/rules.
- Model construction establishes
HPVM.sharedbefore setup emits anything. - Delegate registers logging and calls
hp.setup(). didSetupqueuesdidLaunch = trueonly while the launch latch is false.didLaunchqueuescountText = "Press the button to count".- The countText callback publishes the label and observation refreshes the UI.
A click queues didClickIncrement = true even if its stored value is already
true: processing is driven by dispatch/recentField, not a false-to-true edge.
Counts go 0, 1, …, 7, 17, 18: the special branch adds ten when the pre-click
count is seven; it does not also apply the normal increment. Count changes queue
"Count: '<value>'", which the same presentation effect publishes.
Setup does not reset count. Repeating setup after launch normally leaves the latch and counter intact. Registering logging repeatedly is a different issue: it appends callbacks and can duplicate messages.
4. HP representation by platform
| Target | Component | Model observation | View observation | Startup trigger |
|---|---|---|---|---|
| macOS | Shared Swift class | Combine ObservableObject, @Published |
SwiftUI @ObservedObject |
AppKit launch callback |
| iOS | Same class | Same Apple model | Same SwiftUI view | UIKit launch callback |
| Android | Kotlin object |
mutableStateOf inside HPVM object |
Composable reads HPVM.countText |
Activity onCreate |
| Linux | Same Swift class | SwiftCrossUI ObservableObject, @Published |
SwiftCrossUI @State |
Delegate init |
| Windows | Same Swift class | Same Linux model | Same Linux view | Content onAppear calls delegate setup |
Swift component and lifetime
HPComponent is a class with a strong ctrl property and a weak static
singleton. Its constructor publishes itself and registers generated effects
and shoulds. setup() sends F.didSetup. Delegates strongly retain both hp
and hpVM; weak globals alone do not keep either alive. A component must exist
before hpSet and a model before the first countText effect.
This is a single-component-instance design, not isolated state per window. Constructing a second component/model changes the shared routing target. Multiple WindowGroup windows currently share a delegate's state; use explicit controller injection and per-window ownership if a new app requires isolation.
Apple observation is not SwiftCrossUI observation
The Apple model imports Combine. SwiftUI's @ObservedObject observes its
@Published countText. Replacing that property wrapper with SwiftUI @State
would not give the same subscription for this Combine class. Migrating to
Apple's newer Observation macro is a separate design/minimum-OS change.
The Linux model imports SwiftCrossUI and uses that framework's similarly named
protocol/property wrapper. SwiftCrossUI @State subscribes to its observable
object. Windows reuses these exact files; it must not use the Combine model.
The model's public shape is deliberately identical so generated effects work
unchanged. No @ObservableObject macro is used by these models.
Kotlin representation and activity recreation
HPComponent is handwritten as an object, because generated hpSet addresses
HPComponent.ctrl directly. val hp = HPComponent references its existing
singleton; HPComponent() would be invalid. Registration occurs once in its
object initializer. HPVM is another object; countText by mutableStateOf("")
causes Compose readers to recompose, and its shared property supports the
transpiled effect. That effect first references/initializes HPVM if necessary.
HPActivityDelegate is an object retaining hp. Its initializer registers
logging once; setup() calls hp.setup() on every Activity creation. Thus the
in-process singleton survives activity recreation and avoids re-registering
logging, while the launch latch prevents reinitializing the label. Process
termination loses the counter: there is no persistence or saved-state restore.
5. Entry points and native differences
- macOS: SwiftUI
HPAppuses@NSApplicationDelegateAdaptor; its delegate owns component/model, activates the application, registers logging and sets up HP inapplicationDidFinishLaunching. Closing the last window terminates the app. WindowGroup defaults to 640×480. - iOS:
@UIApplicationDelegateAdaptorconstructs the UIKit delegate. Its launch callback registers logging, sets up HP and returns true. There is no macOS foreground activation code. The plist permits portrait, upside-down portrait and both landscape orientations. - Android:
MainActivitycalls the delegate beforesetContent, enables edge-to-edge light system bars, and centers HPView in a full-size white Box insideMyApplicationTheme. The manifest starts.MainActivityand takes its label from resources. - Linux: importing GtkBackend chooses GTK. The app explicitly creates the
backend with ID
org.opengamestudio.hello-platform. Delegate initialization sets up HP before HPView is constructed. There is no icon call in the delegate. - Windows: importing WinUIBackend selects WinUI. Delegate construction only
retains HP/model; HPView's
onAppearcallsdelegate.setup(), which logs, starts HP, and invokesotherSetupWindowIcon(101). WindowGroup'sidwould identify a scene, not substitute for the GTK application ID.
Windows setup has no one-time guard. A repeated appearance may append logging callbacks again, although component registrations occur only during component construction. SwiftCrossUI onAppear runs before presentation; it is not a contract that the native window exists. The icon helper visits only windows already owned by the calling thread; absent windows are not retried. Preserve this actual behavior when describing it, and validate lifecycle timing in a new app rather than assuming that an appearance hook guarantees a native HWND.
6. UI parity and deliberate adaptation
Mirror existing platform implementations as closely as the target platform allows, including internal structure, not just visible behavior. Compare the macOS and iOS counterparts before creating or changing Android files. Preserve file roles, names, component/model/view ownership, initialization order, lifecycle wiring, helper boundaries and placement of constants. For example, when Apple's RenderVM creates and owns glView, Android's RenderVM should also own its creation and lifetime rather than MainActivity creating it and keeping a duplicate property. Supply Android's required Context and account for Activity recreation within that ownership structure. Keep native entry points thin and route renderer details through the corresponding delegate, model and helpers. Introduce differences only where required by platform APIs or lifecycle, and explain those differences when presenting the implementation. Before finishing, compare counterpart files for structural parity as well as behavior; a successful build alone is insufficient.
The Apple and SwiftCrossUI views contain a VStack with spacing 16, padding 40,
a largeTitle heading, a title3.monospaced() count label, and an Increment
button dispatching the same event. iOS's component view is itself a symlink to
the macOS implementation. SwiftCrossUI differs in imports and observation only.
Compose mirrors the structure with a horizontally centered Column, 16dp spaced
arrangement, 40dp padding, headlineLarge, a titleMedium label with
FontFamily.Monospace, and a Material button. These named styles are conceptual
matches, not identical fonts or pixel metrics. Native window sizing, navigation
bars, accessibility scaling and toolkit defaults can affect visual centering.
Preserve visible text, capitalization, structure and business behavior when creating an analogue. Use named typography instead of hardcoded font sizes. Prefer Kotlin wildcard imports for multiple symbols from the same package; alias conflicting names (as MainActivity does for graphics Color).
7. Source-link topology
Sort imports, includes and equivalent dependency declarations alphabetically on all platforms, unless compiler requirements mandate a different order. Preserve required ordering between implementation macros and their associated includes.
Sort methods alphabetically by name within each class or object on all platforms, including lifecycle callbacks such as RenderGLView's onDrawFrame, onPause, onSurfaceChanged and onSurfaceCreated. Keep constructors and initialization blocks before the methods, and preserve any declaration order required by the compiler.
Resolve links to understand ownership; do not edit through copied duplicates.
If a component file has different implementations across platforms or languages,
place those implementations in platform subdirectories, not the component root
(for example, use render/mac/, render/ios/ and render/android/). When some
platforms share an implementation, keep the real file in one platform directory
and symlink the others to it. For example, components/render/mac/renderConst.swift
owns the Swift constants, components/render/ios/renderConst.swift links to
../mac/renderConst.swift, and Android owns render/android/renderConst.kt.
App targets link to their corresponding platform file. Reserve the component
root for files shared across platforms without platform-specific counterparts.
| File in app target | macOS/iOS origin | Linux/Windows origin |
|---|---|---|
src/dialect.swift |
macOS is generated real file; iOS links directly to it | Both link directly to macOS's generated file |
src/hp/hp.swift |
components/hp/hp.swift |
Linux via components/hp/linux/hp.swift -> ../hp.swift; Windows directly to shared component |
src/hp/hpVM.swift |
components/hp/hpVM.swift |
components/hp/linux/hpVM.swift for both |
src/hp/view/HPView.swift |
mac view; iOS via components/hp/ios/view/HPView.swift -> ../../../hp/mac/view/HPView.swift |
components/hp/linux/view/HPView.swift for both |
src/other/other.swift |
components/other/other.swift |
Same shared source |
src/other/otherWindows.swift |
Not included | Windows only, from components/other/windows/otherWindows.swift |
Android links its hp component/model/view and other helper to real Kotlin files
in components/, under app/src/main/kotlin/org/opengamestudio/. Source package
remains org.opengamestudio; directories below it do not imply Kotlin packages.
For this app depth, Swift src/hp and src/other links need five parent
traversals to repository components/; src/hp/view needs six. Links from
ver-ios/Assets.xcassets/AppIcon.appiconset to repository res need five.
Do not copy those counts blindly to a differently nested app. Calculate each
relative path, preserve it as a symlink, and check it resolves. On Windows enable
Git symlink support and OS permissions/Developer Mode before checkout.
8. Generation and platform build matrix
Current generation is repository-local: app step/generateDialect calls
repository util/run-generator, which runs swift ext/generator-script.swift.
It no longer requires building the sibling Dialect executable. Output paths in
YAML resolve relative to the YAML file. Both Swift and Kotlin outputs are
configured, so generation for an Apple target also processes Kotlin. The
vendored generator has an Ollama-backed conversion stage; check its current
model/server constants when reproducing the environment. Never edit generated
files as a lasting implementation change.
| Command (from app directory) | Steps / result |
|---|---|
util/build-mac |
Generate both outputs → build Swift package → assemble .app |
util/run-mac |
Execute packaged .app/Contents/MacOS/hello-platform |
util/prepare-ios |
Generate both outputs → XcodeGen; does not compile iOS |
util/prepare-android |
Generate both outputs; does not run Gradle |
util/build-linux |
Build existing Swift output → install desktop package/assets |
util/run-linux |
gtk-launch installed desktop entry, not the build-tree binary |
util/build-windows |
Export APP_RES_DIR → build existing Swift output |
util/run-windows |
Run .build/debug/hello-platform.exe; no build or preflight check |
Entry scripts set SDIR using pwd -P, T, TARGET and STEP=0. Sourced steps consume
positional parameters and increment STEP in the same shell. Keep banners in the
established format, e.g. echo -e "\n> > > > Step №$STEP. Build '$TARGET' for Windows".
A sourced step's cd persists; use SDIR-based paths for later steps. Some existing
steps leave paths unquoted, so spaces in checkout paths are not uniformly handled.
When an analogue's step script is byte-for-byte identical to the corresponding
hello-platform/util/step script, use a relative symlink instead of a copy.
Compare contents first and verify the link resolves. In hello-raylib,
buildMac, generateDialect, packageMac and runMac link to
../../../hello-platform/util/step/<name>. These sourced scripts use the calling
entry script's SDIR, so they operate on the analogue. macOS now discovers raylib
through pkg-config, so buildMac no longer needs a separate RAYLIB_PREFIX export.
For raylib analogues, name the C bridge translation unit raybri.c, not
Raylib.c. Keep each platform's real translation unit in
components/raybri/<platform>/raybri.c, and symlink it from the target's raybri
directory: ver-mac/src/raybri/, ver-ios/src/raybri/, or Android's
app/src/main/c/raybri/. Keep Package.swift, CMake and header search paths aligned
with those locations. The iOS project includes src in header search paths so
the moved translation unit can still reference sibling EGL headers.
hello-raylib/ver-android follows hello-platform's Gradle/Compose layout and
renders a native blue background beneath the HRB title. MainActivity calls
HRBActivityDelegate.setup(this) before composing the UI. The delegate sets up both
HRB and Render components and retains RenderVM. HRB files link directly to
components/hrb/android/, renderer files to components/render/android/, and
console helpers to components/other/other.kt. Its application ID is
org.opengamestudio.helloraylib; the source namespace remains org.opengamestudio.
Its centered HRBView mirrors the Apple view: 40dp padding, a headlineLarge
white title offset by (1dp, 1dp), then the black title on top. Both read
HRBVM.title, initialized to hello-raylib through Dialect. MainActivity places
RenderView() beneath HRBView in a full-size Box; rlgl paints the blue background.
There are no counters or buttons. Transparent system bars use light icons over blue.
The launcher retains the established legacy/adaptive icon resources. Density PNGs
link to the matching hello-platform Android images; adaptive artwork links directly
to repository res/AppIcon.png.
All hello-raylib targets use the same hello-raylib/dialect.yml, including its renderer
rules. Android's RenderComponent registers the generated effects and shoulds.
renderInit calls
raybriLoadExtensions() followed by raybriInit(), mirroring macOS; its caller
must first make a GL context current.
renderRecreateSurface lives in renderAux.kt, mirroring macOS's file structure.
Do not add a separate Android Dialect definition.
Android RenderView hosts a GLSurfaceView through Compose's AndroidView.
GLSurfaceView creates an OpenGL ES 3 context, drives frames and swaps buffers.
onSurfaceCreated dispatches didPrepareAndroidGL, whose shared should emits
didPrepareGL to initialize raybri and enable continuous rendering. This rule
runs for every new Android context, rather than only once per process.
onSurfaceChanged sends framebuffer dimensions through reshapePixelSize;
onDrawFrame calls renderDraw, which invokes raybriRender. GLSurfaceView owns
EGL surface recreation, so renderRecreateSurface is a no-op, as on macOS.
Initial component setup finishes before the view starts rendering. Subsequent
renderer events and native graphics calls run on the GL thread. Activity pause
queues willDeinit before pausing GLSurfaceView. queueEvent guarantees the GL
thread, not the presence of a current context. Resume restarts the view; newly
created contexts initialize fresh resources. Activity destruction calls delegate
tearDown to clear the model's view and Context references. The Apple
Render component/model implementations live in components/render/mac/, with
matching symlinks in components/render/ios/, following the platform-file rule.
The native bridge is built by ver-android/CMakeLists.txt from
app/src/main/c/raybri/raybri.c, linked to
components/raybri/android/raybri.c, using the shared raybri header and an externally fetched
rlgl.h. ver-android/gradle/libs.versions.toml owns raylib = "6.2", referring
to the official raylib tag. Gradle passes it to CMake as
-DRAYLIB_VERSION=.... CMake uses FetchContent to download only rlgl.h into
its build directory, retaining the upstream license. No environment variable or
generated revision file is needed; preparation only generates Dialect sources.
It links GLESv3, log and m; Gradle pins NDK 28.2.13676358 and CMake
3.22.1 and packages libraybri.so; CMakeLists declares a minimum of 3.11.0
and uses FetchContent_Populate, which is available in that version.
Kotlin JNI declarations link to components/raybri/android/raybri.kt and
raybriAux.kt. Do not call them until a GL context is
current. These are top-level raybriInit, raybriLoadExtensions, raybriRender
and raybriShutdown functions, matching the Swift-facing C names. Extension
loading is a separate JNI call to the C raybriLoadExtensions() helper in
Android's raybriAux.h, which calls rlLoadExtensions(NULL); it is not part of
raybriInit. As on macOS, library and extension loading live in raybriAux.
Standalone rlgl diagnostics use a TRACELOG override: Android forwards messages
to Logcat through __android_log_print, while iOS writes to stderr with a newline
per message, making the diagnostics visible in the app's console.
Android's library name is RAYBRI_ANDROID_LIB in raybriConst.kt.
raybriLoadExtensions() explicitly calls System.loadLibrary(RAYBRI_ANDROID_LIB)
and then the private JNI function raybriLoadExtensionsNative(). Call it before
raybriInit() or any other native bridge function. JNI exports target
RaybriAuxKt for extension loading
and RaybriKt for initialization, rendering and shutdown.
Pixel-size fields use [Int] in the shared YAML and Swift model; convert to
Int32 only when passing dimensions to the C renderer. Android's model
uses Array<Int> to match the unchanged generator's collection declarations.
Shared YAML uses RENDER_PIXEL_SIZE_1x1 to keep collection construction in
handwritten platform code: let RENDER_PIXEL_SIZE_1x1 = [1, 1] in macOS's
renderConst.swift (also linked by iOS), and val RENDER_PIXEL_SIZE_1x1 = arrayOf(1, 1) in Android's
renderConst.kt. Targets link their corresponding constant file. The preparation
flag is assigned directly in YAML and translated by the configured 7b model.
Handwritten callbacks and effects must not change didPrepareGL; keep its
assignments in YAML rather than adding defensive resets or cleanup guards.
When a constant needs a different representation across languages, the expected
solution is to reference one shared constant name in YAML and define its value
in each language's handwritten constant file. For example, replace
c.pixelSize = [1, 1] with c.pixelSize = RENDER_PIXEL_SIZE_1x1; Swift defines
that name as [1, 1], while Kotlin defines it as arrayOf(1, 1). This keeps the
shared rule identical while giving each language the required collection type.
Prefer this approach over helper functions or generator changes for translating
such constant values. Link each target to its corresponding constant file.
util/prepare-android sources the shared step/generateDialect, which generates
both the macOS Swift file and Android's dialect.kt; never hand-edit them.
Apple preparation/builds also generate both outputs, so they require the configured
Ollama server/model for Kotlin conversion, as hello-platform does.
Build Android with ./gradlew assembleDebug from ver-android, using JDK 21 and
the Android SDK; configure machine-specific SDK paths locally, not in Git.
Verified on 2026-11-07: Android, macOS and iOS simulator builds pass. Small_30
(API 30) displays the native blue background and centered title in portrait and
landscape, and restores both after background/resume. Native logs confirm rlgl
resource cleanup and reinitialization across pause/resume and Activity recreation.
- macOS: tools 5.9, executable source root
src, deployment macOS 13. Bundle plist currently says minimum 11.0, inconsistent with Package.swift; use 13 as the package's actual target floor and reconcile values for a new app. - iOS: XcodeGen project, iOS 15, asset catalog plus
src, separate Info.plist. - Android: AGP 8.7.3 / Kotlin 2.1.0, Gradle wrapper 9.3.1, Compose BOM
2024.12.01, Java/Kotlin bytecode 1.8. Current minSdk is 24, compile/target 35;
do not inherit the earlier OGS Blue minSdk 23 assumption. Requires JDK/SDK setup;
local.propertiesis machine-specific and ignored. - Linux: tools 5.10; SwiftCrossUI and GtkBackend products; GTK development libraries and desktop utilities required. No automatic generation in build.
- Windows: tools 5.10; SwiftCrossUI and WinUIBackend products. Git Bash scripts cd to the package before build/run; no cygpath, exec, PowerShell or resource compiler step. Install a working native Swift/Windows SDK/WinUI runtime setup. The Windows architecture used is whatever the toolchain selects; scripts do not currently specify an x64 cross-compilation triple.
Both desktop cross-UI packages depend on branch v0.10.0 of
https://github.com/moreSwift/swift-cross-ui. That is a branch requirement, not
an immutable version pin; Package.resolved is ignored. Changes upstream can
therefore affect builds. Do not interpret earlier successful user builds as a
fresh cross-platform verification of this checkout.
9. Packaging, identity and icons
macOS packageMac copies the debug binary, plist and dereferenced ver-mac/res
into .build/hello-platform.app. Its icon link points to repository AppIcon.icns.
iOS asset-catalog PNG links to repository res/AppIcon.png. Android uses density
PNG resources plus API-26 adaptive definitions; keep legacy fallback artwork for
its older minimum API and preserve manifest/resource names.
Linux packageLinux is an install step, not a distributable archive: it copies the
binary to ~/.local/bin, installs a desktop file under XDG user applications, and
places the 1024px PNG in hicolor's matching size/app-ID location. It substitutes
%APP_NAME%, %APP_EXEC%, %APP_ID% in shared res/linux-app.desktop with GNU
sed, then directly calls gtk-update-icon-cache and update-desktop-database.
Missing utilities fail the build script. Replacements assume ordinary paths
(no unescaped sed metacharacters). GtkBackend ID, desktop filename, Icon and
StartupWMClass must agree. APP_NAME is a display name; TARGET names the binary.
Windows ver-windows/res/AppIcon.res links to repository res/AppIcon.res.
This ready-made binary contains RT_ICON images 1–6 and RT_GROUP_ICON 101.
No ICO or RC source is needed by the build; replacing PNG artwork alone does not
update this resource. The manifest force-unwraps APP_RES_DIR and passes
-Xlinker <resDir>/AppIcon.res without a platform condition. Even metadata-only
SwiftPM commands need that environment variable. buildWindows exports it from
$SDIR/../ver-windows/res, without copying or recompiling the resource. The user
confirmed their Git Bash path works in their Windows build; do not reintroduce
path conversion speculatively.
Executable resources provide Explorer/taskbar artwork separately from window
icons. otherSetupWindowIcon(101) uses C Win32 APIs from WinSDK: enumerates
current-thread windows, loads small/large shared icons from the executable and
sends WM_SETICON. The numeric ID must match the resource group; it is not an
address to dereference. Pass callback state via LPARAM, not a captured Swift
parameter. Convert LPARAM explicitly to Int for UnsafePointer(bitPattern:).
Return true as WindowsBool, not integer 1. LR_SHARED handles are Windows-owned;
do not destroy them. The helper ignores failed loads and enumeration failure.
Identity is represented in several places: Apple bundle IDs and names in plists,
iOS project.yml, desktop package/target names, GTK ID, Linux launcher, Android
namespace/applicationId/string resources, and Windows resource linkage. Current
Android applicationId is org.opengamestudio.helloplatform (no hyphen), while its
source namespace is org.opengamestudio. Do not blindly replace namespace with
the app ID. Update all relevant identities together for a new analogue.
10. Recipe for a new analogue
- Choose the app folder, binary/display names, component prefix (for example
XY/xy), reverse-domain IDs, and desired platform minimums. - Create one app dialect.yml with the new Context/Component and only the fields,
rules and effects needed. Use branch labels ending in colons. Rename the
output paths if package/source paths differ. Generate before compiling code
that refers to new F fields. Kotlin F syntax is not Swift
static letsyntax. - Add handwritten component, model and view sources in
components/<prefix>. Keep the platform-neutral Swift component shared. Add Apple and cross-UI models separately because their observation frameworks differ. Share views inside each compatible UI family. Add Kotlin mirrors, not copies of Swift. - Keep names aligned across YAML, generated setters and handwritten types. Generated Swift assumes a retained component's weak singleton; Kotlin assumes an object with ctrl. Provide model shared access before the first output effect.
- Write thin platform entry/delegate files and connect native startup in the manner appropriate to that toolkit. Register callbacks once per controller; make repeated lifecycle entry safe if applicable. Avoid duplicating business rules or storing authoritative count in UI state.
- Make real app directories with relative file symlinks. Link generated Swift directly to its canonical macOS file, shared helpers directly to components, and Linux/Windows to the same cross-UI model/view. Avoid copied duplicate files or unnecessary chains through another app target.
- Adapt Package.swift, XcodeGen, Gradle, manifests, plists and asset references. Copy the Gradle wrapper intentionally; do not copy local.properties, .build, build outputs, IDE state, .git or machine-specific caches.
- Add util entry scripts and step files, preserve SDIR/TARGET/STEP conventions,
banners and build/generate/package boundaries. Symlink identical step scripts
to hello-platform as described above; retain app-specific scripts separately.
The fixed ../../../ repository
traversal in this sample assumes
hello/<app>/util; recompute for other depths. - Wire shared icons through platform assets. An embedded Windows group ID and runtime helper argument must agree. Do not add resource compilation to builds unless requested; update the precompiled artifact separately when needed.
- Audit links and source names, then validate generation, compilation, runtime startup label and increment behavior independently per platform when allowed. Check 7→17, model publication, activity/window recreation, icons, identities and platform-only dependencies. Honor any instruction not to build.
Useful read-only checks from the repository root:
find components hello -type l ! -exec test -e {} \; -not -path '*/.build/*'
rg 'HPComponent|HPVM|hpSet' components/hp hello/hello-platform
rg 'hello-platform|helloplatform' hello/hello-platform res/linux-app.desktop
11. What is established versus still worth checking
Source inspection establishes topology, dispatch logic, imports, target settings, script commands and resource references described here. The user previously reported Windows builds and visible icon artwork; that is useful evidence, not proof of every lifecycle path. This document does not certify present Linux, Windows, Apple or Android builds. Known reuse hazards include repeat Windows logging registration, early window-icon timing, force-unwrapped globals/env, main-thread assumptions, stale generated outputs on desktop builds, different minimum-version declarations and mutable upstream branch dependencies.
Older docs/hello-platform.md remains a walkthrough, but contains historical
statements about sibling-generator prerequisites and narrower platform coverage.
For creating new analogues use this source-checked blueprint, and verify current
files whenever the two documents disagree.
12. hello-raylib: source study and Linux analogue
Studied the current macOS, iOS and Android sources on 2026-11-07 before adding Linux. This section describes existing behavior, including unresolved differences; an identified improvement is not evidence that the code already implements it.
Layers, source ownership and observation
HRB and Render are independent components. HRB owns the title; Render owns graphics preparation, framebuffer dimensions and teardown events. A native view owns the context and presents the raylib image behind a native title view. No platform calls raylib InitWindow or hands its event loop to raylib.
| Layer | Responsibility | Sharing boundary |
|---|---|---|
| App entry/delegate | Retain components/models, register logging, set up components, compose RenderView beneath HRBView | Native entry points differ; ownership/order should mirror |
| dialect.yml | Title, once-per-controller launch, preparation rules, pixel-size propagation and cleanup effects | One YAML; iOS/Linux link directly to generated ver-mac/src/dialect.swift; Kotlin is separately generated |
| HRB component | Construct controller, register rules/effects, expose setup | Common hrb.swift for Swift; object in Kotlin |
| HRB model/view | Observe title and draw black text over a white displaced copy | Apple Combine/@ObservedObject; Linux SwiftCrossUI/@State; Android Compose state |
| Render component | Register renderer rules/effects and emit didSetup | macOS owns Swift source, iOS/Linux component files symlink to it |
| Render VM/helpers/views | Own native view and implement the common render functions using native graphics APIs | Files stay under platform directories; compatible files are symlinked |
| Raybri | Common init/render/shutdown graphics commands plus platform symbol loading and language bindings | Shared raybri.h; component-owned platform raybri.c linked from each target |
Apple delegates strongly retain HRBComponent, HRBVM, RenderComponent and RenderVM. Weak singleton/shared properties route events but do not own those objects. Kotlin components/models are process-wide objects. Android setup(context) stores the Activity Context and creates glView in RenderVM; MainActivity no longer owns a second view property. onDestroy calls delegate tearDown to clear both references. Activity recreation calls setup again; GL context recreation alone does not. Ordinary rotation currently follows Activity recreation, deliberately.
The shared title is "hello-raylib". Apple and Android use a centered padded view with white text displaced one unit down/right beneath black text. Retain that structure and named heading typography in analogues; toolkit font metrics and physical pixel density can differ.
Event flow and lifecycle contracts
HRB setup emits didSetup; the once-per-controller didLaunch rule initializes its title. Render setup initializes pixelSize to RENDER_PIXEL_SIZE_1x1 through its launch rule, without initializing GL. Only the native context-ready callback emits the platform preparation event. Its rule emits didPrepareGL; generated effects then call renderInit, set VM.didPrepareGL and call renderStartTimer, in that order. Resize emits reshapePixelSize; rules propagate pixelSize and request renderRecreateSurface through willRecreateSurface. All dispatch is synchronous on the caller's thread, not automatically marshalled to a UI or graphics thread.
| Responsibility | macOS | iOS | Android | Linux |
|---|---|---|---|---|
| VM-owned view | NSOpenGLView | EGL/ANGLE-backed UIView | GLSurfaceView created by delegate setup | Lazily created GtkGLArea wrapper |
| Context-ready input | prepareOpenGL → didPrepareMacGL | didMoveToWindow → didPrepareIOSGL | onSurfaceCreated → didPrepareAndroidGL | realize → didPrepareLinuxGL |
| Context/presentation | Explicit makeCurrent and flushBuffer | EGL init/reset/makeCurrent/swapBuffers | GLSurfaceView manages context and swapping | GTK makes current, binds framebuffer and composites output |
| Frame scheduling | Foundation Timer marks needsDisplay | Foundation Timer calls renderDraw | GLSurfaceView continuous rendering | GTK frame-clock tick queues rendering |
| Thread | Main for current callbacks/timer | Main for current callbacks/timer | GL thread after initial setup | GTK main thread |
| Pixel size | convertToBacking(bounds) | Scaled bounds, rounded | Callback dimensions already pixels | Resize viewport dimensions already scaled |
| renderRecreateSurface | No-op | Recreate EGL surface | No-op | No-op |
| Cleanup event | View deinit | View deinit | View onPause queues willDeinit | unrealize before GTK's context teardown |
Preparation rules intentionally differ: iOS gates its event with !didPrepareGL; macOS, Android and Linux accept each native preparation event. Express any future state-policy change in YAML, never by resetting flags in handwritten callbacks. View lifetime, graphics-context lifetime and component/controller lifetime are distinct. Android pause and Linux unrealize release graphics resources while their component/controller may survive. queueEvent guarantees Android's rendering thread but does not create, restore or guarantee a current EGL context.
iOS cleanup stops its timer, makes the context current, calls raybriShutdown and then glbriShutdown. The latter lives in components/glbri/ios/glbri.h and owns unbinding, surface/context destruction and display termination. Preserve that order so graphics resources are released before their context disappears.
Raybri implementation and unresolved parity findings
raybriInit calls rlglInit(1, 1) and sets blue clearColor. raybriRender sets the viewport, clears color/depth and flushes the active render batch. raybriShutdown calls rlglClose. These functions neither draw the title nor create native windows.
macOS and Linux discover installed raylib through a CRaylib system-library target with pkgConfig: "raylib". Both bridge targets use src/raybri and publicHeadersPath ".". macOS no longer needs RAYLIB_PREFIX or manual include/library path flags. components/craylib/shim.h owns the shared header. Platform-specific module maps live in components/craylib/mac/ and components/craylib/linux/. Each app target's src/craylib directory links directly to that shared shim and its platform's module map. The module maps differ because Linux additionally links libGL. macOS still uses dlopen/dlsym for system OpenGL entry points. RAYBRI_MAC_GL now lives only in components/raybri/mac/raybriConst.h; the iOS target no longer compiles it. iOS and Android compile standalone ES3 rlgl. iOS obtains headers from an external raylib XCFramework and links ANGLE EGL/GLES; Android CMake fetches the pinned rlgl header and builds the JNI library. Keep RLGL_IMPLEMENTATION's final inclusion after the declaration-only bridge includes. Android exposes free Kotlin functions, with library/extension loading in raybriAux.kt and JNI wrappers in raybri.c.
Remaining findings from the three-platform study:
- iOS does not yet call raybriLoadExtensions; macOS and Android do before raybriInit. rlLoadExtensions also initializes ES3 capability flags, so a matching iOS helper/call is a functional improvement, not just a naming change.
- The inspected macOS installation reports raylib 6.0; Android pins 6.2 and the local iOS headers report 6.2. RLGL_VERSION alone does not identify the exact raylib revision. Aligning dependency versions remains a separate decision. The macOS linker also warns that the installed raylib dylib was built for macOS 26.0 while the package targets 13.0; a successful local build does not demonstrate compatibility with older macOS releases.
- macOS has a didPrepareGL draw guard absent from Android. Check native startup ordering before changing it; do not copy defensive checks into other targets.
- Apple startTime is written but never read, RENDER_MODEL_CUBE is unused, and the render root still contains unused desktop GLSL shader constants. These were identified rather than silently removed or duplicated into new platforms.
- Android logging registration currently repeats inside delegate setup and Render logging is registered after render.setup. Registrations can accumulate across Activity recreation and miss initial setup events. Apple/Linux register Render logging before setup. Native logging sinks also differ in severity handling.
Linux implementation and reuse map
ver-linux follows hello-platform/ver-linux: Swift tools 5.10, SwiftCrossUI and GtkBackend from branch v0.10.0, HRBApp/HRBAppDelegate, relative component symlinks under src, and the existing generated Swift engine. A separate RaylibBridge C target depends on the CRaylib system-library target, which uses pkg-config raylib and links raylib plus desktop libGL. Install Swift, GTK 4 development files, pkg-config, raylib development files and OpenGL headers including GL/glx.h. Linux uses the installed raylib; it does not claim to pin its version.
Linux links common hrb.swift directly, and render.swift/renderConst.swift through components/render/linux symlinks to macOS owners. HRBVM and HRBView use the same SwiftCrossUI observation approach as hello-platform. This branch lacks offset, so top/leading padding inside a top-leading ZStack expresses the white title's one-unit displacement. The overall title remains centered over RenderView.
RenderVM lazily creates glView because the delegate/model can exist before GTK initialization. The VM still owns it; do not move creation into the app entry. RenderView implements GtkWidgetRepresentable and returns that view, matching Apple's representables. RenderGLView wraps GtkGLArea and connects ABI-correct C callbacks: render returns gboolean; resize takes gint dimensions; realize runs after the default handler, unrealize before it. Its on-methods are alphabetical. The wrapper avoids Gtk.GLArea's generated render binding, which returns Void.
Linux requests desktop OpenGL 3.2 with depth support, matching macOS's requested profile version. The installed raylib still normally uses its OpenGL 3.3 backend; lowering the requested context version does not change that backend or establish compatibility with hardware limited to 3.2. Its raybriGLLoader uses glXGetProcAddressARB without opening a raylib window. renderInit makes the context current, loads extensions, then initializes raybri. renderDraw uses GTK's already-bound framebuffer: do not bind framebuffer zero or swap buffers manually. The resize callback already receives physical pixels; do not multiply by scale again. renderStartTimer uses GTK's frame clock because GTK's main loop does not drive Foundation Timer. renderDeinit removes the tick callback, makes the context current and shuts down raybri before GTK's unrealize handler releases the context.
didPrepareLinuxGL is declared and handled in the common dialect.yml. Regenerate both language outputs; never create a second Linux engine or handwritten state resets. All Swift targets continue sharing the macOS-generated engine directly.
util/build-linux sources buildLinux then packageLinux; util/run-linux sources runLinux. All three step scripts link directly to hello-platform's counterparts. Packaging reuses res/linux-app.desktop and res/AppIcon.png. GTK ID, launcher and icon names are org.opengamestudio.hello-raylib. Native raylib/GTK libraries must remain installed: packaging does not bundle them. Like hello-platform, Linux build uses existing generated Swift rather than invoking Kotlin conversion.
From hello/hello-raylib:
../../util/run-generator --file=dialect.yml
util/build-linux
util/run-linux
Validation must distinguish package-manifest, Swift syntax, Bash syntax and symlink checks on macOS from an actual Linux compilation and graphical run. On Linux verify first frame, resize/DPI changes, unrealize/realize cleanup and reinitialization, title observation and launcher/icon association. Do not infer those results from Apple/Android builds or manifest evaluation.
Checks performed for this addition on 2026-11-07: both Dialect outputs regenerated; macOS and iOS simulator builds and Android compileDebugKotlin passed. The Linux package manifest evaluated, new Swift files parsed, Bash scripts passed bash -n, and the source symlink audit found no dangling links. An actual Linux build and graphical run remain unverified: this macOS workspace has neither a Linux runtime nor GTK 4 development files. No Linux build/run success is claimed.
Reference APIs checked against the implementation: SwiftCrossUI GTK representable, GTK GLArea, GTK resize, GTK unrealize, GTK framebuffer/scale implementation, rlgl extension initialization.
GL bridge naming
The iOS EGL helper component is named glbri to avoid collisions with external EGL/egl.h headers on case-insensitive filesystems. Its source owners are components/glbri/ios/glbri.h and glbriConst.h; ver-ios/src/glbri links directly to those files. Helper functions use the glbri prefix, state is GLBriState and bridge constants/macros use GLBRI_. Native EGL API names and framework includes remain unchanged.
Windows UI-only stage
hello-raylib/ver-windows currently mirrors hello-platform/ver-windows's SwiftCrossUI and WinUIBackend skeleton. HRBApp presents HRBView and calls delegate setup from onAppear. The delegate retains HRBComponent and HRBVM, registers logging once in init, initializes the title through Dialect and applies otherSetupWindowIcon(101).
The app links hrb.swift directly from components/hrb and the SwiftCrossUI model/view directly from components/hrb/linux. It shares the generated ver-mac/src/dialect.swift without changing dialect.yml. Because that engine also references Render symbols, components/render/windows contains a placeholder VM and no-op effect/auxiliary functions; render.swift and renderConst.swift link to the macOS owners. The delegate does not create or start Render, and there is no native graphics view or bridge yet.
run-windows differs from hello-platform's entry script only by TARGET; build-windows also exports RAYLIB_DIR. Their step scripts symlink directly to hello-platform's implementations. res/AppIcon.res links to the repository resource; the shared build step exports APP_RES_DIR for resource linkage. No ANGLE dependency, DLL packaging or icon generation is part of this stage. Host manifest/syntax and symlink checks do not replace a native Windows build/run.
The Windows executable now depends on a CRaylib system-library target under src/craylib, with direct symlinks to the shared shim.h and Windows module map. It exposes rlgl.h without linking a raylib library or making graphics calls. build-windows exports RAYLIB_DIR, defaulting to a raylib checkout alongside mj; override it to select another checkout. Package.swift force-unwraps that variable and adds its src directory to the Swift Clang importer's search path. Direct manifest commands also need RAYLIB_DIR. No pkg-config installation is required.