Compare commits
26
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
713b8c6ce3 | ||
|
|
92b3c29c85 | ||
|
|
2d8e066700 | ||
|
|
ed0c597192 | ||
|
|
fb5075a997 | ||
|
|
3e8f513a29 | ||
|
|
916a40611c | ||
|
|
235ff0a41d | ||
|
|
be9f360084 | ||
|
|
59362bde0f | ||
|
|
48fe768689 | ||
|
|
e7966cac80 | ||
|
|
f3432515ac | ||
|
|
ac861fe881 | ||
|
|
657d0e21fd | ||
|
|
18f5023c02 | ||
|
|
6feb0c1575 | ||
|
|
148b511009 | ||
|
|
af063209ff | ||
|
|
163aa3052b | ||
|
|
426504c748 | ||
|
|
30de42caca | ||
|
|
31005e0861 | ||
|
|
d12118e80a | ||
|
|
8b30fa4e7c | ||
|
|
3549b0be95 |
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 Riyyi
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -40,6 +40,8 @@ vendor
|
|||||||
- microui (temp)
|
- microui (temp)
|
||||||
- box3d?
|
- box3d?
|
||||||
- build.sh -> bootstrap shim for `compile/build.odin`
|
- build.sh -> bootstrap shim for `compile/build.odin`
|
||||||
|
- stb
|
||||||
|
- kb (https://github.com/JimmyLefevre/kb)
|
||||||
|
|
||||||
## Hot Reload
|
## Hot Reload
|
||||||
|
|
||||||
@@ -52,3 +54,10 @@ skips building the engine if its already running (pgrep).
|
|||||||
|
|
||||||
no hot reload does not use game.dll, instead it imports the game source
|
no hot reload does not use game.dll, instead it imports the game source
|
||||||
as a normal Odin package during build.
|
as a normal Odin package during build.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
This project is licensed under the [MIT License](LICENSE), unless otherwise
|
||||||
|
noted. Individual files or subdirectories may carry a different license (for
|
||||||
|
example, the [Unlicense](https://unlicense.org)); in those cases, the license
|
||||||
|
terms specified in the file or directory take precedence.
|
||||||
|
|||||||
@@ -0,0 +1,55 @@
|
|||||||
|
# Simple textured cube
|
||||||
|
# 8 vertices, 6 faces (12 triangles), per-face UVs
|
||||||
|
|
||||||
|
o Cube
|
||||||
|
|
||||||
|
# Positions
|
||||||
|
v -1.0 -1.0 1.0
|
||||||
|
v 1.0 -1.0 1.0
|
||||||
|
v 1.0 1.0 1.0
|
||||||
|
v -1.0 1.0 1.0
|
||||||
|
v -1.0 -1.0 -1.0
|
||||||
|
v 1.0 -1.0 -1.0
|
||||||
|
v 1.0 1.0 -1.0
|
||||||
|
v -1.0 1.0 -1.0
|
||||||
|
|
||||||
|
# Texture coordinates
|
||||||
|
vt 0.0 0.0
|
||||||
|
vt 1.0 0.0
|
||||||
|
vt 1.0 1.0
|
||||||
|
vt 0.0 1.0
|
||||||
|
|
||||||
|
# Normals
|
||||||
|
vn 0.0 0.0 1.0
|
||||||
|
vn 0.0 0.0 -1.0
|
||||||
|
vn 1.0 0.0 0.0
|
||||||
|
vn -1.0 0.0 0.0
|
||||||
|
vn 0.0 1.0 0.0
|
||||||
|
vn 0.0 -1.0 0.0
|
||||||
|
|
||||||
|
# Faces (front, back, right, left, top, bottom)
|
||||||
|
# Each face uses two triangles: (0,1,2) and (0,2,3)
|
||||||
|
|
||||||
|
# Front (+Z)
|
||||||
|
f 1/1/1 2/2/1 3/3/1
|
||||||
|
f 1/1/1 3/3/1 4/4/1
|
||||||
|
|
||||||
|
# Back (-Z)
|
||||||
|
f 6/1/2 5/2/2 8/3/2
|
||||||
|
f 6/1/2 8/3/2 7/4/2
|
||||||
|
|
||||||
|
# Right (+X)
|
||||||
|
f 2/1/3 6/2/3 7/3/3
|
||||||
|
f 2/1/3 7/3/3 3/4/3
|
||||||
|
|
||||||
|
# Left (-X)
|
||||||
|
f 5/1/4 1/2/4 4/3/4
|
||||||
|
f 5/1/4 4/3/4 8/4/4
|
||||||
|
|
||||||
|
# Top (+Y)
|
||||||
|
f 4/1/5 3/2/5 7/3/5
|
||||||
|
f 4/1/5 7/3/5 8/4/5
|
||||||
|
|
||||||
|
# Bottom (-Y)
|
||||||
|
f 5/1/6 6/2/6 2/3/6
|
||||||
|
f 5/1/6 2/3/6 1/4/6
|
||||||
+2027
File diff suppressed because it is too large
Load Diff
+85
-46
@@ -14,17 +14,20 @@ import "../vendor/brokkr"
|
|||||||
when ODIN_OS == .Windows {
|
when ODIN_OS == .Windows {
|
||||||
LIB_EXT :: ".dll"
|
LIB_EXT :: ".dll"
|
||||||
OS_NAME :: "windows"
|
OS_NAME :: "windows"
|
||||||
} else when ODIN_OS == .Darwin {
|
}
|
||||||
|
else when ODIN_OS == .Darwin {
|
||||||
LIB_EXT :: ".dylib"
|
LIB_EXT :: ".dylib"
|
||||||
OS_NAME :: "macos"
|
OS_NAME :: "macos"
|
||||||
} else {
|
}
|
||||||
|
else {
|
||||||
LIB_EXT :: ".so"
|
LIB_EXT :: ".so"
|
||||||
OS_NAME :: "linux"
|
OS_NAME :: "linux"
|
||||||
}
|
}
|
||||||
|
|
||||||
when ODIN_ARCH == .amd64 {
|
when ODIN_ARCH == .amd64 {
|
||||||
ARCH_NAME :: "x86_64"
|
ARCH_NAME :: "x86_64"
|
||||||
} else when ODIN_ARCH == .arm64 {
|
}
|
||||||
|
else when ODIN_ARCH == .arm64 {
|
||||||
ARCH_NAME :: "aarch64"
|
ARCH_NAME :: "aarch64"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -32,8 +35,6 @@ PROJECT_NAME :: "sindri"
|
|||||||
BUILD_DIRECTORY :: "out/"
|
BUILD_DIRECTORY :: "out/"
|
||||||
|
|
||||||
GAME_SRC_DIR :: "game/"
|
GAME_SRC_DIR :: "game/"
|
||||||
GAME_LIB_PATH :: BUILD_DIRECTORY + "game" + LIB_EXT
|
|
||||||
GAME_LIB_TMP_PATH :: BUILD_DIRECTORY + "game_tmp" + LIB_EXT
|
|
||||||
|
|
||||||
ENGINE_DIR :: "src/"
|
ENGINE_DIR :: "src/"
|
||||||
ENGINE_OUTPUT :: BUILD_DIRECTORY + PROJECT_NAME
|
ENGINE_OUTPUT :: BUILD_DIRECTORY + PROJECT_NAME
|
||||||
@@ -47,6 +48,7 @@ Options :: struct {
|
|||||||
debug: bool `args:"optional" usage:"Build project in debug-mode."`,
|
debug: bool `args:"optional" usage:"Build project in debug-mode."`,
|
||||||
release: bool `args:"optional" usage:"Build project in release-mode."`,
|
release: bool `args:"optional" usage:"Build project in release-mode."`,
|
||||||
run: bool `args:"optional" usage:"Run project."`,
|
run: bool `args:"optional" usage:"Run project."`,
|
||||||
|
hot_reload: bool `args:"optional" usage:"Hot-reload project."`,
|
||||||
wgpu_init: bool `args:"optional" usage:"Prepare wgpu-native."`,
|
wgpu_init: bool `args:"optional" usage:"Prepare wgpu-native."`,
|
||||||
wgpu_version: string `args:"optional" usage:"Override the wgpu release version to init."`,
|
wgpu_version: string `args:"optional" usage:"Override the wgpu release version to init."`,
|
||||||
fmt: bool `args:"optional" usage:"Run odinfmt."`,
|
fmt: bool `args:"optional" usage:"Run odinfmt."`,
|
||||||
@@ -77,8 +79,9 @@ main :: proc() {
|
|||||||
if opts.debug do build_project(true, opts.overflow[:])
|
if opts.debug do build_project(true, opts.overflow[:])
|
||||||
if opts.release do build_project(false, opts.overflow[:])
|
if opts.release do build_project(false, opts.overflow[:])
|
||||||
if opts.run do run_project(opts.overflow[:])
|
if opts.run do run_project(opts.overflow[:])
|
||||||
|
if opts.hot_reload do hot_reload(!opts.release, opts.overflow[:])
|
||||||
if opts.wgpu_init do wgpu_init(opts.wgpu_version)
|
if opts.wgpu_init do wgpu_init(opts.wgpu_version)
|
||||||
if opts.fmt do format_source()
|
if opts.fmt && !format_source() do os.exit(1)
|
||||||
if opts.pre_commit do pre_commit()
|
if opts.pre_commit do pre_commit()
|
||||||
|
|
||||||
// Fallback to building project, if no option provided
|
// Fallback to building project, if no option provided
|
||||||
@@ -91,17 +94,12 @@ main :: proc() {
|
|||||||
// Build project
|
// Build project
|
||||||
|
|
||||||
// Build the game library ('game/') and the engine ('src/')
|
// Build the game library ('game/') and the engine ('src/')
|
||||||
build_project :: proc(debug: bool, odin_extra_args: []string) {
|
build_project :: proc(debug: bool, extra_args: []string) {
|
||||||
version := project_version()
|
version := project_version()
|
||||||
|
|
||||||
// Setup compiled wgpu binary
|
// Setup compiled wgpu binary
|
||||||
wgpu_init()
|
wgpu_init()
|
||||||
|
|
||||||
// ----------------------------------------
|
|
||||||
// Game compile
|
|
||||||
|
|
||||||
build_game(debug, version, odin_extra_args)
|
|
||||||
|
|
||||||
// ----------------------------------------
|
// ----------------------------------------
|
||||||
// Engine compile
|
// Engine compile
|
||||||
|
|
||||||
@@ -111,7 +109,7 @@ build_project :: proc(debug: bool, odin_extra_args: []string) {
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
build_engine(debug, version, odin_extra_args)
|
build_engine(debug, version, extra_args)
|
||||||
}
|
}
|
||||||
|
|
||||||
// Shared builder between game/engine
|
// Shared builder between game/engine
|
||||||
@@ -124,6 +122,7 @@ build_common :: proc(
|
|||||||
b := brokkr.builder_make()
|
b := brokkr.builder_make()
|
||||||
brokkr.build(&b, dir)
|
brokkr.build(&b, dir)
|
||||||
brokkr.append(&b, "-show-timings")
|
brokkr.append(&b, "-show-timings")
|
||||||
|
brokkr.collection(&b, "game", ".")
|
||||||
brokkr.collection(&b, PROJECT_NAME, "src")
|
brokkr.collection(&b, PROJECT_NAME, "src")
|
||||||
brokkr.collection(&b, "gram", "vendor/gram/src")
|
brokkr.collection(&b, "gram", "vendor/gram/src")
|
||||||
brokkr.collection(&b, "wgpu", "vendor")
|
brokkr.collection(&b, "wgpu", "vendor")
|
||||||
@@ -144,24 +143,6 @@ build_common :: proc(
|
|||||||
return b
|
return b
|
||||||
}
|
}
|
||||||
|
|
||||||
// Build the game as a dynamic library loaded by the engine
|
|
||||||
build_game :: proc(debug: bool, version: string, extra_args: []string) {
|
|
||||||
b := build_common(GAME_SRC_DIR, debug, version, extra_args)
|
|
||||||
defer brokkr.builder_destroy(&b)
|
|
||||||
brokkr.mode(&b, .Dynamic)
|
|
||||||
// Use a temp file because it first writes an empty file, which the engine
|
|
||||||
// would load before it is actually fully written
|
|
||||||
brokkr.out(&b, GAME_LIB_TMP_PATH)
|
|
||||||
if err := brokkr.execute(&b); err != nil {
|
|
||||||
os.exit(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
if !os.is_file(GAME_LIB_TMP_PATH) {
|
|
||||||
die("build produced no game lib %q", GAME_LIB_TMP_PATH)
|
|
||||||
}
|
|
||||||
os.rename(GAME_LIB_TMP_PATH, GAME_LIB_PATH)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Build the engine executable
|
// Build the engine executable
|
||||||
build_engine :: proc(debug: bool, version: string, extra_args: []string) {
|
build_engine :: proc(debug: bool, version: string, extra_args: []string) {
|
||||||
b := build_common(ENGINE_DIR, debug, version, extra_args)
|
b := build_common(ENGINE_DIR, debug, version, extra_args)
|
||||||
@@ -174,8 +155,7 @@ build_engine :: proc(debug: bool, version: string, extra_args: []string) {
|
|||||||
|
|
||||||
run_project :: proc(extra_args: []string) {
|
run_project :: proc(extra_args: []string) {
|
||||||
// Build project if it wasnt already
|
// Build project if it wasnt already
|
||||||
if !os.exists(ENGINE_OUTPUT) ||
|
if !os.exists(output_path(ENGINE_OUTPUT)) do build_project(true, {})
|
||||||
!os.exists(GAME_LIB_PATH) { build_project(true, {}) }
|
|
||||||
|
|
||||||
cmd := []string{output_path(ENGINE_OUTPUT)}
|
cmd := []string{output_path(ENGINE_OUTPUT)}
|
||||||
line := slice.concatenate(
|
line := slice.concatenate(
|
||||||
@@ -206,6 +186,35 @@ run_project :: proc(extra_args: []string) {
|
|||||||
os.exit(res.exit_code)
|
os.exit(res.exit_code)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
hot_reload :: proc(debug: bool, extra_args: []string) {
|
||||||
|
if engine_is_running() {
|
||||||
|
process := output_path(PROJECT_NAME)
|
||||||
|
when ODIN_OS == .Windows {
|
||||||
|
// Ask process to shut down gracefully (equivalent to SIGTERM)
|
||||||
|
_, ok, _ := exec([]string{"taskkill", "/IM", process + ".exe"})
|
||||||
|
if !ok {
|
||||||
|
die("hot reload: failed to terminate running %s", process)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
_, ok, _ := exec([]string{"pkill", "-TERM", "-x", process})
|
||||||
|
if !ok {
|
||||||
|
die(
|
||||||
|
"hot reload: failed to send SIGTERM to running %s",
|
||||||
|
process,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Wait for process to terminate
|
||||||
|
for engine_is_running() {
|
||||||
|
time.sleep(time.Millisecond * 20)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
run_project(extra_args)
|
||||||
|
}
|
||||||
|
|
||||||
// -----------------------------------------
|
// -----------------------------------------
|
||||||
// wgpu setup
|
// wgpu setup
|
||||||
|
|
||||||
@@ -214,7 +223,8 @@ wgpu_init :: proc(version_override := "") {
|
|||||||
when ODIN_OS == .Windows {
|
when ODIN_OS == .Windows {
|
||||||
target_name :=
|
target_name :=
|
||||||
"wgpu-" + OS_NAME + "-" + ARCH_NAME + "-msvc" + "-release"
|
"wgpu-" + OS_NAME + "-" + ARCH_NAME + "-msvc" + "-release"
|
||||||
} else {
|
}
|
||||||
|
else {
|
||||||
target_name := "wgpu-" + OS_NAME + "-" + ARCH_NAME + "-release"
|
target_name := "wgpu-" + OS_NAME + "-" + ARCH_NAME + "-release"
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -310,7 +320,8 @@ wgpu_init :: proc(version_override := "") {
|
|||||||
); dl_err != nil {
|
); dl_err != nil {
|
||||||
die("wgpu setup: failed to download wgpu-native release")
|
die("wgpu setup: failed to download wgpu-native release")
|
||||||
}
|
}
|
||||||
} else {
|
}
|
||||||
|
else {
|
||||||
if dl_err := brokkr.execute_command(
|
if dl_err := brokkr.execute_command(
|
||||||
[]string{"curl", "-fL", "--retry", "3", "-o", zip_path, url},
|
[]string{"curl", "-fL", "--retry", "3", "-o", zip_path, url},
|
||||||
); dl_err != nil {
|
); dl_err != nil {
|
||||||
@@ -334,7 +345,8 @@ wgpu_init :: proc(version_override := "") {
|
|||||||
); ex_err != nil {
|
); ex_err != nil {
|
||||||
die("wgpu setup: failed to extract wgpu-native release")
|
die("wgpu setup: failed to extract wgpu-native release")
|
||||||
}
|
}
|
||||||
} else {
|
}
|
||||||
|
else {
|
||||||
// Matches scripts/wgpu-init.sh.
|
// Matches scripts/wgpu-init.sh.
|
||||||
if ex_err := brokkr.execute_command(
|
if ex_err := brokkr.execute_command(
|
||||||
[]string{"unzip", "-o", "-q", zip_path, "-d", target},
|
[]string{"unzip", "-o", "-q", zip_path, "-d", target},
|
||||||
@@ -379,7 +391,8 @@ bindings_version_from_file :: proc(
|
|||||||
chmod_recursively :: proc(path: string) {
|
chmod_recursively :: proc(path: string) {
|
||||||
when ODIN_OS == .Windows {
|
when ODIN_OS == .Windows {
|
||||||
return
|
return
|
||||||
} else {
|
}
|
||||||
|
else {
|
||||||
info, err := os.stat(path, context.temp_allocator)
|
info, err := os.stat(path, context.temp_allocator)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
die(
|
die(
|
||||||
@@ -482,34 +495,59 @@ rewrite_imports :: proc(path: string, old_import, new_import: string) {
|
|||||||
// Formatting
|
// Formatting
|
||||||
|
|
||||||
// Run `odinfmt -w` on source directory
|
// Run `odinfmt -w` on source directory
|
||||||
format_source :: proc() {
|
format_source :: proc(quiet := false) -> bool {
|
||||||
|
err: brokkr.Error
|
||||||
for dir in ([]string{GAME_SRC_DIR, ENGINE_DIR}) {
|
for dir in ([]string{GAME_SRC_DIR, ENGINE_DIR}) {
|
||||||
err := brokkr.execute_command([]string{"odinfmt", "-w", dir})
|
if !quiet {
|
||||||
if err != nil do os.exit(1)
|
err = brokkr.execute_command([]string{"odinfmt", "-w", dir})
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
err = brokkr.execute_command(
|
||||||
|
[]string{"odinfmt", "-w", dir},
|
||||||
|
nil,
|
||||||
|
0,
|
||||||
|
nil, // stdin
|
||||||
|
nil, // stdout
|
||||||
|
)
|
||||||
|
}
|
||||||
|
if err != nil do return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
// -----------------------------------------
|
// -----------------------------------------
|
||||||
// Git pre-commit hook
|
// Git pre-commit hook
|
||||||
|
|
||||||
pre_commit :: proc() {
|
pre_commit :: proc() {
|
||||||
|
// Stash additional changes
|
||||||
err := brokkr.execute_command(
|
err := brokkr.execute_command(
|
||||||
[]string{"git", "stash", "push", "--keep-index", "--quiet"},
|
[]string{"git", "stash", "push", "--keep-index", "--quiet"},
|
||||||
)
|
)
|
||||||
if err != nil do os.exit(1)
|
if err != nil do os.exit(1)
|
||||||
|
|
||||||
format_source()
|
// Pop additional changes
|
||||||
|
cleanup :: proc() {
|
||||||
|
err := brokkr.execute_command(
|
||||||
|
[]string{"git", "stash", "pop", "--quiet"},
|
||||||
|
)
|
||||||
|
if err != nil do os.exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
ok := format_source(true)
|
||||||
|
if !ok {
|
||||||
|
cleanup()
|
||||||
|
os.exit(1)
|
||||||
|
}
|
||||||
|
|
||||||
err = brokkr.execute_command([]string{"git", "diff", "--quiet"})
|
err = brokkr.execute_command([]string{"git", "diff", "--quiet"})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
log.error("formatting changed staged files; commit aborted")
|
log.error("formatting changed staged files; commit aborted")
|
||||||
_ = brokkr.execute_command([]string{"git", "checkout", "--", "."})
|
log.error("additional unstaged changes are in the git stash (if any)")
|
||||||
_ = brokkr.execute_command([]string{"git", "stash", "pop", "--quiet"})
|
|
||||||
os.exit(1)
|
os.exit(1)
|
||||||
}
|
}
|
||||||
|
|
||||||
err = brokkr.execute_command([]string{"git", "stash", "pop", "--quiet"})
|
cleanup()
|
||||||
if err != nil do os.exit(1)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// -----------------------------------------
|
// -----------------------------------------
|
||||||
@@ -560,7 +598,8 @@ engine_is_running :: proc() -> bool {
|
|||||||
)
|
)
|
||||||
if !ok do return false
|
if !ok do return false
|
||||||
return strings.contains(string(out), PROJECT_NAME + ".exe")
|
return strings.contains(string(out), PROJECT_NAME + ".exe")
|
||||||
} else {
|
}
|
||||||
|
else {
|
||||||
_, ok, code := exec([]string{"pgrep", "-x", PROJECT_NAME}, false)
|
_, ok, code := exec([]string{"pgrep", "-x", PROJECT_NAME}, false)
|
||||||
if !ok do return false
|
if !ok do return false
|
||||||
return code == 0
|
return code == 0
|
||||||
|
|||||||
@@ -0,0 +1,47 @@
|
|||||||
|
# Hot Reloading
|
||||||
|
|
||||||
|
Instead of having the engine as an exe and game as a dll, and having to jump
|
||||||
|
through hoops to share libraries internal state between them we do it
|
||||||
|
differently. The engine and game live in the same binary, compiled fully each
|
||||||
|
time. We rely mostly on static memory, and register these memory regions. Then
|
||||||
|
when we want to hot reload: we send a close signal to the running instance, it
|
||||||
|
writes a snapshot of the active memory to disk, instance closes, recompile,
|
||||||
|
restart the application, it restores the memory from the snapshot.
|
||||||
|
|
||||||
|
## Byte Layout On Disk
|
||||||
|
|
||||||
|
```odin
|
||||||
|
Snapshot_Header :: struct #packed #all_or_none {
|
||||||
|
magic_string: u32,
|
||||||
|
version: u16, // spec of the snapshot
|
||||||
|
app_version: [4 + time.MIN_YYYY_DATE_LEN + 8]u8, // example: `dev-2026-09-23-a4084b3`
|
||||||
|
region_count: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
Region_Header :: struct #packed #all_or_none {
|
||||||
|
name_size: u32,
|
||||||
|
data_size: u32,
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
[ Snapshot_Header ]
|
||||||
|
[ Region_Header ]
|
||||||
|
[ name bytes ]
|
||||||
|
[ data bytes ]
|
||||||
|
[ Region_Header ]
|
||||||
|
[ name bytes ]
|
||||||
|
[ data bytes ]
|
||||||
|
[ etc.. ]
|
||||||
|
|
||||||
|
## Diff Checking
|
||||||
|
|
||||||
|
Use hashing per memory segment to do a sanity diff-check.
|
||||||
|
|
||||||
|
```odin
|
||||||
|
import "core:crypto/hash"
|
||||||
|
|
||||||
|
data: []byte = ...
|
||||||
|
|
||||||
|
digest := hash.hash_bytes(hash.Algorithm.SHA256, data)
|
||||||
|
defer delete(digest)
|
||||||
|
```
|
||||||
+112
-41
@@ -1,86 +1,159 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (C) 2026 Riyyi
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*/
|
||||||
|
|
||||||
package game
|
package game
|
||||||
|
|
||||||
import "core:fmt"
|
import "core:fmt"
|
||||||
|
import "core:math"
|
||||||
import "core:time"
|
import "core:time"
|
||||||
|
|
||||||
import "sindri:base"
|
import "sindri:base"
|
||||||
import "sindri:core"
|
import "sindri:core"
|
||||||
|
import "sindri:platform"
|
||||||
|
|
||||||
// -----------------------------------------
|
// -----------------------------------------
|
||||||
|
// Types
|
||||||
|
|
||||||
Game_Memory :: struct {
|
Game_Memory :: struct {
|
||||||
should_close: bool,
|
should_close: bool,
|
||||||
|
camera: core.Thing_Ref,
|
||||||
}
|
}
|
||||||
|
|
||||||
g: ^Game_Memory
|
Test_Memory :: struct {
|
||||||
|
asd: int,
|
||||||
|
qwe: int,
|
||||||
|
}
|
||||||
|
|
||||||
// -----------------------------------------
|
// -----------------------------------------
|
||||||
|
// Variables
|
||||||
|
|
||||||
@(export)
|
g: Game_Memory
|
||||||
memory :: proc() -> rawptr {
|
t: Test_Memory
|
||||||
return g
|
|
||||||
|
engine: ^core.Engine_API
|
||||||
|
|
||||||
|
game_api := core.Game_API {
|
||||||
|
register_api = register_api,
|
||||||
|
register_memory = register_memory,
|
||||||
|
init_once = init_once,
|
||||||
|
init = init,
|
||||||
|
update = update,
|
||||||
|
render = render,
|
||||||
|
destroy = destroy,
|
||||||
|
should_close = should_close,
|
||||||
|
force_reload = force_reload,
|
||||||
|
force_restart = force_restart,
|
||||||
}
|
}
|
||||||
|
|
||||||
@(export)
|
mouse_last: base.Vec2
|
||||||
memory_free :: proc() {
|
|
||||||
free(g)
|
// -----------------------------------------
|
||||||
|
// Public functions
|
||||||
|
|
||||||
|
api :: proc() -> ^core.Game_API {
|
||||||
|
return &game_api
|
||||||
}
|
}
|
||||||
|
|
||||||
@(export)
|
register_api :: proc(api: ^core.Engine_API) {
|
||||||
memory_size :: proc() -> int {
|
engine = api
|
||||||
return size_of(Game_Memory)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@(export)
|
register_memory :: proc() {
|
||||||
memory_set :: proc(mem: rawptr) {
|
base.register_region("game_memory", &g, size_of(Game_Memory))
|
||||||
g = (^Game_Memory)(mem)
|
base.register_region("test_memory", &t, size_of(Test_Memory))
|
||||||
|
|
||||||
// Here you can also set your own global variables. A good idea is to make
|
|
||||||
// your global variables into pointers that point to something inside `g`.
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@(export)
|
|
||||||
settings :: proc() -> base.Settings {
|
|
||||||
return base.Settings {
|
|
||||||
width = 960,
|
|
||||||
height = 540,
|
|
||||||
title = "WGPU Native Triangle",
|
|
||||||
mode = base.WindowMode.Windowed,
|
|
||||||
refresh = 60,
|
|
||||||
vsync = true,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@(export)
|
|
||||||
init_once :: proc() {
|
init_once :: proc() {
|
||||||
fmt.println("init once")
|
fmt.println("init once")
|
||||||
|
|
||||||
|
g.camera = core.thing_add(engine.things)
|
||||||
|
|
||||||
|
camera := core.thing_get(engine.things, g.camera)
|
||||||
|
camera.pos = {0, 2, 5}
|
||||||
|
camera.rot = {-(25 * math.PI / 180), 0, 0}
|
||||||
}
|
}
|
||||||
|
|
||||||
@(export)
|
|
||||||
init :: proc() {
|
init :: proc() {
|
||||||
fmt.println("hello from .dll!")
|
fmt.println("hello from the game!")
|
||||||
|
|
||||||
g = new(Game_Memory)
|
g.should_close = false
|
||||||
memory_set(g)
|
|
||||||
|
cube_ref := core.asset_load_model(engine.assets, "assets/cube.obj")
|
||||||
|
suzanne_ref := core.asset_load_model(engine.assets, "assets/suzanne.obj")
|
||||||
|
|
||||||
|
cube := core.asset_get(engine.assets, cube_ref).data.(core.Model)
|
||||||
|
suzanne := core.asset_get(engine.assets, suzanne_ref).data.(core.Model)
|
||||||
|
|
||||||
|
platform.create_material("dummy")
|
||||||
|
platform.create_renderable(
|
||||||
|
"assets/cube.obj",
|
||||||
|
cube.vertices,
|
||||||
|
cube.indices,
|
||||||
|
0,
|
||||||
|
)
|
||||||
|
platform.create_renderable(
|
||||||
|
"assets/suzanne.obj",
|
||||||
|
suzanne.vertices,
|
||||||
|
suzanne.indices,
|
||||||
|
3,
|
||||||
|
)
|
||||||
|
platform.create_renderable(
|
||||||
|
"assets/suzanne.obj",
|
||||||
|
suzanne.vertices,
|
||||||
|
suzanne.indices,
|
||||||
|
-3,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@(export)
|
clicked: bool
|
||||||
|
captured: bool
|
||||||
update :: proc(dt: f32) {
|
update :: proc(dt: f32) {
|
||||||
fmt.println("dt:", dt)
|
fmt.println("dt:", dt)
|
||||||
|
|
||||||
if core.key_state(.Key_Escape) == .Press {
|
if platform.os_key_state(.Key_Escape) == .Press {
|
||||||
g.should_close = true
|
g.should_close = true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if platform.os_key_state(.Key_F5) == .Press do t.asd = 555
|
||||||
|
if platform.os_key_state(.Key_F6) == .Press do t.asd = 666
|
||||||
|
|
||||||
|
if platform.os_mouse_button_state(.Left) == .Press && !clicked {
|
||||||
|
clicked = true
|
||||||
|
platform.os_set_mouse_capture(!captured)
|
||||||
|
captured = !captured
|
||||||
|
}
|
||||||
|
if platform.os_mouse_button_state(.Left) == .Release {
|
||||||
|
clicked = false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mouse delta
|
||||||
|
pos := platform.os_mouse_position()
|
||||||
|
if mouse_last == 0 do mouse_last = pos // restore position after hot-reload
|
||||||
|
mouse_delta := pos - mouse_last
|
||||||
|
mouse_last = pos
|
||||||
|
|
||||||
|
// Update camera
|
||||||
|
camera := core.thing_get(engine.things, g.camera)
|
||||||
|
sensitivity := base.settings().mouse_sensitivity
|
||||||
|
core.camera_update(dt, camera, mouse_delta, sensitivity)
|
||||||
|
}
|
||||||
|
|
||||||
|
render :: proc() {
|
||||||
|
camera := core.thing_get(engine.things, g.camera)
|
||||||
|
platform.state.camera = {camera.pos, camera.rot}
|
||||||
}
|
}
|
||||||
|
|
||||||
@(export)
|
|
||||||
destroy :: proc() {
|
destroy :: proc() {
|
||||||
fmt.println("bye")
|
fmt.println("bye")
|
||||||
|
|
||||||
|
fmt.println(t.asd, t.qwe)
|
||||||
}
|
}
|
||||||
|
|
||||||
start := time.tick_now()
|
start := time.tick_now()
|
||||||
|
|
||||||
@(export)
|
|
||||||
should_close :: proc() -> bool {
|
should_close :: proc() -> bool {
|
||||||
elapsed := time.tick_since(start)
|
elapsed := time.tick_since(start)
|
||||||
seconds := time.duration_seconds(elapsed)
|
seconds := time.duration_seconds(elapsed)
|
||||||
@@ -89,12 +162,10 @@ should_close :: proc() -> bool {
|
|||||||
return g.should_close
|
return g.should_close
|
||||||
}
|
}
|
||||||
|
|
||||||
@(export)
|
|
||||||
force_reload :: proc() -> bool {
|
force_reload :: proc() -> bool {
|
||||||
return core.key_state(.Key_F5) == .Press
|
return platform.os_key_state(.Key_F5) == .Press
|
||||||
}
|
}
|
||||||
|
|
||||||
@(export)
|
|
||||||
force_restart :: proc() -> bool {
|
force_restart :: proc() -> bool {
|
||||||
return core.key_state(.Key_F6) == .Press
|
return platform.os_key_state(.Key_F6) == .Press
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
{
|
{
|
||||||
"$schema": "https://raw.githubusercontent.com/DanielGavin/ols/master/misc/odinfmt.schema.json",
|
"$schema": "https://raw.githubusercontent.com/DanielGavin/ols/master/misc/odinfmt.schema.json",
|
||||||
|
"align_comments": true,
|
||||||
"align_struct_fields": true,
|
"align_struct_fields": true,
|
||||||
"align_struct_values": true,
|
"align_struct_values": true,
|
||||||
|
"brace_style": "Stroustrup",
|
||||||
"character_width": 80,
|
"character_width": 80,
|
||||||
"indent_cases": true,
|
"indent_cases": true,
|
||||||
"newline_limit": 1,
|
"newline_limit": 1,
|
||||||
"newline_style": "LF",
|
"newline_style": "LF",
|
||||||
|
"preserve_struct_blank_lines": true,
|
||||||
"sort_imports": true,
|
"sort_imports": true,
|
||||||
"space_single_line_blocks": true,
|
"space_single_line_blocks": true,
|
||||||
"tabs": true,
|
"tabs": true,
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
{
|
{
|
||||||
"collections": [
|
"collections": [
|
||||||
|
{ "name": "game", "path": "." },
|
||||||
{ "name": "sindri", "path": "src" },
|
{ "name": "sindri", "path": "src" },
|
||||||
{ "name": "gram", "path": "vendor/gram/src" },
|
{ "name": "gram", "path": "vendor/gram/src" },
|
||||||
{ "name": "wgpu", "path": "vendor" }
|
{ "name": "wgpu", "path": "vendor" }
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
../../out/arena_log.json
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 5.8 KiB |
@@ -0,0 +1,866 @@
|
|||||||
|
<!-- SPDX-License-Identifier: Unlicense -->
|
||||||
|
|
||||||
|
<!DOCTYPE html>
|
||||||
|
<html lang="en">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||||
|
<title>Arena Memory Flame Graph</title>
|
||||||
|
<style>
|
||||||
|
:root {
|
||||||
|
--bg: #0f1115;
|
||||||
|
--panel: #16181d;
|
||||||
|
--text: #e0e2e8;
|
||||||
|
--muted: #8b8f98;
|
||||||
|
--push: #3b82f6;
|
||||||
|
--pop: #ef4444;
|
||||||
|
--clear: #f59e0b;
|
||||||
|
--border: #2a2d35;
|
||||||
|
}
|
||||||
|
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
|
||||||
|
html, body {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
height: 100vh;
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
|
||||||
|
body {
|
||||||
|
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
|
||||||
|
background: var(--bg);
|
||||||
|
color: var(--text);
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
}
|
||||||
|
|
||||||
|
header {
|
||||||
|
padding: 1rem 1.5rem;
|
||||||
|
border-bottom: 1px solid var(--border);
|
||||||
|
background: var(--panel);
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: 1rem;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
h1 { margin: 0; font-size: 1.25rem; }
|
||||||
|
|
||||||
|
.stats {
|
||||||
|
display: flex;
|
||||||
|
gap: 1.5rem;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.stats span strong {
|
||||||
|
color: var(--text);
|
||||||
|
margin-left: 0.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
main {
|
||||||
|
flex: 1;
|
||||||
|
padding: 1rem;
|
||||||
|
display: grid;
|
||||||
|
grid-template-rows: auto auto 1fr auto;
|
||||||
|
grid-template-columns: auto 1fr;
|
||||||
|
gap: 1rem;
|
||||||
|
min-height: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.controls { grid-column: 1 / -1; }
|
||||||
|
|
||||||
|
.controls {
|
||||||
|
display: flex;
|
||||||
|
gap: 0.75rem;
|
||||||
|
align-items: center;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
.controls label {
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.controls input[type="range"] {
|
||||||
|
width: 160px;
|
||||||
|
}
|
||||||
|
|
||||||
|
button {
|
||||||
|
background: #252830;
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
color: var(--text);
|
||||||
|
padding: 0.4rem 0.8rem;
|
||||||
|
border-radius: 0.375rem;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
button:hover { background: #2e323b; }
|
||||||
|
|
||||||
|
#tabs {
|
||||||
|
grid-row: 2;
|
||||||
|
grid-column: 1 / -1;
|
||||||
|
display: none;
|
||||||
|
gap: 0.5rem;
|
||||||
|
flex-wrap: wrap;
|
||||||
|
align-items: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
#tabs.visible {
|
||||||
|
display: flex;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab {
|
||||||
|
background: var(--panel);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
color: var(--muted);
|
||||||
|
padding: 0.4rem 0.8rem;
|
||||||
|
border-radius: 0.375rem;
|
||||||
|
cursor: pointer;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab:hover {
|
||||||
|
background: #2e323b;
|
||||||
|
color: var(--text);
|
||||||
|
}
|
||||||
|
|
||||||
|
.tab.active {
|
||||||
|
background: var(--push);
|
||||||
|
color: #fff;
|
||||||
|
border-color: var(--push);
|
||||||
|
}
|
||||||
|
|
||||||
|
.separate-toggle {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 0.4rem;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 0.875rem;
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
.separate-toggle input {
|
||||||
|
cursor: pointer;
|
||||||
|
}
|
||||||
|
|
||||||
|
#viewport {
|
||||||
|
grid-row: 3;
|
||||||
|
grid-column: 2;
|
||||||
|
background: var(--panel);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 0.5rem;
|
||||||
|
overflow: hidden;
|
||||||
|
position: relative;
|
||||||
|
cursor: grab;
|
||||||
|
min-height: 0;
|
||||||
|
height: 100%;
|
||||||
|
}
|
||||||
|
|
||||||
|
#viewport.grabbing { cursor: grabbing; }
|
||||||
|
|
||||||
|
#viewport svg {
|
||||||
|
position: absolute;
|
||||||
|
top: 0;
|
||||||
|
left: 0;
|
||||||
|
width: 100%;
|
||||||
|
height: 100%;
|
||||||
|
display: block;
|
||||||
|
shape-rendering: crispEdges;
|
||||||
|
}
|
||||||
|
|
||||||
|
#y-axis {
|
||||||
|
grid-row: 3;
|
||||||
|
grid-column: 1;
|
||||||
|
position: relative;
|
||||||
|
padding-right: 0.5rem;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 0.75rem;
|
||||||
|
min-width: 4rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
#y-axis .tick {
|
||||||
|
position: absolute;
|
||||||
|
right: 0.5rem;
|
||||||
|
transform: translateY(-50%);
|
||||||
|
text-align: right;
|
||||||
|
line-height: 1;
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
|
||||||
|
#timeline-axis {
|
||||||
|
grid-row: 4;
|
||||||
|
grid-column: 2;
|
||||||
|
position: relative;
|
||||||
|
padding: 0.25rem 0;
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 0.75rem;
|
||||||
|
border-top: 1px solid var(--border);
|
||||||
|
height: 1.5rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
#timeline-axis .tick {
|
||||||
|
position: absolute;
|
||||||
|
top: 0.25rem;
|
||||||
|
transform: translateX(-50%);
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
#timeline-axis .tick::before {
|
||||||
|
content: '';
|
||||||
|
position: absolute;
|
||||||
|
top: -3px;
|
||||||
|
left: 50%;
|
||||||
|
width: 1px;
|
||||||
|
height: 6px;
|
||||||
|
background: var(--muted);
|
||||||
|
transform: translateX(-50%);
|
||||||
|
}
|
||||||
|
|
||||||
|
.frame {
|
||||||
|
stroke: rgba(0, 0, 0, 0.25);
|
||||||
|
stroke-width: 0.5px;
|
||||||
|
transition: opacity 0.1s;
|
||||||
|
}
|
||||||
|
|
||||||
|
.frame:hover {
|
||||||
|
stroke: #fff;
|
||||||
|
stroke-width: 1px;
|
||||||
|
opacity: 0.9;
|
||||||
|
}
|
||||||
|
|
||||||
|
#tooltip {
|
||||||
|
position: fixed;
|
||||||
|
pointer-events: none;
|
||||||
|
background: rgba(15, 17, 21, 0.95);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 0.375rem;
|
||||||
|
padding: 0.75rem;
|
||||||
|
font-size: 0.8rem;
|
||||||
|
line-height: 1.5;
|
||||||
|
color: var(--text);
|
||||||
|
box-shadow: 0 8px 24px rgba(0,0,0,0.35);
|
||||||
|
opacity: 0;
|
||||||
|
transition: opacity 0.1s;
|
||||||
|
max-width: 320px;
|
||||||
|
z-index: 100;
|
||||||
|
}
|
||||||
|
|
||||||
|
#tooltip .row { display: flex; gap: 0.5rem; }
|
||||||
|
#tooltip .key { color: var(--muted); min-width: 3.5rem; }
|
||||||
|
#tooltip .value { word-break: break-all; }
|
||||||
|
#tooltip .kind { font-weight: 600; text-transform: uppercase; font-size: 0.75rem; }
|
||||||
|
|
||||||
|
.legend {
|
||||||
|
display: flex;
|
||||||
|
gap: 1rem;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: center;
|
||||||
|
flex: 1;
|
||||||
|
font-size: 0.875rem;
|
||||||
|
color: var(--muted);
|
||||||
|
}
|
||||||
|
|
||||||
|
.legend .swatch {
|
||||||
|
display: inline-block;
|
||||||
|
width: 0.75rem;
|
||||||
|
height: 0.75rem;
|
||||||
|
border-radius: 2px;
|
||||||
|
margin-right: 0.35rem;
|
||||||
|
}
|
||||||
|
|
||||||
|
.error {
|
||||||
|
padding: 2rem;
|
||||||
|
color: #f87171;
|
||||||
|
text-align: center;
|
||||||
|
}
|
||||||
|
|
||||||
|
.hint {
|
||||||
|
color: var(--muted);
|
||||||
|
font-size: 0.8rem;
|
||||||
|
margin-left: auto;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<header>
|
||||||
|
<h1>Arena Memory Flame Graph</h1>
|
||||||
|
<div class="stats">
|
||||||
|
<span>Entries<strong id="stat-entries">-</strong></span>
|
||||||
|
<span>Live at peak<strong id="stat-peak">-</strong></span>
|
||||||
|
<span>Max bytes<strong id="stat-bytes">-</strong></span>
|
||||||
|
<span>Timeline<strong id="stat-time">-</strong></span>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<main>
|
||||||
|
<div class="controls">
|
||||||
|
<label>Zoom X <input id="zoomX" type="range" min="0.5" max="20" step="0.5" value="10"></label>
|
||||||
|
<label>Zoom Y <input id="zoomY" type="range" min="0.5" max="10" step="0.5" value="5"></label>
|
||||||
|
<button id="reset">Reset view</button>
|
||||||
|
<label class="separate-toggle">
|
||||||
|
<input id="separate" type="checkbox">
|
||||||
|
Separate
|
||||||
|
</label>
|
||||||
|
<div class="legend">
|
||||||
|
<span><span class="swatch" style="background:linear-gradient(180deg,#60a5fa,#2563eb)"></span>Allocation</span>
|
||||||
|
<span><span class="swatch" style="background:#ef4444"></span>Pop</span>
|
||||||
|
<span><span class="swatch" style="background:#f59e0b"></span>Clear</span>
|
||||||
|
</div>
|
||||||
|
<span class="hint">Pan by dragging. Hover a block for details.</span>
|
||||||
|
</div>
|
||||||
|
<div id="tabs"></div>
|
||||||
|
<div id="y-axis"></div>
|
||||||
|
<div id="viewport"></div>
|
||||||
|
<div id="timeline-axis"></div>
|
||||||
|
</main>
|
||||||
|
|
||||||
|
<div id="tooltip"></div>
|
||||||
|
|
||||||
|
<script>
|
||||||
|
const LOG_URL = 'arena_log.json';
|
||||||
|
const viewport = document.getElementById('viewport');
|
||||||
|
const tooltip = document.getElementById('tooltip');
|
||||||
|
const zoomXInput = document.getElementById('zoomX');
|
||||||
|
const zoomYInput = document.getElementById('zoomY');
|
||||||
|
const separateCheckbox = document.getElementById('separate');
|
||||||
|
const tabsContainer = document.getElementById('tabs');
|
||||||
|
|
||||||
|
const KIND_COLORS = {
|
||||||
|
Push: '#3b82f6',
|
||||||
|
Pop: '#ef4444',
|
||||||
|
Clear: '#f59e0b',
|
||||||
|
};
|
||||||
|
|
||||||
|
const ZOOM_X_MID = 10;
|
||||||
|
const ZOOM_Y_MID = 5;
|
||||||
|
|
||||||
|
let combinedDataset = null;
|
||||||
|
let arenaDatasets = new Map();
|
||||||
|
let globalMinTime = 0;
|
||||||
|
let globalMaxTime = 0;
|
||||||
|
let globalTimeSpan = 0;
|
||||||
|
let currentMode = 'combined';
|
||||||
|
let currentArenaId = null;
|
||||||
|
const viewStates = new Map();
|
||||||
|
|
||||||
|
function formatBytes(n) {
|
||||||
|
if (n >= 1024 * 1024) return (n / (1024 * 1024)).toFixed(2) + ' MiB';
|
||||||
|
if (n >= 1024) return (n / 1024).toFixed(2) + ' KiB';
|
||||||
|
return n + ' B';
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadLog() {
|
||||||
|
const res = await fetch(LOG_URL);
|
||||||
|
if (!res.ok) throw new Error(`Failed to load ${LOG_URL}: ${res.status} ${res.statusText}`);
|
||||||
|
return await res.text();
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseTime(t) {
|
||||||
|
// Odin time format: "2006-01-02 15:04:05.999999999 +0000 UTC"
|
||||||
|
const iso = t
|
||||||
|
.replace(' ', 'T')
|
||||||
|
.replace(/(\.\d{3})\d*/, '$1')
|
||||||
|
.replace(' +0000 UTC', 'Z');
|
||||||
|
return Date.parse(iso);
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseLog(text) {
|
||||||
|
// Try real JSON first; fall back to tolerant regex for Odin's "key = value" output.
|
||||||
|
try {
|
||||||
|
const data = JSON.parse(text);
|
||||||
|
if (Array.isArray(data)) {
|
||||||
|
return data.map(e => ({ ...e, timeMs: parseTime(e.time), id: e.id ?? 'default' }));
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
|
||||||
|
const entries = [];
|
||||||
|
const re = /\{\s*(?:"id"\s*[:=]\s*"?([^",\s]+)"?\s*,\s*)?"kind"\s*[:=]\s*"?(\w+)"?\s*,\s*"time"\s*[:=]\s*"?([^",]+)"?\s*,\s*"loc"\s*[:=]\s*"?([^",]+)"?\s*,\s*"pos"\s*[:=]\s*(\d+)\s*,\s*"size"\s*[:=]\s*(\d+)\s*\}/g;
|
||||||
|
let m;
|
||||||
|
while ((m = re.exec(text)) !== null) {
|
||||||
|
const time = m[3].trim();
|
||||||
|
entries.push({
|
||||||
|
id: m[1] ?? 'default',
|
||||||
|
kind: m[2],
|
||||||
|
time: time,
|
||||||
|
timeMs: parseTime(time),
|
||||||
|
loc: m[4].trim(),
|
||||||
|
pos: parseInt(m[5], 10),
|
||||||
|
size: parseInt(m[6], 10),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return entries;
|
||||||
|
}
|
||||||
|
|
||||||
|
function groupById(entries) {
|
||||||
|
const groups = new Map();
|
||||||
|
for (const e of entries) {
|
||||||
|
const id = e.id ?? 'default';
|
||||||
|
if (!groups.has(id)) groups.set(id, []);
|
||||||
|
groups.get(id).push(e);
|
||||||
|
}
|
||||||
|
return groups;
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildFrames(entries) {
|
||||||
|
const stack = [];
|
||||||
|
const frames = [];
|
||||||
|
let currentY = 0;
|
||||||
|
let peakY = 0;
|
||||||
|
let nextId = 0;
|
||||||
|
const minTimeMs = entries.length > 0 ? entries[0].timeMs : 0;
|
||||||
|
const lastTimeMs = entries.length > 0 ? entries[entries.length - 1].timeMs : 0;
|
||||||
|
const timeSpan = lastTimeMs - minTimeMs;
|
||||||
|
const tailPadding = timeSpan > 0 ? timeSpan * 0.1 : 100;
|
||||||
|
|
||||||
|
for (let i = 0; i < entries.length; i++) {
|
||||||
|
const e = entries[i];
|
||||||
|
if (e.kind === 'Push') {
|
||||||
|
const id = nextId++;
|
||||||
|
const frame = {
|
||||||
|
id,
|
||||||
|
arenaId: e.id,
|
||||||
|
startTime: e.timeMs,
|
||||||
|
endTime: lastTimeMs + tailPadding,
|
||||||
|
size: e.size,
|
||||||
|
origSize: e.size,
|
||||||
|
y: currentY,
|
||||||
|
kind: e.kind,
|
||||||
|
time: e.time,
|
||||||
|
loc: e.loc,
|
||||||
|
pos: e.pos,
|
||||||
|
isFreedTail: false,
|
||||||
|
};
|
||||||
|
stack.push(frame);
|
||||||
|
frames.push(frame);
|
||||||
|
currentY += e.size;
|
||||||
|
if (currentY > peakY) peakY = currentY;
|
||||||
|
} else if (e.kind === 'Pop') {
|
||||||
|
let remaining = e.size;
|
||||||
|
while (remaining > 0 && stack.length > 0) {
|
||||||
|
const top = stack[stack.length - 1];
|
||||||
|
if (top.size > remaining) {
|
||||||
|
// Partial reset: the top allocation is only partly freed.
|
||||||
|
// Keep the lower portion alive and record the freed tail as its own frame.
|
||||||
|
const freed = {
|
||||||
|
id: top.id,
|
||||||
|
arenaId: top.arenaId,
|
||||||
|
startTime: top.startTime,
|
||||||
|
endTime: e.timeMs,
|
||||||
|
size: remaining,
|
||||||
|
origSize: top.origSize,
|
||||||
|
y: currentY - remaining,
|
||||||
|
kind: top.kind,
|
||||||
|
time: top.time,
|
||||||
|
loc: top.loc,
|
||||||
|
pos: top.pos + (top.size - remaining),
|
||||||
|
isFreedTail: true,
|
||||||
|
};
|
||||||
|
frames.push(freed);
|
||||||
|
top.size -= remaining;
|
||||||
|
currentY -= remaining;
|
||||||
|
remaining = 0;
|
||||||
|
} else {
|
||||||
|
stack.pop();
|
||||||
|
top.endTime = e.timeMs;
|
||||||
|
currentY -= top.size;
|
||||||
|
remaining -= top.size;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (e.kind === 'Clear') {
|
||||||
|
while (stack.length > 0) {
|
||||||
|
const top = stack.pop();
|
||||||
|
top.endTime = e.timeMs;
|
||||||
|
currentY -= top.size;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { frames, peakY };
|
||||||
|
}
|
||||||
|
|
||||||
|
function getCurrentDataset() {
|
||||||
|
if (currentMode === 'combined') return combinedDataset;
|
||||||
|
return arenaDatasets.get(currentArenaId) ?? combinedDataset;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getCurrentKey() {
|
||||||
|
return currentMode === 'combined' ? 'combined' : currentArenaId;
|
||||||
|
}
|
||||||
|
|
||||||
|
function getCurrentState() {
|
||||||
|
const key = getCurrentKey();
|
||||||
|
if (!viewStates.has(key)) {
|
||||||
|
viewStates.set(key, { zoomX: 1, zoomY: 1, panX: 0, panY: 0 });
|
||||||
|
}
|
||||||
|
return viewStates.get(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateStats(dataset) {
|
||||||
|
const entries = dataset.entries;
|
||||||
|
const minTime = entries.length > 0 ? entries[0].timeMs : 0;
|
||||||
|
const maxTime = entries.length > 0 ? entries[entries.length - 1].timeMs : 0;
|
||||||
|
const timeSpan = maxTime - minTime;
|
||||||
|
|
||||||
|
document.getElementById('stat-entries').textContent = entries.length;
|
||||||
|
document.getElementById('stat-peak').textContent = formatBytes(dataset.peakY);
|
||||||
|
document.getElementById('stat-bytes').textContent = formatBytes(Math.max(...entries.filter(e => e.kind === 'Push').map(e => e.pos + e.size), 0));
|
||||||
|
document.getElementById('stat-time').textContent = (timeSpan / 1000).toFixed(2) + ' s';
|
||||||
|
}
|
||||||
|
|
||||||
|
function niceStep(range, targetTicks = 5) {
|
||||||
|
if (range <= 0) return 1;
|
||||||
|
const rough = range / targetTicks;
|
||||||
|
const exponent = Math.floor(Math.log10(rough));
|
||||||
|
const fraction = rough / Math.pow(10, exponent);
|
||||||
|
let niceFraction;
|
||||||
|
if (fraction <= 1) niceFraction = 1;
|
||||||
|
else if (fraction <= 2) niceFraction = 2;
|
||||||
|
else if (fraction <= 5) niceFraction = 5;
|
||||||
|
else niceFraction = 10;
|
||||||
|
return niceFraction * Math.pow(10, exponent);
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatTime(ms) {
|
||||||
|
const absMs = Math.abs(ms);
|
||||||
|
if (absMs < 1000) return Math.round(ms) + 'ms';
|
||||||
|
const s = ms / 1000;
|
||||||
|
if (absMs < 10000) return s.toFixed(2) + 's';
|
||||||
|
if (absMs < 60000) return s.toFixed(1) + 's';
|
||||||
|
const m = Math.floor(s / 60);
|
||||||
|
const rs = s % 60;
|
||||||
|
return m + 'm' + rs.toFixed(0).padStart(2, '0') + 's';
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateTimelineAxis() {
|
||||||
|
const xAxis = document.getElementById('timeline-axis');
|
||||||
|
xAxis.innerHTML = '';
|
||||||
|
|
||||||
|
const vs = getCurrentState();
|
||||||
|
const sx = scaleX * vs.zoomX;
|
||||||
|
if (sx === 0 || viewportWidth === 0) return;
|
||||||
|
|
||||||
|
const tLeft = globalMinTime - vs.panX / sx;
|
||||||
|
const tRight = globalMinTime + (viewportWidth - vs.panX) / sx;
|
||||||
|
const rangeMs = tRight - tLeft;
|
||||||
|
if (rangeMs <= 0) return;
|
||||||
|
|
||||||
|
const stepMs = niceStep(rangeMs);
|
||||||
|
const firstOffsetMs = Math.ceil((tLeft - globalMinTime) / stepMs) * stepMs;
|
||||||
|
|
||||||
|
for (let offsetMs = firstOffsetMs; offsetMs <= tRight - globalMinTime + 1e-9; offsetMs += stepMs) {
|
||||||
|
const t = globalMinTime + offsetMs;
|
||||||
|
const x = vs.panX + (t - globalMinTime) * sx;
|
||||||
|
if (x < -50 || x > viewportWidth + 50) continue;
|
||||||
|
|
||||||
|
const tick = document.createElement('div');
|
||||||
|
tick.className = 'tick';
|
||||||
|
tick.textContent = formatTime(offsetMs);
|
||||||
|
tick.style.left = x + 'px';
|
||||||
|
xAxis.appendChild(tick);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateYAxis(peakY) {
|
||||||
|
const yAxis = document.getElementById('y-axis');
|
||||||
|
yAxis.innerHTML = '';
|
||||||
|
|
||||||
|
const vs = getCurrentState();
|
||||||
|
const flameHeight = peakY || 1;
|
||||||
|
const sy = scaleY * vs.zoomY;
|
||||||
|
if (sy === 0 || viewportHeight === 0) return;
|
||||||
|
|
||||||
|
const mTop = Math.max(0, Math.min(peakY, flameHeight + vs.panY / sy));
|
||||||
|
const mBottom = Math.max(0, Math.min(peakY, flameHeight - (viewportHeight - vs.panY) / sy));
|
||||||
|
const range = mTop - mBottom;
|
||||||
|
if (range <= 0) return;
|
||||||
|
|
||||||
|
const step = niceStep(range);
|
||||||
|
const first = Math.ceil(mBottom / step) * step;
|
||||||
|
|
||||||
|
for (let m = first; m <= mTop + 1e-9; m += step) {
|
||||||
|
const y = vs.panY + (flameHeight - m) * sy;
|
||||||
|
if (y < -20 || y > viewportHeight + 20) continue;
|
||||||
|
|
||||||
|
const tick = document.createElement('div');
|
||||||
|
tick.className = 'tick';
|
||||||
|
tick.textContent = formatBytes(Math.round(m));
|
||||||
|
tick.style.top = y + 'px';
|
||||||
|
yAxis.appendChild(tick);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateAxes() {
|
||||||
|
const dataset = getCurrentDataset();
|
||||||
|
updateYAxis(dataset.peakY);
|
||||||
|
updateTimelineAxis();
|
||||||
|
}
|
||||||
|
|
||||||
|
const svgNS = 'http://www.w3.org/2000/svg';
|
||||||
|
let svg, g;
|
||||||
|
let scaleX = 1;
|
||||||
|
let scaleY = 1;
|
||||||
|
let viewportWidth = 0;
|
||||||
|
let viewportHeight = 0;
|
||||||
|
|
||||||
|
function colorFor(kind) {
|
||||||
|
return KIND_COLORS[kind] || '#888';
|
||||||
|
}
|
||||||
|
|
||||||
|
function allocationColor(frame) {
|
||||||
|
const hue = 215;
|
||||||
|
const lightness = 45 + ((frame.id * 7) % 25);
|
||||||
|
if (frame.isFreedTail) {
|
||||||
|
return `hsla(${hue}, 70%, ${lightness + 25}%, 0.45)`;
|
||||||
|
}
|
||||||
|
return `hsla(${hue}, 75%, ${lightness}%, 1)`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateTransform() {
|
||||||
|
const vs = getCurrentState();
|
||||||
|
g.setAttribute('transform', `translate(${vs.panX}, ${vs.panY}) scale(${vs.zoomX * scaleX}, ${vs.zoomY * scaleY})`);
|
||||||
|
updateAxes();
|
||||||
|
}
|
||||||
|
|
||||||
|
function updateScale() {
|
||||||
|
const rect = viewport.getBoundingClientRect();
|
||||||
|
const dataset = getCurrentDataset();
|
||||||
|
const baseWidth = globalTimeSpan || 1;
|
||||||
|
const flameHeight = dataset.peakY || 1;
|
||||||
|
const axisMargin = flameHeight * 0.12;
|
||||||
|
const baseHeight = flameHeight + axisMargin;
|
||||||
|
viewportWidth = rect.width;
|
||||||
|
viewportHeight = rect.height;
|
||||||
|
scaleX = rect.width / baseWidth;
|
||||||
|
scaleY = rect.height / baseHeight;
|
||||||
|
updateTransform();
|
||||||
|
}
|
||||||
|
|
||||||
|
function draw() {
|
||||||
|
while (g.firstChild) g.removeChild(g.firstChild);
|
||||||
|
|
||||||
|
const dataset = getCurrentDataset();
|
||||||
|
const { frames, peakY } = dataset;
|
||||||
|
const flameHeight = peakY || 1;
|
||||||
|
const axisMargin = flameHeight * 0.12;
|
||||||
|
|
||||||
|
for (const f of frames) {
|
||||||
|
const x = f.startTime - globalMinTime;
|
||||||
|
const w = f.endTime - f.startTime;
|
||||||
|
if (w <= 0) continue;
|
||||||
|
|
||||||
|
const rect = document.createElementNS(svgNS, 'rect');
|
||||||
|
rect.setAttribute('x', x);
|
||||||
|
rect.setAttribute('y', flameHeight - (f.y + f.size));
|
||||||
|
rect.setAttribute('width', w);
|
||||||
|
rect.setAttribute('height', f.size);
|
||||||
|
rect.setAttribute('fill', allocationColor(f));
|
||||||
|
rect.setAttribute('class', 'frame');
|
||||||
|
rect.setAttribute('vector-effect', 'non-scaling-stroke');
|
||||||
|
rect.dataset.kind = f.kind;
|
||||||
|
rect.dataset.size = f.size;
|
||||||
|
rect.dataset.origSize = f.origSize;
|
||||||
|
rect.dataset.pos = f.pos;
|
||||||
|
rect.dataset.time = f.time;
|
||||||
|
rect.dataset.loc = f.loc;
|
||||||
|
rect.dataset.id = f.arenaId;
|
||||||
|
rect.dataset.isFreedTail = f.isFreedTail;
|
||||||
|
g.appendChild(rect);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Operation markers at the bottom so Pop/Clear are visible too
|
||||||
|
const markerY = flameHeight + axisMargin * 0.35;
|
||||||
|
for (const e of dataset.entries) {
|
||||||
|
const x = e.timeMs - globalMinTime;
|
||||||
|
const marker = document.createElementNS(svgNS, 'line');
|
||||||
|
marker.setAttribute('x1', x);
|
||||||
|
marker.setAttribute('y1', markerY - axisMargin * 0.25);
|
||||||
|
marker.setAttribute('x2', x);
|
||||||
|
marker.setAttribute('y2', markerY + axisMargin * 0.25);
|
||||||
|
marker.setAttribute('stroke', colorFor(e.kind));
|
||||||
|
marker.setAttribute('stroke-width', '1.5');
|
||||||
|
marker.setAttribute('vector-effect', 'non-scaling-stroke');
|
||||||
|
g.appendChild(marker);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function render() {
|
||||||
|
const dataset = getCurrentDataset();
|
||||||
|
const vs = getCurrentState();
|
||||||
|
|
||||||
|
zoomXInput.value = vs.zoomX * ZOOM_X_MID;
|
||||||
|
zoomYInput.value = vs.zoomY * ZOOM_Y_MID;
|
||||||
|
|
||||||
|
document.querySelectorAll('.tab').forEach(tab => {
|
||||||
|
tab.classList.toggle('active', tab.dataset.id === currentArenaId);
|
||||||
|
});
|
||||||
|
|
||||||
|
updateStats(dataset);
|
||||||
|
draw();
|
||||||
|
updateScale();
|
||||||
|
}
|
||||||
|
|
||||||
|
function setupTabs() {
|
||||||
|
tabsContainer.innerHTML = '';
|
||||||
|
for (const id of arenaDatasets.keys()) {
|
||||||
|
const tab = document.createElement('button');
|
||||||
|
tab.className = 'tab';
|
||||||
|
tab.textContent = id;
|
||||||
|
tab.dataset.id = id;
|
||||||
|
tab.addEventListener('click', () => {
|
||||||
|
currentArenaId = id;
|
||||||
|
render();
|
||||||
|
});
|
||||||
|
tabsContainer.appendChild(tab);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function setupControls() {
|
||||||
|
separateCheckbox.addEventListener('change', () => {
|
||||||
|
currentMode = separateCheckbox.checked ? 'separate' : 'combined';
|
||||||
|
if (currentMode === 'separate' && !currentArenaId) {
|
||||||
|
currentArenaId = arenaDatasets.keys().next().value;
|
||||||
|
}
|
||||||
|
tabsContainer.classList.toggle('visible', currentMode === 'separate');
|
||||||
|
render();
|
||||||
|
});
|
||||||
|
|
||||||
|
zoomXInput.addEventListener('input', () => {
|
||||||
|
getCurrentState().zoomX = parseFloat(zoomXInput.value) / ZOOM_X_MID;
|
||||||
|
updateTransform();
|
||||||
|
});
|
||||||
|
|
||||||
|
zoomYInput.addEventListener('input', () => {
|
||||||
|
getCurrentState().zoomY = parseFloat(zoomYInput.value) / ZOOM_Y_MID;
|
||||||
|
updateTransform();
|
||||||
|
});
|
||||||
|
|
||||||
|
document.getElementById('reset').addEventListener('click', () => {
|
||||||
|
const vs = getCurrentState();
|
||||||
|
vs.zoomX = 1;
|
||||||
|
vs.zoomY = 1;
|
||||||
|
vs.panX = 0;
|
||||||
|
vs.panY = 0;
|
||||||
|
zoomXInput.value = ZOOM_X_MID;
|
||||||
|
zoomYInput.value = ZOOM_Y_MID;
|
||||||
|
updateTransform();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function setupViewport() {
|
||||||
|
svg = document.createElementNS(svgNS, 'svg');
|
||||||
|
g = document.createElementNS(svgNS, 'g');
|
||||||
|
svg.appendChild(g);
|
||||||
|
viewport.innerHTML = '';
|
||||||
|
viewport.appendChild(svg);
|
||||||
|
|
||||||
|
let isDragging = false;
|
||||||
|
let lastX = 0;
|
||||||
|
let lastY = 0;
|
||||||
|
|
||||||
|
viewport.addEventListener('mousedown', e => {
|
||||||
|
isDragging = true;
|
||||||
|
viewport.classList.add('grabbing');
|
||||||
|
lastX = e.clientX;
|
||||||
|
lastY = e.clientY;
|
||||||
|
});
|
||||||
|
|
||||||
|
window.addEventListener('mouseup', () => {
|
||||||
|
isDragging = false;
|
||||||
|
viewport.classList.remove('grabbing');
|
||||||
|
});
|
||||||
|
|
||||||
|
viewport.addEventListener('mousemove', e => {
|
||||||
|
const vs = getCurrentState();
|
||||||
|
if (isDragging) {
|
||||||
|
const dx = e.clientX - lastX;
|
||||||
|
const dy = e.clientY - lastY;
|
||||||
|
vs.panX += dx;
|
||||||
|
vs.panY += dy;
|
||||||
|
lastX = e.clientX;
|
||||||
|
lastY = e.clientY;
|
||||||
|
updateTransform();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (e.target.classList.contains('frame')) {
|
||||||
|
const size = parseInt(e.target.dataset.size, 10);
|
||||||
|
const origSize = parseInt(e.target.dataset.origSize, 10);
|
||||||
|
const isFreedTail = e.target.dataset.isFreedTail === 'true';
|
||||||
|
let extra = '';
|
||||||
|
if (isFreedTail) {
|
||||||
|
extra = `<div class="row"><span class="key">Note</span><span class="value">Freed tail of a ${formatBytes(origSize)} allocation</span></div>`;
|
||||||
|
} else if (size !== origSize) {
|
||||||
|
extra = `<div class="row"><span class="key">Original</span><span class="value">${formatBytes(origSize)}</span></div>`;
|
||||||
|
}
|
||||||
|
tooltip.style.opacity = '1';
|
||||||
|
tooltip.innerHTML = `
|
||||||
|
<div class="kind" style="color:${KIND_COLORS[e.target.dataset.kind] || '#fff'}">${e.target.dataset.kind}</div>
|
||||||
|
${extra}
|
||||||
|
<div class="row"><span class="key">Size</span><span class="value">${formatBytes(size)}</span></div>
|
||||||
|
<div class="row"><span class="key">Pos</span><span class="value">${formatBytes(parseInt(e.target.dataset.pos, 10))}</span></div>
|
||||||
|
<div class="row"><span class="key">Loc</span><span class="value">${e.target.dataset.loc}</span></div>
|
||||||
|
<div class="row"><span class="key">Time</span><span class="value">${e.target.dataset.time}</span></div>
|
||||||
|
<div class="row"><span class="key">Arena</span><span class="value">${e.target.dataset.id}</span></div>
|
||||||
|
`;
|
||||||
|
tooltip.style.left = (e.clientX + 12) + 'px';
|
||||||
|
tooltip.style.top = (e.clientY + 12) + 'px';
|
||||||
|
} else {
|
||||||
|
tooltip.style.opacity = '0';
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
viewport.addEventListener('mouseleave', () => {
|
||||||
|
tooltip.style.opacity = '0';
|
||||||
|
});
|
||||||
|
|
||||||
|
viewport.addEventListener('wheel', e => {
|
||||||
|
e.preventDefault();
|
||||||
|
const vs = getCurrentState();
|
||||||
|
const delta = e.deltaY > 0 ? 0.9 : 1.1;
|
||||||
|
vs.zoomX *= delta;
|
||||||
|
vs.zoomY *= delta;
|
||||||
|
vs.zoomX = Math.max(0.5 / ZOOM_X_MID, Math.min(20 / ZOOM_X_MID, vs.zoomX));
|
||||||
|
vs.zoomY = Math.max(0.5 / ZOOM_Y_MID, Math.min(10 / ZOOM_Y_MID, vs.zoomY));
|
||||||
|
zoomXInput.value = vs.zoomX * ZOOM_X_MID;
|
||||||
|
zoomYInput.value = vs.zoomY * ZOOM_Y_MID;
|
||||||
|
updateTransform();
|
||||||
|
});
|
||||||
|
|
||||||
|
window.addEventListener('resize', updateScale);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function init() {
|
||||||
|
try {
|
||||||
|
const text = await loadLog();
|
||||||
|
const entries = parseLog(text);
|
||||||
|
if (entries.length === 0) throw new Error('No log entries found. Is arena_log.json in the same directory?');
|
||||||
|
|
||||||
|
globalMinTime = entries[0].timeMs;
|
||||||
|
globalMaxTime = entries[entries.length - 1].timeMs;
|
||||||
|
globalTimeSpan = globalMaxTime - globalMinTime;
|
||||||
|
|
||||||
|
const combined = buildFrames(entries);
|
||||||
|
combinedDataset = { entries, ...combined };
|
||||||
|
|
||||||
|
for (const [id, arenaEntries] of groupById(entries)) {
|
||||||
|
const arenaFrames = buildFrames(arenaEntries);
|
||||||
|
arenaDatasets.set(id, { entries: arenaEntries, ...arenaFrames });
|
||||||
|
}
|
||||||
|
|
||||||
|
setupTabs();
|
||||||
|
setupViewport();
|
||||||
|
setupControls();
|
||||||
|
render();
|
||||||
|
} catch (err) {
|
||||||
|
viewport.innerHTML = `<div class="error">${err.message}<br><br>Make sure you serve this page from a local web server so it can fetch arena_log.json.</div>`;
|
||||||
|
console.error(err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
init();
|
||||||
|
</script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
Executable
+14
@@ -0,0 +1,14 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
|
||||||
|
cd -- "$(dirname -- "$0")/arena-flame-graph" || ( echo "failed to cd"; exit 1 )
|
||||||
|
|
||||||
|
if command -v python3 >/dev/null 2>&1; then
|
||||||
|
PYTHON=python3
|
||||||
|
elif command -v python >/dev/null 2>&1; then
|
||||||
|
PYTHON=python
|
||||||
|
else
|
||||||
|
echo "error: Python not found" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
$PYTHON -m http.server
|
||||||
@@ -0,0 +1,291 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (C) 2026 Riyyi
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
package base
|
||||||
|
|
||||||
|
import "base:runtime"
|
||||||
|
import "core:fmt"
|
||||||
|
import "core:mem"
|
||||||
|
import vmem "core:mem/virtual"
|
||||||
|
import "core:os"
|
||||||
|
import "core:path/filepath"
|
||||||
|
import "core:time"
|
||||||
|
|
||||||
|
ARENA_LOG_FILE :: "arena_log.json"
|
||||||
|
|
||||||
|
// -----------------------------------------
|
||||||
|
// Types
|
||||||
|
|
||||||
|
Arena :: struct {
|
||||||
|
arena: vmem.Arena,
|
||||||
|
}
|
||||||
|
|
||||||
|
Arena_Log_Entry_Kind :: enum u8 {
|
||||||
|
Push,
|
||||||
|
Pop,
|
||||||
|
Clear,
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------
|
||||||
|
// Variables
|
||||||
|
|
||||||
|
@(private = "file")
|
||||||
|
arena_log: ^os.File
|
||||||
|
|
||||||
|
@(private = "file")
|
||||||
|
arena_log_count: uint
|
||||||
|
|
||||||
|
// -----------------------------------------
|
||||||
|
// Constructor/destructor
|
||||||
|
|
||||||
|
arena_init_buffer :: proc(buffer: []u8) -> Arena {
|
||||||
|
arena_create_log()
|
||||||
|
|
||||||
|
arena: vmem.Arena
|
||||||
|
err := vmem.arena_init_buffer(&arena, buffer)
|
||||||
|
fmt.ensuref(err == nil, "[arena] failed to init arena")
|
||||||
|
return {arena = arena}
|
||||||
|
}
|
||||||
|
|
||||||
|
arena_init_growing :: proc(
|
||||||
|
reserved: uint = vmem.DEFAULT_ARENA_GROWING_MINIMUM_BLOCK_SIZE,
|
||||||
|
) -> Arena {
|
||||||
|
arena_create_log()
|
||||||
|
|
||||||
|
arena: vmem.Arena
|
||||||
|
err := vmem.arena_init_growing(&arena, reserved)
|
||||||
|
fmt.ensuref(err == nil, "[arena] failed to init arena")
|
||||||
|
return {arena = arena}
|
||||||
|
}
|
||||||
|
|
||||||
|
arena_init_static :: proc(
|
||||||
|
reserved: uint = vmem.DEFAULT_ARENA_STATIC_RESERVE_SIZE,
|
||||||
|
commit_size: uint = vmem.DEFAULT_ARENA_STATIC_COMMIT_SIZE,
|
||||||
|
) -> Arena {
|
||||||
|
arena_create_log()
|
||||||
|
|
||||||
|
arena: vmem.Arena
|
||||||
|
err := vmem.arena_init_static(&arena, reserved, commit_size)
|
||||||
|
fmt.ensuref(err == nil, "[arena] failt to init arena")
|
||||||
|
return {arena = arena}
|
||||||
|
}
|
||||||
|
|
||||||
|
arena_destroy :: proc(arena: ^Arena) {
|
||||||
|
arena_destroy_log()
|
||||||
|
|
||||||
|
assert(arena != nil)
|
||||||
|
vmem.arena_destroy(&arena.arena)
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------
|
||||||
|
// Public functions
|
||||||
|
|
||||||
|
// Allocates memory from the provided arena.
|
||||||
|
arena_alloc :: proc(
|
||||||
|
arena: ^Arena,
|
||||||
|
size: uint,
|
||||||
|
alignment: uint,
|
||||||
|
loc := #caller_location,
|
||||||
|
) -> (
|
||||||
|
data: []u8,
|
||||||
|
err: runtime.Allocator_Error,
|
||||||
|
) {
|
||||||
|
arena_write_log(arena, arena_log, .Push, cast(u64)size, loc)
|
||||||
|
data = vmem.arena_alloc(&arena.arena, size, alignment, loc) or_return
|
||||||
|
return data, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create an `Allocator` from the provided `Arena`
|
||||||
|
arena_allocator :: proc(arena: ^Arena) -> mem.Allocator {
|
||||||
|
return mem.Allocator{arena_allocator_proc, arena}
|
||||||
|
}
|
||||||
|
|
||||||
|
// The allocator procedure used by an `Allocator` produced by `arena_allocator`
|
||||||
|
arena_allocator_proc :: proc(
|
||||||
|
allocator_data: rawptr,
|
||||||
|
mode: mem.Allocator_Mode,
|
||||||
|
size, alignment: int,
|
||||||
|
old_memory: rawptr,
|
||||||
|
old_size: int,
|
||||||
|
loc := #caller_location,
|
||||||
|
) -> (
|
||||||
|
data: []byte,
|
||||||
|
err: vmem.Allocator_Error,
|
||||||
|
) {
|
||||||
|
arena := cast(^Arena)allocator_data
|
||||||
|
|
||||||
|
switch mode {
|
||||||
|
case .Alloc, .Alloc_Non_Zeroed:
|
||||||
|
arena_write_log(arena, arena_log, .Push, cast(u64)size, loc)
|
||||||
|
case .Free:
|
||||||
|
// Not implemented in arena
|
||||||
|
case .Free_All:
|
||||||
|
arena_write_log(
|
||||||
|
arena,
|
||||||
|
arena_log,
|
||||||
|
.Clear,
|
||||||
|
cast(u64)arena.arena.total_used,
|
||||||
|
loc,
|
||||||
|
)
|
||||||
|
case .Resize, .Resize_Non_Zeroed:
|
||||||
|
switch {
|
||||||
|
case old_memory == nil:
|
||||||
|
arena_write_log(
|
||||||
|
arena,
|
||||||
|
arena_log,
|
||||||
|
.Push,
|
||||||
|
cast(u64)size,
|
||||||
|
loc,
|
||||||
|
)
|
||||||
|
case size == old_size:
|
||||||
|
// No-op
|
||||||
|
case size == 0:
|
||||||
|
// Not implemented in arena
|
||||||
|
case size > old_size:
|
||||||
|
arena_write_log(
|
||||||
|
arena,
|
||||||
|
arena_log,
|
||||||
|
.Push,
|
||||||
|
cast(u64)(size - old_size),
|
||||||
|
loc,
|
||||||
|
)
|
||||||
|
case size < old_size:
|
||||||
|
arena_write_log(
|
||||||
|
arena,
|
||||||
|
arena_log,
|
||||||
|
.Pop,
|
||||||
|
cast(u64)(old_size - size),
|
||||||
|
loc,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
case .Query_Features:
|
||||||
|
// No state change
|
||||||
|
case .Query_Info:
|
||||||
|
// Not implemented in arena
|
||||||
|
}
|
||||||
|
|
||||||
|
return vmem.arena_allocator_proc(
|
||||||
|
&arena.arena,
|
||||||
|
mode,
|
||||||
|
size,
|
||||||
|
alignment,
|
||||||
|
old_memory,
|
||||||
|
old_size,
|
||||||
|
loc,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Deallocates all but the first memory block of the arena and resets the allocator's usage to 0.
|
||||||
|
arena_free_all :: proc(arena: ^Arena, loc := #caller_location) {
|
||||||
|
arena_write_log(
|
||||||
|
arena,
|
||||||
|
arena_log,
|
||||||
|
.Clear,
|
||||||
|
cast(u64)arena.arena.total_used,
|
||||||
|
loc,
|
||||||
|
)
|
||||||
|
vmem.arena_free_all(&arena.arena, loc)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resets the memory of a Static or Buffer arena to a specific `position` (offset) and zeroes the previously used memory.
|
||||||
|
arena_static_reset_to :: proc(
|
||||||
|
arena: ^Arena,
|
||||||
|
pos: uint,
|
||||||
|
loc := #caller_location,
|
||||||
|
) -> bool {
|
||||||
|
arena_write_log(
|
||||||
|
arena,
|
||||||
|
arena_log,
|
||||||
|
.Pop,
|
||||||
|
cast(u64)(arena.arena.total_used - pos),
|
||||||
|
loc,
|
||||||
|
)
|
||||||
|
result := vmem.arena_static_reset_to(&arena.arena, pos, loc)
|
||||||
|
return result
|
||||||
|
}
|
||||||
|
|
||||||
|
@(private = "file")
|
||||||
|
arena_write_log :: proc(
|
||||||
|
arena: ^Arena,
|
||||||
|
file: ^os.File,
|
||||||
|
kind: Arena_Log_Entry_Kind,
|
||||||
|
size: u64,
|
||||||
|
loc := #caller_location,
|
||||||
|
) {
|
||||||
|
if arena_log == nil do return
|
||||||
|
|
||||||
|
time := time.now()
|
||||||
|
pos := cast(u64)arena.arena.total_used
|
||||||
|
|
||||||
|
if arena_log_count > 0 {
|
||||||
|
os.write_string(file, ",\n")
|
||||||
|
}
|
||||||
|
arena_log_count += 1
|
||||||
|
|
||||||
|
os.write_string(
|
||||||
|
file,
|
||||||
|
fmt.tprintf(
|
||||||
|
" {{" +
|
||||||
|
"\"id\": \"%p\", " +
|
||||||
|
"\"kind\": \"%v\", " +
|
||||||
|
"\"time\": \"%v\", " +
|
||||||
|
"\"loc\": \"%v %v\", " +
|
||||||
|
"\"pos\": %d, " +
|
||||||
|
"\"size\": %d" +
|
||||||
|
"}}",
|
||||||
|
arena,
|
||||||
|
kind,
|
||||||
|
time,
|
||||||
|
loc,
|
||||||
|
loc.procedure,
|
||||||
|
pos,
|
||||||
|
size,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------
|
||||||
|
// Private functions
|
||||||
|
|
||||||
|
@(private = "file")
|
||||||
|
arena_create_log :: proc() {
|
||||||
|
if arena_log != nil do return
|
||||||
|
|
||||||
|
out, exec_err := os.get_executable_directory(context.temp_allocator)
|
||||||
|
if exec_err != nil {
|
||||||
|
fmt.eprintf("[arena] failed to get exec path")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
arena_log_file_path, join_err := filepath.join(
|
||||||
|
{out, ARENA_LOG_FILE},
|
||||||
|
context.temp_allocator,
|
||||||
|
)
|
||||||
|
if join_err != .None {
|
||||||
|
fmt.eprintln("[arena] failed to construct log path")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
file, create_err := os.create(arena_log_file_path)
|
||||||
|
if create_err != nil {
|
||||||
|
fmt.eprintf("[arena] failed to create log file")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
os.write_string(file, fmt.tprintln("["))
|
||||||
|
|
||||||
|
arena_log = file
|
||||||
|
}
|
||||||
|
|
||||||
|
@(private = "file")
|
||||||
|
arena_destroy_log :: proc() {
|
||||||
|
if arena_log == nil do return
|
||||||
|
|
||||||
|
os.write_string(arena_log, fmt.tprintln("\n]"))
|
||||||
|
os.close(arena_log)
|
||||||
|
arena_log = nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (C) 2026 Riyyi
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
package base
|
||||||
|
|
||||||
|
should_close: bool
|
||||||
+9
-2
@@ -1,3 +1,9 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (C) 2026 Riyyi
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*/
|
||||||
|
|
||||||
package base
|
package base
|
||||||
|
|
||||||
import "base:intrinsics"
|
import "base:intrinsics"
|
||||||
@@ -78,6 +84,9 @@ Joystick_Disconnect_Event :: struct {
|
|||||||
id: i32,
|
id: i32,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO: Settings change event
|
||||||
|
// Settings_Change_Event :: struct {}
|
||||||
|
|
||||||
// Message Receiver
|
// Message Receiver
|
||||||
@(private)
|
@(private)
|
||||||
Listener :: struct {
|
Listener :: struct {
|
||||||
@@ -158,8 +167,6 @@ on_event :: proc(data: Event_Data) {
|
|||||||
drain_event_queue :: proc() {
|
drain_event_queue :: proc() {
|
||||||
assert(event_bus.queue != nil)
|
assert(event_bus.queue != nil)
|
||||||
|
|
||||||
fmt.println("toby!")
|
|
||||||
|
|
||||||
for &event in event_bus.queue {
|
for &event in event_bus.queue {
|
||||||
|
|
||||||
#partial switch e in event.data {
|
#partial switch e in event.data {
|
||||||
|
|||||||
+310
-201
@@ -1,231 +1,340 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (C) 2026 Riyyi
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*/
|
||||||
|
|
||||||
package base
|
package base
|
||||||
|
|
||||||
import "core:c"
|
import "base:runtime"
|
||||||
import "core:dynlib"
|
|
||||||
import "core:fmt"
|
import "core:fmt"
|
||||||
|
import "core:hash/xxhash"
|
||||||
|
import "core:mem"
|
||||||
import "core:os"
|
import "core:os"
|
||||||
|
import "core:path/filepath"
|
||||||
|
import "core:strings"
|
||||||
import "core:time"
|
import "core:time"
|
||||||
|
|
||||||
when ODIN_OS == .Windows {
|
SNAPSHOT_FILE :: "snapshot.sndr"
|
||||||
LIB_EXT :: ".dll"
|
|
||||||
} else when ODIN_OS == .Darwin {
|
|
||||||
LIB_EXT :: ".dylib"
|
|
||||||
} else {
|
|
||||||
LIB_EXT :: ".so"
|
|
||||||
}
|
|
||||||
|
|
||||||
GAME_LIB_DIR :: "out/"
|
MAGIC_STRING :: 0x72646E73 // "rdns" -> "sndr" in little endian
|
||||||
GAME_LIB_PATH :: GAME_LIB_DIR + "game" + LIB_EXT
|
HOT_RELOAD_VERSION :: 1
|
||||||
|
APP_VERSION_SIZE :: 4 + time.MIN_YYYY_DATE_LEN + 8 + 6 // example: `dev-2026-09-23-a4084b3-debug`
|
||||||
|
|
||||||
|
DIGEST :: xxhash.XXH64_hash
|
||||||
|
|
||||||
// -----------------------------------------
|
// -----------------------------------------
|
||||||
|
// Types
|
||||||
|
|
||||||
|
@(private)
|
||||||
|
Snapshot_Header :: struct #packed #all_or_none {
|
||||||
|
magic_string: u32,
|
||||||
|
version: u16, // spec of the snapshot
|
||||||
|
app_version: [APP_VERSION_SIZE]u8,
|
||||||
|
region_count: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
@(private)
|
||||||
|
Region_Header :: struct #packed #all_or_none {
|
||||||
|
name_size: u32,
|
||||||
|
data_size: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
@(private)
|
||||||
|
Memory_Region :: struct {
|
||||||
|
ptr_location: rawptr,
|
||||||
|
// TODO: How do we do hash compare without having to hash current memory every frame?
|
||||||
|
digest: DIGEST, // hash of this region in last snapshot
|
||||||
|
}
|
||||||
|
|
||||||
|
@(private)
|
||||||
Hot_Reload :: struct {
|
Hot_Reload :: struct {
|
||||||
loaded_libs: [dynamic]Game_API,
|
allocator: runtime.Allocator,
|
||||||
}
|
snapshot_path: string,
|
||||||
|
snapshot_header: Snapshot_Header,
|
||||||
Hot_Reload_Error :: enum u8 {
|
region_headers: map[string]Region_Header, // hash of name:size
|
||||||
None = 0,
|
regions: map[string]Memory_Region, // hash of name:size
|
||||||
Load_Game_Lib_Failed = 1,
|
write_full_snapshot: bool,
|
||||||
Unimplemented = 127,
|
|
||||||
Okay = None,
|
|
||||||
}
|
|
||||||
|
|
||||||
Error :: union #shared_nil {
|
|
||||||
Hot_Reload_Error,
|
|
||||||
}
|
|
||||||
|
|
||||||
Game_API :: struct {
|
|
||||||
lib: dynlib.Library,
|
|
||||||
memory: proc() -> rawptr,
|
|
||||||
memory_free: proc(),
|
|
||||||
memory_size: proc() -> int,
|
|
||||||
memory_set: proc(mem: rawptr),
|
|
||||||
settings: proc() -> Settings,
|
|
||||||
init_once: proc(),
|
|
||||||
init: proc(),
|
|
||||||
update: proc(_: f32),
|
|
||||||
render: proc(),
|
|
||||||
destroy: proc(),
|
|
||||||
should_close: proc() -> bool,
|
|
||||||
force_reload: proc() -> bool,
|
|
||||||
force_restart: proc() -> bool,
|
|
||||||
modification_time: time.Time,
|
|
||||||
api_version: int, // iteration of the game lib
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// -----------------------------------------
|
// -----------------------------------------
|
||||||
|
// Variables
|
||||||
|
|
||||||
hot_reload_init :: proc() -> (hr: Hot_Reload, error: Error) {
|
@(private)
|
||||||
api: Game_API
|
hr: Hot_Reload
|
||||||
|
|
||||||
api_ok := load_game_lib(&api)
|
|
||||||
if !api_ok {
|
|
||||||
fmt.println("error: failed to load Game API")
|
|
||||||
return {}, .Load_Game_Lib_Failed
|
|
||||||
}
|
|
||||||
|
|
||||||
hr.loaded_libs = make([dynamic]Game_API, 0, 0, context.allocator)
|
|
||||||
append(&hr.loaded_libs, api)
|
|
||||||
|
|
||||||
return hr, nil
|
|
||||||
}
|
|
||||||
|
|
||||||
hot_reload_destroy :: proc(state: ^Hot_Reload) {
|
|
||||||
for &api in state.loaded_libs {
|
|
||||||
unload_game_lib(&api)
|
|
||||||
}
|
|
||||||
|
|
||||||
delete(state.loaded_libs)
|
|
||||||
}
|
|
||||||
|
|
||||||
// -----------------------------------------
|
// -----------------------------------------
|
||||||
|
// Constructor & destructor
|
||||||
|
|
||||||
active_lib :: proc(hr: ^Hot_Reload) -> ^Game_API {
|
hot_reload_init :: proc(
|
||||||
return &hr.loaded_libs[len(hr.loaded_libs) - 1]
|
app_version: string,
|
||||||
}
|
allocator := context.allocator,
|
||||||
|
) -> os.Error {
|
||||||
should_close :: proc(hr: ^Hot_Reload) -> bool {
|
// Get snapshot path
|
||||||
api := active_lib(hr)
|
out := os.get_executable_directory(allocator) or_return
|
||||||
if api.lib == nil do return true
|
defer delete(out, allocator)
|
||||||
return api.should_close()
|
snapshot_path, err := filepath.join(
|
||||||
}
|
{out, SNAPSHOT_FILE},
|
||||||
|
context.temp_allocator,
|
||||||
copy_lib :: proc(to: string) -> bool {
|
|
||||||
copy_err := os.copy_file(to, GAME_LIB_PATH)
|
|
||||||
if copy_err != nil {
|
|
||||||
fmt.printfln(
|
|
||||||
"error: failed to copy {0} to {1}: {2:v}",
|
|
||||||
GAME_LIB_PATH,
|
|
||||||
to,
|
|
||||||
copy_err,
|
|
||||||
)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
|
|
||||||
return true
|
|
||||||
}
|
|
||||||
|
|
||||||
// Load game lib symbols
|
|
||||||
load_game_lib :: proc(api: ^Game_API) -> bool {
|
|
||||||
mod_time, mod_time_err := os.last_write_time_by_name(GAME_LIB_PATH)
|
|
||||||
if mod_time_err != os.ERROR_NONE {
|
|
||||||
fmt.printfln(
|
|
||||||
"error: failed getting last write time of {0}, error code: {1}",
|
|
||||||
GAME_LIB_PATH,
|
|
||||||
mod_time_err,
|
|
||||||
)
|
|
||||||
return false
|
|
||||||
}
|
|
||||||
api.modification_time = mod_time
|
|
||||||
|
|
||||||
lib_name := fmt.tprintf(
|
|
||||||
GAME_LIB_DIR + "game_{0}" + LIB_EXT,
|
|
||||||
api.api_version,
|
|
||||||
)
|
)
|
||||||
copy_lib(lib_name) or_return
|
snapshot_path_cpy := strings.clone(snapshot_path, allocator)
|
||||||
|
|
||||||
// Match the names of the fields in Game_API to symbols in the game DLL
|
// Copy version string
|
||||||
_, ok := dynlib.initialize_symbols(api, lib_name, "", "lib")
|
version: [APP_VERSION_SIZE]u8
|
||||||
if !ok {
|
n := min(len(app_version), APP_VERSION_SIZE)
|
||||||
fmt.printfln(
|
copy(version[:n], app_version[:n])
|
||||||
"error: failed initializing symbols: {0}",
|
|
||||||
dynlib.last_error(),
|
hr = {
|
||||||
|
allocator = allocator,
|
||||||
|
snapshot_path = snapshot_path_cpy,
|
||||||
|
snapshot_header = {
|
||||||
|
magic_string = MAGIC_STRING,
|
||||||
|
version = HOT_RELOAD_VERSION,
|
||||||
|
app_version = version,
|
||||||
|
region_count = 0,
|
||||||
|
},
|
||||||
|
region_headers = make(map[string]Region_Header, 1, allocator), // initial capacity for nil checks
|
||||||
|
regions = make(map[string]Memory_Region, 1, allocator), // initial capacity for nil checks
|
||||||
|
write_full_snapshot = true,
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
hot_reload_destroy :: proc() {
|
||||||
|
assert(
|
||||||
|
hr.region_headers != nil,
|
||||||
|
"[hot-reload] destroying uninitialized data",
|
||||||
|
)
|
||||||
|
|
||||||
|
assert(hr.regions != nil, "[hot-reload] destroying uninitialized data")
|
||||||
|
|
||||||
|
delete(hr.snapshot_path, hr.allocator)
|
||||||
|
|
||||||
|
for key, region in hr.region_headers do delete(key, hr.allocator)
|
||||||
|
|
||||||
|
delete(hr.region_headers)
|
||||||
|
delete(hr.regions)
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------
|
||||||
|
// Public functions
|
||||||
|
|
||||||
|
register_region :: proc(
|
||||||
|
name: string,
|
||||||
|
ptr_location: rawptr,
|
||||||
|
data_size: u32,
|
||||||
|
) -> os.Error {
|
||||||
|
assert(hr.region_headers != nil, "[hot-reload] uninitialized")
|
||||||
|
assert(hr.regions != nil, "[hot-reload] uninitialized")
|
||||||
|
assert(ptr_location != nil, "[hot_reload] invalid location")
|
||||||
|
assert(data_size > 0, "[hot_reload] invalid type size")
|
||||||
|
|
||||||
|
hash := fmt.tprintf("%v:%d", name, data_size)
|
||||||
|
assert(!(hash in hr.regions), "[hot_reload] double registration")
|
||||||
|
hash_cpy := strings.clone(hash, hr.allocator)
|
||||||
|
hr.region_headers[hash_cpy] = Region_Header {
|
||||||
|
name_size = cast(u32)len(name),
|
||||||
|
data_size = data_size,
|
||||||
|
}
|
||||||
|
hr.regions[hash_cpy] = Memory_Region {
|
||||||
|
ptr_location = ptr_location,
|
||||||
|
digest = {},
|
||||||
|
}
|
||||||
|
|
||||||
|
hr.snapshot_header.region_count += 1
|
||||||
|
|
||||||
|
hr.write_full_snapshot = true
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// returns `fresh` = `true` when booting without a snapshot
|
||||||
|
read_snapshot :: proc() -> (fresh: bool, err: os.Error) {
|
||||||
|
assert(hr.region_headers != nil, "[hot-reload] uninitialized")
|
||||||
|
assert(hr.regions != nil, "[hot-reload] uninitialized")
|
||||||
|
|
||||||
|
if !os.exists(hr.snapshot_path) {
|
||||||
|
hr.write_full_snapshot = true
|
||||||
|
return true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
snapshot := os.open(hr.snapshot_path, {.Read}) or_return
|
||||||
|
defer os.close(snapshot)
|
||||||
|
|
||||||
|
offset: i64
|
||||||
|
|
||||||
|
// Read snapshot header
|
||||||
|
snapshot_header: Snapshot_Header
|
||||||
|
header_bytes := mem.ptr_to_bytes(&snapshot_header)
|
||||||
|
os.read_at(snapshot, header_bytes, offset) or_return
|
||||||
|
offset += size_of(Snapshot_Header)
|
||||||
|
assert(
|
||||||
|
snapshot_header.magic_string == MAGIC_STRING,
|
||||||
|
"[hot-reload] unknown filetype",
|
||||||
|
)
|
||||||
|
assert(
|
||||||
|
snapshot_header.version == HOT_RELOAD_VERSION,
|
||||||
|
"[hot-reload] incompatible snapshot version",
|
||||||
|
)
|
||||||
|
|
||||||
|
region_header: Region_Header
|
||||||
|
for i in 0 ..< snapshot_header.region_count {
|
||||||
|
|
||||||
|
// Read region header
|
||||||
|
header_bytes := mem.ptr_to_bytes(®ion_header)
|
||||||
|
os.read_at(snapshot, header_bytes, offset) or_return
|
||||||
|
offset += size_of(Region_Header)
|
||||||
|
|
||||||
|
// Read region name
|
||||||
|
name_bytes := make([]byte, region_header.name_size, hr.allocator)
|
||||||
|
defer delete(name_bytes, hr.allocator)
|
||||||
|
os.read_at(snapshot, name_bytes, offset) or_return
|
||||||
|
offset += cast(i64)region_header.name_size
|
||||||
|
name := transmute(string)name_bytes[:]
|
||||||
|
|
||||||
|
// Read region data
|
||||||
|
data_bytes := make([]byte, region_header.data_size, hr.allocator)
|
||||||
|
defer delete(data_bytes, hr.allocator)
|
||||||
|
os.read_at(snapshot, data_bytes, offset) or_return
|
||||||
|
offset += cast(i64)region_header.data_size
|
||||||
|
|
||||||
|
// Compare currently registered region with the loaded region
|
||||||
|
key := fmt.tprintf("%v:%d", name, region_header.data_size)
|
||||||
|
new_region_header, ok := hr.region_headers[key]
|
||||||
|
if !ok || region_header.data_size != new_region_header.data_size {
|
||||||
|
hr.write_full_snapshot = true
|
||||||
|
fmt.println("[hot-reload] bail loading region:", name)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create digest and store in registered regions
|
||||||
|
region := &hr.regions[key]
|
||||||
|
digest := xxhash.XXH64(data_bytes)
|
||||||
|
region.digest = digest
|
||||||
|
|
||||||
|
// Copy snapshot memory to the memory region
|
||||||
|
dest := mem.byte_slice(
|
||||||
|
region.ptr_location,
|
||||||
|
cast(int)region_header.data_size,
|
||||||
)
|
)
|
||||||
} else {
|
copy(dest, data_bytes)
|
||||||
// Odin's shared libraries don't register a constructor, so the lib's
|
}
|
||||||
// runtime init (@init procs like os.stdout setup) never runs on load.
|
|
||||||
// Call it explicitly.
|
return false, nil
|
||||||
// Windows doesn't need this: its dynamic build exports DllMain, which
|
}
|
||||||
// the OS calls on load and which runs _startup_runtime itself.
|
|
||||||
when ODIN_OS != .Windows {
|
// Next write will be a full memory snapshot
|
||||||
Entry :: #type proc "c" () -> c.int
|
set_write_full_snapshot :: proc() {
|
||||||
entry_ptr, entry_ok := dynlib.symbol_address(
|
hr.write_full_snapshot = true
|
||||||
api.lib,
|
}
|
||||||
"_odin_entry_point",
|
|
||||||
)
|
// Write memory snapshot, save on writes by diff-ing
|
||||||
if entry_ok do (transmute(Entry)entry_ptr)()
|
write_snapshot :: proc() -> os.Error {
|
||||||
|
assert(hr.region_headers != nil, "[hot-reload] uninitialized")
|
||||||
|
assert(hr.regions != nil, "[hot-reload] uninitialized")
|
||||||
|
|
||||||
|
snapshot: ^os.File
|
||||||
|
if hr.write_full_snapshot || !os.exists(hr.snapshot_path) {
|
||||||
|
snapshot = os.create(hr.snapshot_path) or_return
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
snapshot = os.open(hr.snapshot_path, {.Read, .Write}) or_return
|
||||||
|
}
|
||||||
|
defer os.close(snapshot)
|
||||||
|
|
||||||
|
offset: i64
|
||||||
|
|
||||||
|
// Write header
|
||||||
|
if hr.write_full_snapshot {
|
||||||
|
header_bytes := mem.ptr_to_bytes(&hr.snapshot_header)
|
||||||
|
n := os.write_at(snapshot, header_bytes, offset) or_return
|
||||||
|
}
|
||||||
|
offset += size_of(Snapshot_Header)
|
||||||
|
|
||||||
|
for key, ®ion in hr.regions {
|
||||||
|
header := hr.region_headers[key]
|
||||||
|
|
||||||
|
// Write region header
|
||||||
|
if hr.write_full_snapshot {
|
||||||
|
header_bytes := mem.ptr_to_bytes(&header)
|
||||||
|
os.write_at(snapshot, header_bytes, offset) or_return
|
||||||
|
}
|
||||||
|
offset += size_of(Region_Header)
|
||||||
|
|
||||||
|
// Write region name
|
||||||
|
if hr.write_full_snapshot {
|
||||||
|
name := key[:header.name_size] // get name from first part of the hash
|
||||||
|
name_bytes := transmute([]byte)name
|
||||||
|
os.write_at(snapshot, name_bytes, offset) or_return
|
||||||
|
}
|
||||||
|
offset += cast(i64)header.name_size
|
||||||
|
|
||||||
|
// Write region data (if bytes differ)
|
||||||
|
data_bytes := mem.byte_slice(region.ptr_location, header.data_size)
|
||||||
|
new_digest := xxhash.XXH64(data_bytes)
|
||||||
|
if hr.write_full_snapshot {
|
||||||
|
region.digest = new_digest
|
||||||
|
os.write_at(snapshot, data_bytes, offset) or_return
|
||||||
|
}
|
||||||
|
else if new_digest != region.digest {
|
||||||
|
region.digest = new_digest
|
||||||
|
write_diff_at(snapshot, data_bytes, offset) or_return
|
||||||
|
}
|
||||||
|
offset += cast(i64)header.data_size
|
||||||
|
}
|
||||||
|
|
||||||
|
hr.write_full_snapshot = false
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
write_diff_at :: proc(
|
||||||
|
snapshot: ^os.File,
|
||||||
|
mem_data: []byte,
|
||||||
|
offset: i64,
|
||||||
|
) -> os.Error {
|
||||||
|
size := len(mem_data)
|
||||||
|
|
||||||
|
disk_data := make([]byte, size, hr.allocator)
|
||||||
|
defer delete(disk_data, hr.allocator)
|
||||||
|
os.read_at(snapshot, disk_data, offset) or_return
|
||||||
|
|
||||||
|
diff_idx: int = -1
|
||||||
|
for i := 0; i < size; i += 1 {
|
||||||
|
if mem_data[i] == disk_data[i] {
|
||||||
|
if diff_idx >= 0 {
|
||||||
|
os.write_at(
|
||||||
|
snapshot,
|
||||||
|
mem_data[diff_idx:i],
|
||||||
|
offset + cast(i64)diff_idx,
|
||||||
|
) or_return
|
||||||
|
diff_idx = -1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if diff_idx < 0 {
|
||||||
|
diff_idx = i
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return ok
|
if diff_idx >= 0 {
|
||||||
|
os.write_at(
|
||||||
|
snapshot,
|
||||||
|
mem_data[diff_idx:size],
|
||||||
|
offset + cast(i64)diff_idx,
|
||||||
|
) or_return
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Unload game lib, used during full restarts
|
force_reload :: proc() {
|
||||||
unload_game_lib :: proc(api: ^Game_API) {
|
should_close = true
|
||||||
if api.lib != nil {
|
|
||||||
if !dynlib.unload_library(api.lib) {
|
|
||||||
fmt.eprintfln(
|
|
||||||
"error: failed unloading lib: {0}",
|
|
||||||
dynlib.last_error(),
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if os.remove(
|
|
||||||
fmt.tprintf(GAME_LIB_DIR + "game_{0}" + LIB_EXT, api.api_version),
|
|
||||||
) !=
|
|
||||||
nil {
|
|
||||||
fmt.printfln(
|
|
||||||
"error: failed to remove {0}game_{1}{2} copy",
|
|
||||||
GAME_LIB_DIR,
|
|
||||||
api.api_version,
|
|
||||||
LIB_EXT,
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
reload_game_lib :: proc(hr: ^Hot_Reload) -> (lib: ^Game_API, err: Error) {
|
force_restart :: proc() -> os.Error {
|
||||||
api := active_lib(hr)
|
should_close = true
|
||||||
force_reload := api.force_reload()
|
os.remove(hr.snapshot_path) or_return
|
||||||
force_restart := api.force_restart()
|
|
||||||
reload := force_reload || force_restart
|
|
||||||
|
|
||||||
lib_mod, lib_mod_err := os.last_write_time_by_name(GAME_LIB_PATH)
|
return nil
|
||||||
// TODO: Handle error
|
|
||||||
if lib_mod_err == os.ERROR_NONE && api.modification_time != lib_mod {
|
|
||||||
reload = true
|
|
||||||
}
|
|
||||||
|
|
||||||
if !reload do return api, nil
|
|
||||||
|
|
||||||
new_api: Game_API
|
|
||||||
new_api.api_version = api.api_version + 1
|
|
||||||
new_api_ok := load_game_lib(&new_api)
|
|
||||||
if !new_api_ok {
|
|
||||||
fmt.println("error: failed to load Game API")
|
|
||||||
return nil, .Load_Game_Lib_Failed
|
|
||||||
}
|
|
||||||
|
|
||||||
force_restart = force_restart || api.memory_size() != new_api.memory_size()
|
|
||||||
|
|
||||||
if !force_restart {
|
|
||||||
// This does the normal hot reload
|
|
||||||
|
|
||||||
// Note that we don't unload the old game APIs because that
|
|
||||||
// would unload the lib. The lib can contain stored info
|
|
||||||
// such as string literals. The old libs are only unloaded
|
|
||||||
// on a full reset or on shutdown.
|
|
||||||
memory := api.memory()
|
|
||||||
new_api.memory_set(memory)
|
|
||||||
} else {
|
|
||||||
// This does a full reset. That's basically like opening and
|
|
||||||
// closing the game, without having to restart the executable.
|
|
||||||
//
|
|
||||||
// You end up in here if the game requests a full reset OR
|
|
||||||
// if the size of the game memory has changed. That would
|
|
||||||
// probably lead to a crash anyways.
|
|
||||||
|
|
||||||
api.memory_free()
|
|
||||||
|
|
||||||
for &g in hr.loaded_libs {
|
|
||||||
unload_game_lib(&g)
|
|
||||||
}
|
|
||||||
clear(&hr.loaded_libs)
|
|
||||||
|
|
||||||
new_api.init()
|
|
||||||
}
|
|
||||||
|
|
||||||
append(&hr.loaded_libs, new_api)
|
|
||||||
|
|
||||||
return active_lib(hr), nil
|
|
||||||
}
|
}
|
||||||
|
|||||||
+17
-11
@@ -1,3 +1,9 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (C) 2026 Riyyi
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*/
|
||||||
|
|
||||||
package base
|
package base
|
||||||
|
|
||||||
// -----------------------------------------
|
// -----------------------------------------
|
||||||
@@ -18,17 +24,17 @@ Key :: enum i16 {
|
|||||||
|
|
||||||
// Named printable keys
|
// Named printable keys
|
||||||
Key_Space = 32,
|
Key_Space = 32,
|
||||||
Key_Apostrophe = 39, // '
|
Key_Apostrophe = 39, // '
|
||||||
Key_Comma = 44, // ,
|
Key_Comma = 44, // ,
|
||||||
Key_Minus = 45, // -
|
Key_Minus = 45, // -
|
||||||
Key_Period = 46, // .
|
Key_Period = 46, // .
|
||||||
Key_Slash = 47, // /
|
Key_Slash = 47, // /
|
||||||
Key_Semicolon = 59, // ;
|
Key_Semicolon = 59, // ;
|
||||||
Key_Equal = 61, // =
|
Key_Equal = 61, // =
|
||||||
Key_Left_Bracket = 91, // [
|
Key_Left_Bracket = 91, // [
|
||||||
Key_Backslash = 92, // \
|
Key_Backslash = 92, // \
|
||||||
Key_Right_Bracket = 93, // ]
|
Key_Right_Bracket = 93, // ]
|
||||||
Key_Grave_Accent = 96, // `
|
Key_Grave_Accent = 96, // `
|
||||||
Key_World_1 = 161, // non-US #1
|
Key_World_1 = 161, // non-US #1
|
||||||
Key_World_2 = 162, // non-US #2
|
Key_World_2 = 162, // non-US #2
|
||||||
|
|
||||||
|
|||||||
+37
-6
@@ -1,14 +1,26 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (C) 2026 Riyyi
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*/
|
||||||
|
|
||||||
package base
|
package base
|
||||||
|
|
||||||
// -----------------------------------------
|
// -----------------------------------------
|
||||||
|
// Types
|
||||||
|
|
||||||
Settings :: struct {
|
Settings :: struct {
|
||||||
width: u16,
|
// Window
|
||||||
height: u16,
|
width: u16,
|
||||||
title: string,
|
height: u16,
|
||||||
mode: WindowMode,
|
title: string,
|
||||||
refresh: u16, // 0 = unlimited
|
mode: WindowMode,
|
||||||
vsync: bool,
|
refresh: u16, // 0 = unlimited
|
||||||
|
vsync: bool,
|
||||||
|
fov: f32,
|
||||||
|
// Input
|
||||||
|
mouse_sensitivity: f32,
|
||||||
|
mouse_captured: bool,
|
||||||
// TODO:
|
// TODO:
|
||||||
// windowed resizable y/n
|
// windowed resizable y/n
|
||||||
// exit key (ex: escape)
|
// exit key (ex: escape)
|
||||||
@@ -19,3 +31,22 @@ WindowMode :: enum u8 {
|
|||||||
Borderless = 1,
|
Borderless = 1,
|
||||||
Fullscreen = 2,
|
Fullscreen = 2,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------
|
||||||
|
// Public functions
|
||||||
|
|
||||||
|
settings :: proc() -> Settings {
|
||||||
|
return {
|
||||||
|
// Window
|
||||||
|
width = 960,
|
||||||
|
height = 540,
|
||||||
|
title = "WGPU Native",
|
||||||
|
mode = WindowMode.Windowed,
|
||||||
|
refresh = 60,
|
||||||
|
vsync = true,
|
||||||
|
fov = 60,
|
||||||
|
// Input
|
||||||
|
mouse_sensitivity = 0.005,
|
||||||
|
mouse_captured = false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,23 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (C) 2026 Riyyi
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
package base
|
||||||
|
|
||||||
|
// -----------------------------------------
|
||||||
|
// Types
|
||||||
|
|
||||||
|
Vec2 :: [2]f32
|
||||||
|
Vec3 :: [3]f32
|
||||||
|
Vec4 :: [4]f32
|
||||||
|
|
||||||
|
Mat3 :: matrix[3, 3]f32
|
||||||
|
Mat4 :: matrix[4, 4]f32
|
||||||
|
|
||||||
|
Vertex :: struct #align (4) {
|
||||||
|
pos: Vec3,
|
||||||
|
col: Vec3,
|
||||||
|
uv: Vec2, // texture coordinate
|
||||||
|
}
|
||||||
@@ -0,0 +1,30 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (C) 2026 Riyyi
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
package core
|
||||||
|
|
||||||
|
// -----------------------------------------
|
||||||
|
// Types
|
||||||
|
|
||||||
|
// API for when the Game talks to the Engine.
|
||||||
|
Engine_API :: struct {
|
||||||
|
assets: ^Assets,
|
||||||
|
things: ^Things,
|
||||||
|
}
|
||||||
|
|
||||||
|
// API for when the Engine talks to the Game.
|
||||||
|
Game_API :: struct {
|
||||||
|
register_api: proc(api: ^Engine_API),
|
||||||
|
register_memory: proc(),
|
||||||
|
init_once: proc(),
|
||||||
|
init: proc(),
|
||||||
|
update: proc(dt: f32),
|
||||||
|
render: proc(),
|
||||||
|
destroy: proc(),
|
||||||
|
should_close: proc() -> bool,
|
||||||
|
force_reload: proc() -> bool,
|
||||||
|
force_restart: proc() -> bool,
|
||||||
|
}
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (C) 2026 Riyyi
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
package core
|
||||||
|
|
||||||
|
import "base:runtime"
|
||||||
|
import "core:fmt"
|
||||||
|
import "core:hash/xxhash"
|
||||||
|
import "core:os"
|
||||||
|
|
||||||
|
import "sindri:base"
|
||||||
|
|
||||||
|
ASSET_NIL :: 0
|
||||||
|
ASSETS_MAX :: 512
|
||||||
|
|
||||||
|
DIGEST :: xxhash.XXH64_hash
|
||||||
|
|
||||||
|
// -----------------------------------------
|
||||||
|
// Types
|
||||||
|
|
||||||
|
Model :: struct {
|
||||||
|
vertices: []base.Vertex,
|
||||||
|
indices: []u16,
|
||||||
|
// Some file formats embed their texture
|
||||||
|
// texture: ^Texture2D,
|
||||||
|
}
|
||||||
|
|
||||||
|
Texture :: struct {
|
||||||
|
width: u32,
|
||||||
|
height: u32,
|
||||||
|
id: u32,
|
||||||
|
internal_format: u32,
|
||||||
|
data_format: u32,
|
||||||
|
data_type: u32,
|
||||||
|
}
|
||||||
|
|
||||||
|
Asset_Idx :: u16
|
||||||
|
|
||||||
|
Asset_Ref :: struct {
|
||||||
|
// TODO: 22 bits index, 10 bits generation, so we can store it in one 32bit number
|
||||||
|
idx: Asset_Idx,
|
||||||
|
gen: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
Asset_Kind :: enum {
|
||||||
|
Model,
|
||||||
|
Texture,
|
||||||
|
}
|
||||||
|
|
||||||
|
Asset :: struct {
|
||||||
|
kind: Asset_Kind,
|
||||||
|
|
||||||
|
digest: DIGEST,
|
||||||
|
|
||||||
|
data: union #no_nil {
|
||||||
|
Model,
|
||||||
|
Texture,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
Assets :: struct {
|
||||||
|
allocator: runtime.Allocator,
|
||||||
|
assets: [ASSETS_MAX]Asset,
|
||||||
|
// TODO: Collapse used and gen into 1 array
|
||||||
|
used: [ASSETS_MAX]bool,
|
||||||
|
gen: [ASSETS_MAX]u16,
|
||||||
|
free_list: [ASSETS_MAX]Asset_Idx,
|
||||||
|
next_free: Asset_Idx, // first free'd slot
|
||||||
|
next_unused: Asset_Idx, // never previously used slot
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------
|
||||||
|
// Constructor/destructor
|
||||||
|
|
||||||
|
assets_init :: proc(allocator := context.allocator) -> Assets {
|
||||||
|
return {allocator = allocator}
|
||||||
|
}
|
||||||
|
|
||||||
|
assets_destroy :: proc(a: ^Assets) {
|
||||||
|
for &asset, i in a.assets {
|
||||||
|
if !a.used[i] do continue
|
||||||
|
m, ok := asset.data.(Model)
|
||||||
|
if !ok do continue
|
||||||
|
delete(m.vertices, a.allocator)
|
||||||
|
delete(m.indices, a.allocator)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------
|
||||||
|
// Public functions
|
||||||
|
|
||||||
|
asset_add :: proc(a: ^Assets) -> Asset_Ref {
|
||||||
|
slot: Asset_Idx
|
||||||
|
gen: u16
|
||||||
|
|
||||||
|
// Two-tiered searching of slots:
|
||||||
|
// - first search the free-list, that contains freed up slots
|
||||||
|
// - fallback to the index that has never been allocated before
|
||||||
|
if a.next_free != ASSET_NIL {
|
||||||
|
slot = a.next_free
|
||||||
|
a.next_free = a.free_list[a.next_free]
|
||||||
|
a.free_list[slot] = ASSET_NIL // clean up the pop'ed free-slot
|
||||||
|
}
|
||||||
|
else if (a.next_unused < ASSETS_MAX) {
|
||||||
|
if a.next_unused == ASSET_NIL do a.next_unused = 1 // first ever add()
|
||||||
|
slot = a.next_unused
|
||||||
|
a.next_unused += 1
|
||||||
|
}
|
||||||
|
|
||||||
|
if slot != ASSET_NIL {
|
||||||
|
a.assets[slot] = {} // reset data
|
||||||
|
a.used[slot] = true
|
||||||
|
a.gen[slot] += 1
|
||||||
|
gen = a.gen[slot]
|
||||||
|
}
|
||||||
|
|
||||||
|
return {idx = slot, gen = gen}
|
||||||
|
}
|
||||||
|
|
||||||
|
asset_rem :: proc(a: ^Assets, ref: Asset_Ref) {
|
||||||
|
idx := asset_deref(a, ref)
|
||||||
|
if idx == ASSET_NIL do return
|
||||||
|
|
||||||
|
a.used[idx] = false
|
||||||
|
a.free_list[idx] = a.next_free
|
||||||
|
a.next_free = idx
|
||||||
|
}
|
||||||
|
|
||||||
|
asset_get :: proc(a: ^Assets, ref: Asset_Ref) -> ^Asset {
|
||||||
|
return &a.assets[asset_deref(a, ref)]
|
||||||
|
}
|
||||||
|
|
||||||
|
asset_deref :: proc(a: ^Assets, ref: Asset_Ref) -> Asset_Idx {
|
||||||
|
if ref.idx > ASSET_NIL &&
|
||||||
|
ref.idx < ASSETS_MAX &&
|
||||||
|
a.used[ref.idx] &&
|
||||||
|
ref.gen == a.gen[ref.idx] {
|
||||||
|
return ref.idx
|
||||||
|
}
|
||||||
|
|
||||||
|
return ASSET_NIL
|
||||||
|
}
|
||||||
|
|
||||||
|
asset_find :: proc(a: ^Assets, path: string) -> (Asset_Idx, DIGEST) {
|
||||||
|
digest := xxhash.XXH64(transmute([]u8)path)
|
||||||
|
|
||||||
|
found: u16
|
||||||
|
for i: u16 = 1; i < min(a.next_unused, ASSETS_MAX); i += 1 {
|
||||||
|
if a.used[i] && a.assets[i].digest == digest {
|
||||||
|
return i, digest
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ASSET_NIL, digest
|
||||||
|
}
|
||||||
|
|
||||||
|
asset_load_model :: proc(a: ^Assets, path: string) -> Asset_Ref {
|
||||||
|
asset, digest := asset_find(a, path)
|
||||||
|
if asset != ASSET_NIL {
|
||||||
|
fmt.println("[assets] loading cached model", path)
|
||||||
|
return {idx = asset, gen = a.gen[asset]}
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.println("[assets] loading model", path)
|
||||||
|
vertices, indices, ok := load_obj_model(path, a.allocator)
|
||||||
|
fmt.assertf(ok, "[assets] failed to read model: %s", path)
|
||||||
|
|
||||||
|
ref := asset_add(a)
|
||||||
|
a.assets[ref.idx] = {
|
||||||
|
kind = .Model,
|
||||||
|
digest = digest,
|
||||||
|
data = Model{vertices = vertices, indices = indices},
|
||||||
|
}
|
||||||
|
|
||||||
|
return ref
|
||||||
|
}
|
||||||
|
|
||||||
|
asset_reload_after_hot_reload :: proc(a: ^Assets, path: string) {
|
||||||
|
pwd, pwd_err := os.get_working_directory(context.temp_allocator)
|
||||||
|
if pwd_err != nil {
|
||||||
|
fmt.eprintfln("[assets] failed to get working directory: %s", pwd_err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
w := os.walker_create(path)
|
||||||
|
defer os.walker_destroy(&w)
|
||||||
|
|
||||||
|
for info in os.walker_walk(&w) {
|
||||||
|
if path, err := os.walker_error(&w); err != nil {
|
||||||
|
fmt.eprintfln("[assets] failed walking %s: %s", path, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
a_path := info.fullpath[len(pwd) + 1:]
|
||||||
|
digest := xxhash.XXH64(transmute([]u8)a_path)
|
||||||
|
|
||||||
|
for i: u16 = 1; i < min(a.next_unused, ASSETS_MAX); i += 1 {
|
||||||
|
if !a.used[i] || a.assets[i].kind != .Model do continue
|
||||||
|
if a.assets[i].digest == digest {
|
||||||
|
fmt.println("[assets] loading model", a_path)
|
||||||
|
vertices, indices, ok := load_obj_model(a_path, a.allocator)
|
||||||
|
fmt.assertf(ok, "[assets] failed to read model: %s", a_path)
|
||||||
|
|
||||||
|
a.assets[i].data = Model {
|
||||||
|
vertices = vertices,
|
||||||
|
indices = indices,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Batching:
|
||||||
|
// max_vertices 60k
|
||||||
|
// max_elements 60k
|
||||||
|
// max_texture_slots 32, query gpu or can wgpu do a larger buffer?
|
||||||
|
|
||||||
|
// Scene load: loop through all models, add all model sizes together,
|
||||||
|
// then create a vertex_buffer using the max size, storing the index somewhere.
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (C) 2026 Riyyi
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
package core
|
||||||
|
|
||||||
|
import "core:math"
|
||||||
|
import "core:math/linalg"
|
||||||
|
|
||||||
|
import "sindri:base"
|
||||||
|
import "sindri:platform"
|
||||||
|
|
||||||
|
CAMERA_SPEED :: 5
|
||||||
|
|
||||||
|
// -----------------------------------------
|
||||||
|
// Public functions
|
||||||
|
|
||||||
|
camera_update :: proc(
|
||||||
|
dt: f32,
|
||||||
|
camera: ^Thing,
|
||||||
|
mouse_delta: base.Vec2,
|
||||||
|
sensitivity: f32 = 0.005,
|
||||||
|
) {
|
||||||
|
// Look
|
||||||
|
camera.rot.y -= mouse_delta.x * sensitivity
|
||||||
|
camera.rot.x -= mouse_delta.y * sensitivity
|
||||||
|
camera.rot.x = clamp(camera.rot.x, -math.PI / 2 + 0.01, math.PI / 2 - 0.01)
|
||||||
|
|
||||||
|
// Move (yaw-relative, world-Y up)
|
||||||
|
yaw := linalg.matrix4_rotate(camera.rot.y, {0, 1, 0})
|
||||||
|
forward := (yaw * base.Vec4{0, 0, -1, 0}).xyz
|
||||||
|
right := (yaw * base.Vec4{1, 0, 0, 0}).xyz
|
||||||
|
|
||||||
|
move := base.Vec3{0, 0, 0}
|
||||||
|
if platform.os_key_state(.Key_W) == .Press do move += forward
|
||||||
|
if platform.os_key_state(.Key_S) == .Press do move -= forward
|
||||||
|
if platform.os_key_state(.Key_A) == .Press do move -= right
|
||||||
|
if platform.os_key_state(.Key_D) == .Press do move += right
|
||||||
|
if platform.os_key_state(.Key_Space) == .Press do move += base.Vec3{0, 1, 0}
|
||||||
|
if platform.os_key_state(.Key_Left_Shift) == .Press do move -= base.Vec3{0, 1, 0}
|
||||||
|
|
||||||
|
if move != {0, 0, 0} {
|
||||||
|
move = linalg.normalize(move) * CAMERA_SPEED
|
||||||
|
camera.pos += move * dt
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,25 +0,0 @@
|
|||||||
package core
|
|
||||||
|
|
||||||
import "sindri:base"
|
|
||||||
import "sindri:platform"
|
|
||||||
|
|
||||||
// -----------------------------------------
|
|
||||||
// Public functions
|
|
||||||
|
|
||||||
// Returns the state of the keyboard key
|
|
||||||
key_state :: proc(key: base.Key) -> base.Action {
|
|
||||||
return platform.os_key_state(key)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Returns the state of the mouse button
|
|
||||||
mouse_button_state :: proc(button: base.Mouse_Button) -> base.Action {
|
|
||||||
return platform.os_mouse_button_state(button)
|
|
||||||
}
|
|
||||||
|
|
||||||
// Returns the position of the mouse cursor
|
|
||||||
mouse_position :: proc() -> (x_pos: f32, y_pos: f32) {
|
|
||||||
return platform.os_mouse_position()
|
|
||||||
}
|
|
||||||
|
|
||||||
// -----------------------------------------
|
|
||||||
// Private functions
|
|
||||||
@@ -0,0 +1,157 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (C) 2026 Riyyi
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
package core
|
||||||
|
|
||||||
|
import "core:fmt"
|
||||||
|
import "core:math/linalg"
|
||||||
|
import "core:os"
|
||||||
|
import "core:strconv"
|
||||||
|
import "core:strings"
|
||||||
|
|
||||||
|
import "sindri:base"
|
||||||
|
|
||||||
|
// Minimal OBJ loader: reads v, vt, vn and triangulates convex polygon faces.
|
||||||
|
// Produces one GPU vertex per face corner, then centers and normalizes the
|
||||||
|
// model so it fits roughly inside a [-1, 1] cube at the origin
|
||||||
|
load_obj_model :: proc(
|
||||||
|
path: string,
|
||||||
|
allocator := context.allocator,
|
||||||
|
) -> (
|
||||||
|
vertices: []base.Vertex,
|
||||||
|
indices: []u16,
|
||||||
|
ok: bool,
|
||||||
|
) {
|
||||||
|
data, err := os.read_entire_file_from_path(path, allocator)
|
||||||
|
if err != os.ERROR_NONE {
|
||||||
|
fmt.eprintfln("[obj] failed to read model: %s", path)
|
||||||
|
return nil, nil, false
|
||||||
|
}
|
||||||
|
defer delete(data, allocator)
|
||||||
|
|
||||||
|
positions: [dynamic]base.Vec3
|
||||||
|
uvs: [dynamic]base.Vec2
|
||||||
|
normals: [dynamic]base.Vec3
|
||||||
|
temp_vertices: [dynamic]base.Vertex
|
||||||
|
temp_indices: [dynamic]u16
|
||||||
|
defer {
|
||||||
|
delete(positions)
|
||||||
|
delete(uvs)
|
||||||
|
delete(normals)
|
||||||
|
delete(temp_vertices)
|
||||||
|
delete(temp_indices)
|
||||||
|
}
|
||||||
|
|
||||||
|
text := string(data)
|
||||||
|
for line in strings.split_lines_iterator(&text) {
|
||||||
|
trimmed := strings.trim_space(line)
|
||||||
|
if len(trimmed) == 0 || trimmed[0] == '#' do continue
|
||||||
|
|
||||||
|
fields := strings.fields(trimmed)
|
||||||
|
defer delete(fields)
|
||||||
|
if len(fields) == 0 do continue
|
||||||
|
|
||||||
|
switch fields[0] {
|
||||||
|
case "v":
|
||||||
|
if len(fields) < 4 do continue
|
||||||
|
x, _ := strconv.parse_f32(fields[1])
|
||||||
|
y, _ := strconv.parse_f32(fields[2])
|
||||||
|
z, _ := strconv.parse_f32(fields[3])
|
||||||
|
append(&positions, base.Vec3{x, y, z})
|
||||||
|
case "vt":
|
||||||
|
if len(fields) < 3 do continue
|
||||||
|
u, _ := strconv.parse_f32(fields[1])
|
||||||
|
v, _ := strconv.parse_f32(fields[2])
|
||||||
|
append(&uvs, base.Vec2{u, v})
|
||||||
|
case "vn":
|
||||||
|
if len(fields) < 4 do continue
|
||||||
|
x, _ := strconv.parse_f32(fields[1])
|
||||||
|
y, _ := strconv.parse_f32(fields[2])
|
||||||
|
z, _ := strconv.parse_f32(fields[3])
|
||||||
|
append(&normals, base.Vec3{x, y, z})
|
||||||
|
case "f":
|
||||||
|
face_indices: [dynamic]u16
|
||||||
|
defer delete(face_indices)
|
||||||
|
|
||||||
|
for i := 1; i < len(fields); i += 1 {
|
||||||
|
token := fields[i]
|
||||||
|
slash := strings.index_byte(token, '/')
|
||||||
|
|
||||||
|
vi_str := token
|
||||||
|
vti_str := ""
|
||||||
|
if slash != -1 {
|
||||||
|
vi_str = token[:slash]
|
||||||
|
slash2 := strings.index_byte(token[slash + 1:], '/')
|
||||||
|
if slash2 != -1 {
|
||||||
|
vti_str = token[slash + 1:slash + 1 + slash2]
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
vti_str = token[slash + 1:]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
vi, _ := strconv.parse_int(vi_str)
|
||||||
|
vi -= 1 // OBJ indices are 1-based
|
||||||
|
if vi < 0 || vi >= len(positions) do continue
|
||||||
|
|
||||||
|
uv := base.Vec2{0, 0}
|
||||||
|
if len(vti_str) > 0 {
|
||||||
|
vti, _ := strconv.parse_int(vti_str)
|
||||||
|
vti -= 1
|
||||||
|
if vti >= 0 && vti < len(uvs) {
|
||||||
|
uv = uvs[vti]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if vi < len(uvs) {
|
||||||
|
uv = uvs[vi]
|
||||||
|
}
|
||||||
|
|
||||||
|
append(
|
||||||
|
&temp_vertices,
|
||||||
|
base.Vertex {
|
||||||
|
pos = positions[vi],
|
||||||
|
col = {1, 1, 1},
|
||||||
|
uv = uv,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
append(&face_indices, cast(u16)(len(temp_vertices) - 1))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Triangulate convex polygon by fanning from the first vertex
|
||||||
|
for i := 2; i < len(face_indices); i += 1 {
|
||||||
|
append(&temp_indices, face_indices[0])
|
||||||
|
append(&temp_indices, face_indices[i - 1])
|
||||||
|
append(&temp_indices, face_indices[i])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if len(temp_vertices) == 0 {
|
||||||
|
return nil, nil, false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Center and normalize: fit the model inside a roughly [-1, 1] cube
|
||||||
|
min_p := temp_vertices[0].pos
|
||||||
|
max_p := temp_vertices[0].pos
|
||||||
|
for v in temp_vertices {
|
||||||
|
min_p = linalg.min(min_p, v.pos)
|
||||||
|
max_p = linalg.max(max_p, v.pos)
|
||||||
|
}
|
||||||
|
center := (min_p + max_p) * 0.5
|
||||||
|
size := max_p - min_p
|
||||||
|
max_size := max(size.x, size.y, size.z)
|
||||||
|
scale := 1.8 / max_size
|
||||||
|
|
||||||
|
for &v in temp_vertices {
|
||||||
|
v.pos = (v.pos - center) * scale
|
||||||
|
}
|
||||||
|
|
||||||
|
vertices = make([]base.Vertex, len(temp_vertices), allocator)
|
||||||
|
indices = make([]u16, len(temp_indices), allocator)
|
||||||
|
copy(vertices, temp_vertices[:])
|
||||||
|
copy(indices, temp_indices[:])
|
||||||
|
return vertices, indices, true
|
||||||
|
}
|
||||||
@@ -0,0 +1,116 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (C) 2026 Riyyi
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Large Array of Things
|
||||||
|
// - Fixed size arrays and handles
|
||||||
|
// - ZII (Zero Is Initialization) and NIL over null
|
||||||
|
// - Intrusive lists and trees
|
||||||
|
// - Fat structs (SoA, AoS, byte soup)
|
||||||
|
|
||||||
|
package core
|
||||||
|
|
||||||
|
import "sindri:base"
|
||||||
|
|
||||||
|
THING_NIL :: 0
|
||||||
|
THINGS_MAX :: 1024
|
||||||
|
|
||||||
|
// -----------------------------------------
|
||||||
|
// Types
|
||||||
|
|
||||||
|
Thing_Idx :: u16
|
||||||
|
|
||||||
|
Thing_Ref :: struct {
|
||||||
|
// TODO: 22 bits index, 10 bits generation, so we can store it in one 32bit number
|
||||||
|
idx: Thing_Idx,
|
||||||
|
gen: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
Thing_Kind :: enum {
|
||||||
|
Camera,
|
||||||
|
Player,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fixed size fat struct
|
||||||
|
Thing :: struct {
|
||||||
|
kind: Thing_Kind,
|
||||||
|
|
||||||
|
pos: base.Vec3,
|
||||||
|
rot: base.Vec3,
|
||||||
|
scale: base.Vec3,
|
||||||
|
|
||||||
|
model: ^Model,
|
||||||
|
|
||||||
|
// TODO: intrusive list
|
||||||
|
// parent: Thing_Ref
|
||||||
|
// first_kid: Thing_Ref
|
||||||
|
// prev_sib: Thing_Ref
|
||||||
|
// next_sib: Thing_Ref
|
||||||
|
}
|
||||||
|
|
||||||
|
Things :: struct {
|
||||||
|
things: [THINGS_MAX]Thing,
|
||||||
|
// TODO: Collapse used and gen into 1 array
|
||||||
|
used: [THINGS_MAX]bool,
|
||||||
|
gen: [THINGS_MAX]u16,
|
||||||
|
free_list: [THINGS_MAX]Thing_Idx,
|
||||||
|
next_free: Thing_Idx, // first free'd slot
|
||||||
|
next_unused: Thing_Idx, // never previously used slot
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------
|
||||||
|
// Public functions
|
||||||
|
|
||||||
|
thing_add :: proc(t: ^Things) -> Thing_Ref {
|
||||||
|
slot: Thing_Idx
|
||||||
|
gen: u16
|
||||||
|
|
||||||
|
// Two-tiered searching of slots:
|
||||||
|
// - first search the free-list, that contains freed up slots
|
||||||
|
// - fallback to the index that has never been allocated before
|
||||||
|
if t.next_free != THING_NIL {
|
||||||
|
slot = t.next_free
|
||||||
|
t.next_free = t.free_list[t.next_free]
|
||||||
|
t.free_list[slot] = THING_NIL // clean up the pop'ed free-slot
|
||||||
|
}
|
||||||
|
else if (t.next_unused < THINGS_MAX) {
|
||||||
|
if t.next_unused == THING_NIL do t.next_unused = 1 // first ever add()
|
||||||
|
slot = t.next_unused
|
||||||
|
t.next_unused += 1
|
||||||
|
}
|
||||||
|
|
||||||
|
if slot != THING_NIL {
|
||||||
|
t.things[slot] = {} // reset data
|
||||||
|
t.used[slot] = true
|
||||||
|
t.gen[slot] += 1
|
||||||
|
gen = t.gen[slot]
|
||||||
|
}
|
||||||
|
|
||||||
|
return {idx = slot, gen = gen}
|
||||||
|
}
|
||||||
|
|
||||||
|
thing_rem :: proc(t: ^Things, ref: Thing_Ref) {
|
||||||
|
idx := thing_deref(t, ref)
|
||||||
|
if idx == THING_NIL do return
|
||||||
|
|
||||||
|
t.used[idx] = false
|
||||||
|
t.free_list[idx] = t.next_free
|
||||||
|
t.next_free = idx
|
||||||
|
}
|
||||||
|
|
||||||
|
thing_get :: proc(t: ^Things, ref: Thing_Ref) -> ^Thing {
|
||||||
|
return &t.things[thing_deref(t, ref)]
|
||||||
|
}
|
||||||
|
|
||||||
|
thing_deref :: proc(t: ^Things, ref: Thing_Ref) -> Thing_Idx {
|
||||||
|
if ref.idx > THING_NIL &&
|
||||||
|
ref.idx < THINGS_MAX &&
|
||||||
|
t.used[ref.idx] &&
|
||||||
|
ref.gen == t.gen[ref.idx] {
|
||||||
|
return ref.idx
|
||||||
|
}
|
||||||
|
|
||||||
|
return THING_NIL
|
||||||
|
}
|
||||||
+89
-21
@@ -1,64 +1,132 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (C) 2026 Riyyi
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*/
|
||||||
|
|
||||||
package sindri
|
package sindri
|
||||||
|
|
||||||
import "core:fmt"
|
import "core:fmt"
|
||||||
import "core:time"
|
import "core:time"
|
||||||
|
|
||||||
|
import "game:game"
|
||||||
import "sindri:base"
|
import "sindri:base"
|
||||||
|
import "sindri:core"
|
||||||
import "sindri:platform"
|
import "sindri:platform"
|
||||||
|
|
||||||
VERSION :: #config(VERSION, "dev")
|
VERSION :: #config(VERSION, "dev")
|
||||||
|
|
||||||
// -----------------------------------------
|
// -----------------------------------------
|
||||||
|
// Variables
|
||||||
|
|
||||||
|
arena: base.Arena
|
||||||
|
|
||||||
|
// -----------------------------------------
|
||||||
|
// Public functions
|
||||||
|
|
||||||
main :: proc() {
|
main :: proc() {
|
||||||
fmt.println("hello world!", VERSION)
|
fmt.println("hello world!", VERSION)
|
||||||
|
|
||||||
// Hot reload development functionality
|
arena = base.arena_init_static()
|
||||||
hr, err := base.hot_reload_init()
|
defer base.arena_destroy(&arena)
|
||||||
defer base.hot_reload_destroy(&hr)
|
allocator := base.arena_allocator(&arena)
|
||||||
|
|
||||||
// Event system
|
// Hot reload development functionality
|
||||||
base.event_bus_init()
|
base.hot_reload_init(VERSION, allocator)
|
||||||
|
defer base.hot_reload_destroy()
|
||||||
|
|
||||||
|
// Load game API & settings
|
||||||
|
api := game.api()
|
||||||
|
defer api.destroy()
|
||||||
|
settings := base.settings()
|
||||||
|
|
||||||
|
// Event systems
|
||||||
|
base.event_bus_init(allocator)
|
||||||
defer base.event_bus_destroy()
|
defer base.event_bus_destroy()
|
||||||
|
|
||||||
base.event_subscribe(base.Key_Press_Event, test)
|
base.event_subscribe(base.Key_Press_Event, test)
|
||||||
|
|
||||||
api := base.active_lib(&hr)
|
// Listen for OS signals (SIGINT, SIGTERM)
|
||||||
settings := api.settings()
|
platform.signals_init()
|
||||||
|
defer platform.signals_destroy()
|
||||||
|
|
||||||
// Initialize Window
|
// Initialize Window
|
||||||
platform.os_init(settings)
|
platform.os_init(settings)
|
||||||
platform.os_set_monitor(settings)
|
platform.os_set_monitor(settings)
|
||||||
|
platform.os_set_mouse_capture(settings.mouse_captured)
|
||||||
defer platform.os_destroy()
|
defer platform.os_destroy()
|
||||||
|
|
||||||
// Initialize GPU resources
|
// Initialize GPU resources
|
||||||
platform.instance_init(settings)
|
platform.instance_init(settings, allocator)
|
||||||
defer platform.instance_destroy()
|
defer platform.instance_destroy()
|
||||||
|
|
||||||
api.init_once()
|
// Assets
|
||||||
|
assets := core.assets_init(allocator)
|
||||||
|
defer core.assets_destroy(&assets)
|
||||||
|
|
||||||
|
// Large Array of Things
|
||||||
|
things := new(core.Things, allocator)
|
||||||
|
defer free(things, allocator)
|
||||||
|
|
||||||
|
// Register engine API
|
||||||
|
engine_api := core.Engine_API {
|
||||||
|
assets = &assets,
|
||||||
|
things = things,
|
||||||
|
}
|
||||||
|
api.register_api(&engine_api)
|
||||||
|
|
||||||
|
// Register memory regions
|
||||||
|
base.register_region("assets", cast(rawptr)&assets, size_of(core.Assets))
|
||||||
|
base.register_region("things", things, size_of(core.Things))
|
||||||
|
api.register_memory()
|
||||||
|
|
||||||
|
// Read memory snapshot
|
||||||
|
fresh, err := base.read_snapshot()
|
||||||
|
fmt.assertf(err == nil, "[main] failed to read snapshot", err)
|
||||||
|
assets.allocator = allocator
|
||||||
|
|
||||||
|
// Init
|
||||||
|
if fresh {
|
||||||
|
api.init_once()
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
core.asset_reload_after_hot_reload(&assets, "assets")
|
||||||
|
}
|
||||||
api.init()
|
api.init()
|
||||||
|
|
||||||
gt: f64 = 0
|
dt: f64
|
||||||
dt: f32
|
gt: f64
|
||||||
|
st: f64
|
||||||
|
|
||||||
|
for !api.should_close() &&
|
||||||
|
!platform.os_should_close() &&
|
||||||
|
!base.should_close {
|
||||||
|
|
||||||
for !platform.os_should_close() && !base.should_close(&hr) {
|
|
||||||
start := time.tick_now()
|
start := time.tick_now()
|
||||||
|
|
||||||
platform.os_poll_events()
|
platform.os_poll_events()
|
||||||
base.drain_event_queue()
|
base.drain_event_queue()
|
||||||
api.update(dt)
|
api.update(cast(f32)dt)
|
||||||
|
base.write_snapshot()
|
||||||
|
|
||||||
platform.frame(dt)
|
// loop through Things, if model -> render
|
||||||
|
// register the Things inside game.odin
|
||||||
|
|
||||||
dt = f32(time.duration_seconds(time.tick_since(start)))
|
api.render()
|
||||||
gt += f64(dt)
|
platform.frame()
|
||||||
|
|
||||||
// Hot reload
|
dt = time.duration_seconds(time.tick_since(start))
|
||||||
api, err = base.reload_game_lib(&hr)
|
gt += dt
|
||||||
if err != nil do break
|
st += dt
|
||||||
|
|
||||||
|
if st > 5 {
|
||||||
|
st -= 5
|
||||||
|
base.set_write_full_snapshot()
|
||||||
|
}
|
||||||
|
|
||||||
|
if api.force_reload() do base.force_reload()
|
||||||
|
if api.force_restart() do base.force_restart()
|
||||||
}
|
}
|
||||||
|
|
||||||
api.destroy()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
test :: proc(e: ^base.Key_Press_Event, _: rawptr) -> bool {
|
test :: proc(e: ^base.Key_Press_Event, _: rawptr) -> bool {
|
||||||
|
|||||||
+40
-21
@@ -1,5 +1,12 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (C) 2026 Riyyi
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*/
|
||||||
|
|
||||||
package platform
|
package platform
|
||||||
|
|
||||||
|
import "base:intrinsics"
|
||||||
import "core:fmt"
|
import "core:fmt"
|
||||||
import "core:strings"
|
import "core:strings"
|
||||||
import "vendor:glfw"
|
import "vendor:glfw"
|
||||||
@@ -20,9 +27,7 @@ OS :: struct {
|
|||||||
// Constructor / destructor
|
// Constructor / destructor
|
||||||
|
|
||||||
os_init :: proc(settings: base.Settings) {
|
os_init :: proc(settings: base.Settings) {
|
||||||
if !glfw.Init() {
|
assert(cast(bool)glfw.Init(), "[glfw] init failure")
|
||||||
panic("[glfw] init failure")
|
|
||||||
}
|
|
||||||
|
|
||||||
// Set window properties
|
// Set window properties
|
||||||
glfw.WindowHint(glfw.CLIENT_API, glfw.NO_API) // do not create OpenGL context
|
glfw.WindowHint(glfw.CLIENT_API, glfw.NO_API) // do not create OpenGL context
|
||||||
@@ -30,8 +35,8 @@ os_init :: proc(settings: base.Settings) {
|
|||||||
|
|
||||||
// Create GLFW window
|
// Create GLFW window
|
||||||
state.os.window = glfw.CreateWindow(
|
state.os.window = glfw.CreateWindow(
|
||||||
i32(settings.width),
|
cast(i32)settings.width,
|
||||||
i32(settings.height),
|
cast(i32)settings.height,
|
||||||
strings.unsafe_string_to_cstring(settings.title),
|
strings.unsafe_string_to_cstring(settings.title),
|
||||||
nil,
|
nil,
|
||||||
nil,
|
nil,
|
||||||
@@ -60,8 +65,8 @@ os_set_monitor :: proc(settings: base.Settings) {
|
|||||||
monitor := glfw.GetPrimaryMonitor()
|
monitor := glfw.GetPrimaryMonitor()
|
||||||
x_pos: i32
|
x_pos: i32
|
||||||
y_pos: i32
|
y_pos: i32
|
||||||
width := i32(settings.width)
|
width := cast(i32)settings.width
|
||||||
height := i32(settings.height)
|
height := cast(i32)settings.height
|
||||||
target_monitor: glfw.MonitorHandle
|
target_monitor: glfw.MonitorHandle
|
||||||
|
|
||||||
mode := glfw.GetVideoMode(monitor)
|
mode := glfw.GetVideoMode(monitor)
|
||||||
@@ -81,7 +86,7 @@ os_set_monitor :: proc(settings: base.Settings) {
|
|||||||
glfw.SetWindowAttrib(
|
glfw.SetWindowAttrib(
|
||||||
state.os.window,
|
state.os.window,
|
||||||
glfw.DECORATED,
|
glfw.DECORATED,
|
||||||
i32(glfw.FALSE),
|
cast(i32)glfw.FALSE,
|
||||||
)
|
)
|
||||||
case .Windowed:
|
case .Windowed:
|
||||||
// Put window in the center of the monitor
|
// Put window in the center of the monitor
|
||||||
@@ -91,11 +96,12 @@ os_set_monitor :: proc(settings: base.Settings) {
|
|||||||
glfw.SetWindowAttrib(
|
glfw.SetWindowAttrib(
|
||||||
state.os.window,
|
state.os.window,
|
||||||
glfw.DECORATED,
|
glfw.DECORATED,
|
||||||
i32(glfw.TRUE),
|
cast(i32)glfw.TRUE,
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
refresh := settings.refresh == 0 ? glfw.DONT_CARE : i32(settings.refresh)
|
refresh :=
|
||||||
|
settings.refresh == 0 ? glfw.DONT_CARE : cast(i32)settings.refresh
|
||||||
|
|
||||||
glfw.SetWindowMonitor(
|
glfw.SetWindowMonitor(
|
||||||
state.os.window,
|
state.os.window,
|
||||||
@@ -113,11 +119,12 @@ os_set_callback_proc :: proc(window: rawptr) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
os_should_close :: proc() -> bool {
|
os_should_close :: proc() -> bool {
|
||||||
return bool(glfw.WindowShouldClose(state.os.window))
|
window_close := bool(glfw.WindowShouldClose(state.os.window))
|
||||||
|
return window_close || intrinsics.atomic_load(&quit_signal_received)
|
||||||
}
|
}
|
||||||
|
|
||||||
os_set_should_close :: proc(val: bool) {
|
os_set_should_close :: proc(val: bool) {
|
||||||
glfw.SetWindowShouldClose(state.os.window, b32(val))
|
glfw.SetWindowShouldClose(state.os.window, cast(b32)val)
|
||||||
}
|
}
|
||||||
|
|
||||||
os_poll_events :: proc() {
|
os_poll_events :: proc() {
|
||||||
@@ -126,7 +133,7 @@ os_poll_events :: proc() {
|
|||||||
|
|
||||||
os_get_framebuffer_size :: proc() -> (width, height: u32) {
|
os_get_framebuffer_size :: proc() -> (width, height: u32) {
|
||||||
iw, ih := glfw.GetFramebufferSize(state.os.window)
|
iw, ih := glfw.GetFramebufferSize(state.os.window)
|
||||||
return u32(iw), u32(ih)
|
return cast(u32)iw, cast(u32)ih
|
||||||
}
|
}
|
||||||
|
|
||||||
os_get_surface :: proc(instance: wgpu.Instance) -> wgpu.Surface {
|
os_get_surface :: proc(instance: wgpu.Instance) -> wgpu.Surface {
|
||||||
@@ -134,16 +141,24 @@ os_get_surface :: proc(instance: wgpu.Instance) -> wgpu.Surface {
|
|||||||
}
|
}
|
||||||
|
|
||||||
os_key_state :: proc(key: base.Key) -> base.Action {
|
os_key_state :: proc(key: base.Key) -> base.Action {
|
||||||
return input_action(glfw.GetKey(state.os.window, i32(key)))
|
return input_action(glfw.GetKey(state.os.window, cast(i32)key))
|
||||||
}
|
}
|
||||||
|
|
||||||
os_mouse_button_state :: proc(button: base.Mouse_Button) -> base.Action {
|
os_mouse_button_state :: proc(button: base.Mouse_Button) -> base.Action {
|
||||||
return input_action(glfw.GetMouseButton(state.os.window, i32(button)))
|
return input_action(glfw.GetMouseButton(state.os.window, cast(i32)button))
|
||||||
}
|
}
|
||||||
|
|
||||||
os_mouse_position :: proc() -> (x_pos: f32, y_pos: f32) {
|
os_mouse_position :: proc() -> base.Vec2 {
|
||||||
x_pos_f64, y_pos_64 := glfw.GetCursorPos(state.os.window)
|
x_pos_f64, y_pos_64 := glfw.GetCursorPos(state.os.window)
|
||||||
return f32(x_pos_f64), f32(y_pos_64)
|
return {cast(f32)x_pos_f64, cast(f32)y_pos_64}
|
||||||
|
}
|
||||||
|
|
||||||
|
os_set_mouse_capture :: proc(capture: bool) {
|
||||||
|
glfw.SetInputMode(
|
||||||
|
state.os.window,
|
||||||
|
glfw.CURSOR,
|
||||||
|
capture ? glfw.CURSOR_DISABLED : glfw.CURSOR_NORMAL,
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// -----------------------------------------
|
// -----------------------------------------
|
||||||
@@ -259,7 +274,10 @@ cursor_pos_callback :: proc "c" (
|
|||||||
) {
|
) {
|
||||||
context = state.ctx
|
context = state.ctx
|
||||||
base.on_event(
|
base.on_event(
|
||||||
base.Mouse_Position_Event{x_pos = f32(x_pos), y_pos = f32(y_pos)},
|
base.Mouse_Position_Event {
|
||||||
|
x_pos = cast(f32)x_pos,
|
||||||
|
y_pos = cast(f32)y_pos,
|
||||||
|
},
|
||||||
)
|
)
|
||||||
} // GLFWcursorposfun
|
} // GLFWcursorposfun
|
||||||
|
|
||||||
@@ -272,8 +290,8 @@ scroll_callback :: proc "c" (
|
|||||||
context = state.ctx
|
context = state.ctx
|
||||||
base.on_event(
|
base.on_event(
|
||||||
base.Mouse_Scroll_Event {
|
base.Mouse_Scroll_Event {
|
||||||
x_offset = f32(x_offset),
|
x_offset = cast(f32)x_offset,
|
||||||
y_offset = f32(y_offset),
|
y_offset = cast(f32)y_offset,
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
} // GLFWscrollfun
|
} // GLFWscrollfun
|
||||||
@@ -284,7 +302,8 @@ joystick_callback :: proc "c" (id, connected: i32) {
|
|||||||
context = state.ctx
|
context = state.ctx
|
||||||
if connected == glfw.CONNECTED {
|
if connected == glfw.CONNECTED {
|
||||||
base.on_event(base.Joystick_Connect_Event{id = id})
|
base.on_event(base.Joystick_Connect_Event{id = id})
|
||||||
} else {
|
}
|
||||||
|
else {
|
||||||
base.on_event(base.Joystick_Disconnect_Event{id = id})
|
base.on_event(base.Joystick_Disconnect_Event{id = id})
|
||||||
}
|
}
|
||||||
} // GLFWjoystickfun
|
} // GLFWjoystickfun
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (C) 2026 Riyyi
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
package platform
|
||||||
|
|
||||||
|
import "base:intrinsics"
|
||||||
|
import "core:c/libc"
|
||||||
|
import "core:fmt"
|
||||||
|
|
||||||
|
// -----------------------------------------
|
||||||
|
// Variables
|
||||||
|
|
||||||
|
// Read with atomic_load, safe across threads / interrupt contexts
|
||||||
|
quit_signal_received: bool
|
||||||
|
|
||||||
|
// -----------------------------------------
|
||||||
|
// Public functions
|
||||||
|
|
||||||
|
// Register signal handlers
|
||||||
|
signals_init :: proc() {
|
||||||
|
// SIGINT = Interrupt, typically Ctrl+C
|
||||||
|
if libc.signal(libc.SIGINT, signal_handler) ==
|
||||||
|
cast(proc "c" (_: i32))libc.SIG_ERR {
|
||||||
|
fmt.eprintln("error: failed to register SIGINT handler")
|
||||||
|
}
|
||||||
|
|
||||||
|
// SIGTERM = Normal termination
|
||||||
|
if libc.signal(libc.SIGTERM, signal_handler) ==
|
||||||
|
cast(proc "c" (_: i32))libc.SIG_ERR {
|
||||||
|
fmt.eprintln("error: failed to register SIGTERM handler")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Restore default signal handlers
|
||||||
|
signals_destroy :: proc() {
|
||||||
|
libc.signal(libc.SIGINT, cast(proc "c" (_: i32))libc.SIG_DFL)
|
||||||
|
libc.signal(libc.SIGTERM, cast(proc "c" (_: i32))libc.SIG_DFL)
|
||||||
|
}
|
||||||
|
|
||||||
|
@(private = "file")
|
||||||
|
signal_handler :: proc "c" (sig: i32) {
|
||||||
|
switch sig {
|
||||||
|
case libc.SIGINT, libc.SIGTERM:
|
||||||
|
intrinsics.atomic_store(&quit_signal_received, true)
|
||||||
|
case:
|
||||||
|
context = state.ctx
|
||||||
|
panic("[signal] unhandled signal type")
|
||||||
|
}
|
||||||
|
}
|
||||||
+728
-33
@@ -1,41 +1,121 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (C) 2026 Riyyi
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*/
|
||||||
|
|
||||||
package platform
|
package platform
|
||||||
|
|
||||||
import "base:runtime"
|
import "base:runtime"
|
||||||
import "core:fmt"
|
import "core:fmt"
|
||||||
|
import "core:math"
|
||||||
|
import "core:math/linalg"
|
||||||
|
import "core:os"
|
||||||
import "core:slice"
|
import "core:slice"
|
||||||
|
|
||||||
import "wgpu:wgpu"
|
import "wgpu:wgpu"
|
||||||
|
|
||||||
import "sindri:base"
|
import "sindri:base"
|
||||||
|
|
||||||
|
CAMERA_NEAR :: 0.1
|
||||||
|
CAMERA_FAR :: 100
|
||||||
|
|
||||||
|
// -----------------------------------------
|
||||||
|
// Types
|
||||||
|
|
||||||
|
// Main camera
|
||||||
|
Camera :: struct {
|
||||||
|
pos: base.Vec3,
|
||||||
|
rot: base.Vec3,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Updated once per frame
|
||||||
|
Camera_Uniform :: struct {
|
||||||
|
mvp: base.Mat4,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Updated once per material
|
||||||
|
Material_Uniform :: struct {
|
||||||
|
dummy: f32,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Updated once per mesh
|
||||||
|
Object_Uniform :: struct {
|
||||||
|
transform: base.Mat4,
|
||||||
|
}
|
||||||
|
|
||||||
|
Material :: struct {
|
||||||
|
bind_group: wgpu.BindGroup,
|
||||||
|
uniform_buffer: wgpu.Buffer,
|
||||||
|
}
|
||||||
|
|
||||||
|
Object :: struct {
|
||||||
|
name: string,
|
||||||
|
bind_group: wgpu.BindGroup,
|
||||||
|
uniform_buffer: wgpu.Buffer,
|
||||||
|
}
|
||||||
|
|
||||||
|
Mesh :: struct {
|
||||||
|
vertex_buffer: wgpu.Buffer,
|
||||||
|
index_buffer: wgpu.Buffer,
|
||||||
|
index_count: u32,
|
||||||
|
}
|
||||||
|
|
||||||
// -----------------------------------------
|
// -----------------------------------------
|
||||||
// Variables
|
// Variables
|
||||||
|
|
||||||
// Instance -> Surface -> Adapter -> Device -> Queue
|
// Instance -> Surface -> Adapter -> Device -> Queue
|
||||||
state: struct {
|
state: struct {
|
||||||
ctx: runtime.Context,
|
ctx: runtime.Context,
|
||||||
os: OS,
|
os: OS,
|
||||||
// ----------------------------------------
|
// ----------------------------------------
|
||||||
instance: wgpu.Instance, // entry point: creates Adapter, Device and Surface
|
instance: wgpu.Instance, // entry point: creates Adapter, Device and Surface
|
||||||
surface: wgpu.Surface, // handle to a presentable surface (e.g. a window)
|
surface: wgpu.Surface, // handle to a presentable surface (e.g. a window)
|
||||||
adapter: wgpu.Adapter, // handle to physical GPU
|
adapter: wgpu.Adapter, // handle to physical GPU
|
||||||
device: wgpu.Device, // open connection to a GPU
|
device: wgpu.Device, // open connection to a GPU
|
||||||
queue: wgpu.Queue, // handle to command queue on a Device
|
queue: wgpu.Queue, // handle to command queue on a Device
|
||||||
config: wgpu.SurfaceConfiguration,
|
config: wgpu.SurfaceConfiguration,
|
||||||
module: wgpu.ShaderModule,
|
module: wgpu.ShaderModule,
|
||||||
pipeline_layout: wgpu.PipelineLayout,
|
pipeline_layout: wgpu.PipelineLayout,
|
||||||
pipeline: wgpu.RenderPipeline,
|
pipeline: wgpu.RenderPipeline,
|
||||||
// ----------------------------------------
|
// ----------------------------------------
|
||||||
capabilities: wgpu.SurfaceCapabilities,
|
capabilities: wgpu.SurfaceCapabilities,
|
||||||
vsync: bool,
|
vsync: bool,
|
||||||
|
// ----------------------------------------
|
||||||
|
depth_texture: wgpu.Texture,
|
||||||
|
depth_texture_view: wgpu.TextureView,
|
||||||
|
// ----------------------------------------
|
||||||
|
camera: Camera,
|
||||||
|
camera_uniform_buffer: wgpu.Buffer,
|
||||||
|
camera_bind_group_layout: wgpu.BindGroupLayout,
|
||||||
|
camera_bind_group: wgpu.BindGroup,
|
||||||
|
camera_fov: f32,
|
||||||
|
// ----------------------------------------
|
||||||
|
material_bind_group_layout: wgpu.BindGroupLayout,
|
||||||
|
materials: map[string]Material,
|
||||||
|
// ----------------------------------------
|
||||||
|
objects_bind_group_layout: wgpu.BindGroupLayout,
|
||||||
|
objects: [dynamic]Object,
|
||||||
|
meshes: map[string]Mesh,
|
||||||
|
// ----------------------------------------
|
||||||
|
diffuse_texture: wgpu.Texture,
|
||||||
|
diffuse_texture_view: wgpu.TextureView,
|
||||||
|
diffuse_sampler: wgpu.Sampler,
|
||||||
}
|
}
|
||||||
|
|
||||||
// -----------------------------------------
|
// -----------------------------------------
|
||||||
// Constructor/destructor
|
// Constructor/destructor
|
||||||
|
|
||||||
instance_init :: proc(settings: base.Settings) {
|
instance_init :: proc(
|
||||||
|
settings: base.Settings,
|
||||||
|
allocator := context.allocator,
|
||||||
|
) {
|
||||||
state.ctx = context
|
state.ctx = context
|
||||||
|
|
||||||
|
state.materials = make(map[string]Material, allocator)
|
||||||
|
state.objects = make([dynamic]Object, allocator)
|
||||||
|
state.meshes = make(map[string]Mesh, allocator)
|
||||||
|
|
||||||
wgpu.SetLogCallback(log_callback, nil)
|
wgpu.SetLogCallback(log_callback, nil)
|
||||||
wgpu.SetLogLevel(.Warn)
|
wgpu.SetLogLevel(.Warn)
|
||||||
|
|
||||||
@@ -58,12 +138,49 @@ instance_init :: proc(settings: base.Settings) {
|
|||||||
// Present modes
|
// Present modes
|
||||||
get_present_modes()
|
get_present_modes()
|
||||||
state.vsync = settings.vsync
|
state.vsync = settings.vsync
|
||||||
|
state.camera_fov = settings.fov
|
||||||
|
|
||||||
// Device
|
// Device
|
||||||
wgpu.AdapterRequestDevice(state.adapter, nil, {callback = on_device})
|
wgpu.AdapterRequestDevice(state.adapter, nil, {callback = on_device})
|
||||||
}
|
}
|
||||||
|
|
||||||
instance_destroy :: proc() {
|
instance_destroy :: proc() {
|
||||||
|
wgpu.TextureViewRelease(state.depth_texture_view)
|
||||||
|
wgpu.TextureRelease(state.depth_texture)
|
||||||
|
|
||||||
|
wgpu.SamplerRelease(state.diffuse_sampler)
|
||||||
|
wgpu.TextureViewRelease(state.diffuse_texture_view)
|
||||||
|
wgpu.TextureRelease(state.diffuse_texture)
|
||||||
|
|
||||||
|
wgpu.BufferRelease(state.camera_uniform_buffer)
|
||||||
|
wgpu.BindGroupRelease(state.camera_bind_group)
|
||||||
|
wgpu.BindGroupLayoutRelease(state.camera_bind_group_layout)
|
||||||
|
|
||||||
|
if state.materials != nil {
|
||||||
|
for _, m in state.materials {
|
||||||
|
wgpu.BufferRelease(m.uniform_buffer)
|
||||||
|
wgpu.BindGroupRelease(m.bind_group)
|
||||||
|
}
|
||||||
|
delete(state.materials)
|
||||||
|
}
|
||||||
|
wgpu.BindGroupLayoutRelease(state.material_bind_group_layout)
|
||||||
|
|
||||||
|
if state.meshes != nil {
|
||||||
|
for _, m in state.meshes {
|
||||||
|
wgpu.BufferRelease(m.vertex_buffer)
|
||||||
|
wgpu.BufferRelease(m.index_buffer)
|
||||||
|
}
|
||||||
|
delete(state.meshes)
|
||||||
|
}
|
||||||
|
if state.objects != nil {
|
||||||
|
for r in state.objects {
|
||||||
|
wgpu.BufferRelease(r.uniform_buffer)
|
||||||
|
wgpu.BindGroupRelease(r.bind_group)
|
||||||
|
}
|
||||||
|
delete(state.objects)
|
||||||
|
}
|
||||||
|
wgpu.BindGroupLayoutRelease(state.objects_bind_group_layout)
|
||||||
|
|
||||||
wgpu.RenderPipelineRelease(state.pipeline)
|
wgpu.RenderPipelineRelease(state.pipeline)
|
||||||
wgpu.PipelineLayoutRelease(state.pipeline_layout)
|
wgpu.PipelineLayoutRelease(state.pipeline_layout)
|
||||||
wgpu.ShaderModuleRelease(state.module)
|
wgpu.ShaderModuleRelease(state.module)
|
||||||
@@ -94,11 +211,20 @@ resize :: proc "c" () {
|
|||||||
|
|
||||||
state.config.width, state.config.height = os_get_framebuffer_size()
|
state.config.width, state.config.height = os_get_framebuffer_size()
|
||||||
wgpu.SurfaceConfigure(state.surface, &state.config)
|
wgpu.SurfaceConfigure(state.surface, &state.config)
|
||||||
|
|
||||||
|
create_depth_texture()
|
||||||
}
|
}
|
||||||
|
|
||||||
frame :: proc "c" (dt: f32) {
|
frame :: proc "c" () {
|
||||||
context = state.ctx
|
context = state.ctx
|
||||||
|
|
||||||
|
// Recompute and re-upload the camera matrix every frame, for pos/rot/aspect
|
||||||
|
upload_camera(
|
||||||
|
state.queue,
|
||||||
|
state.camera_uniform_buffer,
|
||||||
|
framebuffer_aspect(),
|
||||||
|
)
|
||||||
|
|
||||||
surface_texture := wgpu.SurfaceGetCurrentTexture(state.surface)
|
surface_texture := wgpu.SurfaceGetCurrentTexture(state.surface)
|
||||||
switch surface_texture.status {
|
switch surface_texture.status {
|
||||||
case .SuccessOptimal, .SuccessSuboptimal:
|
case .SuccessOptimal, .SuccessSuboptimal:
|
||||||
@@ -137,20 +263,74 @@ frame :: proc "c" (dt: f32) {
|
|||||||
loadOp = .Clear,
|
loadOp = .Clear,
|
||||||
storeOp = .Store,
|
storeOp = .Store,
|
||||||
depthSlice = wgpu.DEPTH_SLICE_UNDEFINED,
|
depthSlice = wgpu.DEPTH_SLICE_UNDEFINED,
|
||||||
clearValue = {0, 1, 0, 1},
|
clearValue = {55 / 255.0, 73 / 255.0, 73 / 255.0, 1},
|
||||||
|
},
|
||||||
|
depthStencilAttachment = &wgpu.RenderPassDepthStencilAttachment {
|
||||||
|
view = state.depth_texture_view,
|
||||||
|
depthLoadOp = .Clear,
|
||||||
|
depthStoreOp = .Store,
|
||||||
|
depthClearValue = 1.0,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
wgpu.RenderPassEncoderSetPipeline(render_pass_encoder, state.pipeline)
|
wgpu.RenderPassEncoderSetPipeline(render_pass_encoder, state.pipeline)
|
||||||
wgpu.RenderPassEncoderDraw(
|
|
||||||
|
// Uniform group 0, camera MVP matrix
|
||||||
|
wgpu.RenderPassEncoderSetBindGroup(
|
||||||
render_pass_encoder,
|
render_pass_encoder,
|
||||||
vertexCount = 3,
|
0,
|
||||||
instanceCount = 1,
|
state.camera_bind_group,
|
||||||
firstVertex = 0,
|
dynamicOffsets = nil, // reuse bind group af different byte offsets, per binding
|
||||||
firstInstance = 0,
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// Uniform group 1, materials
|
||||||
|
m := state.materials["dummy"]
|
||||||
|
wgpu.RenderPassEncoderSetBindGroup(
|
||||||
|
render_pass_encoder,
|
||||||
|
1,
|
||||||
|
m.bind_group,
|
||||||
|
dynamicOffsets = nil, // reuse bind group af different byte offsets, per binding
|
||||||
|
)
|
||||||
|
|
||||||
|
// Render all objects
|
||||||
|
for o in state.objects {
|
||||||
|
m := state.meshes[o.name]
|
||||||
|
|
||||||
|
// Uniform group 2, object
|
||||||
|
wgpu.RenderPassEncoderSetBindGroup(
|
||||||
|
render_pass_encoder,
|
||||||
|
2,
|
||||||
|
o.bind_group,
|
||||||
|
dynamicOffsets = nil, // reuse bind group af different byte offsets, per binding
|
||||||
|
)
|
||||||
|
|
||||||
|
wgpu.RenderPassEncoderSetVertexBuffer(
|
||||||
|
render_pass_encoder,
|
||||||
|
slot = 0,
|
||||||
|
buffer = m.vertex_buffer,
|
||||||
|
offset = 0, // offset into buffer to start from
|
||||||
|
size = wgpu.WHOLE_SIZE, // x bytes of the buffer to use
|
||||||
|
)
|
||||||
|
|
||||||
|
wgpu.RenderPassEncoderSetIndexBuffer(
|
||||||
|
render_pass_encoder,
|
||||||
|
buffer = m.index_buffer,
|
||||||
|
format = .Uint16, // type of each element in the buffer
|
||||||
|
offset = 0, // offset into buffer to start from
|
||||||
|
size = wgpu.WHOLE_SIZE, // x bytes of the buffer to use
|
||||||
|
)
|
||||||
|
|
||||||
|
wgpu.RenderPassEncoderDrawIndexed(
|
||||||
|
render_pass_encoder,
|
||||||
|
m.index_count,
|
||||||
|
instanceCount = 1, // draw x instance(s) of the mesh
|
||||||
|
firstIndex = 0, // offset into buffer to start from, useful for drawing sub-mesh
|
||||||
|
baseVertex = 0, // value added to index before vertex fetch, useful for multi-mesh vertex buffers
|
||||||
|
firstInstance = 0, // number to start instance index from
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
wgpu.RenderPassEncoderEnd(render_pass_encoder)
|
wgpu.RenderPassEncoderEnd(render_pass_encoder)
|
||||||
wgpu.RenderPassEncoderRelease(render_pass_encoder)
|
wgpu.RenderPassEncoderRelease(render_pass_encoder)
|
||||||
|
|
||||||
@@ -161,6 +341,152 @@ frame :: proc "c" (dt: f32) {
|
|||||||
wgpu.SurfacePresent(state.surface)
|
wgpu.SurfacePresent(state.surface)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
create_material :: proc(name: string) {
|
||||||
|
if name in state.materials do return
|
||||||
|
|
||||||
|
uniform_buffer := wgpu.DeviceCreateBuffer(
|
||||||
|
state.device,
|
||||||
|
&{
|
||||||
|
label = "material uniform",
|
||||||
|
usage = {.Uniform, .CopyDst}, // shader reads, queue writes
|
||||||
|
size = cast(u64)size_of(Material_Uniform),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
uniform := Material_Uniform{}
|
||||||
|
|
||||||
|
// bufferOffset = offset into buffer to start from
|
||||||
|
wgpu.QueueWriteBuffer(
|
||||||
|
state.queue,
|
||||||
|
uniform_buffer,
|
||||||
|
0,
|
||||||
|
&uniform,
|
||||||
|
size_of(Material_Uniform),
|
||||||
|
)
|
||||||
|
|
||||||
|
entries := [?]wgpu.BindGroupEntry {
|
||||||
|
{
|
||||||
|
binding = 0, // slot 0
|
||||||
|
buffer = uniform_buffer,
|
||||||
|
offset = 0, // offset into buffer to start from
|
||||||
|
size = cast(u64)size_of(Material_Uniform),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
bind_group := wgpu.DeviceCreateBindGroup(
|
||||||
|
state.device,
|
||||||
|
&{
|
||||||
|
label = "material bind group",
|
||||||
|
layout = state.material_bind_group_layout,
|
||||||
|
entryCount = len(entries),
|
||||||
|
entries = raw_data(entries[:]),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
state.materials[name] = {
|
||||||
|
bind_group = bind_group,
|
||||||
|
uniform_buffer = uniform_buffer,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
create_renderable :: proc(
|
||||||
|
name: string,
|
||||||
|
vertices: []base.Vertex,
|
||||||
|
indices: []u16,
|
||||||
|
x_offset: f32,
|
||||||
|
) {
|
||||||
|
uniform_buffer := wgpu.DeviceCreateBuffer(
|
||||||
|
state.device,
|
||||||
|
&{
|
||||||
|
label = "object uniform",
|
||||||
|
usage = {.Uniform, .CopyDst}, // shader reads, queue writes
|
||||||
|
size = cast(u64)size_of(Object_Uniform),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
uniform := Object_Uniform {
|
||||||
|
// transform = linalg.identity(base.Mat4)
|
||||||
|
transform = linalg.matrix4_translate(base.Vec3{x_offset, 0, 0}),
|
||||||
|
}
|
||||||
|
|
||||||
|
// bufferOffset = offset into buffer to start from
|
||||||
|
wgpu.QueueWriteBuffer(
|
||||||
|
state.queue,
|
||||||
|
uniform_buffer,
|
||||||
|
0,
|
||||||
|
&uniform,
|
||||||
|
size_of(Object_Uniform),
|
||||||
|
)
|
||||||
|
|
||||||
|
entries := [?]wgpu.BindGroupEntry {
|
||||||
|
{
|
||||||
|
binding = 0, // slot 0
|
||||||
|
buffer = uniform_buffer,
|
||||||
|
offset = 0, // offset into buffer to start from
|
||||||
|
size = cast(u64)size_of(Object_Uniform),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
bind_group := wgpu.DeviceCreateBindGroup(
|
||||||
|
state.device,
|
||||||
|
&{
|
||||||
|
label = "object bind group",
|
||||||
|
layout = state.objects_bind_group_layout,
|
||||||
|
entryCount = len(entries),
|
||||||
|
entries = raw_data(entries[:]),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
append(
|
||||||
|
&state.objects,
|
||||||
|
Object {
|
||||||
|
name = name,
|
||||||
|
bind_group = bind_group,
|
||||||
|
uniform_buffer = uniform_buffer,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
if name in state.meshes do return
|
||||||
|
|
||||||
|
vertex_buffer := wgpu.DeviceCreateBuffer(
|
||||||
|
state.device,
|
||||||
|
&{
|
||||||
|
label = "vertex buffer",
|
||||||
|
usage = {.Vertex, .CopyDst}, // shader reads, queue writes
|
||||||
|
size = cast(u64)(len(vertices) * size_of(base.Vertex)),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
wgpu.QueueWriteBuffer(
|
||||||
|
state.queue,
|
||||||
|
vertex_buffer,
|
||||||
|
0,
|
||||||
|
raw_data(vertices),
|
||||||
|
cast(uint)(len(vertices) * size_of(base.Vertex)),
|
||||||
|
)
|
||||||
|
|
||||||
|
index_buffer := wgpu.DeviceCreateBuffer(
|
||||||
|
state.device,
|
||||||
|
&{
|
||||||
|
label = "index buffer",
|
||||||
|
usage = {.Index, .CopyDst}, // shader reads, queue writes
|
||||||
|
size = cast(u64)(len(indices) * size_of(u16)),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
wgpu.QueueWriteBuffer(
|
||||||
|
state.queue,
|
||||||
|
index_buffer,
|
||||||
|
0,
|
||||||
|
raw_data(indices),
|
||||||
|
cast(uint)(len(indices) * size_of(u16)),
|
||||||
|
)
|
||||||
|
|
||||||
|
state.meshes[name] = {
|
||||||
|
vertex_buffer = vertex_buffer,
|
||||||
|
index_buffer = index_buffer,
|
||||||
|
index_count = cast(u32)len(indices),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// -----------------------------------------
|
// -----------------------------------------
|
||||||
// Private functions
|
// Private functions
|
||||||
|
|
||||||
@@ -208,18 +534,70 @@ on_device :: proc "c" (
|
|||||||
}
|
}
|
||||||
wgpu.SurfaceConfigure(state.surface, &state.config)
|
wgpu.SurfaceConfigure(state.surface, &state.config)
|
||||||
|
|
||||||
shader :: `
|
// ----------------------------------------
|
||||||
|
// Depth buffer
|
||||||
|
|
||||||
|
create_depth_texture()
|
||||||
|
|
||||||
|
// ----------------------------------------
|
||||||
|
// Compile shader
|
||||||
|
|
||||||
|
camera_struct := to_wgsl_struct(Camera_Uniform, "Camera")
|
||||||
|
defer delete(camera_struct)
|
||||||
|
vertex_input_struct := to_wgsl_struct(
|
||||||
|
base.Vertex,
|
||||||
|
"VertexInput",
|
||||||
|
locations = true,
|
||||||
|
)
|
||||||
|
defer delete(vertex_input_struct)
|
||||||
|
|
||||||
|
material_struct := to_wgsl_struct(Material_Uniform, "Material")
|
||||||
|
defer delete(material_struct)
|
||||||
|
|
||||||
|
renderable_struct := to_wgsl_struct(Object_Uniform, "Renderable")
|
||||||
|
defer delete(renderable_struct)
|
||||||
|
|
||||||
|
shader := fmt.tprintf(
|
||||||
|
`
|
||||||
|
%s
|
||||||
|
%s
|
||||||
|
%s
|
||||||
|
|
||||||
|
@group(0) @binding(0) var<uniform> c: Camera;
|
||||||
|
@group(0) @binding(1) var t_diffuse: texture_2d<f32>;
|
||||||
|
@group(0) @binding(2) var s_diffuse: sampler;
|
||||||
|
|
||||||
|
@group(1) @binding(0) var<uniform> m: Material;
|
||||||
|
|
||||||
|
@group(2) @binding(0) var<uniform> r: Renderable;
|
||||||
|
|
||||||
|
%s
|
||||||
|
|
||||||
|
struct VertexOutput {{
|
||||||
|
@builtin(position) position: vec4<f32>,
|
||||||
|
@location(0) col: vec3<f32>,
|
||||||
|
@location(1) uv: vec2<f32>,
|
||||||
|
}};
|
||||||
|
|
||||||
@vertex
|
@vertex
|
||||||
fn vs_main(@builtin(vertex_index) in_vertex_index: u32) -> @builtin(position) vec4<f32> {
|
fn vs_main(in: VertexInput) -> VertexOutput {{
|
||||||
let x = f32(i32(in_vertex_index) - 1);
|
var out: VertexOutput;
|
||||||
let y = f32(i32(in_vertex_index & 1u) * 2 - 1);
|
out.position = c.mvp * r.transform * vec4<f32>(in.pos, 1.0);
|
||||||
return vec4<f32>(x, y, 0.0, 1.0);
|
out.col = in.col;
|
||||||
}
|
out.uv = in.uv;
|
||||||
|
return out;
|
||||||
|
}}
|
||||||
|
|
||||||
@fragment
|
@fragment
|
||||||
fn fs_main() -> @location(0) vec4<f32> {
|
fn fs_main(in: VertexOutput) -> @location(0) vec4<f32> {{
|
||||||
return vec4<f32>(1.0, 0.0, 0.0, 1.0);
|
return textureSample(t_diffuse, s_diffuse, in.uv) * vec4<f32>(in.col, 1.0);
|
||||||
}`
|
}}
|
||||||
|
`,
|
||||||
|
camera_struct,
|
||||||
|
material_struct,
|
||||||
|
renderable_struct,
|
||||||
|
vertex_input_struct,
|
||||||
|
)
|
||||||
|
|
||||||
state.module = wgpu.DeviceCreateShaderModule(
|
state.module = wgpu.DeviceCreateShaderModule(
|
||||||
state.device,
|
state.device,
|
||||||
@@ -231,12 +609,140 @@ on_device :: proc "c" (
|
|||||||
},
|
},
|
||||||
)
|
)
|
||||||
|
|
||||||
state.pipeline_layout = wgpu.DeviceCreatePipelineLayout(state.device, &{})
|
// ----------------------------------------
|
||||||
|
// Camera uniform: buffer, then the baked layout it will be read through
|
||||||
|
|
||||||
|
state.camera_uniform_buffer = wgpu.DeviceCreateBuffer(
|
||||||
|
state.device,
|
||||||
|
&{
|
||||||
|
label = "camera uniform",
|
||||||
|
usage = {.Uniform, .CopyDst}, // shader reads, queue writes
|
||||||
|
size = cast(u64)size_of(Camera_Uniform),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
camera_layout_entries := [?]wgpu.BindGroupLayoutEntry {
|
||||||
|
{
|
||||||
|
binding = 0, // slot 0
|
||||||
|
visibility = {.Vertex},
|
||||||
|
buffer = {
|
||||||
|
type = .Uniform,
|
||||||
|
minBindingSize = cast(u64)size_of(Camera_Uniform),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
binding = 1, // slot 1
|
||||||
|
visibility = {.Fragment},
|
||||||
|
texture = {
|
||||||
|
sampleType = .Float,
|
||||||
|
viewDimension = ._2D,
|
||||||
|
multisampled = false,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
binding = 2, // slot 2
|
||||||
|
visibility = {.Fragment},
|
||||||
|
sampler = {type = .Filtering},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
state.camera_bind_group_layout = wgpu.DeviceCreateBindGroupLayout(
|
||||||
|
state.device,
|
||||||
|
&{
|
||||||
|
label = "camera layout",
|
||||||
|
entryCount = len(camera_layout_entries),
|
||||||
|
entries = raw_data(camera_layout_entries[:]),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
// ----------------------------------------
|
||||||
|
// Material baked layout
|
||||||
|
|
||||||
|
material_layout_entries := [?]wgpu.BindGroupLayoutEntry {
|
||||||
|
{
|
||||||
|
binding = 0, // slot 0
|
||||||
|
visibility = {.Fragment},
|
||||||
|
buffer = {
|
||||||
|
type = .Uniform,
|
||||||
|
minBindingSize = cast(u64)size_of(Material_Uniform),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
state.material_bind_group_layout = wgpu.DeviceCreateBindGroupLayout(
|
||||||
|
state.device,
|
||||||
|
&{
|
||||||
|
label = "material layout",
|
||||||
|
entryCount = len(material_layout_entries),
|
||||||
|
entries = raw_data(material_layout_entries[:]),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
// ----------------------------------------
|
||||||
|
// Renderable baked layout
|
||||||
|
|
||||||
|
renderable_layout_entries := [?]wgpu.BindGroupLayoutEntry {
|
||||||
|
{
|
||||||
|
binding = 0, // slot 0
|
||||||
|
visibility = {.Vertex},
|
||||||
|
buffer = {
|
||||||
|
type = .Uniform,
|
||||||
|
minBindingSize = cast(u64)size_of(Object_Uniform),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
state.objects_bind_group_layout = wgpu.DeviceCreateBindGroupLayout(
|
||||||
|
state.device,
|
||||||
|
&{
|
||||||
|
label = "renderable layout",
|
||||||
|
entryCount = len(renderable_layout_entries),
|
||||||
|
entries = raw_data(renderable_layout_entries[:]),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
// ----------------------------------------
|
||||||
|
// Diffuse texture + sampler
|
||||||
|
|
||||||
|
state.diffuse_texture, state.diffuse_texture_view, state.diffuse_sampler =
|
||||||
|
create_diffuse_texture(state.device, state.queue)
|
||||||
|
|
||||||
|
// ----------------------------------------
|
||||||
|
// Buffer shape
|
||||||
|
|
||||||
|
vertex_attributes := to_vertex_attributes(base.Vertex)
|
||||||
|
|
||||||
|
vertex_layout := wgpu.VertexBufferLayout {
|
||||||
|
stepMode = .Vertex,
|
||||||
|
arrayStride = size_of(base.Vertex),
|
||||||
|
attributeCount = len(vertex_attributes),
|
||||||
|
attributes = raw_data(vertex_attributes),
|
||||||
|
}
|
||||||
|
|
||||||
|
// ----------------------------------------
|
||||||
|
// Render pipeline
|
||||||
|
|
||||||
|
group_layouts := [?]wgpu.BindGroupLayout {
|
||||||
|
state.camera_bind_group_layout,
|
||||||
|
state.material_bind_group_layout,
|
||||||
|
state.objects_bind_group_layout,
|
||||||
|
}
|
||||||
|
state.pipeline_layout = wgpu.DeviceCreatePipelineLayout(
|
||||||
|
state.device,
|
||||||
|
&{
|
||||||
|
bindGroupLayoutCount = len(group_layouts),
|
||||||
|
bindGroupLayouts = raw_data(group_layouts[:]),
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
state.pipeline = wgpu.DeviceCreateRenderPipeline(
|
state.pipeline = wgpu.DeviceCreateRenderPipeline(
|
||||||
state.device,
|
state.device,
|
||||||
&{
|
&{
|
||||||
|
label = "pipeline",
|
||||||
layout = state.pipeline_layout,
|
layout = state.pipeline_layout,
|
||||||
vertex = {module = state.module, entryPoint = "vs_main"},
|
vertex = {
|
||||||
|
module = state.module,
|
||||||
|
entryPoint = "vs_main",
|
||||||
|
bufferCount = 1,
|
||||||
|
buffers = &vertex_layout,
|
||||||
|
},
|
||||||
fragment = &{
|
fragment = &{
|
||||||
module = state.module,
|
module = state.module,
|
||||||
entryPoint = "fs_main",
|
entryPoint = "fs_main",
|
||||||
@@ -248,6 +754,34 @@ on_device :: proc "c" (
|
|||||||
},
|
},
|
||||||
primitive = {topology = .TriangleList},
|
primitive = {topology = .TriangleList},
|
||||||
multisample = {count = 1, mask = 0xFFFFFFFF},
|
multisample = {count = 1, mask = 0xFFFFFFFF},
|
||||||
|
depthStencil = &wgpu.DepthStencilState {
|
||||||
|
format = .Depth24Plus,
|
||||||
|
depthWriteEnabled = .True,
|
||||||
|
depthCompare = .Less,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
// ----------------------------------------
|
||||||
|
// Camera bind group
|
||||||
|
|
||||||
|
bind_group_entries := [?]wgpu.BindGroupEntry {
|
||||||
|
{
|
||||||
|
binding = 0, // slot 0
|
||||||
|
buffer = state.camera_uniform_buffer,
|
||||||
|
offset = 0, // offset into buffer to start from
|
||||||
|
size = cast(u64)size_of(Camera_Uniform),
|
||||||
|
},
|
||||||
|
{binding = 1, textureView = state.diffuse_texture_view},
|
||||||
|
{binding = 2, sampler = state.diffuse_sampler},
|
||||||
|
}
|
||||||
|
state.camera_bind_group = wgpu.DeviceCreateBindGroup(
|
||||||
|
state.device,
|
||||||
|
&{
|
||||||
|
label = "camera bind group",
|
||||||
|
layout = state.camera_bind_group_layout,
|
||||||
|
entryCount = len(bind_group_entries),
|
||||||
|
entries = raw_data(bind_group_entries[:]),
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
@@ -279,7 +813,8 @@ pick_present_mode :: proc(vsync: bool) -> wgpu.PresentMode {
|
|||||||
if slice.contains(present_modes, wgpu.PresentMode.FifoRelaxed) {
|
if slice.contains(present_modes, wgpu.PresentMode.FifoRelaxed) {
|
||||||
return .FifoRelaxed // Adaptive Vsync
|
return .FifoRelaxed // Adaptive Vsync
|
||||||
}
|
}
|
||||||
} else {
|
}
|
||||||
|
else {
|
||||||
if slice.contains(present_modes, wgpu.PresentMode.Immediate) {
|
if slice.contains(present_modes, wgpu.PresentMode.Immediate) {
|
||||||
return .Immediate // Vsync Off
|
return .Immediate // Vsync Off
|
||||||
}
|
}
|
||||||
@@ -290,3 +825,163 @@ pick_present_mode :: proc(vsync: bool) -> wgpu.PresentMode {
|
|||||||
|
|
||||||
return .Fifo // Vsync On
|
return .Fifo // Vsync On
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Depth buffer: same size as the surface, should get recreated on resize
|
||||||
|
@(private = "file")
|
||||||
|
create_depth_texture :: proc() {
|
||||||
|
if state.depth_texture != nil {
|
||||||
|
wgpu.TextureViewRelease(state.depth_texture_view)
|
||||||
|
wgpu.TextureRelease(state.depth_texture)
|
||||||
|
}
|
||||||
|
|
||||||
|
state.depth_texture = wgpu.DeviceCreateTexture(
|
||||||
|
state.device,
|
||||||
|
&{
|
||||||
|
label = "depth texture",
|
||||||
|
usage = {.RenderAttachment},
|
||||||
|
dimension = ._2D,
|
||||||
|
size = {
|
||||||
|
width = state.config.width,
|
||||||
|
height = state.config.height,
|
||||||
|
depthOrArrayLayers = 1,
|
||||||
|
},
|
||||||
|
format = .Depth24Plus,
|
||||||
|
mipLevelCount = 1,
|
||||||
|
sampleCount = 1,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
state.depth_texture_view = wgpu.TextureCreateView(state.depth_texture, nil)
|
||||||
|
}
|
||||||
|
|
||||||
|
@(private = "file")
|
||||||
|
framebuffer_aspect :: proc() -> f32 {
|
||||||
|
width, height := os_get_framebuffer_size()
|
||||||
|
if height == 0 {
|
||||||
|
return 1
|
||||||
|
}
|
||||||
|
return cast(f32)width / cast(f32)height
|
||||||
|
}
|
||||||
|
|
||||||
|
// Perspective projection, WebGPU flavour
|
||||||
|
@(private = "file")
|
||||||
|
camera_perspective :: proc(fovy_degrees, aspect, near, far: f32) -> base.Mat4 {
|
||||||
|
gl := linalg.matrix4_perspective(
|
||||||
|
fovy_degrees * math.PI / 180.0,
|
||||||
|
aspect,
|
||||||
|
near,
|
||||||
|
far,
|
||||||
|
)
|
||||||
|
// GL's clip space is [-1, 1] and WebGPU's clip space is [0, 1],
|
||||||
|
// so fold z with a remap: z' = 1/2 z + 1/2 w
|
||||||
|
remap := linalg.identity(base.Mat4)
|
||||||
|
remap[2, 2] = 0.5
|
||||||
|
remap[2, 3] = 0.5
|
||||||
|
return remap * gl
|
||||||
|
}
|
||||||
|
|
||||||
|
@(private = "file")
|
||||||
|
camera_mvp :: proc(aspect: f32) -> base.Mat4 {
|
||||||
|
projection := camera_perspective(
|
||||||
|
state.camera_fov,
|
||||||
|
aspect,
|
||||||
|
CAMERA_NEAR,
|
||||||
|
CAMERA_FAR,
|
||||||
|
)
|
||||||
|
|
||||||
|
yaw := linalg.matrix4_rotate(state.camera.rot.y, {0, 1, 0})
|
||||||
|
pitch := linalg.matrix4_rotate(state.camera.rot.x, {1, 0, 0})
|
||||||
|
rotation := yaw * pitch
|
||||||
|
|
||||||
|
forward := (rotation * base.Vec4{0, 0, -1, 0}).xyz
|
||||||
|
up := (rotation * base.Vec4{0, 1, 0, 0}).xyz
|
||||||
|
|
||||||
|
view := linalg.matrix4_look_at_f32(
|
||||||
|
state.camera.pos,
|
||||||
|
state.camera.pos + forward,
|
||||||
|
up,
|
||||||
|
)
|
||||||
|
// model = identity: the loader already centered the model at the origin
|
||||||
|
return projection * view // * model
|
||||||
|
}
|
||||||
|
|
||||||
|
@(private = "file")
|
||||||
|
upload_camera :: proc(queue: wgpu.Queue, buffer: wgpu.Buffer, aspect: f32) {
|
||||||
|
uniforms := Camera_Uniform {
|
||||||
|
mvp = camera_mvp(aspect),
|
||||||
|
}
|
||||||
|
// bufferOffset = offset into buffer to start from
|
||||||
|
wgpu.QueueWriteBuffer(queue, buffer, 0, &uniforms, size_of(Camera_Uniform))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Test 256x256 checkerboard texture, uploaded once
|
||||||
|
@(private = "file")
|
||||||
|
create_diffuse_texture :: proc(
|
||||||
|
device: wgpu.Device,
|
||||||
|
queue: wgpu.Queue,
|
||||||
|
) -> (
|
||||||
|
wgpu.Texture,
|
||||||
|
wgpu.TextureView,
|
||||||
|
wgpu.Sampler,
|
||||||
|
) {
|
||||||
|
width, height: u32 = 256, 256
|
||||||
|
pixels := make([]u8, width * height * 4)
|
||||||
|
defer delete(pixels)
|
||||||
|
|
||||||
|
for y in 0 ..< height {
|
||||||
|
for x in 0 ..< width {
|
||||||
|
checker := ((x / 32) + (y / 32)) % 2 == 0
|
||||||
|
idx := (y * width + x) * 4
|
||||||
|
if checker {
|
||||||
|
pixels[idx + 0] = 240
|
||||||
|
pixels[idx + 1] = 240
|
||||||
|
pixels[idx + 2] = 240
|
||||||
|
pixels[idx + 3] = 255
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
pixels[idx + 0] = 64
|
||||||
|
pixels[idx + 1] = 64
|
||||||
|
pixels[idx + 2] = 64
|
||||||
|
pixels[idx + 3] = 255
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
texture := wgpu.DeviceCreateTexture(
|
||||||
|
device,
|
||||||
|
&{
|
||||||
|
label = "diffuse texture",
|
||||||
|
usage = {.TextureBinding, .CopyDst}, // shader samples, queue writes
|
||||||
|
dimension = ._2D,
|
||||||
|
size = {width = width, height = height, depthOrArrayLayers = 1},
|
||||||
|
format = .RGBA8Unorm,
|
||||||
|
mipLevelCount = 1,
|
||||||
|
sampleCount = 1,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
// Upload texture to GPU
|
||||||
|
wgpu.QueueWriteTexture(
|
||||||
|
queue,
|
||||||
|
&{texture = texture, mipLevel = 0, origin = {0, 0, 0}, aspect = .All}, // destination
|
||||||
|
raw_data(pixels),
|
||||||
|
len(pixels),
|
||||||
|
&{offset = 0, bytesPerRow = width * 4, rowsPerImage = height}, // data layout
|
||||||
|
&{width = width, height = height, depthOrArrayLayers = 1}, // 3D extent
|
||||||
|
)
|
||||||
|
|
||||||
|
view := wgpu.TextureCreateView(texture, nil)
|
||||||
|
|
||||||
|
sampler := wgpu.DeviceCreateSampler(
|
||||||
|
device,
|
||||||
|
&{
|
||||||
|
addressModeU = .Repeat,
|
||||||
|
addressModeV = .Repeat,
|
||||||
|
magFilter = .Nearest,
|
||||||
|
minFilter = .Nearest,
|
||||||
|
mipmapFilter = .Nearest,
|
||||||
|
maxAnisotropy = 1,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
return texture, view, sampler
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,286 @@
|
|||||||
|
/*
|
||||||
|
* Copyright (C) 2026 Riyyi
|
||||||
|
*
|
||||||
|
* SPDX-License-Identifier: MIT
|
||||||
|
*/
|
||||||
|
|
||||||
|
package platform
|
||||||
|
|
||||||
|
import "core:fmt"
|
||||||
|
import "core:reflect"
|
||||||
|
import "core:strings"
|
||||||
|
|
||||||
|
import "wgpu:wgpu"
|
||||||
|
|
||||||
|
// -----------------------------------------
|
||||||
|
// Types
|
||||||
|
|
||||||
|
// -----------------------------------------
|
||||||
|
// Public functions
|
||||||
|
|
||||||
|
// Generate a WGSL struct declaration from an Odin struct type.
|
||||||
|
// The caller owns the returned string (allocated on context.allocator).
|
||||||
|
//
|
||||||
|
// If locations is true, each member is prefixed with @location(n). This is
|
||||||
|
// required for vertex input structs; uniform structs should use false.
|
||||||
|
to_wgsl_struct :: proc(
|
||||||
|
$T: typeid,
|
||||||
|
name: string,
|
||||||
|
locations := false,
|
||||||
|
) -> string {
|
||||||
|
ti := base_type_info(type_info_of(T))
|
||||||
|
s, ok := ti.variant.(reflect.Type_Info_Struct)
|
||||||
|
if !ok do fmt.panicf("[wgpu_reflect] %s is not a struct", typeid_of(T))
|
||||||
|
|
||||||
|
b: strings.Builder
|
||||||
|
strings.write_string(&b, "struct ")
|
||||||
|
strings.write_string(&b, name)
|
||||||
|
strings.write_string(&b, " {\n")
|
||||||
|
|
||||||
|
names := s.names[:s.field_count]
|
||||||
|
types := s.types[:s.field_count]
|
||||||
|
for i in 0 ..< s.field_count {
|
||||||
|
wgsl_type, type_ok := to_wgsl_type(types[i])
|
||||||
|
if !type_ok {
|
||||||
|
fmt.panicf("[wgpu_reflect] cannot map field %s to WGSL", names[i])
|
||||||
|
}
|
||||||
|
if locations {
|
||||||
|
fmt.sbprintf(
|
||||||
|
&b,
|
||||||
|
"\t@location(%d) %s: %s,\n",
|
||||||
|
i,
|
||||||
|
names[i],
|
||||||
|
wgsl_type,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
fmt.sbprintf(&b, "\t%s: %s,\n", names[i], wgsl_type)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
strings.write_string(&b, "};")
|
||||||
|
return strings.to_string(b)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate a []wgpu.VertexAttribute array that matches the fields of struct T.
|
||||||
|
// The caller owns the returned slice (allocated on context.allocator)
|
||||||
|
to_vertex_attributes :: proc($T: typeid) -> []wgpu.VertexAttribute {
|
||||||
|
ti := base_type_info(type_info_of(T))
|
||||||
|
s, ok := ti.variant.(reflect.Type_Info_Struct)
|
||||||
|
if !ok do fmt.panicf("[wgpu_reflect] %s is not a struct", typeid_of(T))
|
||||||
|
|
||||||
|
attrs := make([]wgpu.VertexAttribute, s.field_count)
|
||||||
|
names := s.names[:s.field_count]
|
||||||
|
types := s.types[:s.field_count]
|
||||||
|
offsets := s.offsets[:s.field_count]
|
||||||
|
|
||||||
|
for i in 0 ..< s.field_count {
|
||||||
|
format, format_ok := to_vertex_format(types[i])
|
||||||
|
if !format_ok {
|
||||||
|
fmt.panicf(
|
||||||
|
"[wgpu_reflect] cannot map field %s to a vertex format",
|
||||||
|
names[i],
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
attrs[i] = wgpu.VertexAttribute {
|
||||||
|
format = format,
|
||||||
|
offset = cast(u64)offsets[i],
|
||||||
|
shaderLocation = u32(i),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return attrs
|
||||||
|
}
|
||||||
|
|
||||||
|
// -----------------------------------------
|
||||||
|
// Private functions
|
||||||
|
|
||||||
|
// Strips named-type wrappers so we can inspect the underlying type
|
||||||
|
@(private = "file")
|
||||||
|
base_type_info :: proc(type_info: ^reflect.Type_Info) -> ^reflect.Type_Info {
|
||||||
|
#partial switch v in type_info.variant {
|
||||||
|
case reflect.Type_Info_Named:
|
||||||
|
return base_type_info(v.base)
|
||||||
|
}
|
||||||
|
return type_info
|
||||||
|
}
|
||||||
|
|
||||||
|
// Map an Odin type to a WGSL scalar/vector/matrix type name
|
||||||
|
@(private = "file")
|
||||||
|
to_wgsl_type :: proc(type_info: ^reflect.Type_Info) -> (string, bool) {
|
||||||
|
ti := base_type_info(type_info)
|
||||||
|
|
||||||
|
#partial switch v in ti.variant {
|
||||||
|
case reflect.Type_Info_Float:
|
||||||
|
switch ti.size {
|
||||||
|
case 4:
|
||||||
|
return "f32", true
|
||||||
|
case 8:
|
||||||
|
return "f64", true
|
||||||
|
}
|
||||||
|
|
||||||
|
case reflect.Type_Info_Integer:
|
||||||
|
prefix := v.signed ? "i" : "u"
|
||||||
|
switch ti.size {
|
||||||
|
case 1:
|
||||||
|
return fmt.tprintf("%s8", prefix), true
|
||||||
|
case 2:
|
||||||
|
return fmt.tprintf("%s16", prefix), true
|
||||||
|
case 4:
|
||||||
|
return fmt.tprintf("%s32", prefix), true
|
||||||
|
case 8:
|
||||||
|
return fmt.tprintf("%s64", prefix), true
|
||||||
|
}
|
||||||
|
|
||||||
|
case reflect.Type_Info_Array:
|
||||||
|
elem_type, elem_ok := to_wgsl_type(v.elem)
|
||||||
|
if !elem_ok do return "", false
|
||||||
|
switch v.count {
|
||||||
|
case 2:
|
||||||
|
return fmt.tprintf("vec2<%s>", elem_type), true
|
||||||
|
case 3:
|
||||||
|
return fmt.tprintf("vec3<%s>", elem_type), true
|
||||||
|
case 4:
|
||||||
|
return fmt.tprintf("vec4<%s>", elem_type), true
|
||||||
|
}
|
||||||
|
|
||||||
|
case reflect.Type_Info_Matrix:
|
||||||
|
elem_type, elem_ok := to_wgsl_type(v.elem)
|
||||||
|
if !elem_ok do return "", false
|
||||||
|
return fmt.tprintf(
|
||||||
|
"mat%dx%d<%s>",
|
||||||
|
v.column_count,
|
||||||
|
v.row_count,
|
||||||
|
elem_type,
|
||||||
|
),
|
||||||
|
true
|
||||||
|
|
||||||
|
case:
|
||||||
|
fmt.panicf("[wgpu_reflect] unimplemented type translation: %v", ti)
|
||||||
|
}
|
||||||
|
|
||||||
|
return "", false
|
||||||
|
}
|
||||||
|
|
||||||
|
// Map an Odin type to a wgpu.VertexFormat.
|
||||||
|
// Only handles the scalar/vector numeric formats commonly used as vertex attributes
|
||||||
|
@(private = "file")
|
||||||
|
to_vertex_format :: proc(
|
||||||
|
type_info: ^reflect.Type_Info,
|
||||||
|
) -> (
|
||||||
|
wgpu.VertexFormat,
|
||||||
|
bool,
|
||||||
|
) {
|
||||||
|
ti := base_type_info(type_info)
|
||||||
|
|
||||||
|
#partial switch v in ti.variant {
|
||||||
|
case reflect.Type_Info_Float:
|
||||||
|
if ti.size == 2 do return .Float16, true
|
||||||
|
else if ti.size == 4 do return .Float32, true
|
||||||
|
|
||||||
|
case reflect.Type_Info_Integer:
|
||||||
|
if v.signed {
|
||||||
|
switch ti.size {
|
||||||
|
case 1:
|
||||||
|
return .Sint8, true
|
||||||
|
case 2:
|
||||||
|
return .Sint16, true
|
||||||
|
case 4:
|
||||||
|
return .Sint32, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
switch ti.size {
|
||||||
|
case 1:
|
||||||
|
return .Uint8, true
|
||||||
|
case 2:
|
||||||
|
return .Uint16, true
|
||||||
|
case 4:
|
||||||
|
return .Uint32, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
case reflect.Type_Info_Array:
|
||||||
|
elem := base_type_info(v.elem)
|
||||||
|
#partial switch ev in elem.variant {
|
||||||
|
case reflect.Type_Info_Float:
|
||||||
|
if elem.size == 2 {
|
||||||
|
switch v.count {
|
||||||
|
case 2:
|
||||||
|
return .Float16x2, true
|
||||||
|
case 4:
|
||||||
|
return .Float16x4, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if elem.size == 4 {
|
||||||
|
switch v.count {
|
||||||
|
case 2:
|
||||||
|
return .Float32x2, true
|
||||||
|
case 3:
|
||||||
|
return .Float32x3, true
|
||||||
|
case 4:
|
||||||
|
return .Float32x4, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
case reflect.Type_Info_Integer:
|
||||||
|
if ev.signed {
|
||||||
|
switch elem.size {
|
||||||
|
case 1:
|
||||||
|
switch v.count {
|
||||||
|
case 2:
|
||||||
|
return .Sint8x2, true
|
||||||
|
case 4:
|
||||||
|
return .Sint8x4, true
|
||||||
|
}
|
||||||
|
case 2:
|
||||||
|
switch v.count {
|
||||||
|
case 2:
|
||||||
|
return .Sint16x2, true
|
||||||
|
case 4:
|
||||||
|
return .Sint16x4, true
|
||||||
|
}
|
||||||
|
case 4:
|
||||||
|
switch v.count {
|
||||||
|
case 2:
|
||||||
|
return .Sint32x2, true
|
||||||
|
case 3:
|
||||||
|
return .Sint32x3, true
|
||||||
|
case 4:
|
||||||
|
return .Sint32x4, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
switch elem.size {
|
||||||
|
case 1:
|
||||||
|
switch v.count {
|
||||||
|
case 2:
|
||||||
|
return .Uint8x2, true
|
||||||
|
case 4:
|
||||||
|
return .Uint8x4, true
|
||||||
|
}
|
||||||
|
case 2:
|
||||||
|
switch (v.count) {
|
||||||
|
case 2:
|
||||||
|
return .Uint16x2, true
|
||||||
|
case 4:
|
||||||
|
return .Uint16x4, true
|
||||||
|
}
|
||||||
|
case 4:
|
||||||
|
switch (v.count) {
|
||||||
|
case 2:
|
||||||
|
return .Uint32x2, true
|
||||||
|
case 3:
|
||||||
|
return .Uint32x3, true
|
||||||
|
case 4:
|
||||||
|
return .Uint32x4, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return .Float32, false
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user