1 parent
1515a9483b
commit
fb28dd55c7
77 files changed
+1598
-543
No files matched your search
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,440 @@
|
||||
#include "raybri.h"
|
||||
|
||||
#include "raylib.h"
|
||||
#include "rlgl.h"
|
||||
#include "raymath.h"
|
||||
|
||||
#include <dlfcn.h>
|
||||
#include <math.h>
|
||||
#include <stddef.h>
|
||||
#include <stdio.h>
|
||||
#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;
|
||||
static float sr_rot_z = 0.0f;
|
||||
|
||||
static int sr_ready = 0;
|
||||
|
||||
static Model sr_model = { 0 };
|
||||
static int sr_has_model = 0;
|
||||
|
||||
static Material sr_cube_material = { 0 };
|
||||
static Material sr_cube_shadow_material = { 0 };
|
||||
static Texture2D sr_cube_normal = { 0 };
|
||||
|
||||
static Model sr_ground_model = { 0 };
|
||||
static Material sr_ground_material = { 0 };
|
||||
static Material sr_ground_shadow_material = { 0 };
|
||||
|
||||
static Shader sr_main_shader = { 0 };
|
||||
static Shader sr_shadow_shader = { 0 };
|
||||
|
||||
static int sr_shadow_fbo = 0;
|
||||
static unsigned int sr_shadow_color = 0;
|
||||
static unsigned int sr_shadow_depth = 0;
|
||||
|
||||
static Matrix sr_light_view = { 0 };
|
||||
static Matrix sr_light_proj = { 0 };
|
||||
static Vector3 sr_light_pos = { 0.0f, 0.0f, 0.0f };
|
||||
|
||||
// Main shader uniform locations
|
||||
static int loc_light_pos = -1;
|
||||
static int loc_light_color = -1;
|
||||
static int loc_ambient = -1;
|
||||
static int loc_light_enabled = -1;
|
||||
static int loc_emissive = -1;
|
||||
static int loc_albedo_color = -1;
|
||||
static int loc_shadow_map = -1;
|
||||
static int loc_shadow_bias = -1;
|
||||
static int loc_shadow_softness = -1;
|
||||
static int loc_normal_map = -1;
|
||||
static int loc_normal_strength = -1;
|
||||
static int loc_light_mvp = -1;
|
||||
static int loc_is_ground = -1;
|
||||
static int loc_grid_color = -1;
|
||||
static int loc_camera_pos = -1;
|
||||
static int loc_fog_color = -1;
|
||||
static int loc_fog_start = -1;
|
||||
static int loc_fog_end = -1;
|
||||
|
||||
// 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 void sr_load_shaders(const char *main_vs, const char *main_fs,
|
||||
const char *shadow_vs, const char *shadow_fs)
|
||||
{
|
||||
sr_main_shader = LoadShaderFromMemory(main_vs, main_fs);
|
||||
sr_shadow_shader = LoadShaderFromMemory(shadow_vs, shadow_fs);
|
||||
|
||||
loc_light_pos = GetShaderLocation(sr_main_shader, "u_lightPos");
|
||||
loc_light_color = GetShaderLocation(sr_main_shader, "u_lightColor");
|
||||
loc_ambient = GetShaderLocation(sr_main_shader, "u_ambient");
|
||||
loc_light_enabled = GetShaderLocation(sr_main_shader, "u_lightEnabled");
|
||||
loc_emissive = GetShaderLocation(sr_main_shader, "u_emissive");
|
||||
loc_albedo_color = GetShaderLocation(sr_main_shader, "u_albedoColor");
|
||||
loc_shadow_map = GetShaderLocation(sr_main_shader, "u_shadowMap");
|
||||
loc_shadow_bias = GetShaderLocation(sr_main_shader, "u_shadowBias");
|
||||
loc_shadow_softness = GetShaderLocation(sr_main_shader, "u_shadowSoftness");
|
||||
loc_normal_map = GetShaderLocation(sr_main_shader, "u_normalMap");
|
||||
loc_normal_strength = GetShaderLocation(sr_main_shader, "u_normalStrength");
|
||||
loc_light_mvp = GetShaderLocation(sr_main_shader, "u_lightMVP");
|
||||
loc_is_ground = GetShaderLocation(sr_main_shader, "u_isGround");
|
||||
loc_grid_color = GetShaderLocation(sr_main_shader, "u_gridColor");
|
||||
loc_camera_pos = GetShaderLocation(sr_main_shader, "u_cameraPos");
|
||||
loc_fog_color = GetShaderLocation(sr_main_shader, "u_fogColor");
|
||||
loc_fog_start = GetShaderLocation(sr_main_shader, "u_fogStart");
|
||||
loc_fog_end = GetShaderLocation(sr_main_shader, "u_fogEnd");
|
||||
|
||||
// Build a framebuffer whose depth attachment is a sampleable TEXTURE (raylib's
|
||||
// LoadRenderTexture() uses a non-sampleable renderbuffer, so we build it by hand).
|
||||
sr_shadow_fbo = rlLoadFramebuffer();
|
||||
sr_shadow_color = rlLoadTexture(NULL, sr_cfg.shadow_size, sr_cfg.shadow_size, RL_PIXELFORMAT_UNCOMPRESSED_R8G8B8A8, 1);
|
||||
sr_shadow_depth = rlLoadTextureDepth(sr_cfg.shadow_size, sr_cfg.shadow_size, false);
|
||||
|
||||
rlEnableFramebuffer(sr_shadow_fbo);
|
||||
rlFramebufferAttach(sr_shadow_fbo, sr_shadow_color, RL_ATTACHMENT_COLOR_CHANNEL0, RL_ATTACHMENT_TEXTURE2D, 0);
|
||||
rlFramebufferAttach(sr_shadow_fbo, sr_shadow_depth, RL_ATTACHMENT_DEPTH, RL_ATTACHMENT_TEXTURE2D, 0);
|
||||
int shadow_ok = rlFramebufferComplete(sr_shadow_fbo);
|
||||
fprintf(stderr, "SR: shadow framebuffer %s\n", shadow_ok ? "complete" : "INCOMPLETE");
|
||||
rlDisableFramebuffer();
|
||||
}
|
||||
|
||||
static void sr_build_ground(void)
|
||||
{
|
||||
Mesh ground_mesh = GenMeshPlane(sr_cfg.ground_size, sr_cfg.ground_size, 1, 1);
|
||||
sr_ground_model = LoadModelFromMesh(ground_mesh);
|
||||
sr_ground_material = LoadMaterialDefault();
|
||||
sr_ground_material.shader = sr_main_shader;
|
||||
sr_ground_shadow_material = LoadMaterialDefault();
|
||||
sr_ground_shadow_material.shader = sr_shadow_shader;
|
||||
}
|
||||
|
||||
// Uniforms that never change between frames are uploaded once at startup.
|
||||
// SetShaderValue() is a bare glUniform*(), so the program must be bound.
|
||||
static void sr_config_shaders(void)
|
||||
{
|
||||
sr_light_pos = (Vector3){ 0.0f, 4.2f, 0.0f };
|
||||
|
||||
Vector3 light_color = { 1.15f, 1.08f, 0.98f };
|
||||
Vector3 ambient = { 0.30f, 0.32f, 0.38f };
|
||||
Vector3 grid_color = { 0.45f, 0.62f, 0.95f };
|
||||
Vector3 fog_color = { 24.0f / 255.0f, 26.0f / 255.0f, 34.0f / 255.0f };
|
||||
Vector3 camera_pos = { 0.0f, 2.6f, 5.6f };
|
||||
float albedo[3] = { 1.0f, 1.0f, 1.0f };
|
||||
float light_amount = 1.0f;
|
||||
float shadow_bias = 0.0025f;
|
||||
float shadow_softness = 4.0f;
|
||||
float fog_start = 10.0f;
|
||||
float fog_end = 34.0f;
|
||||
int shadow_unit = 1;
|
||||
int normal_unit = 2;
|
||||
|
||||
rlEnableShader(sr_main_shader.id);
|
||||
|
||||
SetShaderValue(sr_main_shader, loc_light_pos, &sr_light_pos, SHADER_UNIFORM_VEC3);
|
||||
SetShaderValue(sr_main_shader, loc_light_color, &light_color, SHADER_UNIFORM_VEC3);
|
||||
SetShaderValue(sr_main_shader, loc_ambient, &ambient, SHADER_UNIFORM_VEC3);
|
||||
SetShaderValue(sr_main_shader, loc_light_enabled, &light_amount, SHADER_UNIFORM_FLOAT);
|
||||
SetShaderValue(sr_main_shader, loc_shadow_bias, &shadow_bias, SHADER_UNIFORM_FLOAT);
|
||||
SetShaderValue(sr_main_shader, loc_shadow_softness, &shadow_softness, SHADER_UNIFORM_FLOAT);
|
||||
SetShaderValue(sr_main_shader, loc_grid_color, &grid_color, SHADER_UNIFORM_VEC3);
|
||||
SetShaderValue(sr_main_shader, loc_camera_pos, &camera_pos, SHADER_UNIFORM_VEC3);
|
||||
SetShaderValue(sr_main_shader, loc_fog_color, &fog_color, SHADER_UNIFORM_VEC3);
|
||||
SetShaderValue(sr_main_shader, loc_fog_start, &fog_start, SHADER_UNIFORM_FLOAT);
|
||||
SetShaderValue(sr_main_shader, loc_fog_end, &fog_end, SHADER_UNIFORM_FLOAT);
|
||||
SetShaderValue(sr_main_shader, loc_albedo_color, albedo, SHADER_UNIFORM_VEC3);
|
||||
SetShaderValue(sr_main_shader, loc_shadow_map, &shadow_unit, SHADER_UNIFORM_INT);
|
||||
SetShaderValue(sr_main_shader, loc_normal_map, &normal_unit, SHADER_UNIFORM_INT);
|
||||
|
||||
rlDisableShader();
|
||||
}
|
||||
|
||||
void raybri_init(
|
||||
const char *main_vs,
|
||||
const char *main_fs,
|
||||
const char *shadow_vs,
|
||||
const char *shadow_fs,
|
||||
raybri_config config
|
||||
) {
|
||||
sr_cfg = config;
|
||||
|
||||
// raylib's default INFO logging is noisy; keep warnings and errors only.
|
||||
SetTraceLogLevel(LOG_WARNING);
|
||||
|
||||
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 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;
|
||||
sr_cube_material = sr_model.materials[cube_mat_index];
|
||||
sr_cube_material.shader = sr_main_shader;
|
||||
|
||||
Texture2D base_tex = sr_cube_material.maps[MATERIAL_MAP_DIFFUSE].texture;
|
||||
SetTextureFilter(base_tex, TEXTURE_FILTER_BILINEAR);
|
||||
SetTextureWrap(base_tex, TEXTURE_WRAP_CLAMP);
|
||||
|
||||
char normal_path[1024];
|
||||
snprintf(normal_path, sizeof(normal_path), "%scube_normal.png", asset_dir);
|
||||
if (FileExists(normal_path))
|
||||
{
|
||||
sr_cube_normal = LoadTexture(normal_path);
|
||||
SetTextureFilter(sr_cube_normal, TEXTURE_FILTER_BILINEAR);
|
||||
SetTextureWrap(sr_cube_normal, TEXTURE_WRAP_CLAMP);
|
||||
}
|
||||
|
||||
sr_cube_shadow_material = sr_cube_material;
|
||||
sr_cube_shadow_material.shader = sr_shadow_shader;
|
||||
}
|
||||
else
|
||||
{
|
||||
fprintf(stderr, "SR: failed to load model: %s\n", gltf_path);
|
||||
}
|
||||
}
|
||||
|
||||
void raybri_resize(int width, int height)
|
||||
{
|
||||
if (width > 0) sr_width = width;
|
||||
if (height > 0) sr_height = height;
|
||||
}
|
||||
|
||||
void raybri_set_rotation(float x_deg, float y_deg, float z_deg)
|
||||
{
|
||||
sr_rot_x = x_deg;
|
||||
sr_rot_y = y_deg;
|
||||
sr_rot_z = z_deg;
|
||||
}
|
||||
|
||||
static Matrix sr_cube_transform(void)
|
||||
{
|
||||
return sr_transform((Vector3){ 0.0f, 1.1f, 0.0f }, 1.0f, sr_rot_x, sr_rot_y, sr_rot_z);
|
||||
}
|
||||
|
||||
static void sr_draw_object(Model model, Material material, Matrix model_mat,
|
||||
Texture2D normal, float is_ground, float emissive);
|
||||
|
||||
static void sr_render_main_pass(void)
|
||||
{
|
||||
// --- Main pass: camera ---
|
||||
rlViewport(0, 0, sr_width, sr_height);
|
||||
rlSetFramebufferWidth(sr_width);
|
||||
rlSetFramebufferHeight(sr_height);
|
||||
|
||||
rlClearColor(24, 26, 34, 255);
|
||||
rlClearScreenBuffers();
|
||||
|
||||
rlMatrixMode(RL_PROJECTION);
|
||||
rlPushMatrix();
|
||||
rlLoadIdentity();
|
||||
|
||||
float aspect = (float)sr_width / (float)sr_height;
|
||||
double top = (double)sr_cfg.near_plane * tan((double)sr_cfg.fov_y * 0.5 * DEG2RAD);
|
||||
double right = top * (double)aspect;
|
||||
rlFrustum(-right, right, -top, top, (double)sr_cfg.near_plane, (double)sr_cfg.far_plane);
|
||||
|
||||
rlMatrixMode(RL_MODELVIEW);
|
||||
rlLoadIdentity();
|
||||
|
||||
Vector3 eye = { 0.0f, 2.6f, 5.6f };
|
||||
Vector3 target = { 0.0f, 1.0f, 0.0f };
|
||||
Vector3 up = { 0.0f, 1.0f, 0.0f };
|
||||
|
||||
Matrix view = MatrixLookAt(eye, target, up);
|
||||
rlMultMatrixf(MatrixToFloat(view));
|
||||
|
||||
rlEnableDepthTest();
|
||||
rlEnableBackfaceCulling();
|
||||
rlSetCullFace(RL_CULL_FACE_BACK);
|
||||
|
||||
rlEnableShader(sr_main_shader.id);
|
||||
|
||||
rlActiveTextureSlot(1);
|
||||
rlEnableTexture(sr_shadow_depth);
|
||||
rlActiveTextureSlot(0);
|
||||
|
||||
// --- Ground (procedural grid floor) ---
|
||||
sr_draw_object(sr_ground_model, sr_ground_material, MatrixTranslate(0.0f, 0.0f, 0.0f), (Texture2D){ 0 }, 1.0f, 0.0f);
|
||||
|
||||
// --- Cubes ---
|
||||
if (sr_has_model)
|
||||
{
|
||||
sr_draw_object(sr_model, sr_cube_material, sr_cube_transform(), sr_cube_normal, 0.0f, 0.0f);
|
||||
}
|
||||
|
||||
// Flush while the projection/modelview matrices are still active, otherwise
|
||||
// rlgl draws the pending batch with the restored (2D) projection.
|
||||
rlDrawRenderBatchActive();
|
||||
|
||||
// --- Restore matrices (equivalent to raylib's EndMode3D) ---
|
||||
rlMatrixMode(RL_PROJECTION);
|
||||
rlPopMatrix();
|
||||
rlMatrixMode(RL_MODELVIEW);
|
||||
rlLoadIdentity();
|
||||
rlDisableDepthTest();
|
||||
rlDisableBackfaceCulling();
|
||||
}
|
||||
|
||||
static void sr_render_shadow_pass(void)
|
||||
{
|
||||
rlViewport(0, 0, sr_cfg.shadow_size, sr_cfg.shadow_size);
|
||||
rlSetFramebufferWidth(sr_cfg.shadow_size);
|
||||
rlSetFramebufferHeight(sr_cfg.shadow_size);
|
||||
|
||||
rlEnableFramebuffer(sr_shadow_fbo);
|
||||
|
||||
rlClearColor(255, 255, 255, 255);
|
||||
rlClearScreenBuffers();
|
||||
|
||||
rlEnableDepthTest();
|
||||
rlEnableBackfaceCulling();
|
||||
rlSetCullFace(RL_CULL_FACE_FRONT);
|
||||
|
||||
rlMatrixMode(RL_PROJECTION);
|
||||
rlPushMatrix();
|
||||
rlLoadIdentity();
|
||||
rlMultMatrixf(MatrixToFloat(sr_light_proj));
|
||||
|
||||
rlMatrixMode(RL_MODELVIEW);
|
||||
rlLoadIdentity();
|
||||
rlMultMatrixf(MatrixToFloat(sr_light_view));
|
||||
|
||||
if (sr_has_model)
|
||||
{
|
||||
DrawMesh(sr_model.meshes[0], sr_cube_shadow_material, sr_cube_transform());
|
||||
}
|
||||
|
||||
rlDrawRenderBatchActive();
|
||||
|
||||
rlMatrixMode(RL_PROJECTION);
|
||||
rlPopMatrix();
|
||||
|
||||
rlSetCullFace(RL_CULL_FACE_BACK);
|
||||
rlDisableFramebuffer();
|
||||
|
||||
rlViewport(0, 0, sr_width, sr_height);
|
||||
rlSetFramebufferWidth(sr_width);
|
||||
rlSetFramebufferHeight(sr_height);
|
||||
rlDisableDepthTest();
|
||||
}
|
||||
|
||||
static void sr_set_light_mvp(Matrix model)
|
||||
{
|
||||
Matrix light_mvp = MatrixMultiply(MatrixMultiply(model, sr_light_view), sr_light_proj);
|
||||
SetShaderValueMatrix(sr_main_shader, loc_light_mvp, light_mvp);
|
||||
}
|
||||
|
||||
static void sr_bind_normal(Texture2D tex)
|
||||
{
|
||||
rlActiveTextureSlot(2);
|
||||
if (tex.id > 0) rlEnableTexture(tex.id);
|
||||
rlActiveTextureSlot(0);
|
||||
}
|
||||
|
||||
static void sr_draw_object(Model model, Material material, Matrix model_mat,
|
||||
Texture2D normal, float is_ground, float emissive)
|
||||
{
|
||||
sr_set_light_mvp(model_mat);
|
||||
|
||||
float normal_strength = (normal.id > 0) ? 1.0f : 0.0f;
|
||||
SetShaderValue(sr_main_shader, loc_emissive, &emissive, SHADER_UNIFORM_FLOAT);
|
||||
SetShaderValue(sr_main_shader, loc_is_ground, &is_ground, SHADER_UNIFORM_FLOAT);
|
||||
SetShaderValue(sr_main_shader, loc_normal_strength, &normal_strength, SHADER_UNIFORM_FLOAT);
|
||||
|
||||
sr_bind_normal(normal);
|
||||
|
||||
DrawMesh(model.meshes[0], material, model_mat);
|
||||
}
|
||||
|
||||
void raybri_render(void)
|
||||
{
|
||||
if (!sr_ready) return;
|
||||
|
||||
rlDrawRenderBatchActive();
|
||||
|
||||
// --- Light (point light above the scene) ---
|
||||
Vector3 light_target = (Vector3){ 0.0f, -2.0f, 0.0f };
|
||||
Vector3 light_up = (Vector3){ 0.0f, 0.0f, -1.0f };
|
||||
sr_light_view = MatrixLookAt(sr_light_pos, light_target, light_up);
|
||||
sr_light_proj = MatrixPerspective(90.0 * DEG2RAD, 1.0, 1.5, 16.0);
|
||||
|
||||
sr_render_shadow_pass();
|
||||
sr_render_main_pass();
|
||||
}
|
||||
|
||||
void raybri_shutdown(void)
|
||||
{
|
||||
if (!sr_ready) return;
|
||||
|
||||
if (sr_has_model)
|
||||
{
|
||||
UnloadModel(sr_model);
|
||||
sr_has_model = 0;
|
||||
}
|
||||
|
||||
UnloadModel(sr_ground_model);
|
||||
|
||||
if (sr_cube_normal.id > 0)
|
||||
{
|
||||
UnloadTexture(sr_cube_normal);
|
||||
sr_cube_normal.id = 0;
|
||||
}
|
||||
|
||||
if (sr_shadow_color > 0) rlUnloadTexture(sr_shadow_color);
|
||||
if (sr_shadow_depth > 0) rlUnloadTexture(sr_shadow_depth);
|
||||
if (sr_shadow_fbo > 0) rlUnloadFramebuffer(sr_shadow_fbo);
|
||||
if (sr_main_shader.id > 0) UnloadShader(sr_main_shader);
|
||||
if (sr_shadow_shader.id > 0) UnloadShader(sr_shadow_shader);
|
||||
|
||||
rlglClose();
|
||||
sr_ready = 0;
|
||||
}
|
||||
@@ -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) {}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -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]
|
||||
}
|
||||
@@ -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
|
||||
]
|
||||
@@ -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);
|
||||
}
|
||||
"""
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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,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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user