diff --git a/AGENTS.md b/AGENTS.md index 61fa521..16dbfbd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -31,9 +31,14 @@ components/ SHARED source-of-truth for all components. root/mac/view/RootView.swift Per-platform SwiftUI view game/ver-mac/ macOS app (SPM executable target "ogs-mahjong") - Package.swift SPM manifest (macOS 13+, swift-tools 5.9) + Package.swift SPM manifest (macOS 13+, swift-tools 5.9); SPM C target + "RaylibBridge" (bridge/) + links Homebrew raylib 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. src/ GameApp.swift @main SwiftUI App entry AppDelegate.swift Creates RootComponent + RootVM, calls root.setup() @@ -42,6 +47,7 @@ game/ver-mac/ macOS app (SPM executable target "ogs-mahjong") 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 ref/swiftraylib Symlink to ../../swiftraylib — the raylib/SwiftUI renderer sample the game will use for 3D rendering. @@ -68,6 +74,7 @@ src/other/other.swift -> ../../../../components/other/other.swift ( 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) ``` SPM silently **skips** a dangling symlink (no error), so after moving @@ -95,6 +102,19 @@ So `/Volumes/MOE/p/dialect` must exist and its generator must be built before 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 `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`. +(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. + ## Build & Run ```bash @@ -106,9 +126,9 @@ 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` — `cd game/ver-mac && swift build` +2. `buildMac` — `brew --prefix raylib` -> `RAYLIB_PREFIX`, `swift build` 3. `packageMac` — assembles `.build/OGS Mahjong.app` (binary `ogs-mahjong`, - `Info.plist`, `Resources/AppIcon.icns`) + `Info.plist`, `Resources/AppIcon.icns`, `Resources/assets/`) ## Editing the dialect diff --git a/components/root/mac/view/RaylibGLView.swift b/components/root/mac/view/RaylibGLView.swift new file mode 100644 index 0000000..998daf6 --- /dev/null +++ b/components/root/mac/view/RaylibGLView.swift @@ -0,0 +1,140 @@ +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() + updatePixelSize() + needsDisplay = true + } + + override func viewDidChangeBackingProperties() { + super.viewDidChangeBackingProperties() + updatePixelSize() + 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 * 18.0, t * 60.0, 0.0) + + sr_render() + + context.flushBuffer() + } + + deinit { + renderTimer?.invalidate() + openGLContext?.makeCurrentContext() + sr_shutdown() + } +} diff --git a/components/root/mac/view/RootView.swift b/components/root/mac/view/RootView.swift index ccd1ea7..5234ae8 100644 --- a/components/root/mac/view/RootView.swift +++ b/components/root/mac/view/RootView.swift @@ -8,17 +8,22 @@ struct RootView: View { } var body: some View { - VStack(spacing: 16) { - Text("Hello, World!") - .font(.largeTitle) + ZStack { + RaylibGLView() + .ignoresSafeArea() - Text(vm.countText) - .font(.title3.monospacedDigit()) + VStack(spacing: 16) { + Text("Hello, World!") + .font(.largeTitle) - Button("Increment") { - rootSet(F.didClickIncrement, true) + Text(vm.countText) + .font(.title3.monospacedDigit()) + + Button("Increment") { + rootSet(F.didClickIncrement, true) + } } + .padding(40) } - .padding(40) } } diff --git a/game/ver-mac/Package.swift b/game/ver-mac/Package.swift index e2b4221..3d9def7 100644 --- a/game/ver-mac/Package.swift +++ b/game/ver-mac/Package.swift @@ -1,5 +1,8 @@ // swift-tools-version: 5.9 import PackageDescription +import Foundation + +let raylibPrefix = ProcessInfo.processInfo.environment["RAYLIB_PREFIX"] ?? "/opt/homebrew" let package = Package( name: "OGSMahjong", @@ -7,9 +10,24 @@ let package = Package( .macOS(.v13) ], targets: [ + .target( + name: "RaylibBridge", + path: "bridge", + publicHeadersPath: "include", + cSettings: [ + .unsafeFlags(["-I", "\(raylibPrefix)/include"]) + ] + ), .executableTarget( name: "ogs-mahjong", - path: "src" + dependencies: ["RaylibBridge"], + path: "src", + linkerSettings: [ + .unsafeFlags([ + "-L", "\(raylibPrefix)/lib", + "-lraylib" + ]) + ] ) ] ) diff --git a/game/ver-mac/Resources/assets/cube_rotating.gltf b/game/ver-mac/Resources/assets/cube_rotating.gltf deleted file mode 100644 index 79cc5d8..0000000 --- a/game/ver-mac/Resources/assets/cube_rotating.gltf +++ /dev/null @@ -1,185 +0,0 @@ -{ - "asset": { - "version": "2.0", - "generator": "swiftraylib sample" - }, - "scene": 0, - "scenes": [ - { - "nodes": [ - 0 - ] - } - ], - "nodes": [ - { - "mesh": 0, - "name": "Cube" - } - ], - "meshes": [ - { - "name": "Cube", - "primitives": [ - { - "attributes": { - "POSITION": 0, - "NORMAL": 1, - "TEXCOORD_0": 2 - }, - "indices": 3, - "material": 0, - "mode": 4 - } - ] - } - ], - "materials": [ - { - "name": "CubeFaces", - "pbrMetallicRoughness": { - "baseColorTexture": { - "index": 0 - }, - "metallicFactor": 0.0, - "roughnessFactor": 1.0 - } - } - ], - "textures": [ - { - "sampler": 0, - "source": 0 - } - ], - "images": [ - { - "uri": "cube_texture.png" - } - ], - "samplers": [ - { - "magFilter": 9729, - "minFilter": 9729, - "wrapS": 33071, - "wrapT": 33071 - } - ], - "accessors": [ - { - "bufferView": 0, - "componentType": 5126, - "count": 24, - "type": "VEC3", - "min": [ - -1.0, - -1.0, - -1.0 - ], - "max": [ - 1.0, - 1.0, - 1.0 - ] - }, - { - "bufferView": 1, - "componentType": 5126, - "count": 24, - "type": "VEC3" - }, - { - "bufferView": 2, - "componentType": 5126, - "count": 24, - "type": "VEC2" - }, - { - "bufferView": 3, - "componentType": 5123, - "count": 36, - "type": "SCALAR" - }, - { - "bufferView": 4, - "componentType": 5126, - "count": 5, - "type": "SCALAR", - "min": [ - 0.0 - ], - "max": [ - 4.0 - ] - }, - { - "bufferView": 5, - "componentType": 5126, - "count": 5, - "type": "VEC4" - } - ], - "bufferViews": [ - { - "buffer": 0, - "byteOffset": 0, - "byteLength": 288, - "target": 34962 - }, - { - "buffer": 0, - "byteOffset": 288, - "byteLength": 288, - "target": 34962 - }, - { - "buffer": 0, - "byteOffset": 576, - "byteLength": 192, - "target": 34962 - }, - { - "buffer": 0, - "byteOffset": 768, - "byteLength": 72, - "target": 34963 - }, - { - "buffer": 0, - "byteOffset": 840, - "byteLength": 20 - }, - { - "buffer": 0, - "byteOffset": 860, - "byteLength": 80 - } - ], - "buffers": [ - { - "uri": "data:application/octet-stream;base64,AACAPwAAgL8AAIC/AACAPwAAgD8AAIC/AACAPwAAgD8AAIA/AACAPwAAgL8AAIA/AACAvwAAgL8AAIC/AACAvwAAgL8AAIA/AACAvwAAgD8AAIA/AACAvwAAgD8AAIC/AACAvwAAgD8AAIC/AACAvwAAgD8AAIA/AACAPwAAgD8AAIA/AACAPwAAgD8AAIC/AACAvwAAgL8AAIC/AACAPwAAgL8AAIC/AACAPwAAgL8AAIA/AACAvwAAgL8AAIA/AACAvwAAgL8AAIA/AACAPwAAgL8AAIA/AACAPwAAgD8AAIA/AACAvwAAgD8AAIA/AACAvwAAgL8AAIC/AACAvwAAgD8AAIC/AACAPwAAgD8AAIC/AACAPwAAgL8AAIC/AACAPwAAAAAAAAAAAACAPwAAAAAAAAAAAACAPwAAAAAAAAAAAACAPwAAAAAAAAAAAACAvwAAAAAAAAAAAACAvwAAAAAAAAAAAACAvwAAAAAAAAAAAACAvwAAAAAAAAAAAAAAAAAAgD8AAAAAAAAAAAAAgD8AAAAAAAAAAAAAgD8AAAAAAAAAAAAAgD8AAAAAAAAAAAAAgL8AAAAAAAAAAAAAgL8AAAAAAAAAAAAAgL8AAAAAAAAAAAAAgL8AAAAAAAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIA/AAAAAAAAAAAAAIC/AAAAAAAAAAAAAIC/AAAAAAAAAAAAAIC/AAAAAAAAAAAAAIC/VVWpPgAA/j5VVak+AACAO6uqKjsAAIA7q6oqOwAA/j4AAKw+AAD+PgAAKj8AAP4+AAAqPwAAgDsAAKw+AACAO1VVKz8AAP4+VVUrPwAAgDtVVX8/AACAO1VVfz8AAP4+q6oqOwAAAT9VVak+AAABP1VVqT4AAH8/q6oqOwAAfz8AAKw+AAB/PwAAKj8AAH8/AAAqPwAAAT8AAKw+AAABP1VVfz8AAH8/VVV/PwAAAT9VVSs/AAABP1VVKz8AAH8/AAABAAIAAAACAAMABAAFAAYABAAGAAcACAAJAAoACAAKAAsADAANAA4ADAAOAA8AEAARABIAEAASABMAFAAVABYAFAAWABcAAAAAAAAAgD8AAABAAABAQAAAgEAAAAAAAAAAAAAAAAAAAIA/AAAAAPMENT8AAAAA8wQ1PwAAAAAAAIA/AAAAADIxjSQAAAAA8wQ1PwAAAADzBDW/AAAAADIxDSUAAAAAAACAvw==", - "byteLength": 940 - } - ], - "animations": [ - { - "name": "CubeSpin", - "samplers": [ - { - "input": 4, - "output": 5, - "interpolation": "LINEAR" - } - ], - "channels": [ - { - "sampler": 0, - "target": { - "node": 0, - "path": "rotation" - } - } - ] - } - ] -} diff --git a/game/ver-mac/bridge/include/raylib_bridge.h b/game/ver-mac/bridge/include/raylib_bridge.h new file mode 100644 index 0000000..fcaf199 --- /dev/null +++ b/game/ver-mac/bridge/include/raylib_bridge.h @@ -0,0 +1,30 @@ +#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 diff --git a/game/ver-mac/bridge/raylib_bridge.c b/game/ver-mac/bridge/raylib_bridge.c new file mode 100644 index 0000000..dadff86 --- /dev/null +++ b/game/ver-mac/bridge/raylib_bridge.c @@ -0,0 +1,504 @@ +#include "raylib_bridge.h" + +#include "raylib.h" +#include "rlgl.h" +#include "raymath.h" + +#include +#include +#include +#include + +#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 + +static int sr_width = 1; +static int sr_height = 1; + +// 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 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_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; + +// 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); +} + +// 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 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" + "float shadowFactor()\n" + "{\n" + " vec3 proj = vLightClip.xyz / vLightClip.w;\n" + " proj = proj * 0.5 + 0.5;\n" + "\n" + " if (proj.z > 1.0 || proj.z < 0.0) return 0.0;\n" + " if (proj.x < 0.0 || proj.x > 1.0 || proj.y < 0.0 || proj.y > 1.0) 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) +{ + sr_main_shader = LoadShaderFromMemory(SR_MAIN_VS, SR_MAIN_FS); + sr_shadow_shader = LoadShaderFromMemory(SR_SHADOW_VS, SR_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_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_SHADOW_SIZE, SR_SHADOW_SIZE, RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8, 1); + sr_shadow_depth = rlLoadTextureDepth(SR_SHADOW_SIZE, SR_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_GROUND_SIZE, SR_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; +} + +void sr_init(int width, int height) +{ + if (width > 0) sr_width = width; + if (height > 0) sr_height = height; + + rlLoadExtensions(sr_gl_loader); + rlglInit(sr_width, sr_height); + + sr_load_shaders(); + sr_build_ground(); + + sr_ready = 1; +} + +void sr_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); + + if (sr_has_model) + { + 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); + + 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 sr_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) +{ + 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_render_shadow_pass(void) +{ + rlViewport(0, 0, SR_SHADOW_SIZE, SR_SHADOW_SIZE); + rlSetFramebufferWidth(SR_SHADOW_SIZE); + rlSetFramebufferHeight(SR_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_draw_object(Model model, Material material, Matrix model_mat, 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); + SetShaderValue(sr_main_shader, loc_emissive, &emissive, SHADER_UNIFORM_FLOAT); + SetShaderValue(sr_main_shader, loc_is_ground, &is_ground, SHADER_UNIFORM_FLOAT); + + DrawMesh(model.meshes[0], material, model_mat); +} + +void sr_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(); +} + +void sr_shutdown(void) +{ + if (!sr_ready) return; + + if (sr_has_model) + { + UnloadModel(sr_model); + sr_has_model = 0; + } + + UnloadModel(sr_ground_model); + + 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); + + rlglClose(); + sr_ready = 0; +} diff --git a/game/ver-mac/src/root/view/RaylibGLView.swift b/game/ver-mac/src/root/view/RaylibGLView.swift new file mode 120000 index 0000000..c750636 --- /dev/null +++ b/game/ver-mac/src/root/view/RaylibGLView.swift @@ -0,0 +1 @@ +../../../../../components/root/mac/view/RaylibGLView.swift \ No newline at end of file diff --git a/util/step/buildMac b/util/step/buildMac index 19e41fb..cee602a 100755 --- a/util/step/buildMac +++ b/util/step/buildMac @@ -3,5 +3,15 @@ STEP=$((STEP+1)) echo -e "\n> > > > Step №$STEP. Build 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 +fi +export RAYLIB_PREFIX +echo "> > > > raylib: $RAYLIB_PREFIX" + cd $SDIR/../game/ver-mac swift build # -Xswiftc -swift-version -Xswiftc 6 diff --git a/util/step/packageMac b/util/step/packageMac index 50d668a..87ee9ca 100755 --- a/util/step/packageMac +++ b/util/step/packageMac @@ -13,3 +13,6 @@ 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/"