7 Commits
Author SHA1 Message Date
Михаил Капелько 96a5684709 some 2026-10-22 16:25:06 +03:00
Михаил Капелько 01594353d8 some 2026-10-22 16:21:10 +03:00
Михаил Капелько aca30bfe6a some 2026-10-22 15:55:54 +03:00
Михаил Капелько 0af2d75754 mid smth 2026-10-22 15:37:33 +03:00
Михаил Капелько 7a0a09c2a1 prep 2026-10-22 06:43:31 +03:00
Михаил Капелько 3ae9275dd4 make chkgfx ios stub 2026-10-22 06:39:47 +03:00
Михаил Капелько b00aac5042 пусто 2026-10-22 06:24:11 +03:00
299 changed files with 1289 additions and 8749 deletions

No files matched your search

+2
View File
@@ -9,3 +9,5 @@ gradle-daemon-jvm.properties
local.properties local.properties
Package.resolved Package.resolved
*.xcodeproj *.xcodeproj
Frameworks
raylib-src
+251 -55
View File
@@ -1,73 +1,269 @@
# OGS applications (`mj`) # OGS Mahjong (`mj`)
Native SwiftUI and Compose apps on the Dialect v4 declarative reactive engine. A macOS SwiftUI app for **OGS Mahjong**, built on the **Dialect v4** declarative
Remote: `https://git.opengamestudio.org/mahjong/mahjong`. reactive engine (see the sibling `../dialect` repo — this project is a
downstream consumer of its code generator).
## Apps Business logic lives in `dialect.yml` (YAML). A generator turns it into
`game/ver-mac/src/dialect.swift` (the runtime engine + `struct F` field
constants + component/should/effect registration). The Swift app shell
(`GameApp`/`AppDelegate`) and the SwiftUI views live outside the generated file
and talk to the engine through generated functions like `rootSet(...)`.
- `hello/hello-platform/` — macOS + iOS + Android platform-support sample (Hello counter). Its Remote: `https://git.opengamestudio.org/mahjong/mahjong` · Version: `2.0.0`
structure, startup flow and dialect rules are in
[docs/hello-platform.md](docs/hello-platform.md); read that file whenever anything
from hello-platform is referenced.
## Layout > `dialect.yml` is still the "Root / counter" template with a `Render` context
> bolted on: the Mahjong game logic has not been written yet. The app shell,
> packaging, symlink wiring and the raylib renderer are in place.
- `<app>/dialect.yml` → generates `<app>/ver-mac/src/dialect.swift` and ## Structure
`<app>/ver-android/.../dialect.kt`.
- `components/` — shared source of truth; app `src/` entries are relative symlinks:
edit the real files and keep symlink parity.
- `hello-platform` uses `components/hp/` for its component, view models and views
(`mac/`, `ios/`, `android/`), and `components/other/` for shared helpers.
- `history/gitjs/` — historical JS reference, outside the build.
## Build ```
dialect.yml Single source of truth for the reactive logic.
Generates game/ver-mac/src/dialect.swift
Prereqs: sibling `../dialect` checkout (`util/build-generator`). components/ SHARED source-of-truth for all components.
other/other.swift Shared helpers (otherPrintStderr, otherWriteFile,
otherSetupConsoleLogging, ...)
raybri/raybri.h C API of the raylib bridge (raybri_config, raybri_init,
raybri_load_model, raybri_resize, raybri_set_rotation,
raybri_render, raybri_shutdown); extern "C" guards.
raybri/raybri.c Bridge implementation: rlgl scene, shadow pass, shaders.
root/root.swift RootComponent (owns DialectController, registers
effects + shoulds, sets didSetup on setup())
root/rootVM.swift RootVM (ObservableObject / @Published countText)
root/mac/view/RootView.swift SwiftUI view: RenderView in a ZStack + UI
render/render.swift RenderComponent (controller, effects + shoulds)
render/renderVM.swift RenderVM (weak shared; glView, didPrepareGL,
pixelSize, startTime, timer)
render/renderConst.swift RENDER_CONFIG (raybri_config), RENDER_FPS,
RENDER_MODEL_CUBE, RENDER_OPENGL_ATTRS
render/renderConstShader.swift Substitutes %VERSION% in the shared templates
render/renderAux.swift renderDraw(vm), renderPixelSize(view)
render/renderEffect.swift renderInit, renderLoadCubeModel,
renderStartTimer, renderDeinit
render/mac/view/RenderGLView.swift Thin NSOpenGLView: pixel format, callbacks
-> renderSet(...), draw -> renderDraw
render/mac/view/RenderView.swift NSViewRepresentable wrapper
```sh game/ver-mac/ macOS app (SPM executable target "ogs-mahjong")
cd hello/hello-platform Package.swift SPM manifest (macOS 13+, swift-tools 5.9); C target
util/build-mac "RaylibBridge" (path src/raybri, publicHeadersPath ".") +
util/run-mac links Homebrew raylib; the Swift target excludes raybri
util/prepare-ios # xcodegen; xcodebuild command is in docs/hello-platform.md and gets -Xcc -DGL_SILENCE_DEPRECATION
util/prepare-android # generate dialect.kt; gradlew command is in docs/hello-platform.md Info.plist Bundle id org.opengamestudio.Mahjong, exec ogs-mahjong
Resources/AppIcon.icns App icon
Resources/assets/ Bundled glTF assets: cube.gltf (static),
cube_texture.png, cube_normal.png
src/
GameApp.swift @main SwiftUI App entry
AppDelegate.swift Creates Render/Root components + VMs, calls setup()
dialect.swift GENERATED — do not hand-edit (see chicken-egg below)
other/other.swift -> symlink components/other/other.swift
raybri/raybri.c -> symlink components/raybri/raybri.c
raybri/raybri.h -> symlink components/raybri/raybri.h
render/render.swift -> symlink components/render/render.swift
render/renderAux.swift -> symlink components/render/renderAux.swift
render/renderConst.swift -> symlink components/render/renderConst.swift
render/renderConstShader.swift -> symlink .../renderConstShader.swift
render/renderEffect.swift -> symlink components/render/renderEffect.swift
render/renderVM.swift -> symlink components/render/renderVM.swift
render/view/RenderGLView.swift -> symlink components/render/mac/view/...
render/view/RenderView.swift -> symlink components/render/mac/view/...
root/root.swift -> symlink components/root/root.swift
root/rootVM.swift -> symlink components/root/rootVM.swift
root/view/RootView.swift -> symlink components/root/mac/view/...
ref/swiftraylib Symlink to ../../swiftraylib — the raylib/SwiftUI
renderer sample the game will use for 3D rendering.
util/ Build/run scripts (see Build & Run)
paths APP_MAC = .build/OGS Mahjong.app
build-mac generateDialect -> buildMac -> packageMac
run-mac runMac
rm-mac-geom Resets saved window geometry
step/ Sourced steps: generateDialect, buildMac,
packageMac, runMac
history/gitjs/ GitJS "Glavred" history + the original JS source of the
web Mahjong, kept for reference — not part of the build.
``` ```
`build-mac` regenerates Dialect, runs `swift build` in `ver-mac/`, then packages the ## Symlink parity rule
binary and `ver-mac/res/` into `ver-mac/.build/<App Name>.app`. `ver-ios/` mirrors
`ver-mac/` and shares `dialect.swift`, `HPView` and the app icon via symlinks.
`ver-android/` has its own generated `dialect.kt` and Compose view. Kotlin output is
LLM-transpiled: run `ollama serve` before generating (model `qwen2.5-coder:3b`).
Dangling-symlink audit:
`find components hello -type l ! -exec test -e {} \; -not -path '*/.build/*'`
iOS simulator: use **IVA** (`EB867790-F2C0-4392-9F99-C509D4487FDA`, iPhone 17, `components/` is the source of truth; `game/ver-mac/src/` contains real
iOS 26.5), not iPhone 15 Pro. Android emulator: **Small_30** (`-gpu directories whose files are **relative symlinks** back into `components/`:
swiftshader_indirect` avoids a headless crash).
## Dialect ```
src/other/other.swift -> ../../../../components/other/other.swift (4 up)
src/raybri/raybri.c -> ../../../../components/raybri/raybri.c (4 up)
src/raybri/raybri.h -> ../../../../components/raybri/raybri.h (4 up)
src/render/render.swift -> ../../../../components/render/render.swift (4 up)
src/render/renderAux.swift -> ../../../../components/render/renderAux.swift (4 up)
src/render/renderConst.swift-> ../../../../components/render/renderConst.swift (4 up)
src/render/renderConstShader.swift -> ../../../../components/render/renderConstShader.swift (4 up)
src/render/renderEffect.swift -> ../../../../components/render/renderEffect.swift (4 up)
src/render/renderVM.swift -> ../../../../components/render/renderVM.swift (4 up)
src/root/root.swift -> ../../../../components/root/root.swift (4 up)
src/root/rootVM.swift -> ../../../../components/root/rootVM.swift (4 up)
src/root/view/RootView.swift-> ../../../../../components/root/mac/view/RootView.swift (5 up)
src/render/view/RenderGLView.swift -> ../../../../../components/render/mac/view/RenderGLView.swift (5 up)
src/render/view/RenderView.swift -> ../../../../../components/render/mac/view/RenderView.swift (5 up)
```
- Edit `<app>/dialect.yml` / `components/`, then `util/build-mac`; manual edits to the SPM silently **skips** a dangling symlink (no error), so after moving
generated `dialect.swift` / `dialect.kt` are overwritten. `components/` or a subdir, audit for broken links:
- `struct F` (field names) exists only in the generated files: a new field needs
`static let <field> = "<field>"` hand-patched in ASCII order in both ```bash
`dialect.swift` and `dialect.kt` or `F.<field>` will not build. find . -type l ! -exec test -e {} \; -not -path './.build/*'
- Validate: `ruby -ryaml -e 'YAML.load_file("hello/hello-platform/dialect.yml")'`. ```
Every should-label (`1. Upon each ...`) MUST end with a colon —
`../dialect/components/yml/ymlFun.swift` blindly `dropLast()`s it. Complaints ## Prerequisite: the generator
inside `if:`/`then:` (unquoted `: `) are expected.
`util/step/generateDialect` calls the **sibling** dialect repo:
```bash
$SDIR/../../dialect/util/run-generator --file=$SDIR/../dialect.yml
```
So `/Volumes/MOE/p/dialect` must exist and its generator must be built before
`util/build-mac` can regenerate:
```bash
(cd ../dialect && util/build-generator) # once, or after dialect core changes
```
The generator resolves the `output:` path **relative to `dialect.yml`'s
directory**, which is why `dialect.yml` says `game/ver-mac/src/dialect.swift`.
## Prerequisite: raylib
The 3D scene links against Homebrew **raylib** (`brew install raylib`). The
`RaylibBridge` C target and the link step read `RAYLIB_PREFIX` (default
`/opt/homebrew`); `util/step/buildMac` auto-detects it via `brew --prefix raylib`.
The bridge renders with raylib's rlgl layer into an `NSOpenGLView` — raylib never
creates its own window. `RootView` puts `RenderView` (backed by `RenderGLView`)
behind the SwiftUI UI in a `ZStack`. A textured cube is drawn from `Resources/assets` (`cube.gltf` +
`cube_texture.png` + `cube_normal.png`); the app rotates it each frame via `raybri_set_rotation`.
(raylib's `LoadModelAnimations` only handles *skinned* meshes, so a plain
node-rotation glTF animation cannot be played by the renderer — hence the cube is
app-driven.) `packageMac` bundles `Resources/assets/` into the app.
Shaders live in **Swift** and are shared by both builds: the GLSL bodies are
the `RENDER_SHADER_*_T` templates in
`components/render/renderConstShader.swift`, each starting with the `%VERSION%`
placeholder. The `RENDER_SHADER_*` sources passed to `raybri_init` are produced
by `replacingOccurrences`, choosing `RENDER_SHADER_VERSION_GL` (`#version 150`)
or `RENDER_SHADER_VERSION_ES` (`#version 300 es`) via `#if os(iOS)`. The
directive must be the first shader token, so it cannot be picked by an `#ifdef`
inside the GLSL. Fragment templates also carry `precision highp float;` —
required by GLSL ES, accepted and ignored by desktop GLSL. The iOS ObjC++ bridge
reaches the strings through `@_cdecl` accessors in `RenderIOS.swift`. `RENDER_CONFIG` / `raybri_config` tunables stay in `renderConst.swift`.
`raybri_init` compiles the shaders in place (no storage/`strdup`).
`cube_normal.png` drives tangentless normal mapping via the derivative-based
`cotangentFrame`. The context is OpenGL 3.2 Core (`RENDER_OPENGL_ATTRS`); on
Apple Silicon the driver still reports 4.1/GLSL 4.10.
## Render architecture
The `Render` dialect context owns the GL scene. `RenderGLView` is a thin
`NSOpenGLView`; it only translates AppKit callbacks into dialect fields, and the
`render*` files do the actual work.
1. `AppDelegate` creates `RenderComponent` + `RenderVM` and calls
`render.setup()` -> `didSetup` -> `didLaunch` (should) -> `pixelSize = [1, 1]`.
2. SwiftUI builds `RenderView` -> `RenderGLView`; `prepareOpenGL()` sets
`F.didPrepareGL`. Its oneliners run `renderInit` (`raybri_init`), set
`RenderVM.didPrepareGL = true`, and `renderStartTimer`.
3. `reshape()` / `viewDidChangeBackingProperties()` compute the backing pixel
size via `renderPixelSize` and set `F.reshapePixelSize` /
`F.backingPixelSize`. The `pixelSize` shoulds fold these into `F.pixelSize`,
whose oneliner stores `RenderVM.pixelSize`.
4. The timer only sets `needsDisplay` every `1 / RENDER_FPS`. `draw(_:)` forwards
to `renderDraw` (make context current, `raybri_resize`, `raybri_set_rotation`,
`raybri_render`, `flushBuffer`).
5. A button click runs `rootSet(F.didClickIncrement)` -> RootComponent oneliner
`renderSet(F.didClickIncrement)` -> `renderLoadCubeModel` (the cube is loaded
on demand, not at startup).
6. `RenderGLView.deinit` sets `F.willDeinit` -> `renderDeinit` (stop timer,
`raybri_shutdown`).
**GL context rule**: every raylib call must run with the view's context current.
`renderInit`, `renderLoadCubeModel`, `renderDeinit` and `renderDraw` all call
`openGLContext?.makeCurrentContext()` first. Loading a model/texture without it
fails silently with `WARNING: TEXTURE: Failed to load texture`.
## Build & Run
```bash
util/build-mac # generateDialect + swift build + package OGS Mahjong.app
util/run-mac # runs .build/OGS Mahjong.app/Contents/MacOS/ogs-mahjong
util/rm-mac-geom # reset the app's saved window geometry
```
`build-mac` sources `util/paths` then the `util/step/*` scripts in order:
1. `generateDialect` — runs the sibling generator, writes `src/dialect.swift`
2. `buildMac` — `brew --prefix raylib` -> `RAYLIB_PREFIX`, `swift build`
3. `packageMac` — assembles `.build/OGS Mahjong.app` (binary `ogs-mahjong`,
`Info.plist`, `Resources/AppIcon.icns`, `Resources/assets/`)
## Editing the dialect
- Add/modify contexts and components in `dialect.yml`, then run
`util/build-mac` to regenerate `dialect.swift`.
- **Chicken-egg**: `struct F` (field-name constants) lives only in the
generated `dialect.swift`. Adding a new field to a context in `dialect.yml`
requires hand-patching its `static let <field> = "<field>"` into `struct F`
in `dialect.swift` (ASCII-alphabetical order) if you cannot regenerate first,
otherwise the build fails on `F.<field>` being unresolved.
- `dialect.swift` is generated — edits there are overwritten on the next
`util/build-mac`. Change the source (`dialect.yml` / `components/`) instead.
- **Validate `dialect.yml` after edits** (e.g. `ruby -ryaml -e 'YAML.load_file("dialect.yml")'`).
Every should-branch label (`1. Upon each ...`) MUST end with a colon — the
parser (`components/yml/ymlFun.swift`) blindly `dropLast()`s it, so a missing
colon silently eats the label's last character in the generated `about`
comment. Note the file can never pass a *strict* YAML parser: condition and
reaction lines (under `if:` / `then:`) contain unquoted `: ` (e.g.
`c.countText = "Count: '\(c.count)'"`), which standard YAML rejects. So treat
a parser complaint pointing *inside* an `if:`/`then:` block as expected; any
complaint elsewhere (like a missing branch-label colon) is a real bug.
## Swift 6
The project currently builds in Swift 5 language mode
(`util/step/buildMac` has the Swift 6 flag commented out). Enabling
`-Xswiftc -swift-version -Xswiftc 6` fails today on the singleton/`@MainActor`
concurrency errors (`RootComponent.singleton`, `RootVM.shared` in
`components/root/`, `RenderComponent.singleton`, `RenderVM.shared` in
`components/render/`, and the `RootVM.shared!.countText = ...` /
`RenderVM.shared!.pixelSize = ...` oneliners in the generated `dialect.swift`).
Do not flip it on without addressing those.
## Conventions ## Conventions
- Mirror Swift/iOS into Android (naming, text, layout, styling). - `game/ver-mac/.build/`, `build/`, `.DS_Store`, Xcode/Gradle artifacts are
- Compose: named `MaterialTheme.typography` styles over `fontSize`. git-ignored.
- Kotlin: wildcard imports for multiple declarations from one package, including - Prefer editing files in `components/` (the real files); the `src/` entries are
generated ones; subpackages need separate imports. symlinks.
- `.build/`, `build/`, `.DS_Store`, Xcode/Gradle artifacts are git-ignored. - The generated UI callback plumbing is nonisolated; UI singletons are weak
(`RootComponent.singleton`, `RootVM.shared`, `RenderComponent.singleton`,
`RenderVM.shared`) and are accessed from the generated oneliners with
force-unwrap (`RootVM.shared!.countText = ...`, `RenderVM.shared!.pixelSize = ...`).
- Never call raylib / `raybri_*` without making the view's GL context current first
(see the GL context rule above).
## Source studies ## Skill: source-file study documents
When the task is to produce a source-code study document — a self-contained,
downloadable HTML file with a line-by-line table of the file and its
explanations (and, on request, a second version highlighting changes after a
fix) — follow the skill in `docs/file-summary.md`.
- Write the result to `docs/<FileName>.html` (e.g. `docs/RaylibGLView.html`) and
name the file's Git revision in the header. The file is the source of truth —
document the exact revision requested, not the working tree.
- Existing example: `docs/RaylibGLView.html` — documents the historical
single-cube `RaylibGLView.swift`, since split into `RenderGLView.swift` plus
the `render*` files.
Follow [docs/file-summary.md](docs/file-summary.md) (single-file) and
[docs/mirror-summary.md](docs/mirror-summary.md) (mirrored platforms: one
self-contained HTML with aligned function starts, original line numbers, green/orange
fills, counts, non-repetitive explanations); never substitute working-tree code for a
requested historical revision.
+4 -27
View File
@@ -1,32 +1,9 @@
## Prerequisites ## Prerequisites
### macOS * macOS
* `brew install raylib` `brew install raylib`
### iOS * iOS
* `brew install xcodegen` `brew install xcodegen`
* ghera's [raylib-ios-xcframeworks][rzip] release unpacked and placed alongside the project
### Android
* Android Studio Quail 3 (2026.1.3)
### Linux
* Ubuntu 24.04
* [Swiftly][swiftly] + Swift (installed by Swiftly)
* Swift dependencies (proposed by Swiftly after Swift installation)
`apt-get -y install binutils git gnupg2 libcurl4-openssl-dev libgcc-13-dev libpython3-dev libstdc++-13-dev libxml2-dev libncurses-dev libz3-dev pkg-config zlib1g-dev`
* CrossSwiftUI dependency
`apt-get -y install libgtk-4-dev`
## Components
| Component | macOS | iOS | Android | Linux | Windows | Description |
| --- | --- | --- | --- | --- | --- | --- |
| hp | √ | √ | √ | ? | | **h**ello-**p**latform is a simple UI to validate platform support |
[rzip]: https://github.com/ghera/raylib-iOS/releases/download/6.2.0-iOS/raylib-ios-xcframeworks-6.2.0-iOS.zip
[swiftly]: https://www.swift.org/install/linux/
+1
View File
@@ -0,0 +1 @@
2.0.0
-14
View File
@@ -1,14 +0,0 @@
package org.opengamestudio
object BlueComponent {
val ctrl = DialectController(BlueContext())
init {
blueRegisterEffects(ctrl)
blueRegisterShoulds(ctrl)
}
fun setup() {
blueSet(F.didSetup, true)
}
}
-31
View File
@@ -1,31 +0,0 @@
package org.opengamestudio
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.*
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
@Composable
fun BlueView() {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(16.dp),
modifier = Modifier.padding(40.dp)
) {
Box(contentAlignment = Alignment.Center) {
Text(
text = "Blue",
style = MaterialTheme.typography.headlineLarge,
color = Color.White,
modifier = Modifier.offset(x = 1.dp, y = 1.dp)
)
Text(
text = "Blue",
style = MaterialTheme.typography.headlineLarge,
color = Color.Black
)
}
}
}
-14
View File
@@ -1,14 +0,0 @@
class BlueComponent {
let ctrl = DialectController(BlueContext())
static private(set) weak var singleton: BlueComponent?
init() {
Self.singleton = self
//blueRegisterEffects(ctrl)
blueRegisterShoulds(ctrl)
}
func setup() {
blueSet(F.didSetup, true)
}
}
-9
View File
@@ -1,9 +0,0 @@
import Combine
final class BlueVM: ObservableObject {
static private(set) weak var shared: BlueVM?
init() {
Self.shared = self
}
}
-1
View File
@@ -1 +0,0 @@
../../mac/view/BlueView.swift
-24
View File
@@ -1,24 +0,0 @@
import SwiftUI
struct BlueView: View {
@ObservedObject var vm: BlueVM
init(_ vm: BlueVM) {
self.vm = vm
}
var body: some View {
VStack(spacing: 16) {
ZStack {
Text("Blue")
.font(.largeTitle)
.foregroundStyle(.white)
.offset(x: 1, y: 1)
Text("Blue")
.font(.largeTitle)
.foregroundStyle(.black)
}
}
.padding(40)
}
}
-87
View File
@@ -1,87 +0,0 @@
#ifndef EGL_H
#define EGL_H
#include "eglConst.h"
#include <libEGL/libEGL.h>
#include <libGLESv2/GLES/gl.h>
#include <stdbool.h>
typedef struct EGLState {
void *caLayer;
EGLConfig cfg;
EGLContext ctx;
EGLDisplay display;
EGLSurface surface;
} EGLState;
bool eglInit(EGLState *st);
bool eglMakeCurrentContext(EGLState *st);
bool eglResetSurface(EGLState *st);
// Source
#if defined(EGL_IMPLEMENTATION)
bool eglInit(EGLState *st) {
st->display = eglGetDisplay(EGL_DEFAULT_DISPLAY);
if (st->display == EGL_NO_DISPLAY) {
return false;
}
if (eglInitialize(st->display, NULL, NULL) == EGL_FALSE) {
return false;
}
if (eglBindAPI(EGL_OPENGL_ES_API) == EGL_FALSE) {
return false;
}
EGLint cfgCount = 0;
if (
eglChooseConfig(st->display, EGL_CFG, &st->cfg, 1, &cfgCount) == EGL_FALSE ||
cfgCount < 1
) {
return false;
}
st->ctx = eglCreateContext(st->display, st->cfg, EGL_NO_CONTEXT, EGL_CTX);
if (st->ctx == EGL_NO_CONTEXT) {
return false;
}
return true;
}
bool eglMakeCurrentContext(EGLState *st) {
if (eglMakeCurrent(st->display, st->surface, st->surface, st->ctx) == EGL_FALSE) {
return false;
}
return true;
}
bool eglResetSurface(EGLState *st) {
// Destroy previous surface
if (st->surface != EGL_NO_SURFACE) {
eglDestroySurface(st->display, st->surface);
st->surface = EGL_NO_SURFACE;
}
// Create new surface
// ANGLE on iOS takes a CALayer as the native window
st->surface = eglCreateWindowSurface(
st->display,
st->cfg,
(EGLNativeWindowType)st->caLayer,
NULL
);
if (st->surface == EGL_NO_SURFACE) {
return false;
}
return true;
}
#endif // EGL_IMPLEMENTATION
#endif // EGL_H
-33
View File
@@ -1,33 +0,0 @@
#ifndef EGL_CONST_H
#define EGL_CONST_H
#include <libEGL/libEGL.h>
// Header
extern const EGLint EGL_CFG[];
extern const EGLint EGL_CTX[];
// Source
#if defined(EGL_CONST_IMPLEMENTATION)
const EGLint EGL_CFG[] = {
EGL_RENDERABLE_TYPE, EGL_OPENGL_ES3_BIT,
EGL_SURFACE_TYPE, EGL_WINDOW_BIT,
EGL_RED_SIZE, 8,
EGL_GREEN_SIZE, 8,
EGL_BLUE_SIZE, 8,
EGL_ALPHA_SIZE, 8,
EGL_DEPTH_SIZE, 16,
EGL_NONE
};
const EGLint EGL_CTX[] = {
EGL_CONTEXT_CLIENT_VERSION, 3,
EGL_NONE
};
#endif // EGL_CONST_IMPLEMENTATION
#endif // EGL_CONST_H
-14
View File
@@ -1,14 +0,0 @@
package org.opengamestudio
object HPComponent {
val ctrl = DialectController(HPContext())
init {
hpRegisterEffects(ctrl)
hpRegisterShoulds(ctrl)
}
fun setup() {
hpSet(F.didSetup, true)
}
}
-10
View File
@@ -1,10 +0,0 @@
package org.opengamestudio
import androidx.compose.runtime.*
object HPVM {
var countText by mutableStateOf("")
var shared: HPVM? = this
private set
}
-34
View File
@@ -1,34 +0,0 @@
package org.opengamestudio
import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.*
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.dp
@Composable
fun HPView() {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
modifier = Modifier.padding(40.dp),
verticalArrangement = Arrangement.spacedBy(16.dp)
) {
Text(
style = MaterialTheme.typography.headlineLarge,
text = "Hello, platform!"
)
Text(
fontFamily = FontFamily.Monospace,
style = MaterialTheme.typography.titleMedium,
text = HPVM.countText
)
Button(
onClick = { hpSet(F.didClickIncrement, true) }
) {
Text("Increment")
}
}
}
-14
View File
@@ -1,14 +0,0 @@
class HPComponent {
let ctrl = DialectController(HPContext())
static private(set) weak var singleton: HPComponent?
init() {
Self.singleton = self
hpRegisterEffects(ctrl)
hpRegisterShoulds(ctrl)
}
func setup() {
hpSet(F.didSetup, true)
}
}
-11
View File
@@ -1,11 +0,0 @@
import Combine
final class HPVM: ObservableObject {
@Published var countText = ""
static private(set) weak var shared: HPVM?
init() {
Self.shared = self
}
}
-1
View File
@@ -1 +0,0 @@
../../../hp/mac/view/HPView.swift
-1
View File
@@ -1 +0,0 @@
../hp.swift
-11
View File
@@ -1,11 +0,0 @@
import SwiftCrossUI
final class HPVM: ObservableObject {
@Published var countText = ""
static private(set) weak var shared: HPVM?
init() {
Self.shared = self
}
}
-22
View File
@@ -1,22 +0,0 @@
import SwiftCrossUI
struct HPView: View {
@State var vm: HPVM
init(_ vm: HPVM) {
self.vm = vm
}
var body: some View {
VStack(spacing: 16) {
Text("Hello, platform!")
.font(.largeTitle)
Text(vm.countText)
.font(.title3.monospaced())
Button("Increment") {
hpSet(F.didClickIncrement, true)
}
}
.padding(40)
}
}
-22
View File
@@ -1,22 +0,0 @@
import SwiftUI
struct HPView: View {
@ObservedObject var vm: HPVM
init(_ vm: HPVM) {
self.vm = vm
}
var body: some View {
VStack(spacing: 16) {
Text("Hello, platform!")
.font(.largeTitle)
Text(vm.countText)
.font(.title3.monospaced())
Button("Increment") {
hpSet(F.didClickIncrement, true)
}
}
.padding(40)
}
}
+8
View File
@@ -0,0 +1,8 @@
#ifndef OTHER_BRIDGING_HEADER_H
#define OTHER_BRIDGING_HEADER_H
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <QuartzCore/QuartzCore.h>
#endif
-16
View File
@@ -1,16 +0,0 @@
package org.opengamestudio
fun otherPrintStderr(txt: String) {
System.err.println(txt)
}
fun otherSetupConsoleLogging(
ctrl: DialectController,
prefix: String
) {
ctrl.registerCallback { c ->
val value = c.fieldAny(c.recentField)
val line = "ИГР $prefix k/v: '${c.recentField}'/'$value'"
otherPrintStderr(line)
}
}
-41
View File
@@ -1,41 +0,0 @@
#ifndef RAYBRI_AUX_H
#define RAYBRI_AUX_H
// Header
void *raybriGLLoader(const char *name);
void raybriLoadExtensions(void);
// Source
#if defined(RAYBRI_AUX_IMPLEMENTATION)
#include <dlfcn.h>
#include "raybriConst.h"
#include "rlgl.h"
#include <stddef.h>
// raylib is built as a static/dynamic library with GLFW baked in, but we never
// call InitWindow(). Instead we render into an OpenGL context owned by the
// macOS app, so we must supply the OpenGL entry point loader ourselves.
void *raybriGLLoader(const char *name) {
static void *handle = NULL;
if (handle == NULL) {
handle = dlopen(RAYBRI_MAC_GL, RTLD_LAZY | RTLD_LOCAL);
}
if (handle == NULL) {
return NULL;
}
return dlsym(handle, name);
}
void raybriLoadExtensions(void) {
rlLoadExtensions(raybriGLLoader);
}
#endif // RAYBRI_AUX_IMPLEMENTATION
#endif // RAYBRI_AUX_H
+455
View File
@@ -0,0 +1,455 @@
#include "raybri.h"
#include "raylib.h"
#include "rlgl.h"
#include "raymath.h"
#include <math.h>
#include <stddef.h>
#include <stdio.h>
#include <string.h>
#if !defined(PLATFORM_IOS)
#include <dlfcn.h>
#endif
static int sr_width = 1;
static int sr_height = 1;
// Render configuration supplied by the application (see renderConst.swift).
static raybri_config sr_cfg = { 0 };
// Cube transform (driven by the application, Euler degrees).
static float sr_rot_x = 0.0f;
static float sr_rot_y = 0.0f;
static float sr_rot_z = 0.0f;
static int sr_ready = 0;
static Model sr_model = { 0 };
static int sr_has_model = 0;
static Material sr_cube_material = { 0 };
static Material sr_cube_shadow_material = { 0 };
static Texture2D sr_cube_normal = { 0 };
static Model sr_ground_model = { 0 };
static Material sr_ground_material = { 0 };
static Material sr_ground_shadow_material = { 0 };
static Shader sr_main_shader = { 0 };
static Shader sr_shadow_shader = { 0 };
static int sr_shadow_fbo = 0;
static unsigned int sr_shadow_color = 0;
static unsigned int sr_shadow_depth = 0;
static Matrix sr_light_view = { 0 };
static Matrix sr_light_proj = { 0 };
static Vector3 sr_light_pos = { 0.0f, 0.0f, 0.0f };
// Main shader uniform locations
static int loc_light_pos = -1;
static int loc_light_color = -1;
static int loc_ambient = -1;
static int loc_light_enabled = -1;
static int loc_emissive = -1;
static int loc_albedo_color = -1;
static int loc_shadow_map = -1;
static int loc_shadow_bias = -1;
static int loc_shadow_softness = -1;
static int loc_normal_map = -1;
static int loc_normal_strength = -1;
static int loc_light_mvp = -1;
static int loc_is_ground = -1;
static int loc_grid_color = -1;
static int loc_camera_pos = -1;
static int loc_fog_color = -1;
static int loc_fog_start = -1;
static int loc_fog_end = -1;
#if !defined(PLATFORM_IOS)
// raylib is built as a static/dynamic library with GLFW baked in, but we never
// call InitWindow(). Instead we render into an OpenGL context owned by the
// macOS app, so we must supply the OpenGL entry point loader ourselves.
static void *sr_gl_loader(const char *name)
{
static void *handle = NULL;
if (handle == NULL)
{
handle = dlopen("/System/Library/Frameworks/OpenGL.framework/OpenGL", RTLD_LAZY | RTLD_LOCAL);
}
if (handle == NULL) return NULL;
return dlsym(handle, name);
}
#endif
// Compose a model transform exactly like raylib's DrawModel() does, so the
// matrices we feed to DrawMesh() match what rlgl computes internally.
static Matrix sr_transform(Vector3 pos, float scale, float rx, float ry, float rz)
{
Matrix mat_scale = MatrixScale(scale, scale, scale);
Matrix mat_rotation = MatrixRotateXYZ((Vector3){ rx * DEG2RAD, ry * DEG2RAD, rz * DEG2RAD });
Matrix mat_translation = MatrixTranslate(pos.x, pos.y, pos.z);
return MatrixMultiply(MatrixMultiply(mat_scale, mat_rotation), mat_translation);
}
static void sr_load_shaders(const char *main_vs, const char *main_fs,
const char *shadow_vs, const char *shadow_fs)
{
sr_main_shader = LoadShaderFromMemory(main_vs, main_fs);
sr_shadow_shader = LoadShaderFromMemory(shadow_vs, shadow_fs);
loc_light_pos = GetShaderLocation(sr_main_shader, "u_lightPos");
loc_light_color = GetShaderLocation(sr_main_shader, "u_lightColor");
loc_ambient = GetShaderLocation(sr_main_shader, "u_ambient");
loc_light_enabled = GetShaderLocation(sr_main_shader, "u_lightEnabled");
loc_emissive = GetShaderLocation(sr_main_shader, "u_emissive");
loc_albedo_color = GetShaderLocation(sr_main_shader, "u_albedoColor");
loc_shadow_map = GetShaderLocation(sr_main_shader, "u_shadowMap");
loc_shadow_bias = GetShaderLocation(sr_main_shader, "u_shadowBias");
loc_shadow_softness = GetShaderLocation(sr_main_shader, "u_shadowSoftness");
loc_normal_map = GetShaderLocation(sr_main_shader, "u_normalMap");
loc_normal_strength = GetShaderLocation(sr_main_shader, "u_normalStrength");
loc_light_mvp = GetShaderLocation(sr_main_shader, "u_lightMVP");
loc_is_ground = GetShaderLocation(sr_main_shader, "u_isGround");
loc_grid_color = GetShaderLocation(sr_main_shader, "u_gridColor");
loc_camera_pos = GetShaderLocation(sr_main_shader, "u_cameraPos");
loc_fog_color = GetShaderLocation(sr_main_shader, "u_fogColor");
loc_fog_start = GetShaderLocation(sr_main_shader, "u_fogStart");
loc_fog_end = GetShaderLocation(sr_main_shader, "u_fogEnd");
// Build a framebuffer whose depth attachment is a sampleable TEXTURE (raylib's
// LoadRenderTexture() uses a non-sampleable renderbuffer, so we build it by hand).
sr_shadow_fbo = rlLoadFramebuffer();
sr_shadow_color = rlLoadTexture(NULL, sr_cfg.shadow_size, sr_cfg.shadow_size, RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8, 1);
sr_shadow_depth = rlLoadTextureDepth(sr_cfg.shadow_size, sr_cfg.shadow_size, false);
rlEnableFramebuffer(sr_shadow_fbo);
rlFramebufferAttach(sr_shadow_fbo, sr_shadow_color, RL_ATTACHMENT_COLOR_CHANNEL0, RL_ATTACHMENT_TEXTURE2D, 0);
rlFramebufferAttach(sr_shadow_fbo, sr_shadow_depth, RL_ATTACHMENT_DEPTH, RL_ATTACHMENT_TEXTURE2D, 0);
int shadow_ok = rlFramebufferComplete(sr_shadow_fbo);
fprintf(stderr, "SR: shadow framebuffer %s\n", shadow_ok ? "complete" : "INCOMPLETE");
rlDisableFramebuffer();
}
static void sr_build_ground(void)
{
Mesh ground_mesh = GenMeshPlane(sr_cfg.ground_size, sr_cfg.ground_size, 1, 1);
sr_ground_model = LoadModelFromMesh(ground_mesh);
sr_ground_material = LoadMaterialDefault();
sr_ground_material.shader = sr_main_shader;
sr_ground_shadow_material = LoadMaterialDefault();
sr_ground_shadow_material.shader = sr_shadow_shader;
}
// Uniforms that never change between frames are uploaded once at startup.
// SetShaderValue() is a bare glUniform*(), so the program must be bound.
static void sr_config_shaders(void)
{
sr_light_pos = (Vector3){ 0.0f, 4.2f, 0.0f };
Vector3 light_color = { 1.15f, 1.08f, 0.98f };
Vector3 ambient = { 0.30f, 0.32f, 0.38f };
Vector3 grid_color = { 0.45f, 0.62f, 0.95f };
Vector3 fog_color = { 24.0f / 255.0f, 26.0f / 255.0f, 34.0f / 255.0f };
Vector3 camera_pos = { 0.0f, 2.6f, 5.6f };
float albedo[3] = { 1.0f, 1.0f, 1.0f };
float light_amount = 1.0f;
float shadow_bias = 0.0025f;
float shadow_softness = 4.0f;
float fog_start = 10.0f;
float fog_end = 34.0f;
int shadow_unit = 1;
int normal_unit = 2;
rlEnableShader(sr_main_shader.id);
SetShaderValue(sr_main_shader, loc_light_pos, &sr_light_pos, SHADER_UNIFORM_VEC3);
SetShaderValue(sr_main_shader, loc_light_color, &light_color, SHADER_UNIFORM_VEC3);
SetShaderValue(sr_main_shader, loc_ambient, &ambient, SHADER_UNIFORM_VEC3);
SetShaderValue(sr_main_shader, loc_light_enabled, &light_amount, SHADER_UNIFORM_FLOAT);
SetShaderValue(sr_main_shader, loc_shadow_bias, &shadow_bias, SHADER_UNIFORM_FLOAT);
SetShaderValue(sr_main_shader, loc_shadow_softness, &shadow_softness, SHADER_UNIFORM_FLOAT);
SetShaderValue(sr_main_shader, loc_grid_color, &grid_color, SHADER_UNIFORM_VEC3);
SetShaderValue(sr_main_shader, loc_camera_pos, &camera_pos, SHADER_UNIFORM_VEC3);
SetShaderValue(sr_main_shader, loc_fog_color, &fog_color, SHADER_UNIFORM_VEC3);
SetShaderValue(sr_main_shader, loc_fog_start, &fog_start, SHADER_UNIFORM_FLOAT);
SetShaderValue(sr_main_shader, loc_fog_end, &fog_end, SHADER_UNIFORM_FLOAT);
SetShaderValue(sr_main_shader, loc_albedo_color, albedo, SHADER_UNIFORM_VEC3);
SetShaderValue(sr_main_shader, loc_shadow_map, &shadow_unit, SHADER_UNIFORM_INT);
SetShaderValue(sr_main_shader, loc_normal_map, &normal_unit, SHADER_UNIFORM_INT);
rlDisableShader();
}
void raybri_init(
const char *main_vs,
const char *main_fs,
const char *shadow_vs,
const char *shadow_fs,
raybri_config config
) {
sr_cfg = config;
// raylib's default INFO logging is noisy; keep warnings and errors only.
SetTraceLogLevel(LOG_WARNING);
#if !defined(PLATFORM_IOS)
rlLoadExtensions((void *)sr_gl_loader);
// Init with default 1x1 size
rlglInit(1, 1);
#else
// On iOS the prebuilt raylib (ghera/raylib-iOS) already calls
// rlLoadExtensions() and rlglInit() inside InitWindow(); skip here.
#endif
sr_load_shaders(main_vs, main_fs, shadow_vs, shadow_fs);
sr_config_shaders();
sr_build_ground();
sr_ready = 1;
}
void raybri_load_model(const char *gltf_path)
{
if (!sr_ready || gltf_path == NULL) return;
sr_model = LoadModel(gltf_path);
sr_has_model = (sr_model.meshCount > 0);
// The matching normal map sits next to the glTF; load it separately.
char asset_dir[1024];
const char *slash = strrchr(gltf_path, '/');
size_t dir_len = (slash != NULL) ? (size_t)(slash - gltf_path + 1) : 0;
snprintf(asset_dir, sizeof(asset_dir), "%.*s", (int)dir_len, gltf_path);
if (sr_has_model)
{
fprintf(stderr, "SR: model loaded: %s (%d meshes, %d materials)\n",
gltf_path, sr_model.meshCount, sr_model.materialCount);
int cube_mat_index = (sr_model.materialCount > 0) ? sr_model.meshMaterial[0] : 0;
sr_cube_material = sr_model.materials[cube_mat_index];
sr_cube_material.shader = sr_main_shader;
Texture2D base_tex = sr_cube_material.maps[MATERIAL_MAP_DIFFUSE].texture;
SetTextureFilter(base_tex, TEXTURE_FILTER_BILINEAR);
SetTextureWrap(base_tex, TEXTURE_WRAP_CLAMP);
char normal_path[1024];
snprintf(normal_path, sizeof(normal_path), "%scube_normal.png", asset_dir);
if (FileExists(normal_path))
{
sr_cube_normal = LoadTexture(normal_path);
SetTextureFilter(sr_cube_normal, TEXTURE_FILTER_BILINEAR);
SetTextureWrap(sr_cube_normal, TEXTURE_WRAP_CLAMP);
}
sr_cube_shadow_material = sr_cube_material;
sr_cube_shadow_material.shader = sr_shadow_shader;
}
else
{
fprintf(stderr, "SR: failed to load model: %s\n", gltf_path);
}
}
void raybri_resize(int width, int height)
{
if (width > 0) sr_width = width;
if (height > 0) sr_height = height;
}
void raybri_set_rotation(float x_deg, float y_deg, float z_deg)
{
sr_rot_x = x_deg;
sr_rot_y = y_deg;
sr_rot_z = z_deg;
}
static Matrix sr_cube_transform(void)
{
return sr_transform((Vector3){ 0.0f, 1.1f, 0.0f }, 1.0f, sr_rot_x, sr_rot_y, sr_rot_z);
}
static void sr_draw_object(Model model, Material material, Matrix model_mat,
Texture2D normal, float is_ground, float emissive);
static void sr_render_main_pass(void)
{
// --- Main pass: camera ---
rlViewport(0, 0, sr_width, sr_height);
rlSetFramebufferWidth(sr_width);
rlSetFramebufferHeight(sr_height);
rlClearColor(24, 26, 34, 255);
rlClearScreenBuffers();
rlMatrixMode(RL_PROJECTION);
rlPushMatrix();
rlLoadIdentity();
float aspect = (float)sr_width / (float)sr_height;
double top = (double)sr_cfg.near_plane * tan((double)sr_cfg.fov_y * 0.5 * DEG2RAD);
double right = top * (double)aspect;
rlFrustum(-right, right, -top, top, (double)sr_cfg.near_plane, (double)sr_cfg.far_plane);
rlMatrixMode(RL_MODELVIEW);
rlLoadIdentity();
Vector3 eye = { 0.0f, 2.6f, 5.6f };
Vector3 target = { 0.0f, 1.0f, 0.0f };
Vector3 up = { 0.0f, 1.0f, 0.0f };
Matrix view = MatrixLookAt(eye, target, up);
rlMultMatrixf(MatrixToFloat(view));
rlEnableDepthTest();
rlEnableBackfaceCulling();
rlSetCullFace(RL_CULL_FACE_BACK);
rlEnableShader(sr_main_shader.id);
rlActiveTextureSlot(1);
rlEnableTexture(sr_shadow_depth);
rlActiveTextureSlot(0);
// --- Ground (procedural grid floor) ---
sr_draw_object(sr_ground_model, sr_ground_material, MatrixTranslate(0.0f, 0.0f, 0.0f), (Texture2D){ 0 }, 1.0f, 0.0f);
// --- Cubes ---
if (sr_has_model)
{
sr_draw_object(sr_model, sr_cube_material, sr_cube_transform(), sr_cube_normal, 0.0f, 0.0f);
}
// Flush while the projection/modelview matrices are still active, otherwise
// rlgl draws the pending batch with the restored (2D) projection.
rlDrawRenderBatchActive();
// --- Restore matrices (equivalent to raylib's EndMode3D) ---
rlMatrixMode(RL_PROJECTION);
rlPopMatrix();
rlMatrixMode(RL_MODELVIEW);
rlLoadIdentity();
rlDisableDepthTest();
rlDisableBackfaceCulling();
}
static void sr_render_shadow_pass(void)
{
rlViewport(0, 0, sr_cfg.shadow_size, sr_cfg.shadow_size);
rlSetFramebufferWidth(sr_cfg.shadow_size);
rlSetFramebufferHeight(sr_cfg.shadow_size);
rlEnableFramebuffer(sr_shadow_fbo);
rlClearColor(255, 255, 255, 255);
rlClearScreenBuffers();
rlEnableDepthTest();
rlEnableBackfaceCulling();
rlSetCullFace(RL_CULL_FACE_FRONT);
rlMatrixMode(RL_PROJECTION);
rlPushMatrix();
rlLoadIdentity();
rlMultMatrixf(MatrixToFloat(sr_light_proj));
rlMatrixMode(RL_MODELVIEW);
rlLoadIdentity();
rlMultMatrixf(MatrixToFloat(sr_light_view));
if (sr_has_model)
{
DrawMesh(sr_model.meshes[0], sr_cube_shadow_material, sr_cube_transform());
}
rlDrawRenderBatchActive();
rlMatrixMode(RL_PROJECTION);
rlPopMatrix();
rlSetCullFace(RL_CULL_FACE_BACK);
rlDisableFramebuffer();
rlViewport(0, 0, sr_width, sr_height);
rlSetFramebufferWidth(sr_width);
rlSetFramebufferHeight(sr_height);
rlDisableDepthTest();
}
static void sr_set_light_mvp(Matrix model)
{
Matrix light_mvp = MatrixMultiply(MatrixMultiply(model, sr_light_view), sr_light_proj);
SetShaderValueMatrix(sr_main_shader, loc_light_mvp, light_mvp);
}
static void sr_bind_normal(Texture2D tex)
{
rlActiveTextureSlot(2);
if (tex.id > 0) rlEnableTexture(tex.id);
rlActiveTextureSlot(0);
}
static void sr_draw_object(Model model, Material material, Matrix model_mat,
Texture2D normal, float is_ground, float emissive)
{
sr_set_light_mvp(model_mat);
float normal_strength = (normal.id > 0) ? 1.0f : 0.0f;
SetShaderValue(sr_main_shader, loc_emissive, &emissive, SHADER_UNIFORM_FLOAT);
SetShaderValue(sr_main_shader, loc_is_ground, &is_ground, SHADER_UNIFORM_FLOAT);
SetShaderValue(sr_main_shader, loc_normal_strength, &normal_strength, SHADER_UNIFORM_FLOAT);
sr_bind_normal(normal);
DrawMesh(model.meshes[0], material, model_mat);
}
void raybri_render(void)
{
if (!sr_ready) return;
rlDrawRenderBatchActive();
// --- Light (point light above the scene) ---
Vector3 light_target = (Vector3){ 0.0f, -2.0f, 0.0f };
Vector3 light_up = (Vector3){ 0.0f, 0.0f, -1.0f };
sr_light_view = MatrixLookAt(sr_light_pos, light_target, light_up);
sr_light_proj = MatrixPerspective(90.0 * DEG2RAD, 1.0, 1.5, 16.0);
sr_render_shadow_pass();
sr_render_main_pass();
}
void raybri_shutdown(void)
{
if (!sr_ready) return;
if (sr_has_model)
{
UnloadModel(sr_model);
sr_has_model = 0;
}
UnloadModel(sr_ground_model);
if (sr_cube_normal.id > 0)
{
UnloadTexture(sr_cube_normal);
sr_cube_normal.id = 0;
}
if (sr_shadow_color > 0) rlUnloadTexture(sr_shadow_color);
if (sr_shadow_depth > 0) rlUnloadTexture(sr_shadow_depth);
if (sr_shadow_fbo > 0) rlUnloadFramebuffer(sr_shadow_fbo);
if (sr_main_shader.id > 0) UnloadShader(sr_main_shader);
if (sr_shadow_shader.id > 0) UnloadShader(sr_shadow_shader);
#if !defined(PLATFORM_IOS)
rlglClose();
#endif
sr_ready = 0;
}
+38 -33
View File
@@ -1,42 +1,47 @@
#ifndef RAYBRI_H #ifndef OGS_MAHJONG_RAYLIB_BRIDGE_H
#define RAYBRI_H #define OGS_MAHJONG_RAYLIB_BRIDGE_H
// Header #ifdef __cplusplus
extern "C" {
#endif
void raybriInit(void); // Render configuration, sourced from renderConst.swift.
void raybriRender(int width, int height); typedef struct raybri_config {
void raybriShutdown(void); float fov_y; // vertical field of view (degrees)
float near_plane; // camera near plane
float far_plane; // camera far plane
int shadow_size; // shadow map resolution (px)
float ground_size; // ground plane extent
} raybri_config;
// Source // Initialise the OpenGL-backed raylib scene (no raylib window is created).
// The four shader sources come from renderConstShader.swift (with the
// platform #version already substituted).
void raybri_init(
const char *main_vs,
const char *main_fs,
const char *shadow_vs,
const char *shadow_fs,
raybri_config config
);
#if defined(RAYBRI_IMPLEMENTATION) // Load the textured cube glTF model.
void raybri_load_model(const char *gltf_path);
#include "rlgl.h" // Resize the viewport.
void raybri_resize(int width, int height);
void raybriInit(void) { // Cube rotation, driven by the application (Euler angles, degrees).
//SetTraceLogLevel(LOG_WARNING); void raybri_set_rotation(float x_deg, float y_deg, float z_deg);
// Initialize raylib graphics layer with a placeholder 1x1 framebuffer size // Render one frame.
// Graphics layer includes default texture, shader, render batch and OpenGL state void raybri_render(void);
rlglInit(1, 1);
// Background is painted in blue // Release all GPU resources.
rlClearColor(0, 0, 255, 255); void raybri_shutdown(void);
#ifdef __cplusplus
} }
#endif
void raybriRender(int width, int height) { #endif
// Set the drawing area to the current pixel size
rlViewport(0, 0, width, height);
// Clear color and depth buffers for the next frame
rlClearScreenBuffers();
// Draw any queued geometry
rlDrawRenderBatchActive();
}
void raybriShutdown(void) {
// Release rlgl buffers, shaders and textures
rlglClose();
}
#endif // RAYBRI_IMPLEMENTATION
#endif // RAYBRI_H
-16
View File
@@ -1,16 +0,0 @@
#ifndef RAYBRI_CONST_H
#define RAYBRI_CONST_H
// Header
extern const char RAYBRI_MAC_GL[];
// Source
#if defined(RAYBRI_CONST_IMPLEMENTATION)
const char RAYBRI_MAC_GL[] = "/System/Library/Frameworks/OpenGL.framework/OpenGL";
#endif // RAYBRI_CONST_IMPLEMENTATION
#endif // RAYBRI_CONST_H
+98
View File
@@ -0,0 +1,98 @@
import SwiftUI
import UIKit
// The prebuilt raylib iOS framework owns the app entry point (main()/
// AppDelegate/SceneDelegate in rcore_ios.c). Its SceneDelegate creates the
// window, installs GameViewController as the root and only then calls
// ios_ready(), so by the time rcios_present_overlay() runs there is already a
// key window with a GL-backed root view.
//
// We deliberately do NOT create a second UIWindow: that would sit at a fixed
// windowLevel and break alerts/buttons later. Instead we add the SwiftUI
// content as a child UIViewController of raylib's root view controller, so:
// - buttons receive touches through the normal responder chain;
// - .alert / sheets present correctly in the same window;
// - rotation and geometry changes apply to both layers at once.
//
// ChkgfxComponent/ChkgfxVM live here because the component lifecycle is
// otherwise driven by the (iOS-unavailable) SwiftUI app shell.
enum RenderIOS {
static let chkgfx = ChkgfxComponent()
static let chkgfxVM = ChkgfxVM()
// Inert on iOS (the raylib framework drives the scene), but the generated
// dialect refers to them, so keep them alive.
static let render = RenderComponent()
static let renderVM = RenderVM()
}
// The GLSL sources live in renderConstShader.swift (shared with the macOS
// build, with the platform #version already substituted). Expose them to the
// ObjC++ bridge as C strings; each call returns a malloc'd copy the caller
// must free().
@_cdecl("rcios_shader_main_vs")
public func rciosShaderMainVS() -> UnsafeMutablePointer<CChar>? {
strdup(RENDER_SHADER_MAIN_VS)
}
@_cdecl("rcios_shader_main_fs")
public func rciosShaderMainFS() -> UnsafeMutablePointer<CChar>? {
strdup(RENDER_SHADER_MAIN_FS)
}
@_cdecl("rcios_shader_shadow_vs")
public func rciosShaderShadowVS() -> UnsafeMutablePointer<CChar>? {
strdup(RENDER_SHADER_SHADOW_VS)
}
@_cdecl("rcios_shader_shadow_fs")
public func rciosShaderShadowFS() -> UnsafeMutablePointer<CChar>? {
strdup(RENDER_SHADER_SHADOW_FS)
}
@_cdecl("rcios_present_overlay")
public func rciosPresentOverlay() {
otherSetupConsoleLogging(RenderIOS.chkgfx.ctrl, "Chkgfx")
RenderIOS.chkgfx.setup()
DispatchQueue.main.async {
guard let scene = UIApplication.shared.connectedScenes
.compactMap({ $0 as? UIWindowScene })
.first(where: { $0.activationState == .foregroundActive })
?? UIApplication.shared.connectedScenes
.compactMap({ $0 as? UIWindowScene }).first
else { return }
// raylib's SceneDelegate made its window key before calling ios_ready().
guard let window = scene.windows.first(where: { $0.isKeyWindow })
?? scene.windows.first,
let host = window.rootViewController
else { return }
let root = ChkgfxView(RenderIOS.chkgfxVM)
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top)
let hosting = UIHostingController(rootView: root)
hosting.view.backgroundColor = .clear
// The UI is a passive title for now. Once it gains buttons, drop this
// line; touches will then stay in the SwiftUI layer over the whole
// screen instead of reaching raylib's GameViewController.
hosting.view.isUserInteractionEnabled = false
host.addChild(hosting)
hosting.view.frame = host.view.bounds
hosting.view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
host.view.addSubview(hosting.view)
hosting.didMove(toParent: host)
// addChild retains the hosting controller for as long as it stays
// attached, so no extra strong reference is needed here.
OverlayHost.retained = hosting
}
}
// Optional handle for later use (e.g. presenting an alert from the hosting
// controller). The parent view controller keeps it alive while attached.
private enum OverlayHost {
static weak var retained: UIViewController?
}
-19
View File
@@ -1,19 +0,0 @@
import UIKit
func renderDraw(_ vm: RenderVM) {
guard eglMakeCurrentContext(&vm.glView.st) else { return }
raybriRender(vm.pixelSize[0], vm.pixelSize[1])
eglSwapBuffers(vm.glView.st.display, vm.glView.st.surface)
}
func renderPixelSize(_ view: UIView) -> [Int32] {
let scale = view.contentScaleFactor
let w = Int32(max(1, (view.bounds.width * scale).rounded()))
let h = Int32(max(1, (view.bounds.height * scale).rounded()))
return [w, h]
}
func renderRecreateSurface(_ vm: RenderVM) {
eglResetSurface(&vm.glView.st)
eglMakeCurrentContext(&vm.glView.st)
}
-43
View File
@@ -1,43 +0,0 @@
import Foundation
import QuartzCore
import UIKit
func renderDeinit(_ vm: RenderVM) {
vm.timer?.invalidate()
vm.timer = nil
eglMakeCurrentContext(&vm.glView.st)
raybriShutdown()
eglMakeCurrent(vm.glView.st.display, nil, nil, nil)
eglDestroySurface(vm.glView.st.display, vm.glView.st.surface)
eglDestroyContext(vm.glView.st.display, vm.glView.st.ctx)
eglTerminate(vm.glView.st.display)
}
func renderInit(_ vm: RenderVM) {
// On iOS EGL/ANGLE renders into the UIView's layer
let layer = Unmanaged.passUnretained(vm.glView.layer).toOpaque()
vm.glView.st.caLayer = layer
guard eglInit(&vm.glView.st) else { fatalError("ERROR Could not initialize EGL") }
guard eglResetSurface(&vm.glView.st) else { fatalError("ERROR Could not reset EGL surface") }
guard eglMakeCurrentContext(&vm.glView.st) else { fatalError("ERROR Could not make EGL context current") }
raybriInit()
}
func renderStartTimer(_ vm: RenderVM) {
// Make a time mark for calculating time delta
vm.startTime = CACurrentMediaTime()
// The frame is presented by eglSwapBuffers into the view's layer, not by
// CoreGraphics, so the timer drives the rendering itself instead of
// invalidating the view for a draw(_:) pass the way macOS does
let timer = Timer(timeInterval: 1.0 / RENDER_FPS, repeats: true) { [weak vm] _ in
guard let vm else { return }
renderDraw(vm)
}
vm.timer = timer
// .common means holding buttons in UI does not pause this rendering timer
RunLoop.main.add(timer, forMode: .common)
}
+110
View File
@@ -0,0 +1,110 @@
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#include <stdlib.h>
#include <string>
#include "raylib.h"
#include "raybri.h"
// iOS entry points. The prebuilt raylib.framework (ghera/raylib-iOS) owns
// main()/AppDelegate/SceneDelegate and a full-screen EGL/ANGLE window; it
// calls these three callbacks (see src/platforms/rcore_ios.c). We therefore
// drive the same raybri_* scene as the macOS build from here, and present the
// SwiftUI UI inside raylib's own window (see RenderIOS.swift).
//
// The prebuilt framework already ran rlLoadExtensions()/rlglInit() inside
// InitWindow(), so raybri_init() only compiles the shaders and builds meshes.
#if defined(__cplusplus)
extern "C" void rcios_present_overlay(void); // implemented in Swift (RenderIOS.swift)
#else
void rcios_present_overlay(void);
#endif
// The GLSL sources live in renderConstShader.swift (shared with the macOS
// build, with the platform #version already substituted there). These Swift
// accessors return malloc'd copies that sr_shader() releases.
#if defined(__cplusplus)
extern "C" {
#endif
char *rcios_shader_main_vs(void);
char *rcios_shader_main_fs(void);
char *rcios_shader_shadow_vs(void);
char *rcios_shader_shadow_fs(void);
#if defined(__cplusplus)
}
#endif
static std::string sr_shader(char *(*accessor)(void))
{
char *source = accessor();
std::string shader = source ? source : "";
free(source);
return shader;
}
static double sr_start_time = 0.0;
static int sr_window_ready = 0;
double rcios_time_now(void)
{
return CACurrentMediaTime();
}
extern "C" void ios_ready(void)
{
SetTraceLogLevel(LOG_WARNING);
// Size is ignored on PLATFORM_IOS; the fork sizes the window itself.
InitWindow(0, 0, "OGS chkgfx");
// On iOS raylib's InitWindow loaded the GL functions and called rlglInit,
// so raybri_init() must not repeat it (see raybri.c, RAYBRI_PLATFORM_IOS).
std::string main_vs = sr_shader(rcios_shader_main_vs);
std::string main_fs = sr_shader(rcios_shader_main_fs);
std::string shadow_vs = sr_shader(rcios_shader_shadow_vs);
std::string shadow_fs = sr_shader(rcios_shader_shadow_fs);
raybri_init(
main_vs.c_str(),
main_fs.c_str(),
shadow_vs.c_str(),
shadow_fs.c_str(),
(raybri_config){ 45.0f, 0.1f, 1000.0f, 256, 40.0f }
);
// Same layout as the macOS app bundle: <bundle>/cube/cube.gltf
NSString *gltf = [[[NSBundle mainBundle] resourcePath]
stringByAppendingPathComponent:@"cube/cube.gltf"];
raybri_load_model([gltf UTF8String]);
sr_start_time = rcios_time_now();
sr_window_ready = 1;
// Show ChkgfxView (the SwiftUI title) above the raylib scene.
rcios_present_overlay();
}
extern "C" void ios_update(bool viewSizeChanged)
{
if (!sr_window_ready) return;
int w = GetRenderWidth();
int h = GetRenderHeight();
raybri_resize(w, h);
float t = (float)(rcios_time_now() - sr_start_time);
raybri_set_rotation(t * 6.0f, t * 18.0f, 0.0f);
BeginDrawing();
raybri_render();
EndDrawing();
}
extern "C" void ios_destroy(void)
{
if (!sr_window_ready) return;
raybri_shutdown();
CloseWindow();
sr_window_ready = 0;
}
@@ -0,0 +1,46 @@
import Combine
import Foundation
// On iOS the renderer is the prebuilt raylib framework's own full-screen
// window (see components/render/ios/renderIOS.mm: ios_ready/ios_update/
// ios_destroy). The macOS render component is not used there, but the
// generated dialect.swift still refers to RenderComponent/RenderVM and to the
// renderInit/renderStartTimer/renderLoadCubeModel/renderDeinit oneliners, so
// we provide inert counterparts to keep the dialect compiling.
//
// The real work happens in renderIOS.mm, which talks to the very same
// raybri_* bridge functions these stubs would call on macOS.
final class RenderVM: ObservableObject {
var didPrepareGL = false
var pixelSize = [Int32]()
var startTime: CFTimeInterval = 0
static private(set) weak var shared: RenderVM?
init() {
Self.shared = self
}
}
class RenderComponent {
let ctrl = DialectController(RenderContext())
static private(set) weak var singleton: RenderComponent?
init() {
Self.singleton = self
renderRegisterShoulds(ctrl)
}
func setup() {
renderSet(F.didSetup, true)
}
}
func renderInit(_ vm: RenderVM) {}
func renderStartTimer(_ vm: RenderVM) {}
func renderLoadCubeModel(_ vm: RenderVM) {}
func renderDeinit(_ vm: RenderVM) {}
@@ -1,35 +0,0 @@
import UIKit
final class RenderGLView: UIView {
var st = EGLState()
override init(frame: CGRect) {
super.init(frame: frame)
isOpaque = true
isUserInteractionEnabled = false
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
renderSet(F.willDeinit, true)
}
override func didMoveToWindow() {
super.didMoveToWindow()
guard let window else { return }
contentScaleFactor = window.screen.nativeScale
layer.contentsScale = contentScaleFactor
renderSet(F.didPrepareIOSGL, true);
}
override func layoutSubviews() {
super.layoutSubviews()
let ps = renderPixelSize(self)
renderSet(F.reshapePixelSize, ps)
}
}
@@ -1,10 +0,0 @@
import SwiftUI
import UIKit
struct RenderView: UIViewRepresentable {
func makeUIView(context: Context) -> RenderGLView {
RenderVM.shared!.glView
}
func updateUIView(_ uiView: RenderGLView, context: Context) {}
}
@@ -1,11 +0,0 @@
import AppKit
let RENDER_OPENGL_ATTRS: [NSOpenGLPixelFormatAttribute] = [
UInt32(NSOpenGLPFAOpenGLProfile), UInt32(NSOpenGLProfileVersion3_2Core),
UInt32(NSOpenGLPFAColorSize), 24,
UInt32(NSOpenGLPFAAlphaSize), 8,
UInt32(NSOpenGLPFADepthSize), 24,
UInt32(NSOpenGLPFADoubleBuffer),
UInt32(NSOpenGLPFAAccelerated),
0
]
+12 -12
View File
@@ -15,20 +15,9 @@ final class RenderGLView: NSOpenGLView {
fatalError("init(coder:) has not been implemented") fatalError("init(coder:) has not been implemented")
} }
deinit {
renderSet(F.willDeinit, true)
}
override func draw(_ dirtyRect: NSRect) {
let vm = RenderVM.shared!
if vm.didPrepareGL {
renderDraw(vm)
}
}
override func prepareOpenGL() { override func prepareOpenGL() {
super.prepareOpenGL() super.prepareOpenGL()
renderSet(F.didPrepareMacGL, true) renderSet(F.didPrepareGL, true)
} }
override func reshape() { override func reshape() {
@@ -44,4 +33,15 @@ final class RenderGLView: NSOpenGLView {
let ps = renderPixelSize(self) let ps = renderPixelSize(self)
renderSet(F.backingPixelSize, ps) renderSet(F.backingPixelSize, ps)
} }
override func draw(_ dirtyRect: NSRect) {
let vm = RenderVM.shared!
if vm.didPrepareGL {
renderDraw(vm)
}
}
deinit {
renderSet(F.willDeinit, true)
}
} }
@@ -1,6 +1,7 @@
import AppKit import AppKit
import SwiftUI import SwiftUI
/// Render view for SwiftUI
struct RenderView: NSViewRepresentable { struct RenderView: NSViewRepresentable {
func makeNSView(context: Context) -> RenderGLView { func makeNSView(context: Context) -> RenderGLView {
RenderVM.shared!.glView RenderVM.shared!.glView
@@ -3,7 +3,12 @@ import RaylibBridge
func renderDraw(_ vm: RenderVM) { func renderDraw(_ vm: RenderVM) {
vm.glView.openGLContext?.makeCurrentContext() vm.glView.openGLContext?.makeCurrentContext()
raybriRender(vm.pixelSize[0], vm.pixelSize[1])
raybri_resize(vm.pixelSize[0], vm.pixelSize[1])
let t = Float(CACurrentMediaTime() - vm.startTime)
raybri_set_rotation(t * 6.0, t * 18.0, 0.0)
raybri_render()
vm.glView.openGLContext?.flushBuffer() vm.glView.openGLContext?.flushBuffer()
} }
@@ -13,7 +18,3 @@ func renderPixelSize(_ view: NSView) -> [Int32] {
let h = Int32(max(1, backing.height)) let h = Int32(max(1, backing.height))
return [w, h] return [w, h]
} }
func renderRecreateSurface(_ vm: RenderVM) {
// No-op on macOS
}
+22
View File
@@ -1,2 +1,24 @@
import AppKit
import RaylibBridge
let RENDER_CONFIG = raybri_config(
fov_y: 45.0,
near_plane: 0.1,
far_plane: 1000.0,
shadow_size: 256,
ground_size: 40.0
)
let RENDER_FPS = 60.0 let RENDER_FPS = 60.0
let RENDER_MODEL_CUBE = "/cube/cube.gltf" let RENDER_MODEL_CUBE = "/cube/cube.gltf"
let RENDER_OPENGL_ATTRS: [NSOpenGLPixelFormatAttribute] = [
UInt32(NSOpenGLPFAOpenGLProfile), UInt32(NSOpenGLProfileVersion3_2Core),
UInt32(NSOpenGLPFAColorSize), 24,
UInt32(NSOpenGLPFAAlphaSize), 8,
UInt32(NSOpenGLPFADepthSize), 24,
UInt32(NSOpenGLPFADoubleBuffer),
UInt32(NSOpenGLPFAAccelerated),
0
]
+51 -8
View File
@@ -1,5 +1,27 @@
let RENDER_SHADER_MAIN_FS = """ // GLSL sources shared by the macOS (GLSL 150) and iOS (GLSL ES 300)
#version 150 // builds. A shader's #version directive must precede everything else (even
// "precision"), so it cannot be chosen with an #ifdef inside the GLSL; the
// templates below start with RENDER_SHADER_VERSION_TOKEN and the platform
// version is substituted with replacingOccurrences.
//
// The fragment templates carry "precision highp float;" because GLSL ES has
// no default float precision in the fragment stage; desktop GLSL 1.30+
// accepts and ignores it. GLSL ES vertex shaders default to highp, so the
// vertex templates need no precision statement.
let RENDER_SHADER_VERSION_TOKEN = "%VERSION%"
let RENDER_SHADER_VERSION_GL = "#version 150"
let RENDER_SHADER_VERSION_ES = "#version 300 es"
#if os(iOS)
let RENDER_SHADER_VERSION = RENDER_SHADER_VERSION_ES
#else
let RENDER_SHADER_VERSION = RENDER_SHADER_VERSION_GL
#endif
let RENDER_SHADER_MAIN_FS_T = """
%VERSION%
precision highp float;
in vec3 vWorldPos; in vec3 vWorldPos;
in vec3 vNormal; in vec3 vNormal;
@@ -116,8 +138,13 @@ void main()
} }
""" """
let RENDER_SHADER_MAIN_VS = """ let RENDER_SHADER_MAIN_FS = RENDER_SHADER_MAIN_FS_T.replacingOccurrences(
#version 150 of: RENDER_SHADER_VERSION_TOKEN,
with: RENDER_SHADER_VERSION
)
let RENDER_SHADER_MAIN_VS_T = """
%VERSION%
in vec3 vertexPosition; in vec3 vertexPosition;
in vec2 vertexTexCoord; in vec2 vertexTexCoord;
in vec3 vertexNormal; in vec3 vertexNormal;
@@ -142,8 +169,14 @@ void main()
} }
""" """
let RENDER_SHADER_SHADOW_FS = """ let RENDER_SHADER_MAIN_VS = RENDER_SHADER_MAIN_VS_T.replacingOccurrences(
#version 150 of: RENDER_SHADER_VERSION_TOKEN,
with: RENDER_SHADER_VERSION
)
let RENDER_SHADER_SHADOW_FS_T = """
%VERSION%
precision highp float;
out vec4 finalColor; out vec4 finalColor;
void main() void main()
{ {
@@ -151,8 +184,13 @@ void main()
} }
""" """
let RENDER_SHADER_SHADOW_VS = """ let RENDER_SHADER_SHADOW_FS = RENDER_SHADER_SHADOW_FS_T.replacingOccurrences(
#version 150 of: RENDER_SHADER_VERSION_TOKEN,
with: RENDER_SHADER_VERSION
)
let RENDER_SHADER_SHADOW_VS_T = """
%VERSION%
in vec3 vertexPosition; in vec3 vertexPosition;
uniform mat4 mvp; uniform mat4 mvp;
void main() void main()
@@ -160,3 +198,8 @@ void main()
gl_Position = mvp * vec4(vertexPosition, 1.0); gl_Position = mvp * vec4(vertexPosition, 1.0);
} }
""" """
let RENDER_SHADER_SHADOW_VS = RENDER_SHADER_SHADOW_VS_T.replacingOccurrences(
of: RENDER_SHADER_VERSION_TOKEN,
with: RENDER_SHADER_VERSION
)
@@ -3,10 +3,10 @@ import RaylibBridge
import QuartzCore import QuartzCore
func renderDeinit(_ vm: RenderVM) { func renderDeinit(_ vm: RenderVM) {
print("ИГР renderD")
vm.timer?.invalidate() vm.timer?.invalidate()
vm.timer = nil
vm.glView.openGLContext?.makeCurrentContext() vm.glView.openGLContext?.makeCurrentContext()
raybriShutdown() raybri_shutdown()
} }
func renderInit(_ vm: RenderVM) { func renderInit(_ vm: RenderVM) {
@@ -16,8 +16,20 @@ func renderInit(_ vm: RenderVM) {
var swapInterval: Int32 = 1 var swapInterval: Int32 = 1
vm.glView.openGLContext?.setValues(&swapInterval, for: .swapInterval) vm.glView.openGLContext?.setValues(&swapInterval, for: .swapInterval)
raybriLoadExtensions() // Init Raylib
raybriInit() raybri_init(
RENDER_SHADER_MAIN_VS,
RENDER_SHADER_MAIN_FS,
RENDER_SHADER_SHADOW_VS,
RENDER_SHADER_SHADOW_FS,
RENDER_CONFIG
)
}
func renderLoadCubeModel(_ vm: RenderVM) {
let path = Bundle.main.resourceURL!.path + RENDER_MODEL_CUBE
vm.glView.openGLContext?.makeCurrentContext()
raybri_load_model(path)
} }
func renderStartTimer(_ vm: RenderVM) { func renderStartTimer(_ vm: RenderVM) {
-225
View File
@@ -1,225 +0,0 @@
# hello-platform
Minimal macOS, iOS and Android app that validates the platform foundation: a
"Hello, platform!" title, a count label and an Increment button. All state lives
in Dialect; SwiftUI and Compose only render the view model and send one input
event.
## Layout
```text
hello/hello-platform/
├── dialect.yml Dialect v4 source: fields, oneliners, shoulds
├── util/
│ ├── build-mac generate → build → package
│ ├── run-mac run the packaged .app
│ ├── prepare-ios generate → xcodegen project
│ ├── prepare-android generate Kotlin dialect.kt
│ └── step/
│ ├── generateDialect sibling ../dialect generator on dialect.yml
│ ├── buildMac swift build in ver-mac/
│ ├── packageMac ver-mac/.build/hello-platform.app
│ ├── runMac launch Contents/MacOS/hello-platform
│ └── prepareIOS xcodegen in ver-ios/
├── ver-mac/
│ ├── Package.swift one executable target, path "src", macOS 13
│ ├── Info.plist org.opengamestudio.hello-platform, AppIcon
│ ├── res/AppIcon.icns copied into the bundle's Resources
│ ├── .build/ SPM output + packaged .app (git-ignored)
│ └── src/
│ ├── HPApp.swift @main WindowGroup → HPView
│ ├── HPAppDelegate.swift builds HPComponent + HPVM, logs, calls setup()
│ ├── dialect.swift generated by Dialect, never hand-edited
│ ├── hp/ relative symlinks into components/hp
│ │ ├── hp.swift
│ │ ├── hpVM.swift
│ │ └── view/HPView.swift → components/hp/mac/view/HPView.swift
│ └── other/other.swift relative symlink into components/other
└── ver-ios/
├── project.yml xcodegen: target hello-platform, iOS 15
├── Info.plist org.opengamestudio.hello-platform
├── Assets.xcassets/ AppIcon.appiconset/AppIcon.png → res/AppIcon.png
├── hello-platform.xcodeproj generated, git-ignored
├── .build/ xcodebuild DerivedData (git-ignored)
└── src/
├── HPApp.swift @main WindowGroup → HPView
├── HPAppDelegate.swift same HPComponent + HPVM + logging as macOS
├── dialect.swift symlink → ../../ver-mac/src/dialect.swift
├── hp/ same links as ver-mac, except view/HPView.swift
│ → components/hp/ios/view/HPView.swift
└── other/other.swift same symlink as the macOS tree
```
The Android target mirrors the same layout:
```text
hello/hello-platform/ver-android/
├── settings.gradle.kts rootProject "hello-platform", includes app
├── app/build.gradle.kts org.opengamestudio.helloplatform, Compose
├── gradle/ AGP 8.7.3, Kotlin 2.1.0, wrapper 9.3.1
├── local.properties sdk.dir, git-ignored
├── build/ Gradle output and APK (git-ignored)
└── app/src/main/
├── AndroidManifest.xml label hello-platform, Theme.MyApplication
├── res/ strings, theme, adaptive launcher icon
└── kotlin/org/opengamestudio/
├── MainActivity.kt Compose Box → HPView, edge-to-edge
├── HPActivityDelegate.kt HPComponent + logging, calls setup()
├── dialect.kt generated Kotlin, never hand-edited
├── hp/ relative symlinks into components/hp/android
│ ├── hp.kt
│ ├── hpVM.kt
│ └── view/HPView.kt → components/hp/android/view/HPView.kt
└── other/other.kt relative symlink into components/other
```
`components/` is the source of truth. The `src/hp` and `src/other` entries are
symlinks, so edit the real files under `components/` and keep the links intact.
macOS and iOS share one `dialect.swift` (the iOS one is a symlink to `ver-mac`),
one `HPView` body (the iOS `components/hp/ios/view/HPView.swift` links back to
the macOS view) and one `res/AppIcon.png`. Android has its own generated
`dialect.kt` and Compose view, with the same state and layout.
## Shared components
- `components/hp/hp.swift` — `HPComponent` owns `DialectController(HPContext)`,
registers the generated effects and shoulds, publishes `singleton` and exposes
`setup()` (`hpSet(F.didSetup, true)`).
- `components/hp/hpVM.swift` — `HPVM` is an `ObservableObject` with
`@Published countText` and a weak `shared` instance.
- `components/hp/mac/view/HPView.swift` — SwiftUI view observing `HPVM`; the
button dispatches `hpSet(F.didClickIncrement, true)`. It is platform-neutral,
so `components/hp/ios/view/HPView.swift` is a symlink back to it and both
`src/hp/view/HPView.swift` links resolve to the same file.
- `components/hp/android/` — the Android mirror: `hp.kt` (same `HPComponent`),
`hpVM.kt` (`HPVM` with a Compose `mutableStateOf`) and `view/HPView.kt`
(Compose `Column`, headline, monospaced label, Increment button).
- `components/other/other.swift` / `other.kt` — helpers, including
`otherSetupConsoleLogging(ctrl, "HP")`, which prints every processed field to
stderr as `ИГР HP k/v: '<field>'/'<value>'`.
## Startup flow
1. `HPAppDelegate` creates `HPComponent` (which sets `HPComponent.singleton`)
and then `HPVM` (which sets `HPVM.shared`).
2. The launch callback (`applicationDidFinishLaunching` on macOS,
`application(_:didFinishLaunchingWithOptions:)` on iOS,
`HPActivityDelegate.setup()` in `MainActivity.onCreate` on Android) registers
console logging and calls `hp.setup()`; the macOS one also activates the app.
3. `setup()` queues `didSetup` in the controller.
4. The controller applies the changed field, runs every registered should in
order, and queues each new `recentField` a should returns. Finally it reports
the context to callbacks: logging plus the `countText` oneliner, which copies
`c.countText` into `HPVM.shared`.
5. `HPView` re-renders from the published view model.
## Dialect rules (`dialect.yml`)
Fields: `count`, `countText`, `didClickIncrement`, `didLaunch`, `didSetup`.
Shoulds exist for `count`, `countText` and `didLaunch`; `didClickIncrement` and
`didSetup` are pure inputs.
- `count`:
- on `didClickIncrement` when `count == 7` → `count += 10`;
- on every `didClickIncrement` → `count += 1`.
The first matching rule returns, so the click made while the count is 7 adds
10 and jumps to 17.
- `countText`:
- on `count` → `"Count: '<count>'"`;
- on `didLaunch` → `"Press the button to count"`.
- `didLaunch`: on `didSetup` while `didLaunch == false` → `true`, once.
Oneliners: `countText` → `HPVM.shared!.countText = c.countText`.
## Build and run
```sh
cd hello/hello-platform
util/build-mac
util/run-mac
```
`generateDialect` expects the sibling `../dialect` checkout (so
`/Volumes/MOE/p/dialect` for this workspace). `build-mac` runs the steps in
order: regenerate `ver-mac/src/dialect.swift` and the Android `dialect.kt`,
`swift build`, then package `ver-mac/.build/debug/hello-platform`, `Info.plist`
and `res/` into `ver-mac/.build/hello-platform.app`.
iOS needs `xcodegen` (see README prerequisites):
```sh
cd hello/hello-platform
util/prepare-ios
xcodebuild -project ver-ios/hello-platform.xcodeproj \
-scheme hello-platform -sdk iphonesimulator \
-destination 'generic/platform=iOS Simulator' \
CODE_SIGNING_ALLOWED=NO build
```
`prepare-ios` regenerates `dialect.swift` and then runs `xcodegen` in
`ver-ios/`. The generated `.xcodeproj` and `.build/` are git-ignored, so
re-run it after changing `project.yml` or `Info.plist`.
Android needs the SDK and a JDK; `prepare-android` writes the Kotlin dialect,
then Gradle builds the app:
```sh
cd hello/hello-platform
util/prepare-android
cd ver-android
JAVA_HOME="$HOME/.gradle/jdks/eclipse_adoptium-21-aarch64-os_x.2/jdk-21.0.7+6/Contents/Home" \
./gradlew assembleDebug
```
`ver-android/local.properties` points at `~/Library/Android/sdk` and is
git-ignored, so each checkout needs it once. Install the APK with
`adb install -r app/build/outputs/apk/debug/app-debug.apk` and start
`org.opengamestudio.helloplatform/org.opengamestudio.MainActivity`. Use JDK 21:
AGP 8.7.3 does not accept every newer JDK.
## Pitfalls
- Change `dialect.yml`, not the generated `dialect.swift` / `dialect.kt`;
retyping or reformatting them is pointless because every build overwrites
them.
- The Kotlin output is transpiled through the local LLM, so `ollama serve` must
be running (with `qwen2.5-coder:3b` pulled) before `prepare-android` or
`build-mac`; otherwise generation aborts and `dialect.kt` is left stale.
- Every should label (`1. Upon ...`) must end with a colon: the sibling generator
drops its last character (`../dialect/components/yml/ymlFun.swift`).
- A should function may change only one field; its returned `recentField` drives
the next queue entry.
- The generated oneliner and `hpSet` force-unwrap `HPVM.shared` /
`HPComponent.singleton`; both must exist before dispatch.
- Only one `dialect.swift` exists: `ver-ios/src/dialect.swift` is a symlink to
the macOS file, so `prepare-ios` regenerates the same source. The Kotlin
`dialect.kt` lives in `ver-android` and is generated from the same
`dialect.yml`.
## Linux launcher icon
`ver-linux` uses GtkBackend with application ID
`org.opengamestudio.hello-platform`. On Linux run
`hello/hello-platform/util/build-linux` from the repository root to build and install
the executable under `~/.local/bin`, the desktop entry under
`${XDG_DATA_HOME:-~/.local/share}/applications`, and the shared 1024px
`res/AppIcon.png` under the matching hicolor icon name. The launcher uses an
absolute executable path. Launch from the desktop application menu after
installation; GTK's application ID matches the desktop and icon names.
Desktop-entry installation uses `cp` and GNU `sed -i`; Python is not required.
The replacement supports spaces but assumes paths contain no sed replacement
metacharacters (`&`, `|`, backslashes) or desktop-entry quoting characters.
Requires the normal Swift/GTK build dependencies. Installation is per-user and
requires no root privileges.
The Linux build runs `step/buildLinux` followed by `step/packageLinux`.
The shared launcher template is `res/linux-app.desktop`; packaging copies it
and substitutes `%APP_NAME%`, `%APP_EXEC%` and `%APP_ID%`.
`util/run-linux` uses `gtk-launch org.opengamestudio.hello-platform` to launch
the installed desktop entry with its icon association. Run `util/build-linux`
first to install/update that entry and executable; `gtk-launch` must be available.
`packageLinux` is sourced with the target and display name, like `packageMac`;
it installs the executable, launcher and icon for the current user and refreshes
the desktop/icon caches. It requires GNU sed, gtk-update-icon-cache and
update-desktop-database. The standalone `install-linux` script has been replaced
by this packaging step.
-68
View File
@@ -1,68 +0,0 @@
# Mirrored source-file study documents
Use this workflow when comparing corresponding source files across platforms.
The established example is `docs/render-platform-comparison.html`.
For a single-file study, follow `docs/file-summary.md` instead.
## Source and scope
- Read sources from the exact requested Git revision with `git show REV:path`.
If no revision is specified, use HEAD and record its full commit hash.
- Discover matching relative filenames beneath the two platform directories.
State which platform-only files are excluded; never invent a counterpart.
- Produce one downloadable, self-contained HTML document in `docs/`, with
navigation links and one section per file pair. Preserve earlier documents
unless removal is requested.
- Record both source paths and the source revision. Preserve every source line,
original line number, indentation and blank line. Escape HTML characters.
## Comparison layout
- Use one table per pair with three columns: first platform's numbered source,
second platform's numbered source, and explanation. Do not create separate
line-by-line explanation tables or a Status column.
- Align corresponding function starts where possible. Insert missing-line
placeholders to keep later functions aligned; preserve source order and
original numbers. For example, macOS renderEffect line 12 aligns with iOS
line 16 at revision f0972f0d5ba796e3fa417081f43c00a9654b2aa6.
- Within each function or intervening block, align lines sequentially unless
better semantic alignment is needed. Equal line numbers need not share a row
when function alignment requires padding.
- Compare the exact source text in each aligned row, including whitespace.
Fill BOTH line-number backgrounds green when they match. Fill numbers orange
when they differ. A missing line is an orange-filled dash, not a plain dash.
Keep code backgrounds neutral and retain syntax highlighting.
- Include two filled statistics boxes beneath each section heading: green for
matching line count and percentage, orange for mismatched count and percentage.
Show the total line count as plain text alongside them.
- Count actual lines across BOTH files, including blank lines. A matching pair
contributes two matching lines; a differing pair contributes two mismatches;
a platform-only line contributes one mismatch. Missing placeholders do not
count. Percentages use the combined actual-line total. Recalculate after any
alignment change, and explain this counting convention in the document.
## Explanations
- Explain each distinct point once across the document, at its first relevant
occurrence. Leave later cells empty unless they add information.
- Eliminate semantic repetition, not just identical sentences. Do not repeat
platform/import boilerplate such as “UIKit serves iOS” for every import.
- Explain shared behavior once. Label iOS/macOS details only when needed to
distinguish behavior. Explain the reason or consequence of platform differences.
- Avoid redundant function summaries when the individual operations already
explain the same behavior. Leave blank lines and closing braces unexplained.
- When realigning rows, anchor each platform-specific explanation to its own
source line rather than to the old visual row.
## Presentation and verification
- Inline all CSS and syntax highlighting; no external fonts, scripts or requests.
- Use `<pre><code>`, `white-space: pre-wrap`, and `overflow-wrap: anywhere`.
Give the code columns equal width; ensure long lines remain readable without
horizontal scrolling. Do not use striped row shading.
- Verify every source line and number against the named Git revision, in order,
with no omissions or duplicates. Check function anchors, placeholder fills,
both matching-number fills, statistics, and explanation attachment.
- Review explanations for repeated clauses as well as repeated sentences.
- Inspect the rendered HTML for layout problems. Return a clickable file link;
tell the user to refresh an already open document after updates.
File diff suppressed because it is too large. Load diff
-53
View File
@@ -1,53 +0,0 @@
version: 4
output:
ver-android/app/src/main/kotlin/org/opengamestudio/dialect.kt:
type: kotlin
ver-mac/src/dialect.swift:
type: swift
HPContext:
type: context
fields:
count: Int
countText: String
didClickIncrement: Bool
didLaunch: Bool
didSetup: Bool
HPComponent:
type: component
oneliners:
- countText: HPVM.shared!.countText = c.countText
shoulds:
count:
1. Upon hitting 7:
if:
c.recentField == F.didClickIncrement &&
c.count == 7
then:
c.count += 10
2. Upon each button click:
if:
c.recentField == F.didClickIncrement
then:
c.count += 1
countText:
1. Upon each count change:
if:
c.recentField == F.count
then:
c.countText = "Count: '\(c.count)'"
2. Upon launch:
if:
c.recentField == F.didLaunch
then:
c.countText = "Press the button to count"
didLaunch:
1. Only once during the first setup:
if:
c.recentField == F.didSetup &&
c.didLaunch == false
then:
c.didLaunch = true
-9
View File
@@ -1,9 +0,0 @@
#!/bin/bash -e
SDIR=$(cd "$(dirname "$0")" ; pwd -P)
T=$SDIR/step
TARGET=hello-platform
STEP=0
source $T/buildLinux $TARGET
source $T/packageLinux $TARGET hello-platform
-10
View File
@@ -1,10 +0,0 @@
#!/bin/bash -e
SDIR=$(cd "$(dirname "$0")" ; pwd -P)
T=$SDIR/step
TARGET=hello-platform
STEP=0
source $T/generateDialect $TARGET
source $T/buildMac $TARGET
source $T/packageMac $TARGET hello-platform
@@ -1,8 +0,0 @@
#!/bin/bash -e
SDIR=$(cd "$(dirname "$0")" ; pwd -P)
T=$SDIR/step
TARGET=hello-platform
STEP=0
source $T/generateDialect $TARGET
-9
View File
@@ -1,9 +0,0 @@
#!/bin/bash -e
SDIR=$(cd "$(dirname "$0")" ; pwd -P)
T=$SDIR/step
TARGET=hello-platform
STEP=0
source $T/generateDialect $TARGET
source $T/prepareIOS $TARGET
-7
View File
@@ -1,7 +0,0 @@
#!/bin/bash -e
SDIR=$(cd "$(dirname "$0")" ; pwd -P)
T=$SDIR/step
STEP=0
source $T/runLinux hello-platform hello-platform
-7
View File
@@ -1,7 +0,0 @@
#!/bin/bash -e
SDIR=$(cd "$(dirname "$0")" ; pwd -P)
T=$SDIR/step
STEP=0
source $T/runMac hello-platform hello-platform
@@ -1,8 +0,0 @@
#!/bin/bash -e
TARGET=$1
STEP=$((STEP+1))
echo -e "\n> > > > Step №$STEP. Build '$TARGET' for Linux"
cd $SDIR/../ver-linux
swift build
-8
View File
@@ -1,8 +0,0 @@
#!/bin/bash -e
TARGET=$1
STEP=$((STEP+1))
echo -e "\n> > > > Step №$STEP. Build '$TARGET' for macOS"
cd $SDIR/../ver-mac
swift build
@@ -1,7 +0,0 @@
#!/bin/bash -e
TARGET=$1
STEP=$((STEP+1))
echo -e "\n> > > > Step №$STEP. Generate Dialect for '$TARGET'"
$SDIR/../../../util/run-generator --file=$SDIR/../dialect.yml
@@ -1,29 +0,0 @@
#!/bin/bash -e
TARGET=$1
APP_NAME=$2
STEP=$((STEP+1))
echo -e "\n> > > > Step №$STEP. Make '$APP_NAME' Linux package for '$TARGET'"
APP_DIR="$SDIR/../ver-linux"
DATA_DIR="${XDG_DATA_HOME:-$HOME/.local/share}"
BIN_DIR="$HOME/.local/bin"
APP_ID=org.opengamestudio.$TARGET
mkdir -p "$BIN_DIR" "$DATA_DIR/applications" "$DATA_DIR/icons/hicolor/1024x1024/apps"
cp "$APP_DIR/.build/debug/$TARGET" "$BIN_DIR/$TARGET"
cp "$SDIR/../../../res/AppIcon.png" \
"$DATA_DIR/icons/hicolor/1024x1024/apps/$APP_ID.png"
# Use an absolute executable path: graphical sessions may omit ~/.local/bin.
DESKTOP_FILE="$DATA_DIR/applications/$APP_ID.desktop"
cp "$SDIR/../../../res/linux-app.desktop" "$DESKTOP_FILE"
sed -i \
-e "s|%APP_NAME%|$APP_NAME|g" \
-e "s|%APP_EXEC%|$BIN_DIR/$TARGET|g" \
-e "s|%APP_ID%|$APP_ID|g" \
"$DESKTOP_FILE"
# Update icon cache for new icon to be visible
gtk-update-icon-cache --force --ignore-theme-index "$DATA_DIR/icons/hicolor"
update-desktop-database "$DATA_DIR/applications"
-18
View File
@@ -1,18 +0,0 @@
#!/bin/bash -e
TARGET=$1
APP_NAME=$2
STEP=$((STEP+1))
echo -e "\n> > > > Step №$STEP. Make '$APP_NAME' macOS package for '$TARGET'"
APP_MAC="$SDIR/../ver-mac/.build/$APP_NAME.app"
rm -rf "$APP_MAC"
APP_DAT="$APP_MAC/Contents"
mkdir -p "$APP_DAT/MacOS"
mkdir -p "$APP_DAT/Resources"
cp $SDIR/../ver-mac/.build/debug/$TARGET "$APP_DAT/MacOS/$TARGET"
cp $SDIR/../ver-mac/Info.plist "$APP_DAT/Info.plist"
# Copy resources with symlink dereferencing
cp -R -L $SDIR/../ver-mac/res/* "$APP_DAT/Resources/"
@@ -1,8 +0,0 @@
#!/bin/bash -e
TARGET=$1
STEP=$((STEP+1))
echo -e "\n> > > > Step №$STEP. Generate Xcode project for '$TARGET' iOS"
cd $SDIR/../ver-ios
xcodegen
-8
View File
@@ -1,8 +0,0 @@
#!/bin/bash -e
TARGET=$1
APP_NAME=$2
STEP=$((STEP+1))
echo -e "\n> > > > Step №$STEP. Run Linux app for '$TARGET'"
gtk-launch "org.opengamestudio.$TARGET"
-8
View File
@@ -1,8 +0,0 @@
#!/bin/bash -e
TARGET=$1
APP_NAME=$2
STEP=$((STEP+1))
echo -e "\n> > > > Step №$STEP. Run macOS app for '$TARGET'"
"$SDIR/../ver-mac/.build/$APP_NAME.app/Contents/MacOS/$TARGET"
@@ -1,44 +0,0 @@
import org.jetbrains.kotlin.gradle.dsl.JvmTarget.*
plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.android)
alias(libs.plugins.kotlin.compose)
}
android {
namespace = "org.opengamestudio"
compileSdk = 35
buildFeatures {
compose = true
}
compileOptions {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
defaultConfig {
applicationId = "org.opengamestudio.helloplatform"
minSdk = 24
targetSdk = 35
versionCode = 1
versionName = "1.0"
}
}
dependencies {
implementation(libs.androidx.activity.compose)
implementation(platform(libs.androidx.compose.bom))
implementation(libs.androidx.core.ktx)
implementation(libs.androidx.lifecycle.runtime.ktx)
implementation(libs.androidx.material3)
implementation(libs.androidx.ui)
implementation(libs.androidx.ui.graphics)
implementation(libs.androidx.ui.tooling.preview)
}
kotlin {
compilerOptions {
jvmTarget = JVM_1_8
}
}
@@ -1,29 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<application
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MyApplication"
tools:targetApi="35">
<activity
android:name=".MainActivity"
android:exported="true"
android:label="@string/app_name"
android:theme="@style/Theme.MyApplication"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
@@ -1,13 +0,0 @@
package org.opengamestudio
object HPActivityDelegate {
val hp = HPComponent
init {
otherSetupConsoleLogging(hp.ctrl, "HP")
}
fun setup() {
hp.setup()
}
}
@@ -1,36 +0,0 @@
package org.opengamestudio
import android.graphics.Color
import android.os.Bundle
import androidx.activity.*
import androidx.activity.compose.setContent
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.ui.*
import androidx.compose.ui.graphics.Color as ComposeColor
import org.opengamestudio.ui.theme.MyApplicationTheme
class MainActivity: ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
HPActivityDelegate.setup()
enableEdgeToEdge(
navigationBarStyle = SystemBarStyle.light(Color.TRANSPARENT, Color.TRANSPARENT),
statusBarStyle = SystemBarStyle.light(Color.TRANSPARENT, Color.TRANSPARENT)
)
setContent {
MyApplicationTheme {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier
.fillMaxSize()
.background(ComposeColor.White)
) {
HPView()
}
}
}
}
}
@@ -1,284 +0,0 @@
package org.opengamestudio
val DIALECT_CONTEXT_RECENT_FIELD_NONE = "none"
interface DialectContext {
/**
* Name of the field that has just been changed
*
* Allows should-functions (reducers) to react only to
* relevant changes and ignore other changes of DialectContext
*/
var recentField: String
/**
* Get field's value by its name
*/
fun <T> field(name: String): T
/**
* Erase type
*
* Used by DialectController to assign recent field's value
*/
fun fieldAny(name: String): Any {
return field(name)
}
/**
* Create a copy of the DialectContext derivative
*
* Used by DialectController to treat all derived contexts as DialectContext
*/
fun selfCopy(): DialectContext
/**
* Set field's value by its name
*/
fun setField(name: String, value: Any?)
}
class DialectController(
var context: DialectContext
) {
internal var callbacks = mutableListOf<(c: DialectContext) -> Unit>()
internal var functions = mutableListOf<(c: DialectContext) -> DialectContext>()
var isProcessingQueue = false
internal var queue = mutableListOf<DialectContext>()
fun executeFunctions() {
val c = queue.removeAt(0)
// Keep SSOT: Only allow single field change per should-function
context.recentField = c.recentField
context.setField(c.recentField, c.fieldAny(c.recentField))
for (f in functions) {
val ctx = f(context.selfCopy())
if (ctx.recentField != DIALECT_CONTEXT_RECENT_FIELD_NONE) {
queue.add(ctx)
}
}
reportContext()
}
fun processQueue() {
// Prevent recursion.
if (isProcessingQueue) {
return
}
isProcessingQueue = true
while (queue.size > 0) {
executeFunctions()
}
isProcessingQueue = false
}
fun registerCallback(cb: (c: DialectContext) -> Unit) {
callbacks.add(cb)
}
fun registerFieldCallback(
fieldName: String,
cb: (DialectContext) -> Unit
) {
callbacks.add({ c ->
if (c.recentField == fieldName) {
cb(c)
}
})
}
fun registerFunction(f: (DialectContext) -> DialectContext) {
functions.add(f)
}
fun reportContext() {
for (cb in callbacks) {
cb(context)
}
}
fun set(fieldName: String, value: Any) {
var c = context.selfCopy()
c.setField(fieldName, value)
c.recentField = fieldName
queue.add(c)
processQueue()
}
}
// Register several oneliner callbacks to a controller
@Suppress("UNCHECKED_CAST")
fun registerOneliners(
ctrl: DialectController,
items: Array<Any>
) {
val halfCount = items.size / 2
for (i in 0..<halfCount) {
val field = items[i * 2] as String
val callback = items[i * 2 + 1] as (c: DialectContext) -> Unit
ctrl.registerFieldCallback(field, callback)
}
}
// Context field names for static type check
object F {
const val count = "count"
const val countText = "countText"
const val didClickIncrement = "didClickIncrement"
const val didLaunch = "didLaunch"
const val didSetup = "didSetup"
}
@Suppress("UNCHECKED_CAST")
data class HPContext(
var count: Int = 0,
var countText: String = "",
var didClickIncrement: Boolean = false,
var didLaunch: Boolean = false,
var didSetup: Boolean = false,
override var recentField: String = ""
) : DialectContext {
override fun <T> field(name: String): T {
if (name == "count") {
return count as T
}
else if (name == "countText") {
return countText as T
}
else if (name == "didClickIncrement") {
return didClickIncrement as T
}
else if (name == "didLaunch") {
return didLaunch as T
}
else if (name == "didSetup") {
return didSetup as T
}
return "" as T
}
override fun selfCopy(): DialectContext {
return this.copy()
}
override fun setField(
name: String,
value: Any?
) {
if (name == "count") {
count = value as Int
}
else if (name == "countText") {
countText = value as String
}
else if (name == "didClickIncrement") {
didClickIncrement = value as Boolean
}
else if (name == "didLaunch") {
didLaunch = value as Boolean
}
else if (name == "didSetup") {
didSetup = value as Boolean
}
}
}
fun hpSet(
key: String,
value: Any
) {
HPComponent.ctrl.set(key, value)
}
fun hpShouldResetCount(c: HPContext): HPContext {
val c = c
// 1. Upon hitting 7
if (
c.recentField == F.didClickIncrement &&
c.count == 7
) {
c.count += 10
c.recentField = F.count
return c
}
// 2. Upon each button click
if (
c.recentField == F.didClickIncrement
) {
c.count += 1
c.recentField = F.count
return c
}
c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE
return c
}
fun hpShouldResetCountText(c: HPContext): HPContext {
val c = c
// 1. Upon each count change
if (
c.recentField == F.count
) {
c.countText = "Count: '${c.count}'"
c.recentField = F.countText
return c
}
// 2. Upon launch
if (
c.recentField == F.didLaunch
) {
c.countText = "Press the button to count"
c.recentField = F.countText
return c
}
c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE
return c
}
fun hpShouldResetDidLaunch(c: HPContext): HPContext {
val c = c
// 1. Only once during the first setup
if (
c.recentField == F.didSetup &&
c.didLaunch == false
) {
c.didLaunch = true
c.recentField = F.didLaunch
return c
}
c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE
return c
}
fun hpRegisterShoulds(ctrl: DialectController) {
listOf(
::hpShouldResetCount,
::hpShouldResetCountText,
::hpShouldResetDidLaunch,
).forEach { f ->
ctrl.registerFunction { c -> f(c as HPContext) }
}
}
fun hpRegisterEffects(ctrl: DialectController) {
registerOneliners(ctrl, arrayOf(
F.countText, { c: HPContext -> HPVM.shared!!.countText = c.countText },
))
}
@@ -1 +0,0 @@
../../../../../../../../../../components/hp/android/hp.kt
@@ -1 +0,0 @@
../../../../../../../../../../components/hp/android/hpVM.kt
@@ -1 +0,0 @@
../../../../../../../../../../../components/hp/android/view/HPView.kt
@@ -1 +0,0 @@
../../../../../../../../../../components/other/other.kt
@@ -1,11 +0,0 @@
package org.opengamestudio.ui.theme
import androidx.compose.ui.graphics.Color
val Purple80 = Color(0xFFD0BCFF)
val PurpleGrey80 = Color(0xFFCCC2DC)
val Pink80 = Color(0xFFEFB8C8)
val Purple40 = Color(0xFF6650a4)
val PurpleGrey40 = Color(0xFF625b71)
val Pink40 = Color(0xFF7D5260)
@@ -1,39 +0,0 @@
package org.opengamestudio.ui.theme
import android.os.Build
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.ui.platform.LocalContext
private val DarkColorScheme = darkColorScheme(
primary = Purple80,
secondary = PurpleGrey80,
tertiary = Pink80
)
private val LightColorScheme = lightColorScheme(
primary = Purple40,
secondary = PurpleGrey40,
tertiary = Pink40
)
@Composable
fun MyApplicationTheme(
darkTheme: Boolean = false,
dynamicColor: Boolean = false,
content: @Composable () -> Unit
) {
val colorScheme = when {
dynamicColor && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S ->
if (darkTheme) dynamicDarkColorScheme(LocalContext.current)
else dynamicLightColorScheme(LocalContext.current)
darkTheme -> DarkColorScheme
else -> LightColorScheme
}
MaterialTheme(
colorScheme = colorScheme,
typography = Typography,
content = content
)
}
@@ -1,16 +0,0 @@
package org.opengamestudio.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.*
import androidx.compose.ui.unit.sp
val Typography = Typography(
bodyLarge = TextStyle(
fontFamily = FontFamily.Default,
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.5.sp
)
)
Binary file not shown.

Before

Width:  |  Height:  |  Size: 158 KiB

@@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_artwork" />
<foreground android:drawable="@android:color/transparent" />
</adaptive-icon>
@@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<adaptive-icon xmlns:android="http://schemas.android.com/apk/res/android">
<background android:drawable="@drawable/ic_launcher_artwork" />
<foreground android:drawable="@android:color/transparent" />
</adaptive-icon>
Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 3.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 6.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 11 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 18 KiB

@@ -1,3 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
</resources>
@@ -1,4 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">hello-platform</string>
</resources>
@@ -1,6 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="Theme.MyApplication" parent="android:Theme.Material.NoActionBar">
<item name="android:windowBackground">#FFFFFF</item>
</style>
</resources>
@@ -1,3 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<full-backup-content>
</full-backup-content>
@@ -1,9 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<data-extraction-rules>
<cloud-backup>
<exclude domain="root" />
</cloud-backup>
<device-transfer>
<exclude domain="root" />
</device-transfer>
</data-extraction-rules>
@@ -1,6 +0,0 @@
plugins {
alias(libs.plugins.android.application) apply false
alias(libs.plugins.android.library) apply false
alias(libs.plugins.kotlin.android) apply false
alias(libs.plugins.kotlin.compose) apply false
}
@@ -1,8 +0,0 @@
# Use Compose for Android
android.useAndroidX=true
# Verbose build log
org.gradle.console=verbose
# Cache artifacts
org.gradle.caching=true
# JVM heap for Gradle and daemon
org.gradle.jvmargs=-Xmx4g -XX:MaxMetaspaceSize=1g
@@ -1,24 +0,0 @@
[versions]
activityCompose = "1.9.3"
agp = "8.7.3"
composeBom = "2024.12.01"
coreKtx = "1.15.0"
kotlin = "2.1.0"
lifecycleRuntimeKtx = "2.8.7"
[libraries]
androidx-activity-compose = { group = "androidx.activity", name = "activity-compose", version.ref = "activityCompose" }
androidx-compose-bom = { group = "androidx.compose", name = "compose-bom", version.ref = "composeBom" }
androidx-core-ktx = { group = "androidx.core", name = "core-ktx", version.ref = "coreKtx" }
androidx-lifecycle-runtime-ktx = { group = "androidx.lifecycle", name = "lifecycle-runtime-ktx", version.ref = "lifecycleRuntimeKtx" }
androidx-material3 = { group = "androidx.compose.material3", name = "material3" }
androidx-ui = { group = "androidx.compose.ui", name = "ui" }
androidx-ui-graphics = { group = "androidx.compose.ui", name = "ui-graphics" }
androidx-ui-tooling = { group = "androidx.compose.ui", name = "ui-tooling" }
androidx-ui-tooling-preview = { group = "androidx.compose.ui", name = "ui-tooling-preview" }
[plugins]
android-application = { id = "com.android.application", version.ref = "agp" }
android-library = { id = "com.android.library", version.ref = "agp" }
kotlin-android = { id = "org.jetbrains.kotlin.android", version.ref = "kotlin" }
kotlin-compose = { id = "org.jetbrains.kotlin.plugin.compose", version.ref = "kotlin" }
@@ -1,7 +0,0 @@
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-bin.zip
networkTimeout=10000
validateDistributionUrl=true
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
-251
View File
@@ -1,251 +0,0 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
@@ -1,23 +0,0 @@
pluginManagement {
repositories {
google {
content {
includeGroupByRegex("com\\.android.*")
includeGroupByRegex("com\\.google.*")
includeGroupByRegex("androidx.*")
}
}
mavenCentral()
gradlePluginPortal()
}
}
dependencyResolutionManagement {
repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)
repositories {
google()
mavenCentral()
}
}
rootProject.name = "hello-platform"
include("app")
@@ -1 +0,0 @@
../../../../../../res/AppIcon.png
@@ -1,14 +0,0 @@
{
"images" : [
{
"filename" : "AppIcon.png",
"idiom" : "universal",
"platform" : "ios",
"size" : "1024x1024"
}
],
"info" : {
"author" : "xcode",
"version" : 1
}
}
-29
View File
@@ -1,29 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>CFBundleName</key>
<string>hello-platform</string>
<key>CFBundleDisplayName</key>
<string>hello-platform</string>
<key>CFBundleIdentifier</key>
<string>org.opengamestudio.hello-platform</string>
<key>CFBundleExecutable</key>
<string>hello-platform</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>1.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>UILaunchScreen</key>
<dict/>
<key>UISupportedInterfaceOrientations</key>
<array>
<string>UIInterfaceOrientationLandscapeLeft</string>
<string>UIInterfaceOrientationLandscapeRight</string>
<string>UIInterfaceOrientationPortrait</string>
<string>UIInterfaceOrientationPortraitUpsideDown</string>
</array>
</dict>
</plist>
Loaded 100 of 299 files, more files were not shown because too many files have changed in this diff. Show more