hour 1
This commit is contained in:
commit
1ef7c8c0d8
17 changed files with 1047 additions and 0 deletions
7
.gitignore
vendored
Normal file
7
.gitignore
vendored
Normal file
|
|
@ -0,0 +1,7 @@
|
||||||
|
.idea/
|
||||||
|
.gram/
|
||||||
|
.zed/
|
||||||
|
.zig-cache/
|
||||||
|
zig-out/
|
||||||
|
zig-pkg/
|
||||||
|
bin/
|
||||||
17
LICENSE
Normal file
17
LICENSE
Normal file
|
|
@ -0,0 +1,17 @@
|
||||||
|
Copyright (c) 2025-2026 Karl Zylinski. All rights reserved.
|
||||||
|
|
||||||
|
This software is provided 'as-is', without any express or implied
|
||||||
|
warranty. In no event will the authors be held liable for any damages
|
||||||
|
arising from the use of this software.
|
||||||
|
|
||||||
|
Permission is granted to anyone to use this software for any purpose,
|
||||||
|
including commercial applications, and to alter it and redistribute it
|
||||||
|
freely, subject to the following restrictions:
|
||||||
|
|
||||||
|
1. The origin of this software must not be misrepresented; you must not
|
||||||
|
claim that you wrote the original software. If you use this software
|
||||||
|
in a product, an acknowledgment in the product documentation would be
|
||||||
|
appreciated but is not required.
|
||||||
|
2. Altered source versions must be plainly marked as such, and must not be
|
||||||
|
misrepresented as being the original software.
|
||||||
|
3. This notice may not be removed or altered from any source distribution.
|
||||||
134
README.md
Normal file
134
README.md
Normal file
|
|
@ -0,0 +1,134 @@
|
||||||
|
# Odin + Raylib on the web
|
||||||
|

