Introduce chkgfx (#3)

This commit was merged in pull request #3.
This commit is contained in:
kornerr committed 2026-10-22 05:17:21 +02:00
1 parent 1515a9483b
commit fb28dd55c7
77 files changed
+1598 -543

No files matched your search

+102 -24
View File
@@ -12,9 +12,9 @@ and talk to the engine through generated functions like `rootSet(...)`.
Remote: `https://git.opengamestudio.org/mahjong/mahjong` · Version: `2.0.0`
> Current `dialect.yml` is still the "Root / counter" template inherited from the
> dialect example — the Mahjong game logic has not been written yet. The app
> shell, packaging and symlink wiring are in place.
> `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.
## Structure
@@ -25,29 +25,54 @@ dialect.yml Single source of truth for the reactive logic.
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 Per-platform SwiftUI view
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 RENDER_SHADER_* GLSL sources (GLSL 150)
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
game/ver-mac/ macOS app (SPM executable target "ogs-mahjong")
Package.swift SPM manifest (macOS 13+, swift-tools 5.9); SPM C target
"RaylibBridge" (bridge/) + links Homebrew raylib
Package.swift SPM manifest (macOS 13+, swift-tools 5.9); C target
"RaylibBridge" (path src/raybri, publicHeadersPath ".") +
links Homebrew raylib; the Swift target excludes raybri
and gets -Xcc -DGL_SILENCE_DEPRECATION
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
bridge/ C target "RaylibBridge": raylib_bridge.{c,h}. Renders a
rlgl scene (no raylib window) into an NSOpenGLView.
cube_texture.png, cube_normal.png
src/
GameApp.swift @main SwiftUI App entry
AppDelegate.swift Creates RootComponent + RootVM, calls root.setup()
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
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/RootView.swift
root/view/RaylibGLView.swift -> symlink components/root/mac/view/RaylibGLView.swift
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.
@@ -71,10 +96,19 @@ directories whose files are **relative symlinks** back into `components/`:
```
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/root/view/RaylibGLView.swift -> ../../../../../components/root/mac/view/RaylibGLView.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)
```
SPM silently **skips** a dangling symlink (no error), so after moving
@@ -108,13 +142,50 @@ 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 `RaylibGLView` behind the SwiftUI UI in a
`ZStack`. A textured cube is drawn from `Resources/assets` (`cube.gltf` +
`cube_texture.png`); the app rotates it each frame via `sr_set_rotation`.
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 and render constants live in **Swift**, not in C: GLSL sources are
`RENDER_SHADER_*` in `components/render/renderConstShader.swift`, and
`RENDER_CONFIG` / `raybri_config` tunables are 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
@@ -157,8 +228,10 @@ 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/`, and the `RootVM.shared!.countText = ...` oneliner in the
generated `dialect.swift`). Do not flip it on without addressing those.
`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
@@ -167,8 +240,11 @@ generated `dialect.swift`). Do not flip it on without addressing those.
- Prefer editing files in `components/` (the real files); the `src/` entries are
symlinks.
- The generated UI callback plumbing is nonisolated; UI singletons are weak
(`RootComponent.singleton`, `RootVM.shared`) and are accessed from the
generated oneliners with force-unwrap (`RootVM.shared!.countText = ...`).
(`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).
## Skill: source-file study documents
@@ -180,5 +256,7 @@ 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` (single-cube `RaylibGLView.swift`).
- Existing example: `docs/RaylibGLView.html` — documents the historical
single-cube `RaylibGLView.swift`, since split into `RenderGLView.swift` plus
the `render*` files.
+5
View File
@@ -0,0 +1,5 @@
## Prerequisites
* macOS
`brew install raylib`
+14
View File
@@ -0,0 +1,14 @@
class ChkgfxComponent {
let ctrl = DialectController(ChkgfxContext())
static private(set) weak var singleton: ChkgfxComponent?
init() {
Self.singleton = self
//chkgfxRegisterEffects(ctrl)
chkgfxRegisterShoulds(ctrl)
}
func setup() {
chkgfxSet(F.didSetup, true)
}
}
+9
View File
@@ -0,0 +1,9 @@
import Combine
final class ChkgfxVM: ObservableObject {
static private(set) weak var shared: ChkgfxVM?
init() {
Self.shared = self
}
}
@@ -0,0 +1,24 @@
import SwiftUI
struct ChkgfxView: View {
@ObservedObject var vm: ChkgfxVM
init(_ vm: ChkgfxVM) {
self.vm = vm
}
var body: some View {
VStack(spacing: 16) {
ZStack {
Text("Check graphics")
.font(.largeTitle)
.foregroundStyle(.white)
.offset(x: 1, y: 1)
Text("Check graphics")
.font(.largeTitle)
.foregroundStyle(.black)
}
}
.padding(40)
}
}
@@ -1,4 +1,4 @@
#include "raylib_bridge.h"
#include "raybri.h"
#include "raylib.h"
#include "rlgl.h"
@@ -8,16 +8,14 @@
#include <math.h>
#include <stddef.h>
#include <stdio.h>
#define SR_FOV_Y 45.0f
#define SR_NEAR 0.1f
#define SR_FAR 1000.0f
#define SR_SHADOW_SIZE 1024
#define SR_GROUND_SIZE 40.0f
#include <string.h>
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;
@@ -30,6 +28,7 @@ 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 };
@@ -56,6 +55,8 @@ 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;
@@ -88,146 +89,11 @@ static Matrix sr_transform(Vector3 pos, float scale, float rx, float ry, float r
return MatrixMultiply(MatrixMultiply(mat_scale, mat_rotation), mat_translation);
}
static const char *SR_MAIN_VS =
"#version 330\n"
"layout(location = 0) in vec3 vertexPosition;\n"
"layout(location = 1) in vec2 vertexTexCoord;\n"
"layout(location = 2) in vec3 vertexNormal;\n"
"\n"
"uniform mat4 mvp;\n"
"uniform mat4 matModel;\n"
"uniform mat4 u_lightMVP;\n"
"\n"
"out vec3 vWorldPos;\n"
"out vec3 vNormal;\n"
"out vec2 vTexCoord;\n"
"out vec4 vLightClip;\n"
"\n"
"void main()\n"
"{\n"
" vec4 worldPos = matModel * vec4(vertexPosition, 1.0);\n"
" vWorldPos = worldPos.xyz;\n"
" vNormal = normalize(mat3(matModel) * vertexNormal);\n"
" vTexCoord = vertexTexCoord;\n"
" vLightClip = u_lightMVP * vec4(vertexPosition, 1.0);\n"
" gl_Position = mvp * vec4(vertexPosition, 1.0);\n"
"}\n";
static const char *SR_MAIN_FS =
"#version 330\n"
"\n"
"in vec3 vWorldPos;\n"
"in vec3 vNormal;\n"
"in vec2 vTexCoord;\n"
"in vec4 vLightClip;\n"
"\n"
"uniform sampler2D texture0;\n"
"uniform sampler2D u_shadowMap;\n"
"uniform vec3 u_lightPos;\n"
"uniform vec3 u_lightColor;\n"
"uniform vec3 u_ambient;\n"
"uniform vec3 u_albedoColor;\n"
"uniform float u_lightEnabled;\n"
"uniform float u_emissive;\n"
"uniform float u_shadowBias;\n"
"uniform float u_shadowSoftness;\n"
"uniform float u_isGround;\n"
"uniform vec3 u_gridColor;\n"
"uniform vec3 u_cameraPos;\n"
"uniform vec3 u_fogColor;\n"
"uniform float u_fogStart;\n"
"uniform float u_fogEnd;\n"
"\n"
"out vec4 finalColor;\n"
"\n"
"bool isPixelInShadowMap(vec3 proj)\n"
"{\n"
" return proj.x >= 0.0 && proj.x <= 1.0 &&\n"
" proj.y >= 0.0 && proj.y <= 1.0 &&\n"
" proj.z >= 0.0 && proj.z <= 1.0;\n"
"}\n"
"\n"
"float shadowFactor()\n"
"{\n"
" vec3 proj = vLightClip.xyz / vLightClip.w;\n"
" proj = proj * 0.5 + 0.5;\n"
"\n"
" if (!isPixelInShadowMap(proj)) return 0.0;\n"
"\n"
" int radius = int(u_shadowSoftness);\n"
" vec2 texel = 1.0 / vec2(textureSize(u_shadowMap, 0));\n"
" float sum = 0.0;\n"
" float count = 0.0;\n"
" for (int x = -radius; x <= radius; x++)\n"
" {\n"
" for (int y = -radius; y <= radius; y++)\n"
" {\n"
" float d = texture(u_shadowMap, proj.xy + vec2(float(x), float(y)) * texel).r;\n"
" sum += (proj.z - u_shadowBias > d) ? 1.0 : 0.0;\n"
" count += 1.0;\n"
" }\n"
" }\n"
" return sum / count;\n"
"}\n"
"\n"
"void main()\n"
"{\n"
" vec4 texel = texture(texture0, vTexCoord);\n"
" vec3 albedo = texel.rgb * u_albedoColor;\n"
" vec3 N = normalize(vNormal);\n"
"\n"
" if (u_isGround > 0.5)\n"
" {\n"
" vec2 uv = vWorldPos.xz;\n"
" vec2 gg = abs(fract(uv - 0.5) - 0.5) / fwidth(uv);\n"
" float line = min(gg.x, gg.y);\n"
" float grid = 1.0 - min(line, 1.0);\n"
" albedo = mix(albedo, u_gridColor, grid * 0.7);\n"
" }\n"
"\n"
" vec3 color = albedo * u_ambient;\n"
"\n"
" if (u_lightEnabled > 0.5)\n"
" {\n"
" vec3 toLight = u_lightPos - vWorldPos;\n"
" float dist = length(toLight);\n"
" vec3 L = toLight / max(dist, 0.0001);\n"
" float diff = max(dot(N, L), 0.0);\n"
" float attenuation = 1.0 / (1.0 + 0.14 * dist + 0.07 * dist * dist);\n"
" float shadow = shadowFactor();\n"
" color += albedo * u_lightColor * diff * attenuation * (1.0 - shadow);\n"
" }\n"
"\n"
" color += albedo * u_emissive;\n"
"\n"
" float fogDist = length(u_cameraPos - vWorldPos);\n"
" float fog = clamp((fogDist - u_fogStart) / (u_fogEnd - u_fogStart), 0.0, 1.0);\n"
" color = mix(color, u_fogColor, fog);\n"
"\n"
" finalColor = vec4(color, 1.0);\n"
"}\n";
static const char *SR_SHADOW_VS =
"#version 330\n"
"layout(location = 0) in vec3 vertexPosition;\n"
"uniform mat4 mvp;\n"
"void main()\n"
"{\n"
" gl_Position = mvp * vec4(vertexPosition, 1.0);\n"
"}\n";
static const char *SR_SHADOW_FS =
"#version 330\n"
"out vec4 finalColor;\n"
"void main()\n"
"{\n"
" finalColor = vec4(1.0);\n"
"}\n";
static void sr_load_shaders(void)
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(SR_MAIN_VS, SR_MAIN_FS);
sr_shadow_shader = LoadShaderFromMemory(SR_SHADOW_VS, SR_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");
@@ -238,6 +104,8 @@ static void sr_load_shaders(void)
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");
@@ -249,8 +117,8 @@ static void sr_load_shaders(void)
// 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_SHADOW_SIZE, SR_SHADOW_SIZE, RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8, 1);
sr_shadow_depth = rlLoadTextureDepth(SR_SHADOW_SIZE, SR_SHADOW_SIZE, false);
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);
@@ -262,7 +130,7 @@ static void sr_load_shaders(void)
static void sr_build_ground(void)
{
Mesh ground_mesh = GenMeshPlane(SR_GROUND_SIZE, SR_GROUND_SIZE, 1, 1);
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;
@@ -270,27 +138,82 @@ static void sr_build_ground(void)
sr_ground_shadow_material.shader = sr_shadow_shader;
}
void sr_init(int width, int height)
// 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)
{
if (width > 0) sr_width = width;
if (height > 0) sr_height = height;
sr_light_pos = (Vector3){ 0.0f, 4.2f, 0.0f };
rlLoadExtensions(sr_gl_loader);
rlglInit(sr_width, sr_height);
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;
sr_load_shaders();
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);
rlLoadExtensions((void *)sr_gl_loader);
// Init with default 1x1 size
rlglInit(1, 1);
sr_load_shaders(main_vs, main_fs, shadow_vs, shadow_fs);
sr_config_shaders();
sr_build_ground();
sr_ready = 1;
}
void sr_load_model(const char *gltf_path)
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)
{
int cube_mat_index = (sr_model.materialCount > 0) ? sr_model.meshMaterial[0] : 0;
@@ -301,6 +224,15 @@ void sr_load_model(const char *gltf_path)
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;
}
@@ -310,13 +242,13 @@ void sr_load_model(const char *gltf_path)
}
}
void sr_resize(int width, int height)
void raybri_resize(int width, int height)
{
if (width > 0) sr_width = width;
if (height > 0) sr_height = height;
}
void sr_set_rotation(float x_deg, float y_deg, float z_deg)
void raybri_set_rotation(float x_deg, float y_deg, float z_deg)
{
sr_rot_x = x_deg;
sr_rot_y = y_deg;
@@ -328,11 +260,75 @@ 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_SHADOW_SIZE, SR_SHADOW_SIZE);
rlSetFramebufferWidth(SR_SHADOW_SIZE);
rlSetFramebufferHeight(SR_SHADOW_SIZE);
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);
@@ -377,117 +373,45 @@ static void sr_set_light_mvp(Matrix model)
SetShaderValueMatrix(sr_main_shader, loc_light_mvp, light_mvp);
}
static void sr_draw_object(Model model, Material material, Matrix model_mat, float is_ground, float emissive)
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 albedo[3] = { 1.0f, 1.0f, 1.0f };
SetShaderValue(sr_main_shader, loc_albedo_color, albedo, SHADER_UNIFORM_VEC3);
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 sr_render(void)
void raybri_render(void)
{
if (!sr_ready) return;
rlDrawRenderBatchActive();
// --- Light (point light above the scene) ---
sr_light_pos = (Vector3){ 0.0f, 4.2f, 0.0f };
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();
// --- 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_NEAR * tan((double)SR_FOV_Y * 0.5 * DEG2RAD);
double right = top * (double)aspect;
rlFrustum(-right, right, -top, top, (double)SR_NEAR, (double)SR_FAR);
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);
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 };
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;
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, &eye, 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);
int shadow_unit = 1;
SetShaderValue(sr_main_shader, loc_shadow_map, &shadow_unit, SHADER_UNIFORM_INT);
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), 1.0f, 0.0f);
// --- Cubes ---
if (sr_has_model)
{
sr_draw_object(sr_model, sr_cube_material, sr_cube_transform(), 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();
sr_render_main_pass();
}
void sr_shutdown(void)
void raybri_shutdown(void)
{
if (!sr_ready) return;
@@ -499,6 +423,12 @@ void sr_shutdown(void)
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);
+46
View File
@@ -0,0 +1,46 @@
#ifndef OGS_MAHJONG_RAYLIB_BRIDGE_H
#define OGS_MAHJONG_RAYLIB_BRIDGE_H
#ifdef __cplusplus
extern "C" {
#endif
// Render configuration, sourced from renderConst.swift.
typedef struct raybri_config {
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;
// Initialise the OpenGL-backed raylib scene (no raylib window is created).
// The four shader sources come from renderConstShader.swift.
void raybri_init(
const char *main_vs,
const char *main_fs,
const char *shadow_vs,
const char *shadow_fs,
raybri_config config
);
// Load the textured cube glTF model.
void raybri_load_model(const char *gltf_path);
// Resize the viewport.
void raybri_resize(int width, int height);
// Cube rotation, driven by the application (Euler angles, degrees).
void raybri_set_rotation(float x_deg, float y_deg, float z_deg);
// Render one frame.
void raybri_render(void);
// Release all GPU resources.
void raybri_shutdown(void);
#ifdef __cplusplus
}
#endif
#endif
@@ -0,0 +1,47 @@
import AppKit
final class RenderGLView: NSOpenGLView {
override init(frame frameRect: NSRect) {
guard
let format = NSOpenGLPixelFormat(attributes: RENDER_OPENGL_ATTRS)
else {
fatalError("ERROR Could not create required OpenGL pixel format")
}
super.init(frame: frameRect, pixelFormat: format)!
wantsBestResolutionOpenGLSurface = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareOpenGL() {
super.prepareOpenGL()
renderSet(F.didPrepareGL, true)
}
override func reshape() {
super.reshape()
needsDisplay = true
let ps = renderPixelSize(self)
renderSet(F.reshapePixelSize, ps)
}
override func viewDidChangeBackingProperties() {
super.viewDidChangeBackingProperties()
needsDisplay = true
let ps = renderPixelSize(self)
renderSet(F.backingPixelSize, ps)
}
override func draw(_ dirtyRect: NSRect) {
let vm = RenderVM.shared!
if vm.didPrepareGL {
renderDraw(vm)
}
}
deinit {
renderSet(F.willDeinit, true)
}
}
@@ -0,0 +1,11 @@
import AppKit
import SwiftUI
/// Render view for SwiftUI
struct RenderView: NSViewRepresentable {
func makeNSView(context: Context) -> RenderGLView {
RenderVM.shared!.glView
}
func updateNSView(_ nsView: RenderGLView, context: Context) {}
}
+14
View File
@@ -0,0 +1,14 @@
class RenderComponent {
let ctrl = DialectController(RenderContext())
static private(set) weak var singleton: RenderComponent?
init() {
Self.singleton = self
renderRegisterEffects(ctrl)
renderRegisterShoulds(ctrl)
}
func setup() {
renderSet(F.didSetup, true)
}
}
+20
View File
@@ -0,0 +1,20 @@
import AppKit
import RaylibBridge
func renderDraw(_ vm: RenderVM) {
vm.glView.openGLContext?.makeCurrentContext()
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()
}
func renderPixelSize(_ view: NSView) -> [Int32] {
let backing = view.convertToBacking(view.bounds)
let w = Int32(max(1, backing.width))
let h = Int32(max(1, backing.height))
return [w, h]
}
+24
View File
@@ -0,0 +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_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
]
+162
View File
@@ -0,0 +1,162 @@
let RENDER_SHADER_MAIN_FS = """
#version 150
in vec3 vWorldPos;
in vec3 vNormal;
in vec2 vTexCoord;
in vec4 vLightClip;
uniform sampler2D texture0;
uniform sampler2D u_normalMap;
uniform float u_normalStrength;
uniform sampler2D u_shadowMap;
uniform vec3 u_lightPos;
uniform vec3 u_lightColor;
uniform vec3 u_ambient;
uniform vec3 u_albedoColor;
uniform float u_lightEnabled;
uniform float u_emissive;
uniform float u_shadowBias;
uniform float u_shadowSoftness;
uniform float u_isGround;
uniform vec3 u_gridColor;
uniform vec3 u_cameraPos;
uniform vec3 u_fogColor;
uniform float u_fogStart;
uniform float u_fogEnd;
out vec4 finalColor;
bool isPixelInShadowMap(vec3 proj)
{
return proj.x >= 0.0 && proj.x <= 1.0 &&
proj.y >= 0.0 && proj.y <= 1.0 &&
proj.z >= 0.0 && proj.z <= 1.0;
}
float shadowFactor()
{
vec3 proj = vLightClip.xyz / vLightClip.w;
proj = proj * 0.5 + 0.5;
if (!isPixelInShadowMap(proj)) return 0.0;
int radius = int(u_shadowSoftness);
vec2 texel = 1.0 / vec2(textureSize(u_shadowMap, 0));
float sum = 0.0;
float count = 0.0;
for (int x = -radius; x <= radius; x++)
{
for (int y = -radius; y <= radius; y++)
{
float d = texture(u_shadowMap, proj.xy + vec2(float(x), float(y)) * texel).r;
sum += (proj.z - u_shadowBias > d) ? 1.0 : 0.0;
count += 1.0;
}
}
return sum / count;
}
mat3 cotangentFrame(vec3 N, vec3 p, vec2 uv)
{
vec3 dp1 = dFdx(p);
vec3 dp2 = dFdy(p);
vec2 duv1 = dFdx(uv);
vec2 duv2 = dFdy(uv);
vec3 dp2perp = cross(dp2, N);
vec3 dp1perp = cross(N, dp1);
vec3 T = dp2perp * duv1.x + dp1perp * duv2.x;
vec3 B = dp2perp * duv1.y + dp1perp * duv2.y;
float invmax = inversesqrt(max(dot(T, T), dot(B, B)));
return mat3(T * invmax, B * invmax, N);
}
void main()
{
vec4 texel = texture(texture0, vTexCoord);
vec3 albedo = texel.rgb * u_albedoColor;
vec3 N = normalize(vNormal);
if (u_normalStrength > 0.0)
{
vec3 nm = texture(u_normalMap, vTexCoord).rgb * 2.0 - 1.0;
nm.xy *= u_normalStrength;
N = normalize(cotangentFrame(N, vWorldPos, vTexCoord) * nm);
}
if (u_isGround > 0.5)
{
vec2 uv = vWorldPos.xz;
vec2 gg = abs(fract(uv - 0.5) - 0.5) / fwidth(uv);
float line = min(gg.x, gg.y);
float grid = 1.0 - min(line, 1.0);
albedo = mix(albedo, u_gridColor, grid * 0.7);
}
vec3 color = albedo * u_ambient;
if (u_lightEnabled > 0.5)
{
vec3 toLight = u_lightPos - vWorldPos;
float dist = length(toLight);
vec3 L = toLight / max(dist, 0.0001);
float diff = max(dot(N, L), 0.0);
float attenuation = 1.0 / (1.0 + 0.14 * dist + 0.07 * dist * dist);
float shadow = shadowFactor();
color += albedo * u_lightColor * diff * attenuation * (1.0 - shadow);
}
color += albedo * u_emissive;
float fogDist = length(u_cameraPos - vWorldPos);
float fog = clamp((fogDist - u_fogStart) / (u_fogEnd - u_fogStart), 0.0, 1.0);
color = mix(color, u_fogColor, fog);
finalColor = vec4(color, 1.0);
}
"""
let RENDER_SHADER_MAIN_VS = """
#version 150
in vec3 vertexPosition;
in vec2 vertexTexCoord;
in vec3 vertexNormal;
uniform mat4 mvp;
uniform mat4 matModel;
uniform mat4 u_lightMVP;
out vec3 vWorldPos;
out vec3 vNormal;
out vec2 vTexCoord;
out vec4 vLightClip;
void main()
{
vec4 worldPos = matModel * vec4(vertexPosition, 1.0);
vWorldPos = worldPos.xyz;
vNormal = normalize(mat3(matModel) * vertexNormal);
vTexCoord = vertexTexCoord;
vLightClip = u_lightMVP * vec4(vertexPosition, 1.0);
gl_Position = mvp * vec4(vertexPosition, 1.0);
}
"""
let RENDER_SHADER_SHADOW_FS = """
#version 150
out vec4 finalColor;
void main()
{
finalColor = vec4(1.0);
}
"""
let RENDER_SHADER_SHADOW_VS = """
#version 150
in vec3 vertexPosition;
uniform mat4 mvp;
void main()
{
gl_Position = mvp * vec4(vertexPosition, 1.0);
}
"""
+46
View File
@@ -0,0 +1,46 @@
import Foundation
import RaylibBridge
import QuartzCore
func renderDeinit(_ vm: RenderVM) {
print("ИГР renderD")
vm.timer?.invalidate()
vm.glView.openGLContext?.makeCurrentContext()
raybri_shutdown()
}
func renderInit(_ vm: RenderVM) {
vm.glView.openGLContext?.makeCurrentContext()
// Enable VSync
var swapInterval: Int32 = 1
vm.glView.openGLContext?.setValues(&swapInterval, for: .swapInterval)
// Init Raylib
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) {
// Make a time mark for calculating time delta
vm.startTime = CACurrentMediaTime()
// Schedule repaints every once in FPS seconds
let timer = Timer(timeInterval: 1.0 / RENDER_FPS, repeats: true) { [weak vm] _ in
vm?.glView.needsDisplay = true
}
vm.timer = timer
// .common means holding buttons in UI does not pause this rendering timer
RunLoop.main.add(timer, forMode: .common)
}
+16
View File
@@ -0,0 +1,16 @@
import Combine
import Foundation
final class RenderVM: ObservableObject {
var didPrepareGL = false
let glView = RenderGLView(frame: .zero)
var pixelSize = [Int32]()
var startTime: CFTimeInterval = 0
var timer: Timer?
static private(set) weak var shared: RenderVM?
init() {
Self.shared = self
}
}
-138
View File
@@ -1,138 +0,0 @@
import SwiftUI
import AppKit
import QuartzCore
import RaylibBridge
/// A raylib-driven 3D scene (rendered through rlgl into an NSOpenGLView) that
/// sits behind the SwiftUI interface.
struct RaylibGLView: NSViewRepresentable {
func makeNSView(context: Context) -> RaylibGLNSView {
RaylibGLNSView(frame: .zero)
}
func updateNSView(_ nsView: RaylibGLNSView, context: Context) {}
}
/// An OpenGL view whose context is rendered directly by raylib's rlgl layer,
/// without letting raylib create its own window. Mirrors the reference sample
/// (`swiftraylib`), but drives a single cube that is rotated by the application
/// every frame.
final class RaylibGLNSView: NSOpenGLView {
private var renderTimer: Timer?
private var ready = false
private var pixelWidth: Int32 = 1
private var pixelHeight: Int32 = 1
private var startTime: CFTimeInterval = 0
override init(frame frameRect: NSRect) {
let attributes: [NSOpenGLPixelFormatAttribute] = [
UInt32(NSOpenGLPFAOpenGLProfile), UInt32(NSOpenGLProfileVersion4_1Core),
UInt32(NSOpenGLPFAColorSize), 24,
UInt32(NSOpenGLPFAAlphaSize), 8,
UInt32(NSOpenGLPFADepthSize), 24,
UInt32(NSOpenGLPFADoubleBuffer),
UInt32(NSOpenGLPFAAccelerated),
0
]
guard let format = NSOpenGLPixelFormat(attributes: attributes) else {
fatalError("Unable to create an OpenGL 4.1 core pixel format")
}
super.init(frame: frameRect, pixelFormat: format)!
wantsBestResolutionOpenGLSurface = true
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func prepareOpenGL() {
super.prepareOpenGL()
guard let context = openGLContext else { return }
context.makeCurrentContext()
var swapInterval: Int32 = 1
context.setValues(&swapInterval, for: .swapInterval)
updatePixelSize()
sr_init(pixelWidth, pixelHeight)
loadModel()
startTime = CACurrentMediaTime()
ready = true
startRenderTimer()
}
private func startRenderTimer() {
guard renderTimer == nil else { return }
renderTimer = Timer.scheduledTimer(withTimeInterval: 1.0 / 60.0, repeats: true) { [weak self] _ in
self?.needsDisplay = true
}
}
private func loadModel() {
for path in modelCandidates() where FileManager.default.fileExists(atPath: path) {
sr_load_model(path)
return
}
}
private func modelCandidates() -> [String] {
var paths: [String] = []
if let resources = Bundle.main.resourceURL {
paths.append(resources.appendingPathComponent("assets/cube.gltf").path)
}
let cwd = FileManager.default.currentDirectoryPath
paths.append("\(cwd)/assets/cube.gltf")
if let exe = Bundle.main.executableURL {
let dir = exe.deletingLastPathComponent()
paths.append(dir.appendingPathComponent("assets/cube.gltf").path)
}
return paths
}
override func reshape() {
super.reshape()
needsDisplay = true
}
override func viewDidChangeBackingProperties() {
super.viewDidChangeBackingProperties()
needsDisplay = true
}
private func updatePixelSize() {
let backing = convertToBacking(bounds)
pixelWidth = Int32(max(1, backing.width))
pixelHeight = Int32(max(1, backing.height))
}
override func draw(_ dirtyRect: NSRect) {
guard ready, let context = openGLContext else { return }
context.makeCurrentContext()
updatePixelSize()
sr_resize(pixelWidth, pixelHeight)
let t = Float(CACurrentMediaTime() - startTime)
sr_set_rotation(t * 6.0, t * 18.0, 0.0)
sr_render()
context.flushBuffer()
}
deinit {
renderTimer?.invalidate()
openGLContext?.makeCurrentContext()
sr_shutdown()
}
}
+8 -13
View File
@@ -8,22 +8,17 @@ struct RootView: View {
}
var body: some View {
ZStack {
RaylibGLView()
.ignoresSafeArea()
VStack(spacing: 16) {
Text("Hello, World!")
.font(.largeTitle)
VStack(spacing: 16) {
Text("Hello, World!")
.font(.largeTitle)
Text(vm.countText)
.font(.title3.monospacedDigit())
Text(vm.countText)
.font(.title3.monospacedDigit())
Button("Increment") {
rootSet(F.didClickIncrement, true)
}
Button("Increment") {
rootSet(F.didClickIncrement, true)
}
.padding(40)
}
.padding(40)
}
}
-51
View File
@@ -1,51 +0,0 @@
version: 4
output:
game/ver-mac/src/dialect.swift:
type: swift
RootComponent:
type: component
oneliners:
- countText: print(c.countText)
- countText: RootVM.shared!.countText = c.countText
shoulds:
count:
1. Upon hitting 10 the first time:
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
RootContext:
type: context
fields:
count: Int
countText: String
didClickIncrement: Bool
didLaunch: Bool
didSetup: Bool
@@ -1,30 +0,0 @@
#ifndef OGS_MAHJONG_RAYLIB_BRIDGE_H
#define OGS_MAHJONG_RAYLIB_BRIDGE_H
#ifdef __cplusplus
extern "C" {
#endif
// Initialise the OpenGL-backed raylib scene (no raylib window is created).
void sr_init(int width, int height);
// Load the textured cube glTF model.
void sr_load_model(const char *gltf_path);
// Resize the viewport.
void sr_resize(int width, int height);
// Cube rotation, driven by the application (Euler angles, degrees).
void sr_set_rotation(float x_deg, float y_deg, float z_deg);
// Render one frame.
void sr_render(void);
// Release all GPU resources.
void sr_shutdown(void);
#ifdef __cplusplus
}
#endif
#endif
@@ -1 +0,0 @@
../../../../../components/root/mac/view/RaylibGLView.swift
+67
View File
@@ -0,0 +1,67 @@
version: 4
output:
ver-mac/src/dialect.swift:
type: swift
ChkgfxComponent:
type: component
shoulds:
didLaunch:
1. Only once during the first setup:
if:
c.recentField == F.didSetup &&
c.didLaunch == false
then:
c.didLaunch = true
ChkgfxContext:
type: context
fields:
didLaunch: Bool
didSetup: Bool
RenderContext:
type: context
fields:
backingPixelSize: [Int32]
didLaunch: Bool
didPrepareGL: Bool
didSetup: Bool
pixelSize: [Int32]
reshapePixelSize: [Int32]
willDeinit: Bool
RenderComponent:
type: component
oneliners:
- didPrepareGL: renderInit(RenderVM.shared!)
- didPrepareGL: RenderVM.shared!.didPrepareGL = true
- didPrepareGL: renderStartTimer(RenderVM.shared!)
- didPrepareGL: renderLoadCubeModel(RenderVM.shared!)
- pixelSize: RenderVM.shared!.pixelSize = c.pixelSize
- willDeinit: renderDeinit(RenderVM.shared!)
shoulds:
didLaunch:
1. Only once during the first setup:
if:
c.recentField == F.didSetup &&
c.didLaunch == false
then:
c.didLaunch = true
pixelSize:
1. Upon launch:
if:
c.recentField == F.didLaunch
then:
c.pixelSize = [1, 1]
2. Upon resize:
if:
c.recentField == F.reshapePixelSize
then:
c.pixelSize = c.reshapePixelSize
3. Upon DPI change:
if:
c.recentField == F.backingPixelSize
then:
c.pixelSize = c.backingPixelSize
+26
View File
@@ -0,0 +1,26 @@
<?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>OGS chkgfx</string>
<key>CFBundleDisplayName</key>
<string>OGS chkgfx</string>
<key>CFBundleIdentifier</key>
<string>org.opengamestudio.chkgfx</string>
<key>CFBundleExecutable</key>
<string>ogs-chkgfx</string>
<key>CFBundleIconFile</key>
<string>AppIcon</string>
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>2.0.0</string>
<key>CFBundleVersion</key>
<string>1</string>
<key>LSMinimumSystemVersion</key>
<string>11.0</string>
<key>NSHighResolutionCapable</key>
<true/>
</dict>
</plist>
+37
View File
@@ -0,0 +1,37 @@
// swift-tools-version: 5.9
import Foundation
import PackageDescription
let raylibPrefix = ProcessInfo.processInfo.environment["RAYLIB_PREFIX"] ?? "/opt/homebrew"
let package = Package(
name: "OGSchkgfx",
platforms: [
.macOS(.v13)
],
targets: [
.target(
name: "RaylibBridge",
path: "src/raybri",
publicHeadersPath: ".",
cSettings: [
.unsafeFlags(["-I", "\(raylibPrefix)/include"])
]
),
.executableTarget(
name: "ogs-chkgfx",
dependencies: ["RaylibBridge"],
path: "src",
exclude: ["raybri"],
swiftSettings: [
.unsafeFlags(["-Xcc", "-DGL_SILENCE_DEPRECATION"])
],
linkerSettings: [
.unsafeFlags([
"-L", "\(raylibPrefix)/lib",
"-lraylib"
])
]
)
]
)
+1
View File
@@ -0,0 +1 @@
../../../res/AppIcon.icns
+1
View File
@@ -0,0 +1 @@
../../../res/cube
+26
View File
@@ -0,0 +1,26 @@
import AppKit
final class AppDelegate:
NSObject,
NSApplicationDelegate
{
let chkgfx = ChkgfxComponent()
let chkgfxVM = ChkgfxVM()
let render = RenderComponent()
let renderVM = RenderVM()
func applicationDidFinishLaunching(_ notification: Notification) {
// Bring the app to the foreground
NSApp.setActivationPolicy(.regular)
NSApp.activate(ignoringOtherApps: true)
otherSetupConsoleLogging(chkgfx.ctrl, "Chkgfx")
chkgfx.setup()
otherSetupConsoleLogging(render.ctrl, "Render")
render.setup()
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
true
}
}
+18
View File
@@ -0,0 +1,18 @@
import AppKit
import SwiftUI
@main
struct ChkgfxApp: App {
@NSApplicationDelegateAdaptor(AppDelegate.self) private var appDelegate
var body: some Scene {
WindowGroup {
ZStack {
RenderView()
.ignoresSafeArea()
ChkgfxView(appDelegate.chkgfxVM)
}
}
.defaultSize(width: 640, height: 480)
}
}
+1
View File
@@ -0,0 +1 @@
../../../../components/chkgfx/chkgfx.swift
+1
View File
@@ -0,0 +1 @@
../../../../components/chkgfx/chkgfxVM.swift
+1
View File
@@ -0,0 +1 @@
../../../../../components/chkgfx/mac/view/ChkgfxView.swift
+342
View File
@@ -0,0 +1,342 @@
// Reusable "none" constant
public let DIALECT_CONTEXT_RECENT_FIELD_NONE = "none"
// Base protocol for each component's state
public protocol DialectContext {
var recentField: String { get set }
func field<T>(_ name: String) -> T
func fieldAny(_ name: String) -> Any
mutating func setField(_ name: String, _ value: Any)
}
// Default implementation of `fieldAny` method for the protocol
public extension DialectContext {
func fieldAny(_ name: String) -> Any {
return field(name)
}
}
// The engine of the dialect components
public class DialectController {
var callbacks = [(DialectContext) -> Void]()
var context: DialectContext
var functions = [(DialectContext) -> DialectContext]()
var isProcessingQueue = false
var queue = [DialectContext]()
public init(_ context: DialectContext) {
self.context = context
}
func executeFunctions() {
let c = queue.removeFirst()
// 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 {
let ctx = f(context)
if ctx.recentField != DIALECT_CONTEXT_RECENT_FIELD_NONE {
queue.append(ctx)
}
}
reportContext()
}
func processQueue() {
// Prevent recursion.
if isProcessingQueue {
return
}
isProcessingQueue = true
while (queue.count > 0) {
executeFunctions()
}
isProcessingQueue = false
}
public func registerCallback(_ cb: @escaping (DialectContext) -> Void) {
callbacks.append(cb)
}
public func registerFieldCallback(
_ fieldName: String,
_ cb: @escaping (DialectContext) -> Void
) {
callbacks.append({ c in
if c.recentField == fieldName {
cb(c)
}
})
}
public func registerFunction(_ f: @escaping (DialectContext) -> DialectContext) {
functions.append(f)
}
func reportContext() {
for cb in callbacks {
cb(context)
}
}
public func set(
_ fieldName: String,
_ value: Any
) {
var c = context
c.setField(fieldName, value)
c.recentField = fieldName
queue.append(c)
processQueue()
}
}
// Register several oneliner callbacks to a controller
func registerOneliners<T>(
_ ctrl: DialectController,
_ items: [Any]
) -> T? {
let halfCount = items.count / 2
for i in 0..<halfCount {
let field = items[i * 2] as! String
let callback = items[i * 2 + 1] as! (T) -> Void
ctrl.registerFieldCallback(field) { cc in
let c = cc as! T
callback(c)
}
}
// A hack for generics to operate
return nil
}
// Context field names for static type check
public struct F {
public static let backingPixelSize = "backingPixelSize"
public static let didLaunch = "didLaunch"
public static let didPrepareGL = "didPrepareGL"
public static let didSetup = "didSetup"
public static let pixelSize = "pixelSize"
public static let reshapePixelSize = "reshapePixelSize"
public static let willDeinit = "willDeinit"
}
public struct ChkgfxContext: DialectContext {
public var didLaunch = Bool()
public var didSetup = Bool()
public var recentField = ""
public func field<T>(_ name: String) -> T {
if (name == "didLaunch") {
return didLaunch as! T
}
else if (name == "didSetup") {
return didSetup as! T
}
return "unknown-field-name" as! T
}
public mutating func setField(
_ name: String,
_ value: Any
) {
if (name == "didLaunch") {
didLaunch = value as! Bool
}
else if (name == "didSetup") {
didSetup = value as! Bool
}
}
}
public struct RenderContext: DialectContext {
public var backingPixelSize = [Int32]()
public var didLaunch = Bool()
public var didPrepareGL = Bool()
public var didSetup = Bool()
public var pixelSize = [Int32]()
public var reshapePixelSize = [Int32]()
public var willDeinit = Bool()
public var recentField = ""
public func field<T>(_ name: String) -> T {
if (name == "backingPixelSize") {
return backingPixelSize as! T
}
else if (name == "didLaunch") {
return didLaunch as! T
}
else if (name == "didPrepareGL") {
return didPrepareGL as! T
}
else if (name == "didSetup") {
return didSetup as! T
}
else if (name == "pixelSize") {
return pixelSize as! T
}
else if (name == "reshapePixelSize") {
return reshapePixelSize as! T
}
else if (name == "willDeinit") {
return willDeinit as! T
}
return "unknown-field-name" as! T
}
public mutating func setField(
_ name: String,
_ value: Any
) {
if (name == "backingPixelSize") {
backingPixelSize = value as! [Int32]
}
else if (name == "didLaunch") {
didLaunch = value as! Bool
}
else if (name == "didPrepareGL") {
didPrepareGL = value as! Bool
}
else if (name == "didSetup") {
didSetup = value as! Bool
}
else if (name == "pixelSize") {
pixelSize = value as! [Int32]
}
else if (name == "reshapePixelSize") {
reshapePixelSize = value as! [Int32]
}
else if (name == "willDeinit") {
willDeinit = value as! Bool
}
}
}
public func chkgfxSet(
_ key: String,
_ value: Any
) {
ChkgfxComponent.singleton!.ctrl.set(key, value)
}
public func renderSet(
_ key: String,
_ value: Any
) {
RenderComponent.singleton!.ctrl.set(key, value)
}
func chkgfxShouldResetDidLaunch(_ c: ChkgfxContext) -> ChkgfxContext {
var 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
}
func renderShouldResetDidLaunch(_ c: RenderContext) -> RenderContext {
var 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
}
func renderShouldResetPixelSize(_ c: RenderContext) -> RenderContext {
var c = c
/* 1. Upon launch */
if
c.recentField == F.didLaunch
{
c.pixelSize = [1, 1]
c.recentField = F.pixelSize
return c
}
/* 2. Upon resize */
if
c.recentField == F.reshapePixelSize
{
c.pixelSize = c.reshapePixelSize
c.recentField = F.pixelSize
return c
}
/* 3. Upon DPI change */
if
c.recentField == F.backingPixelSize
{
c.pixelSize = c.backingPixelSize
c.recentField = F.pixelSize
return c
}
c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE
return c
}
func chkgfxRegisterShoulds(_ ctrl: DialectController) {
[
chkgfxShouldResetDidLaunch,
].forEach { f in
ctrl.registerFunction { c in f(c as! ChkgfxContext) }
}
}
func renderRegisterShoulds(_ ctrl: DialectController) {
[
renderShouldResetDidLaunch,
renderShouldResetPixelSize,
].forEach { f in
ctrl.registerFunction { c in f(c as! RenderContext) }
}
}
func renderRegisterEffects(_ ctrl: DialectController) {
let _: RenderContext? = registerOneliners(ctrl, [
F.didPrepareGL, { (c: RenderContext) in renderInit(RenderVM.shared!) },
F.didPrepareGL, { (c: RenderContext) in RenderVM.shared!.didPrepareGL = true },
F.didPrepareGL, { (c: RenderContext) in renderStartTimer(RenderVM.shared!) },
F.didPrepareGL, { (c: RenderContext) in renderLoadCubeModel(RenderVM.shared!) },
F.pixelSize, { (c: RenderContext) in RenderVM.shared!.pixelSize = c.pixelSize },
F.willDeinit, { (c: RenderContext) in renderDeinit(RenderVM.shared!) },
])
}
File renamed without changes.
+1
View File
@@ -0,0 +1 @@
../../../../components/raybri/raybri.c
+1
View File
@@ -0,0 +1 @@
../../../../components/raybri/raybri.h
+1
View File
@@ -0,0 +1 @@
../../../../components/render/render.swift
+1
View File
@@ -0,0 +1 @@
../../../../components/render/renderAux.swift
+1
View File
@@ -0,0 +1 @@
../../../../components/render/renderConst.swift
@@ -0,0 +1 @@
../../../../components/render/renderConstShader.swift
+1
View File
@@ -0,0 +1 @@
../../../../components/render/renderEffect.swift
+1
View File
@@ -0,0 +1 @@
../../../../components/render/renderVM.swift
@@ -0,0 +1 @@
../../../../../components/render/mac/view/RenderGLView.swift
+1
View File
@@ -0,0 +1 @@
../../../../../components/render/mac/view/RenderView.swift
+97
View File
@@ -0,0 +1,97 @@
version: 4
output:
ver-mac/src/dialect.swift:
type: swift
RenderContext:
type: context
fields:
backingPixelSize: [Int32]
didClickIncrement: Bool
didLaunch: Bool
didPrepareGL: Bool
didSetup: Bool
pixelSize: [Int32]
reshapePixelSize: [Int32]
willDeinit: Bool
RenderComponent:
type: component
oneliners:
- didClickIncrement: renderLoadCubeModel(RenderVM.shared!)
- didPrepareGL: renderInit(RenderVM.shared!)
- didPrepareGL: RenderVM.shared!.didPrepareGL = true
- didPrepareGL: renderStartTimer(RenderVM.shared!)
- pixelSize: RenderVM.shared!.pixelSize = c.pixelSize
- willDeinit: renderDeinit(RenderVM.shared!)
shoulds:
didLaunch:
1. Only once during the first setup:
if:
c.recentField == F.didSetup &&
c.didLaunch == false
then:
c.didLaunch = true
pixelSize:
1. Upon launch:
if:
c.recentField == F.didLaunch
then:
c.pixelSize = [1, 1]
2. Upon resize:
if:
c.recentField == F.reshapePixelSize
then:
c.pixelSize = c.reshapePixelSize
3. Upon DPI change:
if:
c.recentField == F.backingPixelSize
then:
c.pixelSize = c.backingPixelSize
RootComponent:
type: component
oneliners:
- countText: RootVM.shared!.countText = c.countText
- didClickIncrement: renderSet(F.didClickIncrement, true)
shoulds:
count:
1. Upon hitting 10 the first time:
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
RootContext:
type: context
fields:
count: Int
countText: String
didClickIncrement: Bool
didLaunch: Bool
didSetup: Bool
@@ -7,7 +7,7 @@
<key>CFBundleDisplayName</key>
<string>OGS Mahjong</string>
<key>CFBundleIdentifier</key>
<string>org.opengamestudio.Mahjong</string>
<string>org.opengamestudio.mahjong</string>
<key>CFBundleExecutable</key>
<string>ogs-mahjong</string>
<key>CFBundleIconFile</key>
@@ -1,6 +1,6 @@
// swift-tools-version: 5.9
import PackageDescription
import Foundation
import PackageDescription
let raylibPrefix = ProcessInfo.processInfo.environment["RAYLIB_PREFIX"] ?? "/opt/homebrew"
@@ -12,8 +12,8 @@ let package = Package(
targets: [
.target(
name: "RaylibBridge",
path: "bridge",
publicHeadersPath: "include",
path: "src/raybri",
publicHeadersPath: ".",
cSettings: [
.unsafeFlags(["-I", "\(raylibPrefix)/include"])
]
@@ -22,6 +22,10 @@ let package = Package(
name: "ogs-mahjong",
dependencies: ["RaylibBridge"],
path: "src",
exclude: ["raybri"],
swiftSettings: [
.unsafeFlags(["-Xcc", "-DGL_SILENCE_DEPRECATION"])
],
linkerSettings: [
.unsafeFlags([
"-L", "\(raylibPrefix)/lib",
+1
View File
@@ -0,0 +1 @@
../../../res/AppIcon.icns
+1
View File
@@ -0,0 +1 @@
../../../res/cube
@@ -4,6 +4,8 @@ final class AppDelegate:
NSObject,
NSApplicationDelegate
{
let render = RenderComponent()
let renderVM = RenderVM()
let root = RootComponent()
let rootVM = RootVM()
@@ -14,6 +16,8 @@ final class AppDelegate:
otherSetupConsoleLogging(root.ctrl, "Root")
root.setup()
otherSetupConsoleLogging(render.ctrl, "Render")
render.setup()
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
@@ -7,7 +7,11 @@ struct GameApp: App {
var body: some Scene {
WindowGroup {
RootView(appDelegate.rootVM)
ZStack {
RenderView()
.ignoresSafeArea()
RootView(appDelegate.rootVM)
}
}
.defaultSize(width: 640, height: 480)
}
@@ -119,13 +119,91 @@ func registerOneliners<T>(
// Context field names for static type check
public struct F {
public static let backingPixelSize = "backingPixelSize"
public static let count = "count"
public static let countText = "countText"
public static let didClickIncrement = "didClickIncrement"
public static let didLaunch = "didLaunch"
public static let didPrepareGL = "didPrepareGL"
public static let didSetup = "didSetup"
public static let pixelSize = "pixelSize"
public static let reshapePixelSize = "reshapePixelSize"
public static let willDeinit = "willDeinit"
}
public struct RenderContext: DialectContext {
public var backingPixelSize = [Int32]()
public var didClickIncrement = Bool()
public var didLaunch = Bool()
public var didPrepareGL = Bool()
public var didSetup = Bool()
public var pixelSize = [Int32]()
public var reshapePixelSize = [Int32]()
public var willDeinit = Bool()
public var recentField = ""
public func field<T>(_ name: String) -> T {
if (name == "backingPixelSize") {
return backingPixelSize as! T
}
else if (name == "didClickIncrement") {
return didClickIncrement as! T
}
else if (name == "didLaunch") {
return didLaunch as! T
}
else if (name == "didPrepareGL") {
return didPrepareGL as! T
}
else if (name == "didSetup") {
return didSetup as! T
}
else if (name == "pixelSize") {
return pixelSize as! T
}
else if (name == "reshapePixelSize") {
return reshapePixelSize as! T
}
else if (name == "willDeinit") {
return willDeinit as! T
}
return "unknown-field-name" as! T
}
public mutating func setField(
_ name: String,
_ value: Any
) {
if (name == "backingPixelSize") {
backingPixelSize = value as! [Int32]
}
else if (name == "didClickIncrement") {
didClickIncrement = value as! Bool
}
else if (name == "didLaunch") {
didLaunch = value as! Bool
}
else if (name == "didPrepareGL") {
didPrepareGL = value as! Bool
}
else if (name == "didSetup") {
didSetup = value as! Bool
}
else if (name == "pixelSize") {
pixelSize = value as! [Int32]
}
else if (name == "reshapePixelSize") {
reshapePixelSize = value as! [Int32]
}
else if (name == "willDeinit") {
willDeinit = value as! Bool
}
}
}
public struct RootContext: DialectContext {
public var count = Int()
public var countText = String()
@@ -178,6 +256,13 @@ public struct RootContext: DialectContext {
}
}
public func renderSet(
_ key: String,
_ value: Any
) {
RenderComponent.singleton!.ctrl.set(key, value)
}
public func rootSet(
_ key: String,
_ value: Any
@@ -185,6 +270,59 @@ public func rootSet(
RootComponent.singleton!.ctrl.set(key, value)
}
func renderShouldResetDidLaunch(_ c: RenderContext) -> RenderContext {
var 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
}
func renderShouldResetPixelSize(_ c: RenderContext) -> RenderContext {
var c = c
/* 1. Upon launch */
if
c.recentField == F.didLaunch
{
c.pixelSize = [1, 1]
c.recentField = F.pixelSize
return c
}
/* 2. Upon resize */
if
c.recentField == F.reshapePixelSize
{
c.pixelSize = c.reshapePixelSize
c.recentField = F.pixelSize
return c
}
/* 3. Upon DPI change */
if
c.recentField == F.backingPixelSize
{
c.pixelSize = c.backingPixelSize
c.recentField = F.pixelSize
return c
}
c.recentField = DIALECT_CONTEXT_RECENT_FIELD_NONE
return c
}
func rootShouldResetCount(_ c: RootContext) -> RootContext {
var c = c
@@ -256,6 +394,16 @@ func rootShouldResetDidLaunch(_ c: RootContext) -> RootContext {
return c
}
func renderRegisterShoulds(_ ctrl: DialectController) {
[
renderShouldResetDidLaunch,
renderShouldResetPixelSize,
].forEach { f in
ctrl.registerFunction { c in f(c as! RenderContext) }
}
}
func rootRegisterShoulds(_ ctrl: DialectController) {
[
rootShouldResetCount,
@@ -267,10 +415,22 @@ func rootRegisterShoulds(_ ctrl: DialectController) {
}
}
func rootRegisterEffects(_ ctrl: DialectController) {
let _: RootContext? = registerOneliners(ctrl, [
F.countText, { (c: RootContext) in print(c.countText) },
F.countText, { (c: RootContext) in RootVM.shared!.countText = c.countText },
func renderRegisterEffects(_ ctrl: DialectController) {
let _: RenderContext? = registerOneliners(ctrl, [
F.didClickIncrement, { (c: RenderContext) in renderLoadCubeModel(RenderVM.shared!) },
F.didPrepareGL, { (c: RenderContext) in renderInit(RenderVM.shared!) },
F.didPrepareGL, { (c: RenderContext) in RenderVM.shared!.didPrepareGL = true },
F.didPrepareGL, { (c: RenderContext) in renderStartTimer(RenderVM.shared!) },
F.pixelSize, { (c: RenderContext) in RenderVM.shared!.pixelSize = c.pixelSize },
F.willDeinit, { (c: RenderContext) in renderDeinit(RenderVM.shared!) },
])
}
func rootRegisterEffects(_ ctrl: DialectController) {
let _: RootContext? = registerOneliners(ctrl, [
F.countText, { (c: RootContext) in RootVM.shared!.countText = c.countText },
F.didClickIncrement, { (c: RootContext) in renderSet(F.didClickIncrement, true) },
])
}
+1
View File
@@ -0,0 +1 @@
../../../../components/other/other.swift
+1
View File
@@ -0,0 +1 @@
../../../../components/raybri/raybri.c
+1
View File
@@ -0,0 +1 @@
../../../../components/raybri/raybri.h
+1
View File
@@ -0,0 +1 @@
../../../../components/render/render.swift
+1
View File
@@ -0,0 +1 @@
../../../../components/render/renderAux.swift
+1
View File
@@ -0,0 +1 @@
../../../../components/render/renderConst.swift
@@ -0,0 +1 @@
../../../../components/render/renderConstShader.swift
+1
View File
@@ -0,0 +1 @@
../../../../components/render/renderEffect.swift
+1
View File
@@ -0,0 +1 @@
../../../../components/render/renderVM.swift
@@ -0,0 +1 @@
../../../../../components/render/mac/view/RenderGLView.swift
+1
View File
@@ -0,0 +1 @@
../../../../../components/render/mac/view/RenderView.swift
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
Binary file not shown.

After

Width:  |  Height:  |  Size: 19 KiB

File renamed without changes.
+12
View File
@@ -0,0 +1,12 @@
#!/bin/bash -e
SDIR=$(cd "$(dirname "$0")" ; pwd -P)
T=$SDIR/step
source $SDIR/paths
TARGET=ogs-chkgfx
STEP=0
source $T/generateDialect $TARGET
source $T/buildMac $TARGET
source $T/packageMac $TARGET "OGS chkgfx"
+12
View File
@@ -0,0 +1,12 @@
#!/bin/bash -e
SDIR=$(cd "$(dirname "$0")" ; pwd -P)
T=$SDIR/step
source $SDIR/paths
TARGET=ogs-mahjong
STEP=0
source $T/generateDialect $TARGET
source $T/buildMac $TARGET
source $T/packageMac $TARGET "OGS Mahjong"
-1
View File
@@ -1 +0,0 @@
APP_MAC="$SDIR/../game/ver-mac/.build/OGS Mahjong.app"
+1 -1
View File
@@ -5,4 +5,4 @@ T=$SDIR/step
source $SDIR/paths
STEP=0
source $T/runMac
source $T/runMac ogs-chkgfx "OGS chkgfx"
+1 -3
View File
@@ -5,6 +5,4 @@ T=$SDIR/step
source $SDIR/paths
STEP=0
source $T/generateDialect
source $T/buildMac
source $T/packageMac
source $T/runMac ogs-mahjong "OGS Mahjong"
+6 -9
View File
@@ -1,17 +1,14 @@
#!/bin/bash -e
TARGET=$1
STEP=$((STEP+1))
echo -e "\n> > > > Step №$STEP. Build for macOS"
echo -e "\n> > > > Step №$STEP. Build '$TARGET' for macOS"
# raylib is required for the 3D scene (used by the RaylibBridge target).
if [[ -z "${RAYLIB_PREFIX:-}" ]] && command -v brew >/dev/null 2>&1; then
RAYLIB_PREFIX="$(HOMEBREW_NO_AUTO_UPDATE=1 brew --prefix raylib 2>/dev/null || true)"
fi
if [[ -z "${RAYLIB_PREFIX:-}" ]]; then
RAYLIB_PREFIX=/opt/homebrew
RAYLIB_PREFIX="$(HOMEBREW_NO_AUTO_UPDATE=1 brew --prefix raylib 2>/dev/null)"
fi
export RAYLIB_PREFIX
echo "> > > > raylib: $RAYLIB_PREFIX"
echo "Raylib: $RAYLIB_PREFIX"
cd $SDIR/../game/ver-mac
swift build # -Xswiftc -swift-version -Xswiftc 6
cd $SDIR/../$TARGET/ver-mac
swift build
+3 -2
View File
@@ -1,6 +1,7 @@
#!/bin/bash -e
TARGET=$1
STEP=$((STEP+1))
echo -e "\n> > > > Step №$STEP. Generate Dialect"
echo -e "\n> > > > Step №$STEP. Generate Dialect for '$TARGET'"
$SDIR/../../dialect/util/run-generator --file=$SDIR/../dialect.yml
$SDIR/../../dialect/util/run-generator --file=$SDIR/../$TARGET/dialect.yml
+10 -10
View File
@@ -1,18 +1,18 @@
#!/bin/bash -e
STEP=$((STEP+1))
echo -e "\n> > > > Step №$STEP. Make an app package for macOS"
TARGET=$1
APP_NAME=$2
STEP=$((STEP+1))
echo -e "\n> > > > Step №$STEP. Make '$APP_NAME' macOS package for '$TARGET'"
APP_MAC="$SDIR/../$TARGET/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/../game/ver-mac/.build/debug/ogs-mahjong" "$APP_DAT/MacOS/ogs-mahjong"
cp "$SDIR/../game/ver-mac/Info.plist" "$APP_DAT/Info.plist"
cp "$SDIR/../game/ver-mac/Resources/AppIcon.icns" "$APP_DAT/Resources/AppIcon.icns"
mkdir -p "$APP_DAT/Resources/assets"
cp "$SDIR/../game/ver-mac/Resources/assets/"* "$APP_DAT/Resources/assets/"
cp $SDIR/../$TARGET/ver-mac/.build/debug/$TARGET "$APP_DAT/MacOS/$TARGET"
cp $SDIR/../$TARGET/ver-mac/Info.plist "$APP_DAT/Info.plist"
# Copy resources with symlink dereferencing
cp -R -L $SDIR/../$TARGET/ver-mac/res/* "$APP_DAT/Resources/"
+4 -2
View File
@@ -1,6 +1,8 @@
#!/bin/bash -e
TARGET=$1
APP_NAME=$2
STEP=$((STEP+1))
echo -e "\n> > > > Step №$STEP. Run macOS app"
echo -e "\n> > > > Step №$STEP. Run macOS app for '$TARGET'"
"$APP_MAC/Contents/MacOS/ogs-mahjong"
"$SDIR/../$TARGET/ver-mac/.build/$APP_NAME.app/Contents/MacOS/$TARGET"