|
||||||
|
|
||||||
|
Make games using Odin + Raylib that works in browser and on desktop.
|
||||||
|
|
||||||
|
Live example: https://zylinski.se/odin-raylib-web/
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
- **Emscripten**. Follow instructions here: https://emscripten.org/docs/getting_started/downloads.html (the stuff under "Installation instructions using the emsdk (recommended)").
|
||||||
|
|
||||||
|
## Getting started
|
||||||
|
|
||||||
|
1. Point `EMSCRIPTEN_SDK_DIR` in `build_web.bat/sh` to where you installed emscripten.
|
||||||
|
2. Run `build_web.bat/sh`.
|
||||||
|
3. Web game is in the `build/web` folder.
|
||||||
|
|
||||||
|
> [!NOTE]
|
||||||
|
> `build_web.bat` is for windows, `build_web.sh` is for Linux / macOS.
|
||||||
|
|
||||||
|
> [!WARNING]
|
||||||
|
> You can't run `build/web/index.html` directly due to "CORS policy" javascript errors. You can work around that by running a small python web server:
|
||||||
|
> - Go to `build/web` in a console.
|
||||||
|
> - Run `python -m http.server`
|
||||||
|
> - Go to `localhost:8000` in your browser.
|
||||||
|
>
|
||||||
|
> _For those who don't have python: Emscripten comes with it. See the `python` folder in your emscripten installation directory._
|
||||||
|
|
||||||
|
Build a desktop executable using `build_desktop.bat/sh`. It will end up in the `build/desktop` folder.
|
||||||
|
|
||||||
|
Put any assets (textures, sounds etc) into the `assets` folder. Emscripten will merge those into the web build. For desktop builds, the `assets` folder is copied to the `build/desktop` folder.
|
||||||
|
|
||||||
|
## What works
|
||||||
|
|
||||||
|
- Use raylib, raygui, rlgl using the default `vendor:raylib` bindings.
|
||||||
|
- Allocator that works with maps and SIMD (uses emcripten's `malloc`).
|
||||||
|
- Temp allocator.
|
||||||
|
- Logger.
|
||||||
|
- `fmt.println` etc
|
||||||
|
- There's a wrapper for `read_entire_file` and `write_entire_file` from `core:os` that can files from `assets` directory, even on web. See `source/utils.odin`
|
||||||
|
|
||||||
|
> [!NOTE]
|
||||||
|
> Files written using `write_entire_file` don't exist outside the browser. They don't survive closing the tab. But you can write a file and load it within the same session. You can use it to make your old desktop code run, even though it won't be possible to _really_ save anything.
|
||||||
|
|
||||||
|
## Debugging
|
||||||
|
|
||||||
|
I recommend debugging the desktop build when you can (add `-debug` inside `build_desktop.bat/sh` and use for example [RAD Debugger](https://github.com/EpicGamesExt/raddebugger)). For web-only bugs, you can add `-g` to the the `emcc` line in the build script. This gives you better crash callstacks. It works in Chrome, not so much in Firefox.
|
||||||
|
|
||||||
|
## Sublime Text
|
||||||
|
|
||||||
|
There is a Sublime project file: `project.sublime-project`. It has a build system that lets you run the web and desktop build scripts.
|
||||||
|
|
||||||
|
## Web build in my Hot Reload template
|
||||||
|
|
||||||
|
My Odin + Raylib + Hot Reload template has been updated with similar capabilities: https://github.com/karl-zylinski/odin-raylib-hot-reload-game-template -- Note: It's just for making a _release web build_, no web hot reloading is supported!
|
||||||
|
|
||||||
|
## How does the web build work?
|
||||||
|
|
||||||
|
Start by looking at `build_web.bat/sh` and see how it uses both the Odin compiler and the emscripten compiler (`emcc`). Raylib requires `emcc` to (among other things) translate OpenGL to WebGL calls. Also see `source/main_web/index_template.html` (used as template for `build/web/index/html`). That HTML file contains javascript that calls the entry-point procedures you'll find in `source/main_web/main_web.odin`. It's a bit special in the way that it sets our Odin stuff up within a callback that comes from emscripten (`instantiateWasm`).
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
### I get `panic: wasm_allocator: initial memory could not be allocated`
|
||||||
|
|
||||||
|
You probably have a global variable that allocates dynamic memory. Move that allocation into the game's `init` proc. This could also happen if initialize dynamic arrays or maps in the global file scope, like so:
|
||||||
|
|
||||||
|
```
|
||||||
|
arr := [dynamic]int { 2, 3, 4 }
|
||||||
|
```
|
||||||
|
|
||||||
|
In that case you can declare it and do the initialization in the `init` proc instead:
|
||||||
|
|
||||||
|
```
|
||||||
|
arr: [dynamic]int
|
||||||
|
|
||||||
|
init :: proc() {
|
||||||
|
arr = { 2, 3, 4 }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
This happens because the context hasn't been initialized with the correct allocator yet.
|
||||||
|
|
||||||
|
The error can also happen if you import some package that does allocations in a procedure tagged with `@(init)`. Once such page is `core:math/big`. That package is in turn imported by `core:encoding/cbor`. So if you import cbor you may get this error. If you need cbor, then you you can try, as a work-around, to run the Odin compiler with the `-default-to-nil-allocator` option. That may break the `core:math/big` package, but you might not need it.
|
||||||
|
|
||||||
|
### I get `RuntimeError: memory access out of bounds`
|
||||||
|
|
||||||
|
Try modifying the `build_web` script and add these flags where it runs `emcc`:
|
||||||
|
```
|
||||||
|
-sALLOW_MEMORY_GROWTH=1 -sINITIAL_HEAP=16777216 -sSTACK_SIZE=65536
|
||||||
|
```
|
||||||
|
The numbers `16777216` and `65536` above are the default values, try bigger ones and see if it helps.
|
||||||
|
|
||||||
|
### I load assets from more folders than the `assets` folder
|
||||||
|
Add an additional `--preload-file folder_name` option to the build script when it runs `emcc`. Then that folder will become part of the web build.
|
||||||
|
|
||||||
|
### I can only use `#version 100` shaders
|
||||||
|
The raylib libraries that come with Odin can only use version 100. That's the default for raylib. But you can recompile raylib so that shaders with version `300 es` works. That's a fairly modern version. It's mostly the same as the common `330` version.
|
||||||
|
|
||||||
|
You'll need to recompile the raylib WASM binaries. That means you need to download the raylib source from here: https://github.com/raysan5/raylib
|
||||||
|
|
||||||
|
When you've downloaded it you need to compile raylib with OpenGL ES3 support. Something like this:
|
||||||
|
|
||||||
|
```
|
||||||
|
make clean
|
||||||
|
make PLATFORM=PLATFORM_WEB GRAPHICS=GRAPHICS_API_OPENGL_ES3 -B
|
||||||
|
```
|
||||||
|
You might also be able to use `mingw32-make` instead of `make` on Windows, if you have mingw installed. You may also be able to invoke `emcc` manually, but you'll have to look through the makefiles to see what commands you need to run.
|
||||||
|
|
||||||
|
You'll need to copy the outputted wasm libs from this build to your raylib bindings, overwriting the old raylib WASM library files.
|
||||||
|
|
||||||
|
When building your game, you need to modify the build script. When it runs `emcc`, add the following: `-sFULL_ES3=1`.
|
||||||
|
|
||||||
|
You can now use the `300 es` version of shaders. Make sure the shaders have this at the top:
|
||||||
|
```
|
||||||
|
#version 300 es
|
||||||
|
precision highp float;
|
||||||
|
```
|
||||||
|
|
||||||
|
Thanks to lucy for figuring this stuff out.
|
||||||
|
|
||||||
|
### Error: `emcc: error: build\web\index.data --from-emcc --preload assets' failed (returned 1)`
|
||||||
|
You might be missing the `assets` folder. It must have at least a single file inside it. You can also remove the `--preload-file assets` from the build script.
|
||||||
|
|
||||||
|
## Questions?
|
||||||
|
|
||||||
|
Talk to me on my Discord server: https://discord.gg/4FsHgtBmFK
|
||||||
|
|
||||||
|
## Acknowledgements
|
||||||
|
Tyzor on the Odin Discord helped me with using `js_wasm32` instead of `freestanding_wasm32`.
|
||||||
|
|
||||||
|
[Caedo's repository](https://github.com/Caedo/raylib_wasm_odin) and [Aronicu's repository](https://github.com/Aronicu/Raylib-WASM) helped me with:
|
||||||
|
- The initial emscripten setup
|
||||||
|
- The logger setup
|
||||||
|
- The idea of using python to host a server
|
||||||
93
build.zig
Normal file
93
build.zig
Normal file
|
|
@ -0,0 +1,93 @@
|
||||||
|
const std = @import("std");
|
||||||
|
const Build = std.Build;
|
||||||
|
|
||||||
|
const program_name = "fortunes-foundation";
|
||||||
|
|
||||||
|
pub fn build(b: *Build) !void {
|
||||||
|
const optimize: std.builtin.OptimizeMode = b.standardOptimizeOption(.{});
|
||||||
|
const target: Build.ResolvedTarget = b.standardTargetOptions(.{});
|
||||||
|
|
||||||
|
const tracy_enable = b.option(bool, "tracy_enable", "Enables Tracy support in the final executable") orelse false;
|
||||||
|
const tracy_callstack = b.option(u32, "tracy_callstack", "Size of the collected callstack") orelse 0;
|
||||||
|
|
||||||
|
const dancer_static_lib = dancer_static_lib: {
|
||||||
|
const odin_exec = b.addSystemCommand(&.{ "odin", "build", "-build-mode:static" });
|
||||||
|
odin_exec.addArg(switch (optimize) {
|
||||||
|
.Debug => "-o:minimal",
|
||||||
|
.ReleaseSafe => "-o:speed",
|
||||||
|
.ReleaseFast => "-o:aggressive",
|
||||||
|
.ReleaseSmall => "-o:size",
|
||||||
|
});
|
||||||
|
if (optimize == .Debug or tracy_enable) {
|
||||||
|
odin_exec.addArg("-debug");
|
||||||
|
}
|
||||||
|
if (tracy_enable) {
|
||||||
|
odin_exec.addArg("-define:TRACY_ENABLE=true");
|
||||||
|
odin_exec.addArg(b.fmt("-define:TRACY_CALLSTACK={}", .{tracy_callstack}));
|
||||||
|
}
|
||||||
|
const dancer_static_lib = odin_exec.addPrefixedOutputFileArg("-out:", switch (target.result.abi) {
|
||||||
|
else => "game.a",
|
||||||
|
});
|
||||||
|
odin_exec.addDirectoryArg(b.path(switch (target.result.cpu.arch) {
|
||||||
|
.wasm32, .wasm64 => "src/main_web",
|
||||||
|
else => "src/main_desktop/",
|
||||||
|
}));
|
||||||
|
odin_exec.has_side_effects = true;
|
||||||
|
break :dancer_static_lib dancer_static_lib;
|
||||||
|
};
|
||||||
|
|
||||||
|
const exe_mod = b.addModule(program_name, .{
|
||||||
|
.target = target,
|
||||||
|
.optimize = optimize,
|
||||||
|
.link_libc = true,
|
||||||
|
.link_libcpp = true,
|
||||||
|
});
|
||||||
|
exe_mod.addObjectFile(dancer_static_lib);
|
||||||
|
|
||||||
|
const raylib_dep = b.dependency("raylib", .{
|
||||||
|
.target = target,
|
||||||
|
.optimize = .ReleaseFast,
|
||||||
|
.linux_display_backend = .X11,
|
||||||
|
.opengl_version = .auto,
|
||||||
|
.raygui = true,
|
||||||
|
});
|
||||||
|
const raylib_compile = raylib_dep.artifact("raylib");
|
||||||
|
exe_mod.linkLibrary(raylib_compile);
|
||||||
|
|
||||||
|
if (tracy_enable) {
|
||||||
|
const tracy_dep = b.dependency("tracy", .{});
|
||||||
|
const tracy_mod = b.addModule("tracy", .{
|
||||||
|
.target = target,
|
||||||
|
.optimize = .ReleaseFast,
|
||||||
|
.link_libc = true,
|
||||||
|
.link_libcpp = true,
|
||||||
|
});
|
||||||
|
tracy_mod.addCMacro("TRACY_ENABLE", "1");
|
||||||
|
tracy_mod.addCMacro("TRACY_CALLSTACK", "16");
|
||||||
|
// tracy_mod.addCMacro("TRACY_VERBOSE", "1");
|
||||||
|
|
||||||
|
// Enable this if sampling is missing.
|
||||||
|
// tracy_mod.addCMacro("TRACY_DISALLOW_HW_TIMER", "1");
|
||||||
|
if (target.query.os_tag == .linux) {
|
||||||
|
tracy_mod.addCMacro("TRACY_LIBUNWIND_BACKTRACE", "1");
|
||||||
|
}
|
||||||
|
tracy_mod.addCSourceFile(.{
|
||||||
|
.file = tracy_dep.path("public/TracyClient.cpp"),
|
||||||
|
.language = .cpp,
|
||||||
|
});
|
||||||
|
exe_mod.addObject(b.addObject(.{ .name = "tracy", .root_module = tracy_mod }));
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((optimize == .ReleaseSmall or optimize == .ReleaseFast) and !tracy_enable) exe_mod.strip = true;
|
||||||
|
const exe = b.addExecutable(.{
|
||||||
|
.root_module = exe_mod,
|
||||||
|
.name = program_name,
|
||||||
|
});
|
||||||
|
exe.lto = if (optimize != .Debug) .full else .none;
|
||||||
|
exe.pie = false;
|
||||||
|
exe.bundle_ubsan_rt = true;
|
||||||
|
exe.bundle_compiler_rt = true;
|
||||||
|
b.installArtifact(exe);
|
||||||
|
|
||||||
|
b.step("run", "Run the game").dependOn(&b.addRunArtifact(exe).step);
|
||||||
|
}
|
||||||
64
build.zig.zon
Normal file
64
build.zig.zon
Normal file
|
|
@ -0,0 +1,64 @@
|
||||||
|
.{
|
||||||
|
.name = .dancer,
|
||||||
|
|
||||||
|
.version = "0.0.0",
|
||||||
|
.fingerprint = 0xb11cc8a94a2a9f63, // Changing this has security and trust implications.
|
||||||
|
.minimum_zig_version = "0.17.0-dev.2264+230c63650",
|
||||||
|
.dependencies = .{
|
||||||
|
// See `zig fetch --save <url>` for a command-line interface for adding dependencies.
|
||||||
|
//.example = .{
|
||||||
|
// // When updating this field to a new URL, be sure to delete the corresponding
|
||||||
|
// // `hash`, otherwise you are communicating that you expect to find the old hash at
|
||||||
|
// // the new URL. If the contents of a URL change this will result in a hash mismatch
|
||||||
|
// // which will prevent zig from using it.
|
||||||
|
// .url = "https://example.com/foo.tar.gz",
|
||||||
|
//
|
||||||
|
// // This is computed from the file contents of the directory of files that is
|
||||||
|
// // obtained after fetching `url` and applying the inclusion rules given by
|
||||||
|
// // `paths`.
|
||||||
|
// //
|
||||||
|
// // This field is the source of truth; packages do not come from a `url`; they
|
||||||
|
// // come from a `hash`. `url` is just one of many possible mirrors for how to
|
||||||
|
// // obtain a package matching this `hash`.
|
||||||
|
// .hash = "...",
|
||||||
|
//
|
||||||
|
// // When this is provided, the package is found in a directory relative to the
|
||||||
|
// // build root. In this case the package's hash is irrelevant and therefore not
|
||||||
|
// // computed. This field and `url` are mutually exclusive.
|
||||||
|
// .path = "foo",
|
||||||
|
//
|
||||||
|
// // When this is set to `true`, a package is declared to be lazily
|
||||||
|
// // fetched. This makes the dependency only get fetched if it is
|
||||||
|
// // actually used.
|
||||||
|
// .lazy = false,
|
||||||
|
//},
|
||||||
|
.raylib = .{
|
||||||
|
.url = "git+https://github.com/raysan5/raylib.git#6.0",
|
||||||
|
.hash = "raylib-6.0.0-whq8uCSwLgWWeF3ec3dbG6Rr36SLFL-s2WJ1Q_2E22Bb",
|
||||||
|
},
|
||||||
|
.flecs = .{
|
||||||
|
.url = "git+https://github.com/SanderMertens/flecs.git#9e874bca2c05b60612cf5b671988adefc0785820",
|
||||||
|
.hash = "N-V-__8AAGh0WwNwXJ0B6dh-lCZzzG1szH8oCwtU3ZYp0Q2D",
|
||||||
|
},
|
||||||
|
.tracy = .{
|
||||||
|
.url = "git+https://github.com/wolfpld/tracy.git#v0.14.1",
|
||||||
|
.hash = "N-V-__8AAAZPdAGoNF3-tqKYHjTOa5QQ02rEWNvkDr-Vpl0C",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
// Specifies the set of files and directories that are included in this package.
|
||||||
|
// Only files and directories listed here are included in the `hash` that
|
||||||
|
// is computed for this package. Only files listed here will remain on disk
|
||||||
|
// when using the zig package manager. As a rule of thumb, one should list
|
||||||
|
// files required for compilation plus any license(s).
|
||||||
|
// Paths are relative to the build root. Use the empty string (`""`) to refer to
|
||||||
|
// the build root itself.
|
||||||
|
// A directory listed here means that all files within, recursively, are included.
|
||||||
|
.paths = .{
|
||||||
|
"build.zig",
|
||||||
|
"build.zig.zon",
|
||||||
|
"src",
|
||||||
|
// For example...
|
||||||
|
//"LICENSE",
|
||||||
|
//"README.md",
|
||||||
|
},
|
||||||
|
}
|
||||||
14
justfile
Normal file
14
justfile
Normal file
|
|
@ -0,0 +1,14 @@
|
||||||
|
build:
|
||||||
|
zig build
|
||||||
|
|
||||||
|
run:
|
||||||
|
zig build run
|
||||||
|
|
||||||
|
release:
|
||||||
|
zig build -Doptimize=ReleaseFast
|
||||||
|
|
||||||
|
run-with-tracy:
|
||||||
|
zig build -Dtracy_enable=true -Dtracy_callstack=32 run
|
||||||
|
|
||||||
|
run-opt-with-tracy:
|
||||||
|
zig build -Doptimize=ReleaseFast -Dtracy_enable=true -Dtracy_callstack=16 run
|
||||||
BIN
src/assets/Besley-Italic.ttf
Normal file
BIN
src/assets/Besley-Italic.ttf
Normal file
Binary file not shown.
BIN
src/assets/Besley-Regular.ttf
Normal file
BIN
src/assets/Besley-Regular.ttf
Normal file
Binary file not shown.
176
src/game.odin
Normal file
176
src/game.odin
Normal file
|
|
@ -0,0 +1,176 @@
|
||||||
|
package game
|
||||||
|
|
||||||
|
import "base:builtin"
|
||||||
|
import "base:intrinsics"
|
||||||
|
import "base:runtime"
|
||||||
|
import "core:c"
|
||||||
|
import hm "core:container/handle_map"
|
||||||
|
import "core:container/queue"
|
||||||
|
import "core:fmt"
|
||||||
|
import "core:log"
|
||||||
|
import "core:mem"
|
||||||
|
import ray "vendor:raylib"
|
||||||
|
|
||||||
|
game: Game
|
||||||
|
Game :: struct {
|
||||||
|
run: bool,
|
||||||
|
assets: map[string]runtime.Load_Directory_File,
|
||||||
|
static_arena: mem.Arena,
|
||||||
|
static_arena_data: [1 * mem.Megabyte]byte,
|
||||||
|
// Allocations here will never be freed
|
||||||
|
static_allocator: runtime.Allocator,
|
||||||
|
cards: [TAROT_COUNT]Card,
|
||||||
|
entities: [TAROT_COUNT]Card_Entity,
|
||||||
|
font: ray.Font,
|
||||||
|
}
|
||||||
|
Vec2 :: [2]f32
|
||||||
|
Card :: struct {
|
||||||
|
suit: Suit,
|
||||||
|
number: i8,
|
||||||
|
}
|
||||||
|
Suit :: enum {
|
||||||
|
Major = 0,
|
||||||
|
Chalice = 1,
|
||||||
|
Coin = 2,
|
||||||
|
Sword = 3,
|
||||||
|
Wand = 4,
|
||||||
|
}
|
||||||
|
MAJOR_COUNT :: 22
|
||||||
|
MINOR_COUNT :: 14
|
||||||
|
TAROT_COUNT :: MAJOR_COUNT + 4 * MINOR_COUNT
|
||||||
|
Card_Entity :: struct {
|
||||||
|
position: Vec2,
|
||||||
|
}
|
||||||
|
Card_Handle :: distinct u8
|
||||||
|
|
||||||
|
init :: proc() {
|
||||||
|
game.run = true
|
||||||
|
|
||||||
|
// NOTE(lilith): Sorting statically included assets
|
||||||
|
assets := #load_directory("assets")
|
||||||
|
game.assets = make(
|
||||||
|
map[string]runtime.Load_Directory_File,
|
||||||
|
len(assets),
|
||||||
|
allocator = game.static_allocator,
|
||||||
|
)
|
||||||
|
for asset in assets {
|
||||||
|
game.assets[asset.name] = asset
|
||||||
|
}
|
||||||
|
|
||||||
|
ray.SetConfigFlags({.WINDOW_RESIZABLE, .VSYNC_HINT})
|
||||||
|
ray.InitWindow(1280, 720, "Fortune's Foundation")
|
||||||
|
|
||||||
|
for number in 0 ..< MAJOR_COUNT {
|
||||||
|
game.cards[number] = Card {
|
||||||
|
suit = .Major,
|
||||||
|
number = i8(number),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for suit in Suit.Chalice ..= Suit.Wand {
|
||||||
|
suit_offset := MAJOR_COUNT + (int(suit) - 1) * MINOR_COUNT
|
||||||
|
for number in 1 ..= MINOR_COUNT {
|
||||||
|
game.cards[suit_offset + number - 1] = Card {
|
||||||
|
suit = suit,
|
||||||
|
number = i8(number),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for &obj, index in soa_zip(card = game.cards[:], entity = game.entities[:]) {
|
||||||
|
obj.entity.position.y = f32(index * 28)
|
||||||
|
log.infof("card: %#v", obj)
|
||||||
|
}
|
||||||
|
|
||||||
|
game.font = ray.LoadFontFromMemory(
|
||||||
|
".ttf",
|
||||||
|
psz_from_slice(game.assets["Besley-Regular.ttf"].data),
|
||||||
|
fontSize = 24,
|
||||||
|
codepoints = nil,
|
||||||
|
codepointCount = 0,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
update :: proc() {
|
||||||
|
free_all(context.temp_allocator)
|
||||||
|
ray.BeginDrawing(); defer ray.EndDrawing()
|
||||||
|
ray.ClearBackground({0, 120, 153, 255})
|
||||||
|
|
||||||
|
for obj, index in soa_zip(card = game.cards[:], entity = game.entities[:]) {
|
||||||
|
// ray.DrawRectangle
|
||||||
|
ray.DrawTextEx(
|
||||||
|
game.font,
|
||||||
|
fmt.ctprintf("%d%s", obj.card.number, ""),
|
||||||
|
position = obj.entity.position,
|
||||||
|
fontSize = 24,
|
||||||
|
spacing = 0,
|
||||||
|
tint = ray.WHITE,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
index_from_card :: proc(card: Card) -> int {
|
||||||
|
suit_offset: int
|
||||||
|
switch card.suit {
|
||||||
|
case .Major:
|
||||||
|
suit_offset = 0
|
||||||
|
case .Chalice:
|
||||||
|
suit_offset = MAJOR_COUNT
|
||||||
|
case .Coin:
|
||||||
|
suit_offset = MAJOR_COUNT + 1 * MINOR_COUNT
|
||||||
|
case .Sword:
|
||||||
|
suit_offset = MAJOR_COUNT + 2 * MINOR_COUNT
|
||||||
|
case .Wand:
|
||||||
|
suit_offset = MAJOR_COUNT + 3 * MINOR_COUNT
|
||||||
|
}
|
||||||
|
number_offset := card.suit == .Major ? card.number : card.number - 1
|
||||||
|
return suit_offset + int(number_offset)
|
||||||
|
}
|
||||||
|
|
||||||
|
text_color :: proc(card: Card) -> ray.Color {
|
||||||
|
switch card.suit {
|
||||||
|
case .Major:
|
||||||
|
return ray.WHITE
|
||||||
|
case .Chalice, .Coin, .Sword, .Wand:
|
||||||
|
return ray.Color{220, 220, 220, 255}
|
||||||
|
}
|
||||||
|
unreachable()
|
||||||
|
}
|
||||||
|
|
||||||
|
background_color :: proc(card: Card) -> ray.Color {
|
||||||
|
switch card.suit {
|
||||||
|
case .Major:
|
||||||
|
return ray.WHITE
|
||||||
|
case .Chalice, .Coin, .Sword, .Wand:
|
||||||
|
return ray.Color{220, 220, 220, 255}
|
||||||
|
}
|
||||||
|
unreachable()
|
||||||
|
}
|
||||||
|
|
||||||
|
// In a web build, this is called when browser changes size. Remove the
|
||||||
|
// `ray.SetWindowSize` call if you don't want a resizable game.
|
||||||
|
parent_window_size_changed :: proc(w, h: int) {
|
||||||
|
ray.SetWindowSize(c.int(w), c.int(h))
|
||||||
|
}
|
||||||
|
|
||||||
|
shutdown :: proc() {
|
||||||
|
ray.CloseWindow()
|
||||||
|
}
|
||||||
|
|
||||||
|
should_run :: proc() -> bool {
|
||||||
|
when ODIN_OS != .JS {
|
||||||
|
// Never run this proc in browser. It contains a 16 ms sleep on web!
|
||||||
|
if ray.WindowShouldClose() {
|
||||||
|
game.run = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return game.run
|
||||||
|
}
|
||||||
|
|
||||||
|
rrect_from_pos_sz :: proc(pos: Vec2, sz: Vec2) -> ray.Rectangle {
|
||||||
|
return {pos.x, pos.y, sz.x, sz.y}
|
||||||
|
}
|
||||||
|
|
||||||
|
psz_from_slice :: proc(slice: []$T) -> (rawptr, i32) {
|
||||||
|
return raw_data(slice), i32(len(slice))
|
||||||
|
}
|
||||||
23
src/main_desktop/main_desktop.odin
Normal file
23
src/main_desktop/main_desktop.odin
Normal file
|
|
@ -0,0 +1,23 @@
|
||||||
|
package main_desktop
|
||||||
|
|
||||||
|
import "core:log"
|
||||||
|
import "core:os"
|
||||||
|
import "core:path/filepath"
|
||||||
|
import game ".."
|
||||||
|
|
||||||
|
main :: proc() {
|
||||||
|
// Set working dir to dir of executable.
|
||||||
|
exe_path := os.args[0]
|
||||||
|
exe_dir := filepath.dir(string(exe_path))
|
||||||
|
os.set_working_directory(exe_dir)
|
||||||
|
|
||||||
|
context.logger = log.create_console_logger()
|
||||||
|
|
||||||
|
game.init()
|
||||||
|
|
||||||
|
for game.should_run() {
|
||||||
|
game.update()
|
||||||
|
}
|
||||||
|
|
||||||
|
game.shutdown()
|
||||||
|
}
|
||||||
126
src/main_web/emscripten_allocator.odin
Normal file
126
src/main_web/emscripten_allocator.odin
Normal file
|
|
@ -0,0 +1,126 @@
|
||||||
|
/*
|
||||||
|
This allocator uses the malloc, calloc, free and realloc procs that emscripten
|
||||||
|
exposes in order to allocate memory. Just like Odin's default heap allocator
|
||||||
|
this uses proper alignment, so that maps and simd works.
|
||||||
|
*/
|
||||||
|
|
||||||
|
package main_web
|
||||||
|
|
||||||
|
import "core:mem"
|
||||||
|
import "core:c"
|
||||||
|
import "base:intrinsics"
|
||||||
|
|
||||||
|
// This will create bindings to emscripten's implementation of libc
|
||||||
|
// memory allocation features.
|
||||||
|
@(default_calling_convention = "c")
|
||||||
|
foreign {
|
||||||
|
calloc :: proc(num, size: c.size_t) -> rawptr ---
|
||||||
|
free :: proc(ptr: rawptr) ---
|
||||||
|
malloc :: proc(size: c.size_t) -> rawptr ---
|
||||||
|
realloc :: proc(ptr: rawptr, size: c.size_t) -> rawptr ---
|
||||||
|
}
|
||||||
|
|
||||||
|
emscripten_allocator :: proc "contextless" () -> mem.Allocator {
|
||||||
|
return mem.Allocator{emscripten_allocator_proc, nil}
|
||||||
|
}
|
||||||
|
|
||||||
|
emscripten_allocator_proc :: proc(
|
||||||
|
allocator_data: rawptr,
|
||||||
|
mode: mem.Allocator_Mode,
|
||||||
|
size, alignment: int,
|
||||||
|
old_memory: rawptr,
|
||||||
|
old_size: int,
|
||||||
|
location := #caller_location
|
||||||
|
) -> (data: []byte, err: mem.Allocator_Error) {
|
||||||
|
// These aligned alloc procs are almost indentical those in
|
||||||
|
// `_heap_allocator_proc` in `core:os`. Without the proper alignment you
|
||||||
|
// cannot use maps and simd features.
|
||||||
|
|
||||||
|
aligned_alloc :: proc(size, alignment: int, zero_memory: bool, old_ptr: rawptr = nil) -> ([]byte, mem.Allocator_Error) {
|
||||||
|
a := max(alignment, align_of(rawptr))
|
||||||
|
space := size + a - 1
|
||||||
|
|
||||||
|
allocated_mem: rawptr
|
||||||
|
if old_ptr != nil {
|
||||||
|
original_old_ptr := mem.ptr_offset((^rawptr)(old_ptr), -1)^
|
||||||
|
allocated_mem = realloc(original_old_ptr, c.size_t(space+size_of(rawptr)))
|
||||||
|
} else if zero_memory {
|
||||||
|
// calloc automatically zeros memory, but it takes a number + size
|
||||||
|
// instead of just size.
|
||||||
|
allocated_mem = calloc(c.size_t(space+size_of(rawptr)), 1)
|
||||||
|
} else {
|
||||||
|
allocated_mem = malloc(c.size_t(space+size_of(rawptr)))
|
||||||
|
}
|
||||||
|
aligned_mem := rawptr(mem.ptr_offset((^u8)(allocated_mem), size_of(rawptr)))
|
||||||
|
|
||||||
|
ptr := uintptr(aligned_mem)
|
||||||
|
aligned_ptr := (ptr - 1 + uintptr(a)) & -uintptr(a)
|
||||||
|
diff := int(aligned_ptr - ptr)
|
||||||
|
if (size + diff) > space || allocated_mem == nil {
|
||||||
|
return nil, .Out_Of_Memory
|
||||||
|
}
|
||||||
|
|
||||||
|
aligned_mem = rawptr(aligned_ptr)
|
||||||
|
mem.ptr_offset((^rawptr)(aligned_mem), -1)^ = allocated_mem
|
||||||
|
|
||||||
|
return mem.byte_slice(aligned_mem, size), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
aligned_free :: proc(p: rawptr) {
|
||||||
|
if p != nil {
|
||||||
|
free(mem.ptr_offset((^rawptr)(p), -1)^)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
aligned_resize :: proc(p: rawptr, old_size: int, new_size: int, new_alignment: int) -> ([]byte, mem.Allocator_Error) {
|
||||||
|
if p == nil {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
return aligned_alloc(new_size, new_alignment, true, p)
|
||||||
|
}
|
||||||
|
|
||||||
|
switch mode {
|
||||||
|
case .Alloc:
|
||||||
|
return aligned_alloc(size, alignment, true)
|
||||||
|
|
||||||
|
case .Alloc_Non_Zeroed:
|
||||||
|
return aligned_alloc(size, alignment, false)
|
||||||
|
|
||||||
|
case .Free:
|
||||||
|
aligned_free(old_memory)
|
||||||
|
return nil, nil
|
||||||
|
|
||||||
|
case .Resize:
|
||||||
|
if old_memory == nil {
|
||||||
|
return aligned_alloc(size, alignment, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
bytes := aligned_resize(old_memory, old_size, size, alignment) or_return
|
||||||
|
|
||||||
|
// realloc doesn't zero the new bytes, so we do it manually.
|
||||||
|
if size > old_size {
|
||||||
|
new_region := raw_data(bytes[old_size:])
|
||||||
|
intrinsics.mem_zero(new_region, size - old_size)
|
||||||
|
}
|
||||||
|
|
||||||
|
return bytes, nil
|
||||||
|
|
||||||
|
case .Resize_Non_Zeroed:
|
||||||
|
if old_memory == nil {
|
||||||
|
return aligned_alloc(size, alignment, false)
|
||||||
|
}
|
||||||
|
|
||||||
|
return aligned_resize(old_memory, old_size, size, alignment)
|
||||||
|
|
||||||
|
case .Query_Features:
|
||||||
|
set := (^mem.Allocator_Mode_Set)(old_memory)
|
||||||
|
if set != nil {
|
||||||
|
set^ = {.Alloc, .Free, .Resize, .Query_Features}
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
|
||||||
|
case .Free_All, .Query_Info:
|
||||||
|
return nil, .Mode_Not_Implemented
|
||||||
|
}
|
||||||
|
return nil, .Mode_Not_Implemented
|
||||||
|
}
|
||||||
91
src/main_web/emscripten_logger.odin
Normal file
91
src/main_web/emscripten_logger.odin
Normal file
|
|
@ -0,0 +1,91 @@
|
||||||
|
/*
|
||||||
|
This logger is largely a copy of the console logger in `core:log`, but it uses
|
||||||
|
emscripten's `puts` proc to write into he console of the web browser.
|
||||||
|
|
||||||
|
This is more or less identical to the logger in Aronicu's repository:
|
||||||
|
https://github.com/Aronicu/Raylib-WASM/tree/main
|
||||||
|
*/
|
||||||
|
|
||||||
|
package main_web
|
||||||
|
|
||||||
|
import "core:c"
|
||||||
|
import "core:fmt"
|
||||||
|
import "core:log"
|
||||||
|
import "core:strings"
|
||||||
|
|
||||||
|
Emscripten_Logger_Opts :: log.Options{.Level, .Short_File_Path, .Line}
|
||||||
|
|
||||||
|
create_emscripten_logger :: proc (lowest := log.Level.Debug, opt := Emscripten_Logger_Opts) -> log.Logger {
|
||||||
|
return log.Logger{data = nil, procedure = logger_proc, lowest_level = lowest, options = opt}
|
||||||
|
}
|
||||||
|
|
||||||
|
// This create's a binding to `puts` which will be linked in as part of the
|
||||||
|
// emscripten runtime.
|
||||||
|
@(default_calling_convention = "c")
|
||||||
|
foreign {
|
||||||
|
puts :: proc(buffer: cstring) -> c.int ---
|
||||||
|
}
|
||||||
|
|
||||||
|
@(private="file")
|
||||||
|
logger_proc :: proc(
|
||||||
|
logger_data: rawptr,
|
||||||
|
level: log.Level,
|
||||||
|
text: string,
|
||||||
|
options: log.Options,
|
||||||
|
location := #caller_location
|
||||||
|
) {
|
||||||
|
b := strings.builder_make(context.temp_allocator)
|
||||||
|
strings.write_string(&b, Level_Headers[level])
|
||||||
|
do_location_header(options, &b, location)
|
||||||
|
fmt.sbprint(&b, text)
|
||||||
|
|
||||||
|
if bc, bc_err := strings.to_cstring(&b); bc_err == nil {
|
||||||
|
puts(bc)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@(private="file")
|
||||||
|
Level_Headers := [?]string {
|
||||||
|
0 ..< 10 = "[DEBUG] --- ",
|
||||||
|
10 ..< 20 = "[INFO ] --- ",
|
||||||
|
20 ..< 30 = "[WARN ] --- ",
|
||||||
|
30 ..< 40 = "[ERROR] --- ",
|
||||||
|
40 ..< 50 = "[FATAL] --- ",
|
||||||
|
}
|
||||||
|
|
||||||
|
@(private="file")
|
||||||
|
do_location_header :: proc(opts: log.Options, buf: ^strings.Builder, location := #caller_location) {
|
||||||
|
if log.Location_Header_Opts & opts == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
fmt.sbprint(buf, "[")
|
||||||
|
file := location.file_path
|
||||||
|
if .Short_File_Path in opts {
|
||||||
|
last := 0
|
||||||
|
for r, i in location.file_path {
|
||||||
|
if r == '/' {
|
||||||
|
last = i + 1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
file = location.file_path[last:]
|
||||||
|
}
|
||||||
|
|
||||||
|
if log.Location_File_Opts & opts != nil {
|
||||||
|
fmt.sbprint(buf, file)
|
||||||
|
}
|
||||||
|
if .Line in opts {
|
||||||
|
if log.Location_File_Opts & opts != nil {
|
||||||
|
fmt.sbprint(buf, ":")
|
||||||
|
}
|
||||||
|
fmt.sbprint(buf, location.line)
|
||||||
|
}
|
||||||
|
|
||||||
|
if .Procedure in opts {
|
||||||
|
if (log.Location_File_Opts | {.Line}) & opts != nil {
|
||||||
|
fmt.sbprint(buf, ":")
|
||||||
|
}
|
||||||
|
fmt.sbprintf(buf, "%s()", location.procedure)
|
||||||
|
}
|
||||||
|
|
||||||
|
fmt.sbprint(buf, "] ")
|
||||||
|
}
|
||||||
114
src/main_web/index_template.html
Normal file
114
src/main_web/index_template.html
Normal file
|
|
@ -0,0 +1,114 @@
|
||||||
|
<!doctype html>
|
||||||
|
<html lang="en-us">
|
||||||
|
<head>
|
||||||
|
<meta charset="utf-8">
|
||||||
|
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
|
||||||
|
|
||||||
|
<title>Odin + Raylib on the web</title>
|
||||||
|
<meta name="title" content="Odin + Raylib on the web">
|
||||||
|
<meta name="description" content="Make games using Odin + Raylib that work in the browser">
|
||||||
|
<meta name="viewport" content="width=device-width">
|
||||||
|
|
||||||
|
<style>
|
||||||
|
body {
|
||||||
|
margin: 0px;
|
||||||
|
overflow: hidden;
|
||||||
|
background-color: black;
|
||||||
|
}
|
||||||
|
canvas.game_canvas {
|
||||||
|
border: 0px none;
|
||||||
|
background-color: black;
|
||||||
|
padding-left: 0;
|
||||||
|
padding-right: 0;
|
||||||
|
margin-left: auto;
|
||||||
|
margin-right: auto;
|
||||||
|
display: block;
|
||||||
|
}
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<canvas class="game_canvas" id="canvas" oncontextmenu="event.preventDefault()" tabindex="-1" onmousedown="event.target.focus()" onkeydown="event.preventDefault()"></canvas>
|
||||||
|
<script type="text/javascript" src="odin.js"></script>
|
||||||
|
<script>
|
||||||
|
var odinMemoryInterface = new odin.WasmMemoryInterface();
|
||||||
|
odinMemoryInterface.setIntSize(4);
|
||||||
|
var odinImports = odin.setupDefaultImports(odinMemoryInterface);
|
||||||
|
|
||||||
|
// The Module is used as configuration for emscripten.
|
||||||
|
var Module = {
|
||||||
|
// This is called by emscripten when it starts up.
|
||||||
|
instantiateWasm: (imports, successCallback) => {
|
||||||
|
const newImports = {
|
||||||
|
...odinImports,
|
||||||
|
...imports
|
||||||
|
}
|
||||||
|
|
||||||
|
return WebAssembly.instantiateStreaming(fetch("index.wasm"), newImports).then(function(output) {
|
||||||
|
var e = output.instance.exports;
|
||||||
|
odinMemoryInterface.setExports(e);
|
||||||
|
odinMemoryInterface.setMemory(e.memory);
|
||||||
|
return successCallback(output.instance);
|
||||||
|
});
|
||||||
|
},
|
||||||
|
// This happens a bit after `instantiateWasm`, when everything is
|
||||||
|
// done setting up. At that point we can run code.
|
||||||
|
onRuntimeInitialized: () => {
|
||||||
|
var e = wasmExports;
|
||||||
|
|
||||||
|
// Calls any procedure marked with @init
|
||||||
|
e._start();
|
||||||
|
|
||||||
|
// See source/main_web/main_web.odin for main_start,
|
||||||
|
// main_update and main_end.
|
||||||
|
e.main_start();
|
||||||
|
|
||||||
|
function send_resize() {
|
||||||
|
var canvas = document.getElementById('canvas');
|
||||||
|
e.web_window_size_changed(canvas.width, canvas.height);
|
||||||
|
}
|
||||||
|
|
||||||
|
window.addEventListener('resize', function(event) {
|
||||||
|
send_resize();
|
||||||
|
}, true);
|
||||||
|
|
||||||
|
// This can probably be done better: Ideally we'd feed the
|
||||||
|
// initial size to `main_start`. But there seems to be a
|
||||||
|
// race condition. `canvas` doesn't have it's correct size yet.
|
||||||
|
send_resize();
|
||||||
|
|
||||||
|
// Runs the "main loop".
|
||||||
|
function do_main_update() {
|
||||||
|
if (!e.main_update()) {
|
||||||
|
e.main_end();
|
||||||
|
|
||||||
|
// Calls procedures marked with @fini
|
||||||
|
e._end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
window.requestAnimationFrame(do_main_update);
|
||||||
|
}
|
||||||
|
|
||||||
|
window.requestAnimationFrame(do_main_update);
|
||||||
|
},
|
||||||
|
print: (function() {
|
||||||
|
var element = document.getElementById("output");
|
||||||
|
if (element) element.value = ''; // clear browser cache
|
||||||
|
return function(text) {
|
||||||
|
if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
|
||||||
|
console.log(text);
|
||||||
|
if (element) {
|
||||||
|
element.value += text + "\n";
|
||||||
|
element.scrollTop = element.scrollHeight; // focus on bottom
|
||||||
|
}
|
||||||
|
};
|
||||||
|
})(),
|
||||||
|
canvas: (function() {
|
||||||
|
return document.getElementById("canvas");
|
||||||
|
})()
|
||||||
|
};
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<!-- Emscripten injects its javascript here -->
|
||||||
|
{{{ SCRIPT }}}
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
51
src/main_web/main_web.odin
Normal file
51
src/main_web/main_web.odin
Normal file
|
|
@ -0,0 +1,51 @@
|
||||||
|
// These procs are the ones that will be called from `index.html`, which is
|
||||||
|
// generated from `index_template.html`.
|
||||||
|
|
||||||
|
package main_web
|
||||||
|
|
||||||
|
import "base:runtime"
|
||||||
|
import "core:c"
|
||||||
|
import "core:mem"
|
||||||
|
import game ".."
|
||||||
|
|
||||||
|
@(private="file")
|
||||||
|
web_context: runtime.Context
|
||||||
|
|
||||||
|
@export
|
||||||
|
main_start :: proc "c" () {
|
||||||
|
context = runtime.default_context()
|
||||||
|
|
||||||
|
// The WASM allocator doesn't seem to work properly in combination with
|
||||||
|
// emscripten. There is some kind of conflict with how the manage memory.
|
||||||
|
// So this sets up an allocator that uses emscripten's malloc.
|
||||||
|
context.allocator = emscripten_allocator()
|
||||||
|
runtime.init_global_temporary_allocator(1*mem.Megabyte)
|
||||||
|
|
||||||
|
// Since we now use js_wasm32 we should be able to remove this and use
|
||||||
|
// context.logger = log.create_console_logger(). However, that one produces
|
||||||
|
// extra newlines on web. So it's a bug in that core lib.
|
||||||
|
context.logger = create_emscripten_logger()
|
||||||
|
|
||||||
|
web_context = context
|
||||||
|
|
||||||
|
game.init()
|
||||||
|
}
|
||||||
|
|
||||||
|
@export
|
||||||
|
main_update :: proc "c" () -> bool {
|
||||||
|
context = web_context
|
||||||
|
game.update()
|
||||||
|
return game.should_run()
|
||||||
|
}
|
||||||
|
|
||||||
|
@export
|
||||||
|
main_end :: proc "c" () {
|
||||||
|
context = web_context
|
||||||
|
game.shutdown()
|
||||||
|
}
|
||||||
|
|
||||||
|
@export
|
||||||
|
web_window_size_changed :: proc "c" (w: c.int, h: c.int) {
|
||||||
|
context = web_context
|
||||||
|
game.parent_window_size_changed(int(w), int(h))
|
||||||
|
}
|
||||||
12
src/utils.odin
Normal file
12
src/utils.odin
Normal file
|
|
@ -0,0 +1,12 @@
|
||||||
|
// Wraps os.read_entire_file and os.write_entire_file, but they also work with emscripten.
|
||||||
|
|
||||||
|
package game
|
||||||
|
|
||||||
|
@(require_results)
|
||||||
|
read_entire_file :: proc(name: string, allocator := context.allocator, loc := #caller_location) -> (data: []byte, success: bool) {
|
||||||
|
return _read_entire_file(name, allocator, loc)
|
||||||
|
}
|
||||||
|
|
||||||
|
write_entire_file :: proc(name: string, data: []byte, truncate := true) -> (success: bool) {
|
||||||
|
return _write_entire_file(name, data, truncate)
|
||||||
|
}
|
||||||
16
src/utils_default.odin
Normal file
16
src/utils_default.odin
Normal file
|
|
@ -0,0 +1,16 @@
|
||||||
|
#+build !wasm32
|
||||||
|
#+build !wasm64p32
|
||||||
|
|
||||||
|
package game
|
||||||
|
|
||||||
|
import "core:os"
|
||||||
|
|
||||||
|
_read_entire_file :: proc(name: string, allocator := context.allocator, loc := #caller_location) -> (data: []byte, success: bool) {
|
||||||
|
err: os.Error
|
||||||
|
data, err = os.read_entire_file(name, allocator, loc)
|
||||||
|
return data, err == nil
|
||||||
|
}
|
||||||
|
|
||||||
|
_write_entire_file :: proc(name: string, data: []byte, truncate := true) -> (success: bool) {
|
||||||
|
return os.write_entire_file(name, data, truncate = truncate) == nil
|
||||||
|
}
|
||||||
109
src/utils_web.odin
Normal file
109
src/utils_web.odin
Normal file
|
|
@ -0,0 +1,109 @@
|
||||||
|
// Implementations of `read_entire_file` and `write_entire_file` using the libc
|
||||||
|
// stuff emscripten exposes. You can read the files that get bundled by
|
||||||
|
// `--preload-file assets` in `build_web` script.
|
||||||
|
|
||||||
|
#+build wasm32, wasm64p32
|
||||||
|
|
||||||
|
package game
|
||||||
|
|
||||||
|
import "base:runtime"
|
||||||
|
import "core:log"
|
||||||
|
import "core:c"
|
||||||
|
import "core:strings"
|
||||||
|
|
||||||
|
// These will be linked in by emscripten.
|
||||||
|
@(default_calling_convention = "c")
|
||||||
|
foreign {
|
||||||
|
fopen :: proc(filename, mode: cstring) -> ^FILE ---
|
||||||
|
fseek :: proc(stream: ^FILE, offset: c.long, whence: Whence) -> c.int ---
|
||||||
|
ftell :: proc(stream: ^FILE) -> c.long ---
|
||||||
|
fclose :: proc(stream: ^FILE) -> c.int ---
|
||||||
|
fread :: proc(ptr: rawptr, size: c.size_t, nmemb: c.size_t, stream: ^FILE) -> c.size_t ---
|
||||||
|
fwrite :: proc(ptr: rawptr, size: c.size_t, nmemb: c.size_t, stream: ^FILE) -> c.size_t ---
|
||||||
|
}
|
||||||
|
|
||||||
|
@(private="file")
|
||||||
|
FILE :: struct {}
|
||||||
|
|
||||||
|
Whence :: enum c.int {
|
||||||
|
SET,
|
||||||
|
CUR,
|
||||||
|
END,
|
||||||
|
}
|
||||||
|
|
||||||
|
// Similar to raylib's LoadFileData
|
||||||
|
_read_entire_file :: proc(name: string, allocator := context.allocator, loc := #caller_location) -> (data: []byte, success: bool) {
|
||||||
|
if name == "" {
|
||||||
|
log.error("No file name provided")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
file := fopen(strings.clone_to_cstring(name, context.temp_allocator), "rb")
|
||||||
|
|
||||||
|
if file == nil {
|
||||||
|
log.errorf("Failed to open file %v", name)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
defer fclose(file)
|
||||||
|
|
||||||
|
fseek(file, 0, .END)
|
||||||
|
size := ftell(file)
|
||||||
|
fseek(file, 0, .SET)
|
||||||
|
|
||||||
|
if size <= 0 {
|
||||||
|
log.errorf("Failed to read file %v", name)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
data_err: runtime.Allocator_Error
|
||||||
|
data, data_err = make([]byte, size, allocator, loc)
|
||||||
|
|
||||||
|
if data_err != nil {
|
||||||
|
log.errorf("Error allocating memory: %v", data_err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
read_size := fread(raw_data(data), 1, c.size_t(size), file)
|
||||||
|
|
||||||
|
if read_size != c.size_t(size) {
|
||||||
|
log.warnf("File %v partially loaded (%i bytes out of %i)", name, read_size, size)
|
||||||
|
}
|
||||||
|
|
||||||
|
log.debugf("Successfully loaded %v", name)
|
||||||
|
return data, true
|
||||||
|
}
|
||||||
|
|
||||||
|
// Similar to raylib's SaveFileData.
|
||||||
|
//
|
||||||
|
// Note: This can save during the current session, but I don't think you can
|
||||||
|
// save any data between sessions. So when you close the tab your saved files
|
||||||
|
// are gone. Perhaps you could communicate back to emscripten and save a cookie.
|
||||||
|
// Or communicate with a server and tell it to save data.
|
||||||
|
_write_entire_file :: proc(name: string, data: []byte, truncate := true) -> (success: bool) {
|
||||||
|
if name == "" {
|
||||||
|
log.error("No file name provided")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
file := fopen(strings.clone_to_cstring(name, context.temp_allocator), truncate ? "wb" : "ab")
|
||||||
|
defer fclose(file)
|
||||||
|
|
||||||
|
if file == nil {
|
||||||
|
log.errorf("Failed to open '%v' for writing", name)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
bytes_written := fwrite(raw_data(data), 1, len(data), file)
|
||||||
|
|
||||||
|
if bytes_written == 0 {
|
||||||
|
log.errorf("Failed to write file %v", name)
|
||||||
|
return
|
||||||
|
} else if bytes_written != len(data) {
|
||||||
|
log.errorf("File partially written, wrote %v out of %v bytes", bytes_written, len(data))
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
log.debugf("File written successfully: %v", name)
|
||||||
|
return true
|
||||||
|
}
|
||||||
Loading…
Add table
Add a link
Reference in a new issue